forge
Explore
Log in

Don't you dare go Hollow

The class×course instance is the academic anchor (K-12 remodel)

Browse files at this commit

ae84034a3eed47b582ba9df604d9925849d2246eAhmet Kaan GümüşParent: 6cf8640
  • feat
    • the class×course instance is the academic anchor (K-12 remodel)
Show full message
✨ feat: the class×course instance is the academic anchor (K-12 remodel)

`course` was a school-wide singleton: enrollment, exams, sessions,
roll-call and homework all keyed on it, so two class sections teaching the same
course shared one roster, one exam set and one timetable. This moves the
academic anchor to `class_course` — the per-class instance — and rebuilds
the academic model around Turkish K-12.

Schema (migrations/school/20260916000001_k12_remodel.sql): `class_course`
becomes an instance (ders_saati, counts_toward_karne, enrollment_count,
class_course_teacher); enrollment re-keys to (class_course, app_user);
exam carries class_course + term (+ exam_audience for shared exams);
course_session / session_attendance / homework re-key; `class_member` is a
soft-leave history table (uuid PK, joined_at/left_at, partial unique index
on the live stint); `academic_year` sits above `term`; `class_group` links
a year, not a term; new `course_membership` (clubs/study), `karne_snapshot`;
settings gain branches/excuse_kinds/absence limits/timezone; profile gains
branch. Drops/recreates the identity-changing tables (pre-customer; the
migration resets every counter on a kept table that pointed at a dropped
one).

Layers: domain/db/service/web rewritten to the instance seam, with
`ensure_instance_teacher` gating instance writes (D10), the report card computed per
instance and weighted by ders_saati, an absence report, `/instances`
and `/academic-years` nests, and `/classes/{id}/instances`. Capacity and
the seat-claim 409 are gone; detach sweeps the whole instance subtree and
unlinks its blob keys.

Gates: cargo check --all-targets, SQLX_OFFLINE check (cache regenerated),
doc_sync, spec_bounds, limits_completeness, clippy -D warnings all green;
cargo nextest run 1370/1370.

300 changed files +13266 -5937

Showing the first 300 files; this commit changes more.

.sqlx/query-00a2401b3c5acee26088b2f978927c983a73f8e8ff47ca6208a429958aec8a73.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE class_course\n SET enrollment_count = GREATEST(enrollment_count - 1, 0)\n WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "00a2401b3c5acee26088b2f978927c983a73f8e8ff47ca6208a429958aec8a73"
14+}
.sqlx/query-df95611307c9d494f12fef5d18258482330944d43abde0416a9c9ad368e68927.json → .sqlx/query-01b0ff298ce9661c87b0fd82d01eca7b6f2912a98fe0b580ce237ab3754fde84.jsonrenamed+26 -14
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\", course AS \"course: CourseId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam WHERE id = $1",
3+ "query": "SELECT DISTINCT ON (e.id)\n e.id AS \"id: ExamId\", e.creator AS \"creator: UserId\",\n e.class_course AS \"class_course: ClassCourseId\",\n e.term AS \"term: TermId\", e.title AS \"title: ExamTitle\",\n e.description AS \"description: ExamDescription\",\n e.kind AS \"kind: ExamKind\", e.mode AS \"mode: ExamMode\",\n e.starts_at AS \"starts_at: Timestamp\",\n e.ends_at AS \"ends_at: Timestamp\",\n e.duration_ms AS \"duration_ms: ExamDuration\",\n e.max_attempts AS \"max_attempts: ExamAttemptLimit\",\n e.allow_rejoin, e.allow_review, e.draft\n FROM exam e\n JOIN exam_audience a ON a.exam = e.id\n WHERE a.class_course = $1\n ORDER BY e.id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -27,17 +27,28 @@
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "course: CourseId",
30+ "name": "class_course: ClassCourseId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
3434 "table": "exam",
35- "name": "course"
35+ "name": "class_course"
3636 }
3737 }
3838 },
3939 {
4040 "ordinal": 3,
41+ "name": "term: TermId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "exam",
46+ "name": "term"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
4152 "name": "title: ExamTitle",
4253 "type_info": "Text",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "description: ExamDescription",
5364 "type_info": "Text",
5465 "origin": {
@@ -59,7 +70,7 @@
5970 }
6071 },
6172 {
62- "ordinal": 5,
73+ "ordinal": 6,
6374 "name": "kind: ExamKind",
6475 "type_info": "Text",
6576 "origin": {
@@ -70,7 +81,7 @@
7081 }
7182 },
7283 {
73- "ordinal": 6,
84+ "ordinal": 7,
7485 "name": "mode: ExamMode",
7586 "type_info": "Text",
7687 "origin": {
@@ -81,7 +92,7 @@
8192 }
8293 },
8394 {
84- "ordinal": 7,
95+ "ordinal": 8,
8596 "name": "starts_at: Timestamp",
8697 "type_info": "Int8",
8798 "origin": {
@@ -92,7 +103,7 @@
92103 }
93104 },
94105 {
95- "ordinal": 8,
106+ "ordinal": 9,
96107 "name": "ends_at: Timestamp",
97108 "type_info": "Int8",
98109 "origin": {
@@ -103,7 +114,7 @@
103114 }
104115 },
105116 {
106- "ordinal": 9,
117+ "ordinal": 10,
107118 "name": "duration_ms: ExamDuration",
108119 "type_info": "Int8",
109120 "origin": {
@@ -114,7 +125,7 @@
114125 }
115126 },
116127 {
117- "ordinal": 10,
128+ "ordinal": 11,
118129 "name": "max_attempts: ExamAttemptLimit",
119130 "type_info": "Int8",
120131 "origin": {
@@ -125,7 +136,7 @@
125136 }
126137 },
127138 {
128- "ordinal": 11,
139+ "ordinal": 12,
129140 "name": "allow_rejoin",
130141 "type_info": "Bool",
131142 "origin": {
@@ -136,7 +147,7 @@
136147 }
137148 },
138149 {
139- "ordinal": 12,
150+ "ordinal": 13,
140151 "name": "allow_review",
141152 "type_info": "Bool",
142153 "origin": {
@@ -147,7 +158,7 @@
147158 }
148159 },
149160 {
150- "ordinal": 13,
161+ "ordinal": 14,
151162 "name": "draft",
152163 "type_info": "Bool",
153164 "origin": {
@@ -170,6 +181,7 @@
170181 false,
171182 false,
172183 false,
184+ false,
173185 true,
174186 true,
175187 true,
@@ -180,5 +192,5 @@
180192 false
181193 ]
182194 },
183- "hash": "df95611307c9d494f12fef5d18258482330944d43abde0416a9c9ad368e68927"
195+ "hash": "01b0ff298ce9661c87b0fd82d01eca7b6f2912a98fe0b580ce237ab3754fde84"
184196 }
.sqlx/query-7eb71ec5abefdb8a1a70959e9f639cd4bc24913d0c44ee7739961329086d629d.json → .sqlx/query-03f5c694634477fdaa10fc15662f1a31b6f132f5998e41991e758e76bd521bab.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT 1 AS \"one\" FROM course WHERE id = $1",
3+ "query": "UPDATE class_course SET enrollment_count = enrollment_count + 1\n WHERE id = $1\n RETURNING 1 AS \"one\"",
44 "describe": {
55 "columns": [
66 {
@@ -19,5 +19,5 @@
1919 null
2020 ]
2121 },
22- "hash": "7eb71ec5abefdb8a1a70959e9f639cd4bc24913d0c44ee7739961329086d629d"
22+ "hash": "03f5c694634477fdaa10fc15662f1a31b6f132f5998e41991e758e76bd521bab"
2323 }
.sqlx/query-6098baf8e32ee3c6eb3bd37515b930c0ce298bc70225c495d101fd61ea326466.json → .sqlx/query-0571110cc25b54c354dd07addbc04cfc921361ef0adfda6c4bf7fd7b2030acd5.jsonrenamed+4 -5
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n course AS \"course: CourseId\", status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"\n FROM session_attendance\n WHERE session = $1 AND app_user = $2\n FOR UPDATE",
3+ "query": "SELECT session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"\n FROM session_attendance WHERE app_user = $1\n ORDER BY session DESC, app_user DESC",
44 "describe": {
55 "columns": [
66 {
@@ -27,12 +27,12 @@
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "course: CourseId",
30+ "name": "class_course: ClassCourseId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
3434 "table": "session_attendance",
35- "name": "course"
35+ "name": "class_course"
3636 }
3737 }
3838 },
@@ -61,7 +61,6 @@
6161 ],
6262 "parameters": {
6363 "Left": [
64- "Uuid",
6564 "Uuid"
6665 ]
6766 },
@@ -73,5 +72,5 @@
7372 false
7473 ]
7574 },
76- "hash": "6098baf8e32ee3c6eb3bd37515b930c0ce298bc70225c495d101fd61ea326466"
75+ "hash": "0571110cc25b54c354dd07addbc04cfc921361ef0adfda6c4bf7fd7b2030acd5"
7776 }
.sqlx/query-ea7ff9d9a99aaab7958441ece5fd6ab36bd33ad09c12a0b8668cc3c084237be8.json → .sqlx/query-07855fc52d457a8d9e5e10ad3997ba433fcce7d204d713b52303ef109795998c.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM enrollment WHERE course = $1",
3+ "query": "DELETE FROM class_member WHERE class = $1",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -10,5 +10,5 @@
1010 },
1111 "nullable": []
1212 },
13- "hash": "ea7ff9d9a99aaab7958441ece5fd6ab36bd33ad09c12a0b8668cc3c084237be8"
13+ "hash": "07855fc52d457a8d9e5e10ad3997ba433fcce7d204d713b52303ef109795998c"
1414 }
.sqlx/query-97201bc98edb694a2e07d8da4fd91718e519bfe092a9cdb735d65f654da2f58d.json → .sqlx/query-08f24207b6ab068c44d1d0728d3bbac39f2b341ea5ecb24040b051f5f4862c49.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "INSERT INTO session_attendance (session, app_user, course, status, marked_by, marked_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (session, app_user) DO UPDATE\n SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by,\n marked_at = EXCLUDED.marked_at\n RETURNING session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n course AS \"course: CourseId\", status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"",
3+ "query": "INSERT INTO session_attendance (session, app_user, class_course, status, marked_by, marked_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (session, app_user) DO UPDATE\n SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by,\n marked_at = EXCLUDED.marked_at\n RETURNING session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"",
44 "describe": {
55 "columns": [
66 {
@@ -27,12 +27,12 @@
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "course: CourseId",
30+ "name": "class_course: ClassCourseId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
3434 "table": "session_attendance",
35- "name": "course"
35+ "name": "class_course"
3636 }
3737 }
3838 },
@@ -77,5 +77,5 @@
7777 false
7878 ]
7979 },
80- "hash": "97201bc98edb694a2e07d8da4fd91718e519bfe092a9cdb735d65f654da2f58d"
80+ "hash": "08f24207b6ab068c44d1d0728d3bbac39f2b341ea5ecb24040b051f5f4862c49"
8181 }
.sqlx/query-81b4c9db5438f7ef71b99fd3b6708567d54c1e79ab50e00647543dc20b44a512.json → .sqlx/query-092906c006f4b98f4e115c3d35605b690d0493d9efb3e9e38f444900a2fd10da.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT ai.file FROM answer_image ai\n JOIN exam e ON e.id = ai.exam WHERE e.course = $1",
3+ "query": "SELECT ai.file FROM answer_image ai\n JOIN exam e ON e.id = ai.exam\n JOIN class_course cc ON cc.id = e.class_course\n WHERE cc.course = $1",
44 "describe": {
55 "columns": [
66 {
@@ -24,5 +24,5 @@
2424 false
2525 ]
2626 },
27- "hash": "81b4c9db5438f7ef71b99fd3b6708567d54c1e79ab50e00647543dc20b44a512"
27+ "hash": "092906c006f4b98f4e115c3d35605b690d0493d9efb3e9e38f444900a2fd10da"
2828 }
.sqlx/query-0df7e90f4408e635e281f54b466ad67696507ef0587488c1327f74d66e3641a3.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM class_course_teacher WHERE class_course = $1 AND teacher = $2",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Uuid"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "0df7e90f4408e635e281f54b466ad67696507ef0587488c1327f74d66e3641a3"
15+}
.sqlx/query-0efbc9fb8e602d2decf3f88b9755835dbd832c36b42d09d1c5313716065bf8d5.jsondeleted+0 -30
@@ -1,30 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "SELECT cm.class AS \"class: uuid::Uuid\"\n FROM class_member cm\n JOIN class_course cc ON cc.class = cm.class AND cc.course = $1\n WHERE cm.app_user = $2 AND cm.class <> $3\n ORDER BY cm.class\n LIMIT 1",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "class: uuid::Uuid",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "class_member",
13- "name": "class"
14- }
15- }
16- }
17- ],
18- "parameters": {
19- "Left": [
20- "Uuid",
21- "Uuid",
22- "Uuid"
23- ]
24- },
25- "nullable": [
26- false
27- ]
28- },
29- "hash": "0efbc9fb8e602d2decf3f88b9755835dbd832c36b42d09d1c5313716065bf8d5"
30-}
.sqlx/query-0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4.jsonadded+30 -0
@@ -0,0 +1,30 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course\n WHERE class = $1 AND course = $2\n AND source = (SELECT id FROM class_blueprint WHERE grade = $3)\n FOR UPDATE",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: uuid::Uuid",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course",
13+ "name": "id"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid",
21+ "Uuid",
22+ "Text"
23+ ]
24+ },
25+ "nullable": [
26+ false
27+ ]
28+ },
29+ "hash": "0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4"
30+}
.sqlx/query-ab04850be17ccfa612ec851c4754d89cec1cc4631b1c76ce237b7859c90c333e.json → .sqlx/query-1105ea5febf1c2c9314b456dc8190a943a329f1319335a7ca8a89a71d6709a6f.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT r.exam AS \"exam: ExamId\", r.app_user AS \"user: UserId\", r.seq,\n r.mark AS \"mark: Mark\", r.graded_by AS \"graded_by: UserId\"\n FROM exam_result r JOIN exam e ON e.id = r.exam\n WHERE r.app_user = $1 AND e.course = $2\n ORDER BY r.exam DESC, r.seq DESC",
3+ "query": "SELECT r.exam AS \"exam: ExamId\", r.app_user AS \"user: UserId\", r.seq,\n r.mark AS \"mark: Mark\", r.graded_by AS \"graded_by: UserId\"\n FROM exam_result r JOIN exam e ON e.id = r.exam\n WHERE r.app_user = $1 AND e.term = $2\n ORDER BY r.exam DESC, r.seq DESC",
44 "describe": {
55 "columns": [
66 {
@@ -73,5 +73,5 @@
7373 false
7474 ]
7575 },
76- "hash": "ab04850be17ccfa612ec851c4754d89cec1cc4631b1c76ce237b7859c90c333e"
76+ "hash": "1105ea5febf1c2c9314b456dc8190a943a329f1319335a7ca8a89a71d6709a6f"
7777 }
.sqlx/query-329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2.json → .sqlx/query-12d52c7ee480928e91938e0f1f20ca2daf8e253b7f3498b463042f09d56b7919.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM course_teacher WHERE course = $1",
3+ "query": "DELETE FROM exam_audience WHERE exam = $1",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -10,5 +10,5 @@
1010 },
1111 "nullable": []
1212 },
13- "hash": "329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2"
13+ "hash": "12d52c7ee480928e91938e0f1f20ca2daf8e253b7f3498b463042f09d56b7919"
1414 }
.sqlx/query-8d790a1eea5cee4318551ecbbba9620df93fc80d550dd340f1a1cb91922ffc7f.json → .sqlx/query-13a8d540e8d0a10833fb4ce5db62e56b8dde68fc37030e90caf641430a50fa79.jsonrenamed+26 -14
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\", course AS \"course: CourseId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam WHERE course = $1 ORDER BY id DESC",
3+ "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\",\n class_course AS \"class_course: ClassCourseId\", term AS \"term: TermId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam WHERE id = $1",
44 "describe": {
55 "columns": [
66 {
@@ -27,17 +27,28 @@
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "course: CourseId",
30+ "name": "class_course: ClassCourseId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
3434 "table": "exam",
35- "name": "course"
35+ "name": "class_course"
3636 }
3737 }
3838 },
3939 {
4040 "ordinal": 3,
41+ "name": "term: TermId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "exam",
46+ "name": "term"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
4152 "name": "title: ExamTitle",
4253 "type_info": "Text",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "description: ExamDescription",
5364 "type_info": "Text",
5465 "origin": {
@@ -59,7 +70,7 @@
5970 }
6071 },
6172 {
62- "ordinal": 5,
73+ "ordinal": 6,
6374 "name": "kind: ExamKind",
6475 "type_info": "Text",
6576 "origin": {
@@ -70,7 +81,7 @@
7081 }
7182 },
7283 {
73- "ordinal": 6,
84+ "ordinal": 7,
7485 "name": "mode: ExamMode",
7586 "type_info": "Text",
7687 "origin": {
@@ -81,7 +92,7 @@
8192 }
8293 },
8394 {
84- "ordinal": 7,
95+ "ordinal": 8,
8596 "name": "starts_at: Timestamp",
8697 "type_info": "Int8",
8798 "origin": {
@@ -92,7 +103,7 @@
92103 }
93104 },
94105 {
95- "ordinal": 8,
106+ "ordinal": 9,
96107 "name": "ends_at: Timestamp",
97108 "type_info": "Int8",
98109 "origin": {
@@ -103,7 +114,7 @@
103114 }
104115 },
105116 {
106- "ordinal": 9,
117+ "ordinal": 10,
107118 "name": "duration_ms: ExamDuration",
108119 "type_info": "Int8",
109120 "origin": {
@@ -114,7 +125,7 @@
114125 }
115126 },
116127 {
117- "ordinal": 10,
128+ "ordinal": 11,
118129 "name": "max_attempts: ExamAttemptLimit",
119130 "type_info": "Int8",
120131 "origin": {
@@ -125,7 +136,7 @@
125136 }
126137 },
127138 {
128- "ordinal": 11,
139+ "ordinal": 12,
129140 "name": "allow_rejoin",
130141 "type_info": "Bool",
131142 "origin": {
@@ -136,7 +147,7 @@
136147 }
137148 },
138149 {
139- "ordinal": 12,
150+ "ordinal": 13,
140151 "name": "allow_review",
141152 "type_info": "Bool",
142153 "origin": {
@@ -147,7 +158,7 @@
147158 }
148159 },
149160 {
150- "ordinal": 13,
161+ "ordinal": 14,
151162 "name": "draft",
152163 "type_info": "Bool",
153164 "origin": {
@@ -170,6 +181,7 @@
170181 false,
171182 false,
172183 false,
184+ false,
173185 true,
174186 true,
175187 true,
@@ -180,5 +192,5 @@
180192 false
181193 ]
182194 },
183- "hash": "8d790a1eea5cee4318551ecbbba9620df93fc80d550dd340f1a1cb91922ffc7f"
195+ "hash": "13a8d540e8d0a10833fb4ce5db62e56b8dde68fc37030e90caf641430a50fa79"
184196 }
.sqlx/query-4f831a3b18f1a0e8221fd5b43610cc540576bed7241370578889dfbe673e19ea.json → .sqlx/query-144d1f4fd9c81491220f809e88fdaf5d363272dab481625db83ed46a7ad0b556.jsonrenamed+17 -5
@@ -1,16 +1,16 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "UPDATE enrollment SET source = NULL\n WHERE course = $1 AND app_user = $2\n RETURNING course AS \"course: CourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\"",
3+ "query": "UPDATE enrollment SET source = NULL\n WHERE class_course = $1 AND app_user = $2\n RETURNING class_course AS \"class_course: ClassCourseId\",\n app_user AS \"user: UserId\", enrolled_by AS \"enrolled_by: UserId\",\n source AS \"source: ClassGroupId\",\n created_at AS \"created_at: Timestamp\"",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "course: CourseId",
8+ "name": "class_course: ClassCourseId",
99 "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
1212 "table": "enrollment",
13- "name": "course"
13+ "name": "class_course"
1414 }
1515 }
1616 },
@@ -46,6 +46,17 @@
4646 "name": "source"
4747 }
4848 }
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+ }
4960 }
5061 ],
5162 "parameters": {
@@ -58,8 +69,9 @@
5869 false,
5970 false,
6071 false,
61- true
72+ true,
73+ false
6274 ]
6375 },
64- "hash": "4f831a3b18f1a0e8221fd5b43610cc540576bed7241370578889dfbe673e19ea"
76+ "hash": "144d1f4fd9c81491220f809e88fdaf5d363272dab481625db83ed46a7ad0b556"
6577 }
.sqlx/query-154463480d697fae6ea5126cecd4290f6401f2579b6f4ac3ca27fa6217c83b18.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT file FROM question_image WHERE exam = ANY($1)",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "file",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "question_image",
13+ "name": "file"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "UuidArray"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "154463480d697fae6ea5126cecd4290f6401f2579b6f4ac3ca27fa6217c83b18"
28+}
.sqlx/query-17717997662b0cecc2997806564fc81433d2b524d59e9fb03aef749780c526cf.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH gone AS (\n DELETE FROM enrollment WHERE app_user = $1 RETURNING class_course\n )\n UPDATE class_course\n SET enrollment_count = GREATEST(enrollment_count - 1, 0)\n WHERE id IN (SELECT gone.class_course FROM gone)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "17717997662b0cecc2997806564fc81433d2b524d59e9fb03aef749780c526cf"
14+}
.sqlx/query-182ea9d92a75c5d83a1588ff046abd4794340651318455ce9a4531eb1bc03d50.jsonadded+26 -0
@@ -0,0 +1,26 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes, branches, excuse_kinds,\n max_excused_absent_days, max_unexcused_absent_days,\n timezone)\n VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = EXCLUDED.exam_kinds,\n grade_bands = EXCLUDED.grade_bands,\n max_file_bytes = EXCLUDED.max_file_bytes,\n chatbot_history_turns = EXCLUDED.chatbot_history_turns,\n max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,\n max_chatbot_threads = EXCLUDED.max_chatbot_threads,\n meal_slots = EXCLUDED.meal_slots,\n meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes,\n branches = EXCLUDED.branches,\n excuse_kinds = EXCLUDED.excuse_kinds,\n max_excused_absent_days = EXCLUDED.max_excused_absent_days,\n max_unexcused_absent_days = EXCLUDED.max_unexcused_absent_days,\n timezone = EXCLUDED.timezone",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Jsonb",
9+ "Jsonb",
10+ "Int8",
11+ "Int8",
12+ "Int8",
13+ "Int8",
14+ "Jsonb",
15+ "Int8",
16+ "Jsonb",
17+ "Jsonb",
18+ "Int8",
19+ "Int8",
20+ "Text"
21+ ]
22+ },
23+ "nullable": []
24+ },
25+ "hash": "182ea9d92a75c5d83a1588ff046abd4794340651318455ce9a4531eb1bc03d50"
26+}
.sqlx/query-81a7b9416011e6f61c2723adbc62c4499ac910c7d1228afb0ccfd1f28b02dc11.json → .sqlx/query-1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size\n FROM app_user WHERE role = $1 ORDER BY id DESC",
3+ "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE role = $1 ORDER BY id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -181,6 +181,17 @@
181181 },
182182 {
183183 "ordinal": 16,
184+ "name": "branch",
185+ "type_info": "Text",
186+ "origin": {
187+ "Table": {
188+ "table": "app_user",
189+ "name": "branch"
190+ }
191+ }
192+ },
193+ {
194+ "ordinal": 17,
184195 "name": "avatar_size",
185196 "type_info": "Int8",
186197 "origin": {
@@ -213,8 +224,9 @@
213224 true,
214225 true,
215226 true,
227+ true,
216228 true
217229 ]
218230 },
219- "hash": "81a7b9416011e6f61c2723adbc62c4499ac910c7d1228afb0ccfd1f28b02dc11"
231+ "hash": "1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88"
220232 }
.sqlx/query-1a78ccdb73cee51188f073d86ea66182fa57873c736f4aacedc60e36774c1e25.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE term SET course_count = GREATEST(course_count - 1, 0)\n WHERE id = $1",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "1a78ccdb73cee51188f073d86ea66182fa57873c736f4aacedc60e36774c1e25"
14-}
.sqlx/query-1ce33939b49f6a42dcdb9508a0756bacd0a8430f82a079e51e5c2cb5e1073bcf.jsondeleted+0 -28
@@ -1,28 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "SELECT class_member_count AS \"heir_count: i64\" FROM class_group\n WHERE id = $1 FOR NO KEY UPDATE",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "heir_count: i64",
9- "type_info": "Int8",
10- "origin": {
11- "Table": {
12- "table": "class_group",
13- "name": "class_member_count"
14- }
15- }
16- }
17- ],
18- "parameters": {
19- "Left": [
20- "Uuid"
21- ]
22- },
23- "nullable": [
24- false
25- ]
26- },
27- "hash": "1ce33939b49f6a42dcdb9508a0756bacd0a8430f82a079e51e5c2cb5e1073bcf"
28-}
.sqlx/query-72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595.json → .sqlx/query-2030dabf14da5e9f428ab9b91b92251c53e561d3f7a797f38ac45cf10c9324d1.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1",
3+ "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1 FOR UPDATE",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "homework",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -115,5 +115,5 @@
115115 false
116116 ]
117117 },
118- "hash": "72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595"
118+ "hash": "2030dabf14da5e9f428ab9b91b92251c53e561d3f7a797f38ac45cf10c9324d1"
119119 }
.sqlx/query-fcce69f1324abd0a60651f5f0bc3f0bcfbdf42be5b2f34f79a40d3c741055135.json → .sqlx/query-22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "INSERT INTO app_user (id, username, person, role, created_at)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size",
3+ "query": "INSERT INTO app_user (id, username, person, role, created_at)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size",
44 "describe": {
55 "columns": [
66 {
@@ -181,6 +181,17 @@
181181 },
182182 {
183183 "ordinal": 16,
184+ "name": "branch",
185+ "type_info": "Text",
186+ "origin": {
187+ "Table": {
188+ "table": "app_user",
189+ "name": "branch"
190+ }
191+ }
192+ },
193+ {
194+ "ordinal": 17,
184195 "name": "avatar_size",
185196 "type_info": "Int8",
186197 "origin": {
@@ -217,8 +228,9 @@
217228 true,
218229 true,
219230 true,
231+ true,
220232 true
221233 ]
222234 },
223- "hash": "fcce69f1324abd0a60651f5f0bc3f0bcfbdf42be5b2f34f79a40d3c741055135"
235+ "hash": "22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f"
224236 }
.sqlx/query-ecacff3f8318067e8abd8d779904deeaf6feb14dd992721d1be5bee56c9d7ff4.json → .sqlx/query-238a5985401d6a8b614a874f7157d75db9e19f14e73dc20249833d28311f7466.jsonrenamed+17 -5
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: TermId\", name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\" FROM term WHERE id = $1",
3+ "query": "SELECT id AS \"id: TermId\", year AS \"year: AcademicYearId\",\n name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\" FROM term WHERE id = $1",
44 "describe": {
55 "columns": [
66 {
@@ -16,6 +16,17 @@
1616 },
1717 {
1818 "ordinal": 1,
19+ "name": "year: AcademicYearId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "term",
24+ "name": "year"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
1930 "name": "name: TermName",
2031 "type_info": "Text",
2132 "origin": {
@@ -26,7 +37,7 @@
2637 }
2738 },
2839 {
29- "ordinal": 2,
40+ "ordinal": 3,
3041 "name": "starts_at: Timestamp",
3142 "type_info": "Int8",
3243 "origin": {
@@ -37,7 +48,7 @@
3748 }
3849 },
3950 {
40- "ordinal": 3,
51+ "ordinal": 4,
4152 "name": "ends_at: Timestamp",
4253 "type_info": "Int8",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "archived_at: Timestamp",
5364 "type_info": "Int8",
5465 "origin": {
@@ -69,8 +80,9 @@
6980 false,
7081 false,
7182 false,
83+ false,
7284 true
7385 ]
7486 },
75- "hash": "ecacff3f8318067e8abd8d779904deeaf6feb14dd992721d1be5bee56c9d7ff4"
87+ "hash": "238a5985401d6a8b614a874f7157d75db9e19f14e73dc20249833d28311f7466"
7688 }
.sqlx/query-23a1369a6a30b803cafaaa75e7203ace62afc4d3bbc55cdec686920ac0fdd570.jsondeleted+0 -25
@@ -1,25 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "DELETE FROM class_course WHERE class = $1 AND course = $2\n AND source = (SELECT id FROM class_blueprint WHERE grade = $3)\n RETURNING 1 AS \"one\"",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "one",
9- "type_info": "Int4",
10- "origin": "Expression"
11- }
12- ],
13- "parameters": {
14- "Left": [
15- "Uuid",
16- "Uuid",
17- "Text"
18- ]
19- },
20- "nullable": [
21- null
22- ]
23- },
24- "hash": "23a1369a6a30b803cafaaa75e7203ace62afc4d3bbc55cdec686920ac0fdd570"
25-}
.sqlx/query-2461d810d04aca273a98714d99f0f1d815e12943439002b4615f379f8586768d.jsonadded+67 -0
@@ -0,0 +1,67 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH seat AS (\n UPDATE course\n SET course_membership_count = course_membership_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO course_membership (course, app_user, added_by, created_at)\n SELECT $1, $2, $3, $4 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING course AS \"course: CourseId\", app_user AS \"user: UserId\",\n added_by AS \"added_by: UserId\",\n created_at AS \"created_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "course: CourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "course_membership",
13+ "name": "course"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "course_membership",
24+ "name": "app_user"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "added_by: UserId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "course_membership",
35+ "name": "added_by"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "created_at: Timestamp",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "course_membership",
46+ "name": "created_at"
47+ }
48+ }
49+ }
50+ ],
51+ "parameters": {
52+ "Left": [
53+ "Uuid",
54+ "Uuid",
55+ "Uuid",
56+ "Int8"
57+ ]
58+ },
59+ "nullable": [
60+ false,
61+ false,
62+ false,
63+ false
64+ ]
65+ },
66+ "hash": "2461d810d04aca273a98714d99f0f1d815e12943439002b4615f379f8586768d"
67+}
.sqlx/query-1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185.json → .sqlx/query-2587404e272948a34f509c791e3e9533b846175d0d29a3a6995338e54790535c.jsonrenamed+6 -6
@@ -1,16 +1,16 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT course AS \"course: CourseId\", teacher AS \"teacher: UserId\"\n FROM course_teacher WHERE course = ANY($1)",
3+ "query": "SELECT class_course AS \"class_course: ClassCourseId\", teacher AS \"teacher: UserId\"\n FROM class_course_teacher WHERE class_course = ANY($1)\n ORDER BY class_course, teacher",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "course: CourseId",
8+ "name": "class_course: ClassCourseId",
99 "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
12- "table": "course_teacher",
13- "name": "course"
12+ "table": "class_course_teacher",
13+ "name": "class_course"
1414 }
1515 }
1616 },
@@ -20,7 +20,7 @@
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
23- "table": "course_teacher",
23+ "table": "class_course_teacher",
2424 "name": "teacher"
2525 }
2626 }
@@ -36,5 +36,5 @@
3636 false
3737 ]
3838 },
39- "hash": "1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185"
39+ "hash": "2587404e272948a34f509c791e3e9533b846175d0d29a3a6995338e54790535c"
4040 }
.sqlx/query-2844f173a4514ccac8bb7064eb7412b962749b10cf16c289f657743512c31130.jsonadded+210 -0
@@ -0,0 +1,210 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH room AS (\n UPDATE term SET exam_count = exam_count + 1\n WHERE id = $3\n RETURNING 1)\n INSERT INTO exam (id, creator, class_course, term, title, description, kind, mode,\n starts_at, ends_at, duration_ms, max_attempts,\n allow_rejoin, allow_review, draft)\n SELECT $1, $2, $4, $3, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15\n WHERE EXISTS (SELECT 1 FROM room)\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n term AS \"term: TermId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: ExamId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "exam",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "creator: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "exam",
24+ "name": "creator"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "class_course: ClassCourseId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "exam",
35+ "name": "class_course"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "term: TermId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "exam",
46+ "name": "term"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "title: ExamTitle",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "exam",
57+ "name": "title"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "description: ExamDescription",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "exam",
68+ "name": "description"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "kind: ExamKind",
75+ "type_info": "Text",
76+ "origin": {
77+ "Table": {
78+ "table": "exam",
79+ "name": "kind"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "mode: ExamMode",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "exam",
90+ "name": "mode"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "starts_at: Timestamp",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "exam",
101+ "name": "starts_at"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "ends_at: Timestamp",
108+ "type_info": "Int8",
109+ "origin": {
110+ "Table": {
111+ "table": "exam",
112+ "name": "ends_at"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "duration_ms: ExamDuration",
119+ "type_info": "Int8",
120+ "origin": {
121+ "Table": {
122+ "table": "exam",
123+ "name": "duration_ms"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "max_attempts: ExamAttemptLimit",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "exam",
134+ "name": "max_attempts"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "allow_rejoin",
141+ "type_info": "Bool",
142+ "origin": {
143+ "Table": {
144+ "table": "exam",
145+ "name": "allow_rejoin"
146+ }
147+ }
148+ },
149+ {
150+ "ordinal": 13,
151+ "name": "allow_review",
152+ "type_info": "Bool",
153+ "origin": {
154+ "Table": {
155+ "table": "exam",
156+ "name": "allow_review"
157+ }
158+ }
159+ },
160+ {
161+ "ordinal": 14,
162+ "name": "draft",
163+ "type_info": "Bool",
164+ "origin": {
165+ "Table": {
166+ "table": "exam",
167+ "name": "draft"
168+ }
169+ }
170+ }
171+ ],
172+ "parameters": {
173+ "Left": [
174+ "Uuid",
175+ "Uuid",
176+ "Uuid",
177+ "Uuid",
178+ "Text",
179+ "Text",
180+ "Text",
181+ "Text",
182+ "Int8",
183+ "Int8",
184+ "Int8",
185+ "Int8",
186+ "Bool",
187+ "Bool",
188+ "Bool"
189+ ]
190+ },
191+ "nullable": [
192+ false,
193+ false,
194+ false,
195+ false,
196+ false,
197+ false,
198+ false,
199+ true,
200+ true,
201+ true,
202+ true,
203+ false,
204+ false,
205+ false,
206+ false
207+ ]
208+ },
209+ "hash": "2844f173a4514ccac8bb7064eb7412b962749b10cf16c289f657743512c31130"
210+}
.sqlx/query-a06578b33fea0609b216e985ebaa1def29c4622e4e864a6e65de141b5b307dab.json → .sqlx/query-285c758abaa028faab45383feaf8eda2d9af8bbaa2c14eacf3c67ab3fe303d89.jsonrenamed+4 -4
@@ -1,16 +1,16 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT course AS \"course: uuid::Uuid\" FROM class_course WHERE class = $1",
3+ "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course WHERE class = $1",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "course: uuid::Uuid",
8+ "name": "id: uuid::Uuid",
99 "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
1212 "table": "class_course",
13- "name": "course"
13+ "name": "id"
1414 }
1515 }
1616 }
@@ -24,5 +24,5 @@
2424 false
2525 ]
2626 },
27- "hash": "a06578b33fea0609b216e985ebaa1def29c4622e4e864a6e65de141b5b307dab"
27+ "hash": "285c758abaa028faab45383feaf8eda2d9af8bbaa2c14eacf3c67ab3fe303d89"
2828 }
.sqlx/query-2a7f0da7e1f564430f7c7c8f1c7bb5421213ecac8fec266ef809e86462fefbe4.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE class_course\n SET enrollment_count = GREATEST(enrollment_count - 1, 0)\n WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "2a7f0da7e1f564430f7c7c8f1c7bb5421213ecac8fec266ef809e86462fefbe4"
14+}
.sqlx/query-2bff8987ce85508ef7c91cc20e868617420d1f923a6704111cb83827dcf3c8d0.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE academic_year\n SET class_count = GREATEST(class_count - 1, 0)\n WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "2bff8987ce85508ef7c91cc20e868617420d1f923a6704111cb83827dcf3c8d0"
14+}
.sqlx/query-41ed454c1cf5fdd24eb5597d30e1c7132eff4962ca53992c2511d67b311ea22b.json → .sqlx/query-2d8f6523cf7856181b08678cb65b731d35db23dfe75554f4f39cf06f6518db42.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM class_course WHERE class = $1 AND course = $2\n RETURNING 1 AS \"one\"",
3+ "query": "SELECT 1 AS \"one\" FROM class_member\n WHERE class = $1 AND app_user = $2 AND left_at IS NULL",
44 "describe": {
55 "columns": [
66 {
@@ -20,5 +20,5 @@
2020 null
2121 ]
2222 },
23- "hash": "41ed454c1cf5fdd24eb5597d30e1c7132eff4962ca53992c2511d67b311ea22b"
23+ "hash": "2d8f6523cf7856181b08678cb65b731d35db23dfe75554f4f39cf06f6518db42"
2424 }
.sqlx/query-2e98a32d2edc7d1ba3b004ffb0d00fb0aa3c54b2a39a7bffd8df239011e23358.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE term SET exam_count = GREATEST(exam_count - 1, 0)\n WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "2e98a32d2edc7d1ba3b004ffb0d00fb0aa3c54b2a39a7bffd8df239011e23358"
14+}
.sqlx/query-2f41b58fa1b14cae34c0c641210b24028b4bc319d20de364b3c5d02e9afb840f.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course WHERE course = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: uuid::Uuid",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course",
13+ "name": "id"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "2f41b58fa1b14cae34c0c641210b24028b4bc319d20de364b3c5d02e9afb840f"
28+}
.sqlx/query-34079575aee9338011e36bb40487447cbdeb10d07d195faf4cb4f540e87788f3.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM course_session WHERE class_course = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "34079575aee9338011e36bb40487447cbdeb10d07d195faf4cb4f540e87788f3"
14+}
.sqlx/query-f14d1fb87ed6f382a95f9b5703f4494065479265f9ef011c51f443751d27447f.json → .sqlx/query-34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n term AS \"term: TermId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = ANY($1)",
3+ "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = ANY($1)",
44 "describe": {
55 "columns": [
66 {
@@ -49,12 +49,12 @@
4949 },
5050 {
5151 "ordinal": 4,
52- "name": "term: TermId",
52+ "name": "year: AcademicYearId",
5353 "type_info": "Uuid",
5454 "origin": {
5555 "Table": {
5656 "table": "class_group",
57- "name": "term"
57+ "name": "year"
5858 }
5959 }
6060 },
@@ -84,5 +84,5 @@
8484 true
8585 ]
8686 },
87- "hash": "f14d1fb87ed6f382a95f9b5703f4494065479265f9ef011c51f443751d27447f"
87+ "hash": "34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806"
8888 }
.sqlx/query-df7311334c93314352406e1097530e602a575930baf28e91933d9fa9adf7a2ed.json → .sqlx/query-35b2fb5639850677d160f6d07f24bf197e5411d6a5547053d0dc9a5e7ece7f4b.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "INSERT INTO enrollment (course, app_user, enrolled_by, source, created_at)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (course, app_user) DO NOTHING\n RETURNING 1 AS \"one\"",
3+ "query": "INSERT INTO enrollment (class_course, app_user, enrolled_by, source, created_at)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (class_course, app_user) DO NOTHING\n RETURNING 1 AS \"one\"",
44 "describe": {
55 "columns": [
66 {
@@ -23,5 +23,5 @@
2323 null
2424 ]
2525 },
26- "hash": "df7311334c93314352406e1097530e602a575930baf28e91933d9fa9adf7a2ed"
26+ "hash": "35b2fb5639850677d160f6d07f24bf197e5411d6a5547053d0dc9a5e7ece7f4b"
2727 }
.sqlx/query-8ef28352094c41d4a797006c84bb13185d1bf95aba508c2a6f9fdad3ab14e2a1.json → .sqlx/query-3a8d10b6ad79c551e94587c938b1ea3843bc9e407e9eed5b1cf9dd25f8233ce3.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM enrollment WHERE course = $1 AND app_user = $2",
3+ "query": "DELETE FROM enrollment WHERE class_course = $1 AND app_user = $2",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -11,5 +11,5 @@
1111 },
1212 "nullable": []
1313 },
14- "hash": "8ef28352094c41d4a797006c84bb13185d1bf95aba508c2a6f9fdad3ab14e2a1"
14+ "hash": "3a8d10b6ad79c551e94587c938b1ea3843bc9e407e9eed5b1cf9dd25f8233ce3"
1515 }
.sqlx/query-4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d.jsondeleted+0 -107
@@ -1,107 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "WITH seat AS (\n UPDATE term\n SET course_count = course_count + 1\n WHERE id = $7 AND course_count < $8\n RETURNING 1)\n INSERT INTO course (id, creator, title, description, kind, term, capacity)\n SELECT $1, $2, $3, $4, $5, $7, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "id: CourseId",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "course",
13- "name": "id"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "creator: UserId",
20- "type_info": "Uuid",
21- "origin": {
22- "Table": {
23- "table": "course",
24- "name": "creator"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "title: CourseTitle",
31- "type_info": "Text",
32- "origin": {
33- "Table": {
34- "table": "course",
35- "name": "title"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "description: CourseDescription",
42- "type_info": "Text",
43- "origin": {
44- "Table": {
45- "table": "course",
46- "name": "description"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "kind: CourseKind",
53- "type_info": "Text",
54- "origin": {
55- "Table": {
56- "table": "course",
57- "name": "kind"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "term: TermId",
64- "type_info": "Uuid",
65- "origin": {
66- "Table": {
67- "table": "course",
68- "name": "term"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "capacity",
75- "type_info": "Int8",
76- "origin": {
77- "Table": {
78- "table": "course",
79- "name": "capacity"
80- }
81- }
82- }
83- ],
84- "parameters": {
85- "Left": [
86- "Uuid",
87- "Uuid",
88- "Text",
89- "Text",
90- "Text",
91- "Int8",
92- "Uuid",
93- "Int8"
94- ]
95- },
96- "nullable": [
97- false,
98- false,
99- false,
100- false,
101- false,
102- true,
103- true
104- ]
105- },
106- "hash": "4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d"
107-}
.sqlx/query-728de093441cfaccc7832a182862ac3d5f43ba9f4349f0140b5978b5fb3378f9.json → .sqlx/query-43ae4864f41cb19de3496a26567bd02ca377db3ea6d0bbbe5106a24c17a84692.jsonrenamed+26 -14
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "UPDATE exam SET title = $2, description = $3, kind = $4, mode = $5,\n starts_at = $6, ends_at = $7, duration_ms = $8,\n max_attempts = $9, allow_rejoin = $10, allow_review = $11,\n draft = $12\n WHERE id = $1\n AND title = $13 AND description = $14 AND kind = $15\n AND mode IS NOT DISTINCT FROM $16\n AND starts_at IS NOT DISTINCT FROM $17\n AND ends_at IS NOT DISTINCT FROM $18\n AND duration_ms IS NOT DISTINCT FROM $19\n AND max_attempts = $20 AND allow_rejoin = $21 AND allow_review = $22\n AND draft = $23\n AND result_count = $24\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n course AS \"course: CourseId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft",
3+ "query": "UPDATE exam SET title = $2, description = $3, kind = $4, mode = $5,\n starts_at = $6, ends_at = $7, duration_ms = $8,\n max_attempts = $9, allow_rejoin = $10, allow_review = $11,\n draft = $12\n WHERE id = $1\n AND title = $13 AND description = $14 AND kind = $15\n AND mode IS NOT DISTINCT FROM $16\n AND starts_at IS NOT DISTINCT FROM $17\n AND ends_at IS NOT DISTINCT FROM $18\n AND duration_ms IS NOT DISTINCT FROM $19\n AND max_attempts = $20 AND allow_rejoin = $21 AND allow_review = $22\n AND draft = $23\n AND result_count = $24\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n term AS \"term: TermId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft",
44 "describe": {
55 "columns": [
66 {
@@ -27,17 +27,28 @@
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "course: CourseId",
30+ "name": "class_course: ClassCourseId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
3434 "table": "exam",
35- "name": "course"
35+ "name": "class_course"
3636 }
3737 }
3838 },
3939 {
4040 "ordinal": 3,
41+ "name": "term: TermId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "exam",
46+ "name": "term"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
4152 "name": "title: ExamTitle",
4253 "type_info": "Text",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "description: ExamDescription",
5364 "type_info": "Text",
5465 "origin": {
@@ -59,7 +70,7 @@
5970 }
6071 },
6172 {
62- "ordinal": 5,
73+ "ordinal": 6,
6374 "name": "kind: ExamKind",
6475 "type_info": "Text",
6576 "origin": {
@@ -70,7 +81,7 @@
7081 }
7182 },
7283 {
73- "ordinal": 6,
84+ "ordinal": 7,
7485 "name": "mode: ExamMode",
7586 "type_info": "Text",
7687 "origin": {
@@ -81,7 +92,7 @@
8192 }
8293 },
8394 {
84- "ordinal": 7,
95+ "ordinal": 8,
8596 "name": "starts_at: Timestamp",
8697 "type_info": "Int8",
8798 "origin": {
@@ -92,7 +103,7 @@
92103 }
93104 },
94105 {
95- "ordinal": 8,
106+ "ordinal": 9,
96107 "name": "ends_at: Timestamp",
97108 "type_info": "Int8",
98109 "origin": {
@@ -103,7 +114,7 @@
103114 }
104115 },
105116 {
106- "ordinal": 9,
117+ "ordinal": 10,
107118 "name": "duration_ms: ExamDuration",
108119 "type_info": "Int8",
109120 "origin": {
@@ -114,7 +125,7 @@
114125 }
115126 },
116127 {
117- "ordinal": 10,
128+ "ordinal": 11,
118129 "name": "max_attempts: ExamAttemptLimit",
119130 "type_info": "Int8",
120131 "origin": {
@@ -125,7 +136,7 @@
125136 }
126137 },
127138 {
128- "ordinal": 11,
139+ "ordinal": 12,
129140 "name": "allow_rejoin",
130141 "type_info": "Bool",
131142 "origin": {
@@ -136,7 +147,7 @@
136147 }
137148 },
138149 {
139- "ordinal": 12,
150+ "ordinal": 13,
140151 "name": "allow_review",
141152 "type_info": "Bool",
142153 "origin": {
@@ -147,7 +158,7 @@
147158 }
148159 },
149160 {
150- "ordinal": 13,
161+ "ordinal": 14,
151162 "name": "draft",
152163 "type_info": "Bool",
153164 "origin": {
@@ -193,6 +204,7 @@
193204 false,
194205 false,
195206 false,
207+ false,
196208 true,
197209 true,
198210 true,
@@ -203,5 +215,5 @@
203215 false
204216 ]
205217 },
206- "hash": "728de093441cfaccc7832a182862ac3d5f43ba9f4349f0140b5978b5fb3378f9"
218+ "hash": "43ae4864f41cb19de3496a26567bd02ca377db3ea6d0bbbe5106a24c17a84692"
207219 }
.sqlx/query-ff6b3600e1cb9dcbd1e573b7eb4892704cb6aa9892e5344d1bde26be16f38a4a.json → .sqlx/query-45b22b65eb9eaa820596249c17fd6d110892e40a200fb22f4998a375067fc1d1.jsonrenamed+3 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "UPDATE course SET enrollment_count = enrollment_count + 1\n WHERE id = $1 AND enrollment_count < COALESCE(capacity, $2)\n RETURNING 1 AS \"one\"",
3+ "query": "UPDATE class_member SET left_at = $3\n WHERE class = $1 AND app_user = $2 AND left_at IS NULL\n RETURNING 1 AS \"one\"",
44 "describe": {
55 "columns": [
66 {
@@ -12,6 +12,7 @@
1212 ],
1313 "parameters": {
1414 "Left": [
15+ "Uuid",
1516 "Uuid",
1617 "Int8"
1718 ]
@@ -20,5 +21,5 @@
2021 null
2122 ]
2223 },
23- "hash": "ff6b3600e1cb9dcbd1e573b7eb4892704cb6aa9892e5344d1bde26be16f38a4a"
24+ "hash": "45b22b65eb9eaa820596249c17fd6d110892e40a200fb22f4998a375067fc1d1"
2425 }
.sqlx/query-15e1d6d5b56bbdbc817402c8b92202dc705ca27d14da7016adb201145c2229b0.json → .sqlx/query-46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size\n FROM app_user WHERE username = $1",
3+ "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE username = $1",
44 "describe": {
55 "columns": [
66 {
@@ -181,6 +181,17 @@
181181 },
182182 {
183183 "ordinal": 16,
184+ "name": "branch",
185+ "type_info": "Text",
186+ "origin": {
187+ "Table": {
188+ "table": "app_user",
189+ "name": "branch"
190+ }
191+ }
192+ },
193+ {
194+ "ordinal": 17,
184195 "name": "avatar_size",
185196 "type_info": "Int8",
186197 "origin": {
@@ -213,8 +224,9 @@
213224 true,
214225 true,
215226 true,
227+ true,
216228 true
217229 ]
218230 },
219- "hash": "15e1d6d5b56bbdbc817402c8b92202dc705ca27d14da7016adb201145c2229b0"
231+ "hash": "46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701"
220232 }
.sqlx/query-48188b56ecdcb1e16edf51509f090685694378e1dd0f6fe7b19f6d4dc8cec676.jsondeleted+0 -41
@@ -1,41 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "SELECT course AS \"course: uuid::Uuid\", app_user AS \"app_user: uuid::Uuid\"\n FROM enrollment WHERE app_user = $1 AND source = $2",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "course: uuid::Uuid",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "enrollment",
13- "name": "course"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "app_user: uuid::Uuid",
20- "type_info": "Uuid",
21- "origin": {
22- "Table": {
23- "table": "enrollment",
24- "name": "app_user"
25- }
26- }
27- }
28- ],
29- "parameters": {
30- "Left": [
31- "Uuid",
32- "Uuid"
33- ]
34- },
35- "nullable": [
36- false,
37- false
38- ]
39- },
40- "hash": "48188b56ecdcb1e16edf51509f090685694378e1dd0f6fe7b19f6d4dc8cec676"
41-}
.sqlx/query-4d6f5584543386bae2d92f27620e600eb755b1d466e134085a9aa4ece67d04d1.jsonadded+24 -0
@@ -0,0 +1,24 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT 1 AS \"one\" FROM class_member\n WHERE class = $1 AND app_user = $2 AND left_at IS NULL",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "one",
9+ "type_info": "Int4",
10+ "origin": "Expression"
11+ }
12+ ],
13+ "parameters": {
14+ "Left": [
15+ "Uuid",
16+ "Uuid"
17+ ]
18+ },
19+ "nullable": [
20+ null
21+ ]
22+ },
23+ "hash": "4d6f5584543386bae2d92f27620e600eb755b1d466e134085a9aa4ece67d04d1"
24+}
.sqlx/query-4f4dacffc966e98307ddf8667527398fe83ee865aa6199dbc7d807d5f1094bf7.jsondeleted+0 -16
@@ -1,16 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE enrollment SET source = $1 WHERE course = $2 AND app_user = $3",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid",
9- "Uuid",
10- "Uuid"
11- ]
12- },
13- "nullable": []
14- },
15- "hash": "4f4dacffc966e98307ddf8667527398fe83ee865aa6199dbc7d807d5f1094bf7"
16-}
.sqlx/query-4fc84b8b8bc1fd2da27b3db19f5405c1d15e51cbbfbfb494239ccce056470ca0.jsonadded+124 -0
@@ -0,0 +1,124 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: AcademicYearId\", name AS \"name: AcademicYearName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\", creator AS \"creator: UserId\",\n grade_promotions AS \"grade_promotions: Json<Vec<GradePromotion>>\",\n class_count, term_count\n FROM academic_year WHERE id = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: AcademicYearId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "academic_year",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "name: AcademicYearName",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "academic_year",
24+ "name": "name"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "starts_at: Timestamp",
31+ "type_info": "Int8",
32+ "origin": {
33+ "Table": {
34+ "table": "academic_year",
35+ "name": "starts_at"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "ends_at: Timestamp",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "academic_year",
46+ "name": "ends_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "archived_at: Timestamp",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "academic_year",
57+ "name": "archived_at"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "creator: UserId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "academic_year",
68+ "name": "creator"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "grade_promotions: Json<Vec<GradePromotion>>",
75+ "type_info": "Jsonb",
76+ "origin": {
77+ "Table": {
78+ "table": "academic_year",
79+ "name": "grade_promotions"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "class_count",
86+ "type_info": "Int8",
87+ "origin": {
88+ "Table": {
89+ "table": "academic_year",
90+ "name": "class_count"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "term_count",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "academic_year",
101+ "name": "term_count"
102+ }
103+ }
104+ }
105+ ],
106+ "parameters": {
107+ "Left": [
108+ "Uuid"
109+ ]
110+ },
111+ "nullable": [
112+ false,
113+ false,
114+ false,
115+ false,
116+ true,
117+ false,
118+ false,
119+ false,
120+ false
121+ ]
122+ },
123+ "hash": "4fc84b8b8bc1fd2da27b3db19f5405c1d15e51cbbfbfb494239ccce056470ca0"
124+}
.sqlx/query-6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1.json → .sqlx/query-5010047bffcbc995e623e4902c3efc3514edb3d09e33df6c9c93780278199077.jsonrenamed+9 -9
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = $1",
3+ "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", class_course_count, course_membership_count\n FROM course WHERE id = $1",
44 "describe": {
55 "columns": [
66 {
@@ -60,23 +60,23 @@
6060 },
6161 {
6262 "ordinal": 5,
63- "name": "term: TermId",
64- "type_info": "Uuid",
63+ "name": "class_course_count",
64+ "type_info": "Int8",
6565 "origin": {
6666 "Table": {
6767 "table": "course",
68- "name": "term"
68+ "name": "class_course_count"
6969 }
7070 }
7171 },
7272 {
7373 "ordinal": 6,
74- "name": "capacity",
74+ "name": "course_membership_count",
7575 "type_info": "Int8",
7676 "origin": {
7777 "Table": {
7878 "table": "course",
79- "name": "capacity"
79+ "name": "course_membership_count"
8080 }
8181 }
8282 }
@@ -92,9 +92,9 @@
9292 false,
9393 false,
9494 false,
95- true,
96- true
95+ false,
96+ false
9797 ]
9898 },
99- "hash": "6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1"
99+ "hash": "5010047bffcbc995e623e4902c3efc3514edb3d09e33df6c9c93780278199077"
100100 }
.sqlx/query-3af1f73e479f61d79291a8318ee6dc7bd7201115f3dfcb37aa46576befd2b817.json → .sqlx/query-508239762c35fa66a85134694106d0e57157af3985d9238fd5f84e1c3d2a2eb0.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM class_member WHERE class = $1 AND app_user = $2\n RETURNING 1 AS \"one\"",
3+ "query": "SELECT 1 AS \"one\" FROM enrollment\n WHERE class_course = $1 AND app_user = $2",
44 "describe": {
55 "columns": [
66 {
@@ -20,5 +20,5 @@
2020 null
2121 ]
2222 },
23- "hash": "3af1f73e479f61d79291a8318ee6dc7bd7201115f3dfcb37aa46576befd2b817"
23+ "hash": "508239762c35fa66a85134694106d0e57157af3985d9238fd5f84e1c3d2a2eb0"
2424 }
.sqlx/query-f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9.json → .sqlx/query-51c9b50b0722b0d49f8202387bc06f833d34598d7556f0f6c02171230b72cd6e.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = $1 ORDER BY id DESC",
3+ "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "homework",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -115,5 +115,5 @@
115115 false
116116 ]
117117 },
118- "hash": "f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9"
118+ "hash": "51c9b50b0722b0d49f8202387bc06f833d34598d7556f0f6c02171230b72cd6e"
119119 }
.sqlx/query-528eb8c289d6edc05eaa85b4f0361933a88f3d8ecce63236da73f0b03b59d722.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH gone AS (\n UPDATE class_member SET left_at = $2\n WHERE app_user = $1 AND left_at IS NULL\n RETURNING class\n )\n UPDATE class_group\n SET class_member_count = GREATEST(class_member_count - 1, 0)\n WHERE id IN (SELECT gone.class FROM gone)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Int8"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "528eb8c289d6edc05eaa85b4f0361933a88f3d8ecce63236da73f0b03b59d722"
15+}
.sqlx/query-551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b.jsonadded+121 -0
@@ -0,0 +1,121 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH updated AS (\n UPDATE class_course\n SET ders_saati = COALESCE($2::bigint, ders_saati::bigint)::smallint,\n counts_toward_karne = COALESCE($3, counts_toward_karne)\n WHERE id = $1\n RETURNING *)\n SELECT u.id AS \"id: ClassCourseId\", u.class AS \"class: ClassGroupId\",\n u.course AS \"course: CourseId\", u.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n u.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n u.counts_toward_karne, u.enrollment_count,\n u.attached_at AS \"attached_at: Timestamp\"\n FROM updated u\n LEFT JOIN class_blueprint b ON b.id = u.source",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: ClassCourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course",
13+ "name": "id"
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+ "ordinal": 3,
41+ "name": "attached_by: UserId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "class_course",
46+ "name": "attached_by"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "source?: ClassBlueprintId",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "class_blueprint",
57+ "name": "grade"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "ders_saati!: DersSaati",
64+ "type_info": "Int8",
65+ "origin": "Expression"
66+ },
67+ {
68+ "ordinal": 6,
69+ "name": "counts_toward_karne",
70+ "type_info": "Bool",
71+ "origin": {
72+ "Table": {
73+ "table": "class_course",
74+ "name": "counts_toward_karne"
75+ }
76+ }
77+ },
78+ {
79+ "ordinal": 7,
80+ "name": "enrollment_count",
81+ "type_info": "Int8",
82+ "origin": {
83+ "Table": {
84+ "table": "class_course",
85+ "name": "enrollment_count"
86+ }
87+ }
88+ },
89+ {
90+ "ordinal": 8,
91+ "name": "attached_at: Timestamp",
92+ "type_info": "Int8",
93+ "origin": {
94+ "Table": {
95+ "table": "class_course",
96+ "name": "attached_at"
97+ }
98+ }
99+ }
100+ ],
101+ "parameters": {
102+ "Left": [
103+ "Uuid",
104+ "Int8",
105+ "Bool"
106+ ]
107+ },
108+ "nullable": [
109+ false,
110+ false,
111+ false,
112+ false,
113+ true,
114+ null,
115+ false,
116+ false,
117+ false
118+ ]
119+ },
120+ "hash": "551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b"
121+}
.sqlx/query-56698618a156770cdb1475134c16e1f513cb6613c0e21bdf033978b2be5d7842.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM course_membership WHERE course = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "56698618a156770cdb1475134c16e1f513cb6613c0e21bdf033978b2be5d7842"
14+}
.sqlx/query-6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f.json → .sqlx/query-57440348e01f5416cefe71d9d638ce723e9ec1cda075ba99093b5fd3ebd88b9c.jsonrenamed+9 -10
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE creator = $1 OR id IN (\n SELECT course FROM course_teacher WHERE teacher = $2)\n ORDER BY id DESC",
3+ "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", class_course_count, course_membership_count\n FROM course WHERE id IN (\n SELECT cc.course FROM class_course_teacher t\n JOIN class_course cc ON cc.id = t.class_course\n WHERE t.teacher = $1)\n ORDER BY id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -60,30 +60,29 @@
6060 },
6161 {
6262 "ordinal": 5,
63- "name": "term: TermId",
64- "type_info": "Uuid",
63+ "name": "class_course_count",
64+ "type_info": "Int8",
6565 "origin": {
6666 "Table": {
6767 "table": "course",
68- "name": "term"
68+ "name": "class_course_count"
6969 }
7070 }
7171 },
7272 {
7373 "ordinal": 6,
74- "name": "capacity",
74+ "name": "course_membership_count",
7575 "type_info": "Int8",
7676 "origin": {
7777 "Table": {
7878 "table": "course",
79- "name": "capacity"
79+ "name": "course_membership_count"
8080 }
8181 }
8282 }
8383 ],
8484 "parameters": {
8585 "Left": [
86- "Uuid",
8786 "Uuid"
8887 ]
8988 },
@@ -93,9 +92,9 @@
9392 false,
9493 false,
9594 false,
96- true,
97- true
95+ false,
96+ false
9897 ]
9998 },
100- "hash": "6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f"
99+ "hash": "57440348e01f5416cefe71d9d638ce723e9ec1cda075ba99093b5fd3ebd88b9c"
101100 }
.sqlx/query-57e14f7219a606a952093053b513fd2a6c8aa10ed7a8676483debf76723cce2b.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT file FROM homework_file\n WHERE submission IN (\n SELECT id FROM homework_submission\n WHERE homework IN (\n SELECT h.id FROM homework h\n JOIN class_course cc ON cc.id = h.class_course\n WHERE cc.course = $1)\n )",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "file",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "homework_file",
13+ "name": "file"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "57e14f7219a606a952093053b513fd2a6c8aa10ed7a8676483debf76723cce2b"
28+}
.sqlx/query-58cc273a1c6380cd70ba606245369cf8b4ea505a2123ebeece417921d6392901.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT file FROM answer_image WHERE exam = ANY($1)",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "file",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "answer_image",
13+ "name": "file"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "UuidArray"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "58cc273a1c6380cd70ba606245369cf8b4ea505a2123ebeece417921d6392901"
28+}
.sqlx/query-5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f.jsonadded+119 -0
@@ -0,0 +1,119 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.id = ANY($1)\n ORDER BY cc.attached_at DESC, cc.id DESC",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: ClassCourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course",
13+ "name": "id"
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+ "ordinal": 3,
41+ "name": "attached_by: UserId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "class_course",
46+ "name": "attached_by"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "source?: ClassBlueprintId",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "class_blueprint",
57+ "name": "grade"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "ders_saati!: DersSaati",
64+ "type_info": "Int8",
65+ "origin": "Expression"
66+ },
67+ {
68+ "ordinal": 6,
69+ "name": "counts_toward_karne",
70+ "type_info": "Bool",
71+ "origin": {
72+ "Table": {
73+ "table": "class_course",
74+ "name": "counts_toward_karne"
75+ }
76+ }
77+ },
78+ {
79+ "ordinal": 7,
80+ "name": "enrollment_count",
81+ "type_info": "Int8",
82+ "origin": {
83+ "Table": {
84+ "table": "class_course",
85+ "name": "enrollment_count"
86+ }
87+ }
88+ },
89+ {
90+ "ordinal": 8,
91+ "name": "attached_at: Timestamp",
92+ "type_info": "Int8",
93+ "origin": {
94+ "Table": {
95+ "table": "class_course",
96+ "name": "attached_at"
97+ }
98+ }
99+ }
100+ ],
101+ "parameters": {
102+ "Left": [
103+ "UuidArray"
104+ ]
105+ },
106+ "nullable": [
107+ false,
108+ false,
109+ false,
110+ false,
111+ false,
112+ null,
113+ false,
114+ false,
115+ false
116+ ]
117+ },
118+ "hash": "5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f"
119+}
.sqlx/query-ff03e27f1d286af08d2468fee7c3e5121c55d9721e19c46c5e05b7ca79c785f4.json → .sqlx/query-5ebfcdfad4e6eb3342cb60e5743a7478fd357924360cf46a635c63aa072c19bf.jsonrenamed+19 -6
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "INSERT INTO term (id, name, starts_at, ends_at, archived_at)\n VALUES ($1, $2, $3, $4, NULL)\n RETURNING id AS \"id: TermId\", name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"",
3+ "query": "WITH room AS (\n UPDATE academic_year SET term_count = term_count + 1\n WHERE id = $5\n RETURNING 1)\n INSERT INTO term (id, name, year, starts_at, ends_at, archived_at)\n SELECT $1, $2, $5, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM room)\n RETURNING id AS \"id: TermId\", year AS \"year: AcademicYearId\",\n name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"",
44 "describe": {
55 "columns": [
66 {
@@ -16,6 +16,17 @@
1616 },
1717 {
1818 "ordinal": 1,
19+ "name": "year: AcademicYearId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "term",
24+ "name": "year"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
1930 "name": "name: TermName",
2031 "type_info": "Text",
2132 "origin": {
@@ -26,7 +37,7 @@
2637 }
2738 },
2839 {
29- "ordinal": 2,
40+ "ordinal": 3,
3041 "name": "starts_at: Timestamp",
3142 "type_info": "Int8",
3243 "origin": {
@@ -37,7 +48,7 @@
3748 }
3849 },
3950 {
40- "ordinal": 3,
51+ "ordinal": 4,
4152 "name": "ends_at: Timestamp",
4253 "type_info": "Int8",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "archived_at: Timestamp",
5364 "type_info": "Int8",
5465 "origin": {
@@ -64,7 +75,8 @@
6475 "Uuid",
6576 "Text",
6677 "Int8",
67- "Int8"
78+ "Int8",
79+ "Uuid"
6880 ]
6981 },
7082 "nullable": [
@@ -72,8 +84,9 @@
7284 false,
7385 false,
7486 false,
87+ false,
7588 true
7689 ]
7790 },
78- "hash": "ff03e27f1d286af08d2468fee7c3e5121c55d9721e19c46c5e05b7ca79c785f4"
91+ "hash": "5ebfcdfad4e6eb3342cb60e5743a7478fd357924360cf46a635c63aa072c19bf"
7992 }
.sqlx/query-619c4c92014c8910ea8278b655d76d295ea421e1e27a8d0dca769b8896df5470.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT term AS \"term: TermId\" FROM exam WHERE id = $1 FOR UPDATE",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "term: TermId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "exam",
13+ "name": "term"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "619c4c92014c8910ea8278b655d76d295ea421e1e27a8d0dca769b8896df5470"
28+}
.sqlx/query-61b2b846ba3a7a820c73bb3f0f81ccb3fefb6d3a83c081f6d0ed9caeab3e0bac.jsonadded+17 -0
@@ -0,0 +1,17 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO karne_snapshot (term, app_user, payload, created_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (term, app_user) DO UPDATE\n SET payload = EXCLUDED.payload, created_at = EXCLUDED.created_at",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Uuid",
10+ "Jsonb",
11+ "Int8"
12+ ]
13+ },
14+ "nullable": []
15+ },
16+ "hash": "61b2b846ba3a7a820c73bb3f0f81ccb3fefb6d3a83c081f6d0ed9caeab3e0bac"
17+}
.sqlx/query-63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.jsonadded+119 -0
@@ -0,0 +1,119 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.class = ANY($1)\n ORDER BY cc.attached_at DESC, cc.id DESC",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: ClassCourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course",
13+ "name": "id"
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+ "ordinal": 3,
41+ "name": "attached_by: UserId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "class_course",
46+ "name": "attached_by"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "source?: ClassBlueprintId",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "class_blueprint",
57+ "name": "grade"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "ders_saati!: DersSaati",
64+ "type_info": "Int8",
65+ "origin": "Expression"
66+ },
67+ {
68+ "ordinal": 6,
69+ "name": "counts_toward_karne",
70+ "type_info": "Bool",
71+ "origin": {
72+ "Table": {
73+ "table": "class_course",
74+ "name": "counts_toward_karne"
75+ }
76+ }
77+ },
78+ {
79+ "ordinal": 7,
80+ "name": "enrollment_count",
81+ "type_info": "Int8",
82+ "origin": {
83+ "Table": {
84+ "table": "class_course",
85+ "name": "enrollment_count"
86+ }
87+ }
88+ },
89+ {
90+ "ordinal": 8,
91+ "name": "attached_at: Timestamp",
92+ "type_info": "Int8",
93+ "origin": {
94+ "Table": {
95+ "table": "class_course",
96+ "name": "attached_at"
97+ }
98+ }
99+ }
100+ ],
101+ "parameters": {
102+ "Left": [
103+ "UuidArray"
104+ ]
105+ },
106+ "nullable": [
107+ false,
108+ false,
109+ false,
110+ false,
111+ false,
112+ null,
113+ false,
114+ false,
115+ false
116+ ]
117+ },
118+ "hash": "63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414"
119+}
.sqlx/query-6975e1ab374116eef46d9453fc93b6a64ba56a775aa5db356d212db2f54de648.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM class_course_teacher WHERE class_course = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "6975e1ab374116eef46d9453fc93b6a64ba56a775aa5db356d212db2f54de648"
14+}
.sqlx/query-f3a4cec1ec1f46679602989fab57cc89a722030f6200af053c392dd6aa9ee9d3.json → .sqlx/query-6a15b173fd0d6d1771319de73aaa95795ab707290b067d1115009dc2d824f6a3.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkResultId\",\n homework AS \"homework: HomeworkId\",\n app_user AS \"user: UserId\",\n status AS \"status: HomeworkStatus\",\n mark AS \"mark: Mark\",\n graded_by AS \"graded_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework_result\n WHERE app_user = $1\n AND homework IN (SELECT id FROM homework WHERE course = $2)\n ORDER BY id DESC",
3+ "query": "SELECT id AS \"id: HomeworkResultId\",\n homework AS \"homework: HomeworkId\",\n app_user AS \"user: UserId\",\n status AS \"status: HomeworkStatus\",\n mark AS \"mark: Mark\",\n graded_by AS \"graded_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework_result\n WHERE app_user = $1\n AND homework IN (SELECT id FROM homework WHERE class_course = $2)\n ORDER BY id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -97,5 +97,5 @@
9797 false
9898 ]
9999 },
100- "hash": "f3a4cec1ec1f46679602989fab57cc89a722030f6200af053c392dd6aa9ee9d3"
100+ "hash": "6a15b173fd0d6d1771319de73aaa95795ab707290b067d1115009dc2d824f6a3"
101101 }
.sqlx/query-6b3d5b06e9cdedb2bd7972fb7d5f01db24f8ac1167e4d5e8c0f885c131cfb716.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE course SET enrollment_count = enrollment_count - 1\n WHERE id = $1",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "6b3d5b06e9cdedb2bd7972fb7d5f01db24f8ac1167e4d5e8c0f885c131cfb716"
14-}
.sqlx/query-f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091.json → .sqlx/query-6c4c14b2948967fa110b0af4e4d2b30b7af969358f18c389713e89056bb0b0cc.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework\n WHERE course = $1\n AND (NOT EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id)\n OR EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id AND a.student = $2))\n ORDER BY id DESC",
3+ "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework\n WHERE class_course = $1\n AND (NOT EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id)\n OR EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id AND a.student = $2))\n ORDER BY id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "homework",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -116,5 +116,5 @@
116116 false
117117 ]
118118 },
119- "hash": "f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091"
119+ "hash": "6c4c14b2948967fa110b0af4e4d2b30b7af969358f18c389713e89056bb0b0cc"
120120 }
.sqlx/query-6d9fc2433d41081225b1d03b1944965c9e35f61c3423e7c0ea36fd951ea9f988.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT teacher AS \"teacher: UserId\" FROM class_course_teacher\n WHERE class_course = $1 ORDER BY teacher",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "teacher: UserId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course_teacher",
13+ "name": "teacher"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "6d9fc2433d41081225b1d03b1944965c9e35f61c3423e7c0ea36fd951ea9f988"
28+}
.sqlx/query-6efeb49c4351e1dfb26a97ab0e2f2e2dfd7b11cd99856f35a41e06d55004bede.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO class_course_teacher (class_course, teacher)\n SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM class_course WHERE id = $1)\n ON CONFLICT DO NOTHING",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Uuid"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "6efeb49c4351e1dfb26a97ab0e2f2e2dfd7b11cd99856f35a41e06d55004bede"
15+}
.sqlx/query-6fafd69d5084dbc0da5c59746eeb6bdbb55926ea72f4ab85493e1bceb94f2754.jsonadded+24 -0
@@ -0,0 +1,24 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT 1 AS \"one\" FROM (\n SELECT e.app_user FROM enrollment e\n WHERE e.app_user = $2\n AND e.class_course IN (SELECT id FROM class_course WHERE course = $1)\n UNION ALL\n SELECT m.app_user FROM course_membership m\n WHERE m.course = $1 AND m.app_user = $2\n ) people LIMIT 1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "one",
9+ "type_info": "Int4",
10+ "origin": "Expression"
11+ }
12+ ],
13+ "parameters": {
14+ "Left": [
15+ "Uuid",
16+ "Uuid"
17+ ]
18+ },
19+ "nullable": [
20+ null
21+ ]
22+ },
23+ "hash": "6fafd69d5084dbc0da5c59746eeb6bdbb55926ea72f4ab85493e1bceb94f2754"
24+}
.sqlx/query-11181bfd9a0abc840f00738f1649925944ca1b05a034647d82835e7f12337591.json → .sqlx/query-70d3d8c7cb74016eb71516a9db2fd7dd62bf80c388814ee0f5cdd771f22a5120.jsonrenamed+12 -12
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT course AS \"course: CourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\"\n FROM enrollment WHERE course = $1 AND app_user = $2",
3+ "query": "SELECT course AS \"course: CourseId\", app_user AS \"user: UserId\",\n added_by AS \"added_by: UserId\", created_at AS \"created_at: Timestamp\"\n FROM course_membership WHERE course = $1 AND app_user = $2",
44 "describe": {
55 "columns": [
66 {
@@ -9,7 +9,7 @@
99 "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
12- "table": "enrollment",
12+ "table": "course_membership",
1313 "name": "course"
1414 }
1515 }
@@ -20,30 +20,30 @@
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
23- "table": "enrollment",
23+ "table": "course_membership",
2424 "name": "app_user"
2525 }
2626 }
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "enrolled_by: UserId",
30+ "name": "added_by: UserId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
34- "table": "enrollment",
35- "name": "enrolled_by"
34+ "table": "course_membership",
35+ "name": "added_by"
3636 }
3737 }
3838 },
3939 {
4040 "ordinal": 3,
41- "name": "source: ClassGroupId",
42- "type_info": "Uuid",
41+ "name": "created_at: Timestamp",
42+ "type_info": "Int8",
4343 "origin": {
4444 "Table": {
45- "table": "enrollment",
46- "name": "source"
45+ "table": "course_membership",
46+ "name": "created_at"
4747 }
4848 }
4949 }
@@ -58,8 +58,8 @@
5858 false,
5959 false,
6060 false,
61- true
61+ false
6262 ]
6363 },
64- "hash": "11181bfd9a0abc840f00738f1649925944ca1b05a034647d82835e7f12337591"
64+ "hash": "70d3d8c7cb74016eb71516a9db2fd7dd62bf80c388814ee0f5cdd771f22a5120"
6565 }
.sqlx/query-719a5da335489982564b3334fd52f86ae36ff88ab1ee7ada8129de8baadea9cf.jsonadded+65 -0
@@ -0,0 +1,65 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH gone AS (\n DELETE FROM course_membership\n WHERE course = $1 AND app_user = $2\n RETURNING course, app_user, added_by, created_at),\n counted AS (\n UPDATE course\n SET course_membership_count = GREATEST(\n course_membership_count - (SELECT count(*) FROM gone), 0)\n WHERE id = $1\n RETURNING 1)\n SELECT course AS \"course: CourseId\", app_user AS \"user: UserId\",\n added_by AS \"added_by: UserId\", created_at AS \"created_at: Timestamp\"\n FROM gone",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "course: CourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "course_membership",
13+ "name": "course"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "course_membership",
24+ "name": "app_user"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "added_by: UserId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "course_membership",
35+ "name": "added_by"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "created_at: Timestamp",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "course_membership",
46+ "name": "created_at"
47+ }
48+ }
49+ }
50+ ],
51+ "parameters": {
52+ "Left": [
53+ "Uuid",
54+ "Uuid"
55+ ]
56+ },
57+ "nullable": [
58+ false,
59+ false,
60+ false,
61+ false
62+ ]
63+ },
64+ "hash": "719a5da335489982564b3334fd52f86ae36ff88ab1ee7ada8129de8baadea9cf"
65+}
.sqlx/query-f18d958fcfb0551be235244ab8b98856fd579f252ccf2a24c37cd34be968421c.json → .sqlx/query-76cda1c341acce57e3f3fe57a377af9c9671ba4d7771d70d05449d3e0e15f348.jsonrenamed+3 -3
@@ -1,11 +1,11 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id FROM exam WHERE course = $1",
3+ "query": "SELECT id AS \"id: uuid::Uuid\" FROM exam WHERE class_course = $1",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "id",
8+ "name": "id: uuid::Uuid",
99 "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
@@ -24,5 +24,5 @@
2424 false
2525 ]
2626 },
27- "hash": "f18d958fcfb0551be235244ab8b98856fd579f252ccf2a24c37cd34be968421c"
27+ "hash": "76cda1c341acce57e3f3fe57a377af9c9671ba4d7771d70d05449d3e0e15f348"
2828 }
.sqlx/query-77a3e1d1772a5d54ec33452c037aa8d10e9a27ed79880fb43b71f5ba9d9a6cc7.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE term SET class_count = GREATEST(class_count - 1, 0)\n WHERE id = $1",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "77a3e1d1772a5d54ec33452c037aa8d10e9a27ed79880fb43b71f5ba9d9a6cc7"
14-}
.sqlx/query-553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2.json → .sqlx/query-77fc62012bd6363d83114c5814f981ae46af9b926746e5b37bcd937fab754437.jsonrenamed+10 -11
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "INSERT INTO course (id, creator, title, description, kind, term, capacity)\n VALUES ($1, $2, $3, $4, $5, NULL, $6)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity",
3+ "query": "INSERT INTO course (id, creator, title, description, kind)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", class_course_count, course_membership_count",
44 "describe": {
55 "columns": [
66 {
@@ -60,23 +60,23 @@
6060 },
6161 {
6262 "ordinal": 5,
63- "name": "term: TermId",
64- "type_info": "Uuid",
63+ "name": "class_course_count",
64+ "type_info": "Int8",
6565 "origin": {
6666 "Table": {
6767 "table": "course",
68- "name": "term"
68+ "name": "class_course_count"
6969 }
7070 }
7171 },
7272 {
7373 "ordinal": 6,
74- "name": "capacity",
74+ "name": "course_membership_count",
7575 "type_info": "Int8",
7676 "origin": {
7777 "Table": {
7878 "table": "course",
79- "name": "capacity"
79+ "name": "course_membership_count"
8080 }
8181 }
8282 }
@@ -87,8 +87,7 @@
8787 "Uuid",
8888 "Text",
8989 "Text",
90- "Text",
91- "Int8"
90+ "Text"
9291 ]
9392 },
9493 "nullable": [
@@ -97,9 +96,9 @@
9796 false,
9897 false,
9998 false,
100- true,
101- true
99+ false,
100+ false
102101 ]
103102 },
104- "hash": "553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2"
103+ "hash": "77fc62012bd6363d83114c5814f981ae46af9b926746e5b37bcd937fab754437"
105104 }
.sqlx/query-786cd981b243bf0c325c5e3aedd34f93f78c53ca5744f1117af3701acdc4a26b.jsonadded+129 -0
@@ -0,0 +1,129 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO academic_year (id, name, starts_at, ends_at, creator, grade_promotions)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: AcademicYearId\", name AS \"name: AcademicYearName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\", creator AS \"creator: UserId\",\n grade_promotions AS \"grade_promotions: Json<Vec<GradePromotion>>\",\n class_count, term_count",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: AcademicYearId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "academic_year",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "name: AcademicYearName",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "academic_year",
24+ "name": "name"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "starts_at: Timestamp",
31+ "type_info": "Int8",
32+ "origin": {
33+ "Table": {
34+ "table": "academic_year",
35+ "name": "starts_at"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "ends_at: Timestamp",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "academic_year",
46+ "name": "ends_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "archived_at: Timestamp",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "academic_year",
57+ "name": "archived_at"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "creator: UserId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "academic_year",
68+ "name": "creator"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "grade_promotions: Json<Vec<GradePromotion>>",
75+ "type_info": "Jsonb",
76+ "origin": {
77+ "Table": {
78+ "table": "academic_year",
79+ "name": "grade_promotions"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "class_count",
86+ "type_info": "Int8",
87+ "origin": {
88+ "Table": {
89+ "table": "academic_year",
90+ "name": "class_count"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "term_count",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "academic_year",
101+ "name": "term_count"
102+ }
103+ }
104+ }
105+ ],
106+ "parameters": {
107+ "Left": [
108+ "Uuid",
109+ "Text",
110+ "Int8",
111+ "Int8",
112+ "Uuid",
113+ "Jsonb"
114+ ]
115+ },
116+ "nullable": [
117+ false,
118+ false,
119+ false,
120+ false,
121+ true,
122+ false,
123+ false,
124+ false,
125+ false
126+ ]
127+ },
128+ "hash": "786cd981b243bf0c325c5e3aedd34f93f78c53ca5744f1117af3701acdc4a26b"
129+}
.sqlx/query-798274cfd929c9142c52291dfb3860ecb756799f7593b3f8a2d0a7b0696bf8b1.jsonadded+52 -0
@@ -0,0 +1,52 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT class_member_count, class_course_count, year AS \"year: uuid::Uuid\"\n FROM class_group WHERE id = $1 FOR UPDATE",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "class_member_count",
9+ "type_info": "Int8",
10+ "origin": {
11+ "Table": {
12+ "table": "class_group",
13+ "name": "class_member_count"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "class_course_count",
20+ "type_info": "Int8",
21+ "origin": {
22+ "Table": {
23+ "table": "class_group",
24+ "name": "class_course_count"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "year: uuid::Uuid",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "class_group",
35+ "name": "year"
36+ }
37+ }
38+ }
39+ ],
40+ "parameters": {
41+ "Left": [
42+ "Uuid"
43+ ]
44+ },
45+ "nullable": [
46+ false,
47+ false,
48+ true
49+ ]
50+ },
51+ "hash": "798274cfd929c9142c52291dfb3860ecb756799f7593b3f8a2d0a7b0696bf8b1"
52+}
.sqlx/query-61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275.json → .sqlx/query-7bfe416ea8b08f2d1a4aaa81aef82762f91183c32dbc6114d7b1a02dafb1d51b.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM homework_assignment WHERE homework IN (\n SELECT id FROM homework WHERE course = $1)",
3+ "query": "DELETE FROM homework_assignment WHERE homework IN (\n SELECT id FROM homework WHERE class_course = $1)",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -10,5 +10,5 @@
1010 },
1111 "nullable": []
1212 },
13- "hash": "61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275"
13+ "hash": "7bfe416ea8b08f2d1a4aaa81aef82762f91183c32dbc6114d7b1a02dafb1d51b"
1414 }
.sqlx/query-3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1.json → .sqlx/query-7ec20ef74e4c4c474e7b6d52a903bafdb4ffe23880c98df3870cd35dc7433448.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1 FOR UPDATE",
3+ "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE class_course = $1 ORDER BY id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "homework",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -115,5 +115,5 @@
115115 false
116116 ]
117117 },
118- "hash": "3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1"
118+ "hash": "7ec20ef74e4c4c474e7b6d52a903bafdb4ffe23880c98df3870cd35dc7433448"
119119 }
.sqlx/query-eefb6fc7a7f418d165f92618225b689ce8619494c52d43ddb09097744fb12565.json → .sqlx/query-7ef15b73d204f84bbf71ddef3381b2cb2b8d818bb1aaf58197b8ab1e9afc425d.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT app_user AS \"app_user: uuid::Uuid\" FROM class_member WHERE class = $1",
3+ "query": "SELECT app_user AS \"app_user: uuid::Uuid\" FROM class_member\n WHERE class = $1 AND left_at IS NULL",
44 "describe": {
55 "columns": [
66 {
@@ -24,5 +24,5 @@
2424 false
2525 ]
2626 },
27- "hash": "eefb6fc7a7f418d165f92618225b689ce8619494c52d43ddb09097744fb12565"
27+ "hash": "7ef15b73d204f84bbf71ddef3381b2cb2b8d818bb1aaf58197b8ab1e9afc425d"
2828 }
.sqlx/query-8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7.json → .sqlx/query-7f1e995a1c731d6083e1c841f0c5d18de461c676133753c70cbffa5fe3bca6b5.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = ANY($1) ORDER BY id DESC",
3+ "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE class_course = ANY($1) ORDER BY id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "homework",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -115,5 +115,5 @@
115115 false
116116 ]
117117 },
118- "hash": "8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7"
118+ "hash": "7f1e995a1c731d6083e1c841f0c5d18de461c676133753c70cbffa5fe3bca6b5"
119119 }
.sqlx/query-86f14780a8f9f8ec6df2ba19902c4bbe0c3aa2a987115e1231ba3726b496a10c.json → .sqlx/query-8043002e1c5ae4f4158daa2f4598197a279e5d696b9fb6267bddc3aae64a6a4a.jsonrenamed+26 -14
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\", course AS \"course: CourseId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam WHERE course = ANY($1) ORDER BY id DESC",
3+ "query": "SELECT DISTINCT ON (e.id)\n e.id AS \"id: ExamId\", e.creator AS \"creator: UserId\",\n e.class_course AS \"class_course: ClassCourseId\",\n e.term AS \"term: TermId\", e.title AS \"title: ExamTitle\",\n e.description AS \"description: ExamDescription\",\n e.kind AS \"kind: ExamKind\", e.mode AS \"mode: ExamMode\",\n e.starts_at AS \"starts_at: Timestamp\",\n e.ends_at AS \"ends_at: Timestamp\",\n e.duration_ms AS \"duration_ms: ExamDuration\",\n e.max_attempts AS \"max_attempts: ExamAttemptLimit\",\n e.allow_rejoin, e.allow_review, e.draft\n FROM exam e\n JOIN exam_audience a ON a.exam = e.id\n WHERE a.class_course = ANY($1)\n ORDER BY e.id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -27,17 +27,28 @@
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "course: CourseId",
30+ "name": "class_course: ClassCourseId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
3434 "table": "exam",
35- "name": "course"
35+ "name": "class_course"
3636 }
3737 }
3838 },
3939 {
4040 "ordinal": 3,
41+ "name": "term: TermId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "exam",
46+ "name": "term"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
4152 "name": "title: ExamTitle",
4253 "type_info": "Text",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "description: ExamDescription",
5364 "type_info": "Text",
5465 "origin": {
@@ -59,7 +70,7 @@
5970 }
6071 },
6172 {
62- "ordinal": 5,
73+ "ordinal": 6,
6374 "name": "kind: ExamKind",
6475 "type_info": "Text",
6576 "origin": {
@@ -70,7 +81,7 @@
7081 }
7182 },
7283 {
73- "ordinal": 6,
84+ "ordinal": 7,
7485 "name": "mode: ExamMode",
7586 "type_info": "Text",
7687 "origin": {
@@ -81,7 +92,7 @@
8192 }
8293 },
8394 {
84- "ordinal": 7,
95+ "ordinal": 8,
8596 "name": "starts_at: Timestamp",
8697 "type_info": "Int8",
8798 "origin": {
@@ -92,7 +103,7 @@
92103 }
93104 },
94105 {
95- "ordinal": 8,
106+ "ordinal": 9,
96107 "name": "ends_at: Timestamp",
97108 "type_info": "Int8",
98109 "origin": {
@@ -103,7 +114,7 @@
103114 }
104115 },
105116 {
106- "ordinal": 9,
117+ "ordinal": 10,
107118 "name": "duration_ms: ExamDuration",
108119 "type_info": "Int8",
109120 "origin": {
@@ -114,7 +125,7 @@
114125 }
115126 },
116127 {
117- "ordinal": 10,
128+ "ordinal": 11,
118129 "name": "max_attempts: ExamAttemptLimit",
119130 "type_info": "Int8",
120131 "origin": {
@@ -125,7 +136,7 @@
125136 }
126137 },
127138 {
128- "ordinal": 11,
139+ "ordinal": 12,
129140 "name": "allow_rejoin",
130141 "type_info": "Bool",
131142 "origin": {
@@ -136,7 +147,7 @@
136147 }
137148 },
138149 {
139- "ordinal": 12,
150+ "ordinal": 13,
140151 "name": "allow_review",
141152 "type_info": "Bool",
142153 "origin": {
@@ -147,7 +158,7 @@
147158 }
148159 },
149160 {
150- "ordinal": 13,
161+ "ordinal": 14,
151162 "name": "draft",
152163 "type_info": "Bool",
153164 "origin": {
@@ -170,6 +181,7 @@
170181 false,
171182 false,
172183 false,
184+ false,
173185 true,
174186 true,
175187 true,
@@ -180,5 +192,5 @@
180192 false
181193 ]
182194 },
183- "hash": "86f14780a8f9f8ec6df2ba19902c4bbe0c3aa2a987115e1231ba3726b496a10c"
195+ "hash": "8043002e1c5ae4f4158daa2f4598197a279e5d696b9fb6267bddc3aae64a6a4a"
184196 }
.sqlx/query-83d5da7f52ee983e49f3c4dcd99472f5a8ba4a9017363f04c35173284da42037.jsondeleted+0 -145
@@ -1,145 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "WITH new_row AS (\n INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = $1,\n grade_bands = $3,\n max_file_bytes = $4,\n chatbot_history_turns = $5,\n max_chatbot_message_len = $6,\n max_chatbot_threads = $7,\n meal_slots = $8,\n meal_cancel_cutoff_minutes = $10\n WHERE settings.exam_kinds IS NOT DISTINCT FROM $13\n AND settings.grade_bands IS NOT DISTINCT FROM $14\n AND settings.max_file_bytes IS NOT DISTINCT FROM $15\n AND settings.chatbot_history_turns IS NOT DISTINCT FROM $16\n AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $17\n AND settings.max_chatbot_threads IS NOT DISTINCT FROM $18\n AND settings.meal_slots IS NOT DISTINCT FROM $19\n AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20\n AND COALESCE((SELECT array_agg(s.status ORDER BY s.status)\n FROM settings_attendance_status s\n WHERE s.settings = settings.id), '{}')\n IS NOT DISTINCT FROM $11::text[]\n AND (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = settings.id)\n IS NOT DISTINCT FROM $12::text[]\n RETURNING exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes),\n status_del AS (\n DELETE FROM settings_attendance_status\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n status_ins AS (\n INSERT INTO settings_attendance_status (settings, status)\n SELECT 'school', t.status FROM unnest($2::text[]) AS t(status)\n CROSS JOIN (SELECT count(*) AS deleted FROM status_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING status),\n tag_del AS (\n DELETE FROM settings_dietary_tag\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n tag_ins AS (\n INSERT INTO settings_dietary_tag (settings, tag)\n SELECT 'school', t.tag FROM unnest($9::text[]) AS t(tag)\n CROSS JOIN (SELECT count(*) AS deleted FROM tag_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING tag)\n SELECT r.exam_kinds AS \"exam_kinds: Json<Vec<ExamKindDef>>\",\n COALESCE((SELECT array_agg(status ORDER BY status)\n FROM status_ins), '{}') AS \"attendance_statuses!: Vec<String>\",\n r.grade_bands AS \"grade_bands: Json<Vec<GradeBand>>\",\n r.max_file_bytes,\n r.chatbot_history_turns,\n r.max_chatbot_message_len,\n r.max_chatbot_threads,\n r.meal_slots AS \"meal_slots: Json<Vec<MealSlotDef>>\",\n (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags,\n r.meal_cancel_cutoff_minutes\n FROM new_row r",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "exam_kinds: Json<Vec<ExamKindDef>>",
9- "type_info": "Jsonb",
10- "origin": {
11- "Table": {
12- "table": "settings",
13- "name": "exam_kinds"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "attendance_statuses!: Vec<String>",
20- "type_info": "TextArray",
21- "origin": "Expression"
22- },
23- {
24- "ordinal": 2,
25- "name": "grade_bands: Json<Vec<GradeBand>>",
26- "type_info": "Jsonb",
27- "origin": {
28- "Table": {
29- "table": "settings",
30- "name": "grade_bands"
31- }
32- }
33- },
34- {
35- "ordinal": 3,
36- "name": "max_file_bytes",
37- "type_info": "Int8",
38- "origin": {
39- "Table": {
40- "table": "settings",
41- "name": "max_file_bytes"
42- }
43- }
44- },
45- {
46- "ordinal": 4,
47- "name": "chatbot_history_turns",
48- "type_info": "Int8",
49- "origin": {
50- "Table": {
51- "table": "settings",
52- "name": "chatbot_history_turns"
53- }
54- }
55- },
56- {
57- "ordinal": 5,
58- "name": "max_chatbot_message_len",
59- "type_info": "Int8",
60- "origin": {
61- "Table": {
62- "table": "settings",
63- "name": "max_chatbot_message_len"
64- }
65- }
66- },
67- {
68- "ordinal": 6,
69- "name": "max_chatbot_threads",
70- "type_info": "Int8",
71- "origin": {
72- "Table": {
73- "table": "settings",
74- "name": "max_chatbot_threads"
75- }
76- }
77- },
78- {
79- "ordinal": 7,
80- "name": "meal_slots: Json<Vec<MealSlotDef>>",
81- "type_info": "Jsonb",
82- "origin": {
83- "Table": {
84- "table": "settings",
85- "name": "meal_slots"
86- }
87- }
88- },
89- {
90- "ordinal": 8,
91- "name": "dietary_tags",
92- "type_info": "TextArray",
93- "origin": "Expression"
94- },
95- {
96- "ordinal": 9,
97- "name": "meal_cancel_cutoff_minutes",
98- "type_info": "Int8",
99- "origin": {
100- "Table": {
101- "table": "settings",
102- "name": "meal_cancel_cutoff_minutes"
103- }
104- }
105- }
106- ],
107- "parameters": {
108- "Left": [
109- "Jsonb",
110- "TextArray",
111- "Jsonb",
112- "Int8",
113- "Int8",
114- "Int8",
115- "Int8",
116- "Jsonb",
117- "TextArray",
118- "Int8",
119- "TextArray",
120- "TextArray",
121- "Jsonb",
122- "Jsonb",
123- "Int8",
124- "Int8",
125- "Int8",
126- "Int8",
127- "Jsonb",
128- "Int8"
129- ]
130- },
131- "nullable": [
132- false,
133- null,
134- false,
135- true,
136- true,
137- true,
138- true,
139- true,
140- null,
141- true
142- ]
143- },
144- "hash": "83d5da7f52ee983e49f3c4dcd99472f5a8ba4a9017363f04c35173284da42037"
145-}
.sqlx/query-a92d51459fd6a61999d70d959abd8bf67e730615135df1850ccf57de3090a402.json → .sqlx/query-852e8ede2b2713be5244b108c8e74d5fe800c12fa4e1f6c30f68b80f07509ef9.jsonrenamed+5 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n course AS \"course: CourseId\", status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"\n FROM session_attendance WHERE app_user = $1\n ORDER BY session DESC, app_user DESC",
3+ "query": "SELECT session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"\n FROM session_attendance\n WHERE session = $1 AND app_user = $2\n FOR UPDATE",
44 "describe": {
55 "columns": [
66 {
@@ -27,12 +27,12 @@
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "course: CourseId",
30+ "name": "class_course: ClassCourseId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
3434 "table": "session_attendance",
35- "name": "course"
35+ "name": "class_course"
3636 }
3737 }
3838 },
@@ -61,6 +61,7 @@
6161 ],
6262 "parameters": {
6363 "Left": [
64+ "Uuid",
6465 "Uuid"
6566 ]
6667 },
@@ -72,5 +73,5 @@
7273 false
7374 ]
7475 },
75- "hash": "a92d51459fd6a61999d70d959abd8bf67e730615135df1850ccf57de3090a402"
76+ "hash": "852e8ede2b2713be5244b108c8e74d5fe800c12fa4e1f6c30f68b80f07509ef9"
7677 }
.sqlx/query-e7049ca4ddf6a6103dbecabe61f56992e9e2105e5c2de3b148d5533e4ffc8989.json → .sqlx/query-85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size\n FROM app_user WHERE id = $1 FOR UPDATE",
3+ "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE id = $1 FOR UPDATE",
44 "describe": {
55 "columns": [
66 {
@@ -181,6 +181,17 @@
181181 },
182182 {
183183 "ordinal": 16,
184+ "name": "branch",
185+ "type_info": "Text",
186+ "origin": {
187+ "Table": {
188+ "table": "app_user",
189+ "name": "branch"
190+ }
191+ }
192+ },
193+ {
194+ "ordinal": 17,
184195 "name": "avatar_size",
185196 "type_info": "Int8",
186197 "origin": {
@@ -213,8 +224,9 @@
213224 true,
214225 true,
215226 true,
227+ true,
216228 true
217229 ]
218230 },
219- "hash": "e7049ca4ddf6a6103dbecabe61f56992e9e2105e5c2de3b148d5533e4ffc8989"
231+ "hash": "85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f"
220232 }
.sqlx/query-716d9e1ecf8ea90abaf127ffb5b1b437be5acb0b4b8e49f53de51a1d31566c07.json → .sqlx/query-87d155cfa8873b0ef20d5c940bb40effbc3eff4648cc6383428794385d6e5381.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT file FROM homework_file\n WHERE submission IN (\n SELECT id FROM homework_submission\n WHERE homework IN (SELECT id FROM homework WHERE course = $1)\n )",
3+ "query": "SELECT file FROM homework_file\n WHERE submission IN (SELECT id FROM homework_submission WHERE homework IN (\n SELECT id FROM homework WHERE class_course = $1))",
44 "describe": {
55 "columns": [
66 {
@@ -24,5 +24,5 @@
2424 false
2525 ]
2626 },
27- "hash": "716d9e1ecf8ea90abaf127ffb5b1b437be5acb0b4b8e49f53de51a1d31566c07"
27+ "hash": "87d155cfa8873b0ef20d5c940bb40effbc3eff4648cc6383428794385d6e5381"
2828 }
.sqlx/query-2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632.json → .sqlx/query-881c48b6dbe3f2a277a120b9b50c21b51853743ede360b1cd589b2540ddc5663.jsonrenamed+9 -9
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = ANY($1)",
3+ "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", class_course_count, course_membership_count\n FROM course WHERE id = ANY($1)",
44 "describe": {
55 "columns": [
66 {
@@ -60,23 +60,23 @@
6060 },
6161 {
6262 "ordinal": 5,
63- "name": "term: TermId",
64- "type_info": "Uuid",
63+ "name": "class_course_count",
64+ "type_info": "Int8",
6565 "origin": {
6666 "Table": {
6767 "table": "course",
68- "name": "term"
68+ "name": "class_course_count"
6969 }
7070 }
7171 },
7272 {
7373 "ordinal": 6,
74- "name": "capacity",
74+ "name": "course_membership_count",
7575 "type_info": "Int8",
7676 "origin": {
7777 "Table": {
7878 "table": "course",
79- "name": "capacity"
79+ "name": "course_membership_count"
8080 }
8181 }
8282 }
@@ -92,9 +92,9 @@
9292 false,
9393 false,
9494 false,
95- true,
96- true
95+ false,
96+ false
9797 ]
9898 },
99- "hash": "2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632"
99+ "hash": "881c48b6dbe3f2a277a120b9b50c21b51853743ede360b1cd589b2540ddc5663"
100100 }
.sqlx/query-8aae97d23b8c2da4be5def3d350c2fe1fb78b8157c1db427bee32014dfa3dc84.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "WITH gone AS (\n DELETE FROM class_member WHERE app_user = $1 RETURNING class\n )\n UPDATE class_group\n SET class_member_count = GREATEST(class_member_count - 1, 0)\n WHERE id IN (SELECT gone.class FROM gone)",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "8aae97d23b8c2da4be5def3d350c2fe1fb78b8157c1db427bee32014dfa3dc84"
14-}
.sqlx/query-8c2168cfc71adc23d664dc5cf830c9e25d5af1371fd17c109826757b76a558a2.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH gone AS (\n DELETE FROM course_membership WHERE app_user = $1 RETURNING course\n )\n UPDATE course\n SET course_membership_count = GREATEST(course_membership_count - 1, 0)\n WHERE id IN (SELECT gone.course FROM gone)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "8c2168cfc71adc23d664dc5cf830c9e25d5af1371fd17c109826757b76a558a2"
14+}
.sqlx/query-8d42c2a8b87d9f503f123515bc00554d4a9dc13dfa7f3acc707d464a83899777.jsonadded+24 -0
@@ -0,0 +1,24 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM class_member\n WHERE class = $1 AND app_user = $2 AND left_at IS NULL\n RETURNING 1 AS \"one\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "one",
9+ "type_info": "Int4",
10+ "origin": "Expression"
11+ }
12+ ],
13+ "parameters": {
14+ "Left": [
15+ "Uuid",
16+ "Uuid"
17+ ]
18+ },
19+ "nullable": [
20+ null
21+ ]
22+ },
23+ "hash": "8d42c2a8b87d9f503f123515bc00554d4a9dc13dfa7f3acc707d464a83899777"
24+}
.sqlx/query-8d76160e8b143ddee72c34878fbe9bf3140bea9c12f8c3ba324fc16c81167905.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH gone AS (\n DELETE FROM exam WHERE class_course = $1\n RETURNING term),\n terms AS (\n SELECT term, count(*) AS n FROM gone GROUP BY term)\n UPDATE term t SET exam_count = GREATEST(t.exam_count - c.n, 0)\n FROM terms c WHERE t.id = c.term",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "8d76160e8b143ddee72c34878fbe9bf3140bea9c12f8c3ba324fc16c81167905"
14+}
.sqlx/query-58e602261d1ddb31b9b0d25cb87f46934b0c584727551c8f85d4744b543af99f.json → .sqlx/query-8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size\n FROM app_user WHERE id = $1",
3+ "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE id = $1",
44 "describe": {
55 "columns": [
66 {
@@ -181,6 +181,17 @@
181181 },
182182 {
183183 "ordinal": 16,
184+ "name": "branch",
185+ "type_info": "Text",
186+ "origin": {
187+ "Table": {
188+ "table": "app_user",
189+ "name": "branch"
190+ }
191+ }
192+ },
193+ {
194+ "ordinal": 17,
184195 "name": "avatar_size",
185196 "type_info": "Int8",
186197 "origin": {
@@ -213,8 +224,9 @@
213224 true,
214225 true,
215226 true,
227+ true,
216228 true
217229 ]
218230 },
219- "hash": "58e602261d1ddb31b9b0d25cb87f46934b0c584727551c8f85d4744b543af99f"
231+ "hash": "8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537"
220232 }
.sqlx/query-1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019.json → .sqlx/query-8fcc7fe1692f122310769d3575feabbf9648a92d9c0ad9ecb62a69779c21ef43.jsonrenamed+9 -9
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course ORDER BY id DESC",
3+ "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", class_course_count, course_membership_count\n FROM course ORDER BY id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -60,23 +60,23 @@
6060 },
6161 {
6262 "ordinal": 5,
63- "name": "term: TermId",
64- "type_info": "Uuid",
63+ "name": "class_course_count",
64+ "type_info": "Int8",
6565 "origin": {
6666 "Table": {
6767 "table": "course",
68- "name": "term"
68+ "name": "class_course_count"
6969 }
7070 }
7171 },
7272 {
7373 "ordinal": 6,
74- "name": "capacity",
74+ "name": "course_membership_count",
7575 "type_info": "Int8",
7676 "origin": {
7777 "Table": {
7878 "table": "course",
79- "name": "capacity"
79+ "name": "course_membership_count"
8080 }
8181 }
8282 }
@@ -90,9 +90,9 @@
9090 false,
9191 false,
9292 false,
93- true,
94- true
93+ false,
94+ false
9595 ]
9696 },
97- "hash": "1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019"
97+ "hash": "8fcc7fe1692f122310769d3575feabbf9648a92d9c0ad9ecb62a69779c21ef43"
9898 }
.sqlx/query-92ea6ff42015debf72f3b8c0ddd7231567b66c5dbd0dfd2963a28b4c165f06ab.jsondeleted+0 -28
@@ -1,28 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "DELETE FROM class_group\n WHERE id = $1\n AND class_member_count = 0 AND class_course_count = 0\n RETURNING term AS \"term: uuid::Uuid\"",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "term: uuid::Uuid",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "class_group",
13- "name": "term"
14- }
15- }
16- }
17- ],
18- "parameters": {
19- "Left": [
20- "Uuid"
21- ]
22- },
23- "nullable": [
24- true
25- ]
26- },
27- "hash": "92ea6ff42015debf72f3b8c0ddd7231567b66c5dbd0dfd2963a28b4c165f06ab"
28-}
.sqlx/query-9940a3506ed6882085ce27f65989e951ea068ae7b732f465dc51153f7bc6179f.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE course SET enrollment_count = GREATEST(enrollment_count - 1, 0)\n WHERE id = $1",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "9940a3506ed6882085ce27f65989e951ea068ae7b732f465dc51153f7bc6179f"
14-}
.sqlx/query-9deffffa653f4fd1ca19b27972a9fcdbc399d9548adbff68bfd32af4a1adc4dd.jsonadded+215 -0
@@ -0,0 +1,215 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH new_row AS (\n INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes, branches, excuse_kinds,\n max_excused_absent_days, max_unexcused_absent_days,\n timezone)\n VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10, $21, $22, $23, $24, $25)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = $1,\n grade_bands = $3,\n max_file_bytes = $4,\n chatbot_history_turns = $5,\n max_chatbot_message_len = $6,\n max_chatbot_threads = $7,\n meal_slots = $8,\n meal_cancel_cutoff_minutes = $10,\n branches = $21,\n excuse_kinds = $22,\n max_excused_absent_days = $23,\n max_unexcused_absent_days = $24,\n timezone = $25\n WHERE settings.exam_kinds IS NOT DISTINCT FROM $13\n AND settings.grade_bands IS NOT DISTINCT FROM $14\n AND settings.max_file_bytes IS NOT DISTINCT FROM $15\n AND settings.chatbot_history_turns IS NOT DISTINCT FROM $16\n AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $17\n AND settings.max_chatbot_threads IS NOT DISTINCT FROM $18\n AND settings.meal_slots IS NOT DISTINCT FROM $19\n AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20\n AND settings.branches IS NOT DISTINCT FROM $26\n AND settings.excuse_kinds IS NOT DISTINCT FROM $27\n AND settings.max_excused_absent_days IS NOT DISTINCT FROM $28\n AND settings.max_unexcused_absent_days IS NOT DISTINCT FROM $29\n AND settings.timezone IS NOT DISTINCT FROM $30\n AND COALESCE((SELECT array_agg(s.status ORDER BY s.status)\n FROM settings_attendance_status s\n WHERE s.settings = settings.id), '{}')\n IS NOT DISTINCT FROM $11::text[]\n AND (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = settings.id)\n IS NOT DISTINCT FROM $12::text[]\n RETURNING exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes,\n branches, excuse_kinds, max_excused_absent_days,\n max_unexcused_absent_days, timezone),\n status_del AS (\n DELETE FROM settings_attendance_status\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n status_ins AS (\n INSERT INTO settings_attendance_status (settings, status)\n SELECT 'school', t.status FROM unnest($2::text[]) AS t(status)\n CROSS JOIN (SELECT count(*) AS deleted FROM status_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING status),\n tag_del AS (\n DELETE FROM settings_dietary_tag\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n tag_ins AS (\n INSERT INTO settings_dietary_tag (settings, tag)\n SELECT 'school', t.tag FROM unnest($9::text[]) AS t(tag)\n CROSS JOIN (SELECT count(*) AS deleted FROM tag_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING tag)\n SELECT r.exam_kinds AS \"exam_kinds: Json<Vec<ExamKindDef>>\",\n COALESCE((SELECT array_agg(status ORDER BY status)\n FROM status_ins), '{}') AS \"attendance_statuses!: Vec<String>\",\n r.grade_bands AS \"grade_bands: Json<Vec<GradeBand>>\",\n r.max_file_bytes,\n r.chatbot_history_turns,\n r.max_chatbot_message_len,\n r.max_chatbot_threads,\n r.meal_slots AS \"meal_slots: Json<Vec<MealSlotDef>>\",\n (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags,\n r.meal_cancel_cutoff_minutes,\n r.branches AS \"branches: Json<Vec<String>>\",\n r.excuse_kinds AS \"excuse_kinds: Json<Vec<String>>\",\n r.max_excused_absent_days,\n r.max_unexcused_absent_days,\n r.timezone\n FROM new_row r",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "exam_kinds: Json<Vec<ExamKindDef>>",
9+ "type_info": "Jsonb",
10+ "origin": {
11+ "Table": {
12+ "table": "settings",
13+ "name": "exam_kinds"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "attendance_statuses!: Vec<String>",
20+ "type_info": "TextArray",
21+ "origin": "Expression"
22+ },
23+ {
24+ "ordinal": 2,
25+ "name": "grade_bands: Json<Vec<GradeBand>>",
26+ "type_info": "Jsonb",
27+ "origin": {
28+ "Table": {
29+ "table": "settings",
30+ "name": "grade_bands"
31+ }
32+ }
33+ },
34+ {
35+ "ordinal": 3,
36+ "name": "max_file_bytes",
37+ "type_info": "Int8",
38+ "origin": {
39+ "Table": {
40+ "table": "settings",
41+ "name": "max_file_bytes"
42+ }
43+ }
44+ },
45+ {
46+ "ordinal": 4,
47+ "name": "chatbot_history_turns",
48+ "type_info": "Int8",
49+ "origin": {
50+ "Table": {
51+ "table": "settings",
52+ "name": "chatbot_history_turns"
53+ }
54+ }
55+ },
56+ {
57+ "ordinal": 5,
58+ "name": "max_chatbot_message_len",
59+ "type_info": "Int8",
60+ "origin": {
61+ "Table": {
62+ "table": "settings",
63+ "name": "max_chatbot_message_len"
64+ }
65+ }
66+ },
67+ {
68+ "ordinal": 6,
69+ "name": "max_chatbot_threads",
70+ "type_info": "Int8",
71+ "origin": {
72+ "Table": {
73+ "table": "settings",
74+ "name": "max_chatbot_threads"
75+ }
76+ }
77+ },
78+ {
79+ "ordinal": 7,
80+ "name": "meal_slots: Json<Vec<MealSlotDef>>",
81+ "type_info": "Jsonb",
82+ "origin": {
83+ "Table": {
84+ "table": "settings",
85+ "name": "meal_slots"
86+ }
87+ }
88+ },
89+ {
90+ "ordinal": 8,
91+ "name": "dietary_tags",
92+ "type_info": "TextArray",
93+ "origin": "Expression"
94+ },
95+ {
96+ "ordinal": 9,
97+ "name": "meal_cancel_cutoff_minutes",
98+ "type_info": "Int8",
99+ "origin": {
100+ "Table": {
101+ "table": "settings",
102+ "name": "meal_cancel_cutoff_minutes"
103+ }
104+ }
105+ },
106+ {
107+ "ordinal": 10,
108+ "name": "branches: Json<Vec<String>>",
109+ "type_info": "Jsonb",
110+ "origin": {
111+ "Table": {
112+ "table": "settings",
113+ "name": "branches"
114+ }
115+ }
116+ },
117+ {
118+ "ordinal": 11,
119+ "name": "excuse_kinds: Json<Vec<String>>",
120+ "type_info": "Jsonb",
121+ "origin": {
122+ "Table": {
123+ "table": "settings",
124+ "name": "excuse_kinds"
125+ }
126+ }
127+ },
128+ {
129+ "ordinal": 12,
130+ "name": "max_excused_absent_days",
131+ "type_info": "Int8",
132+ "origin": {
133+ "Table": {
134+ "table": "settings",
135+ "name": "max_excused_absent_days"
136+ }
137+ }
138+ },
139+ {
140+ "ordinal": 13,
141+ "name": "max_unexcused_absent_days",
142+ "type_info": "Int8",
143+ "origin": {
144+ "Table": {
145+ "table": "settings",
146+ "name": "max_unexcused_absent_days"
147+ }
148+ }
149+ },
150+ {
151+ "ordinal": 14,
152+ "name": "timezone",
153+ "type_info": "Text",
154+ "origin": {
155+ "Table": {
156+ "table": "settings",
157+ "name": "timezone"
158+ }
159+ }
160+ }
161+ ],
162+ "parameters": {
163+ "Left": [
164+ "Jsonb",
165+ "TextArray",
166+ "Jsonb",
167+ "Int8",
168+ "Int8",
169+ "Int8",
170+ "Int8",
171+ "Jsonb",
172+ "TextArray",
173+ "Int8",
174+ "TextArray",
175+ "TextArray",
176+ "Jsonb",
177+ "Jsonb",
178+ "Int8",
179+ "Int8",
180+ "Int8",
181+ "Int8",
182+ "Jsonb",
183+ "Int8",
184+ "Jsonb",
185+ "Jsonb",
186+ "Int8",
187+ "Int8",
188+ "Text",
189+ "Jsonb",
190+ "Jsonb",
191+ "Int8",
192+ "Int8",
193+ "Text"
194+ ]
195+ },
196+ "nullable": [
197+ false,
198+ null,
199+ false,
200+ true,
201+ true,
202+ true,
203+ true,
204+ true,
205+ null,
206+ true,
207+ true,
208+ true,
209+ true,
210+ true,
211+ true
212+ ]
213+ },
214+ "hash": "9deffffa653f4fd1ca19b27972a9fcdbc399d9548adbff68bfd32af4a1adc4dd"
215+}
.sqlx/query-9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a.jsondeleted+0 -15
@@ -1,15 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "INSERT INTO course_teacher (course, teacher)\n SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM course WHERE id = $1)\n ON CONFLICT DO NOTHING",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid",
9- "Uuid"
10- ]
11- },
12- "nullable": []
13- },
14- "hash": "9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a"
15-}
.sqlx/query-9e916d8594cc7fba78ed9661a00e146c2128431f24d78885cddf87325bae9cd5.jsonadded+29 -0
@@ -0,0 +1,29 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course\n WHERE class = $1 AND course = $2 FOR UPDATE",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: uuid::Uuid",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course",
13+ "name": "id"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid",
21+ "Uuid"
22+ ]
23+ },
24+ "nullable": [
25+ false
26+ ]
27+ },
28+ "hash": "9e916d8594cc7fba78ed9661a00e146c2128431f24d78885cddf87325bae9cd5"
29+}
.sqlx/query-fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e.json → .sqlx/query-a16a5a66d59d7658e931ed1a9796a46317fd0820fa5eefc6fb4a3316948d9026.jsonrenamed+62 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT s.exam_kinds AS \"exam_kinds: Json<Vec<ExamKindDef>>\",\n COALESCE((SELECT array_agg(t.status ORDER BY t.status)\n FROM settings_attendance_status t\n WHERE t.settings = s.id), '{}') AS \"attendance_statuses!: Vec<String>\",\n s.grade_bands AS \"grade_bands: Json<Vec<GradeBand>>\",\n s.max_file_bytes,\n s.chatbot_history_turns,\n s.max_chatbot_message_len,\n s.max_chatbot_threads,\n s.meal_slots AS \"meal_slots: Json<Vec<MealSlotDef>>\",\n (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = s.id) AS dietary_tags,\n s.meal_cancel_cutoff_minutes\n FROM settings s WHERE s.id = 'school'",
3+ "query": "SELECT s.exam_kinds AS \"exam_kinds: Json<Vec<ExamKindDef>>\",\n COALESCE((SELECT array_agg(t.status ORDER BY t.status)\n FROM settings_attendance_status t\n WHERE t.settings = s.id), '{}') AS \"attendance_statuses!: Vec<String>\",\n s.grade_bands AS \"grade_bands: Json<Vec<GradeBand>>\",\n s.max_file_bytes,\n s.chatbot_history_turns,\n s.max_chatbot_message_len,\n s.max_chatbot_threads,\n s.meal_slots AS \"meal_slots: Json<Vec<MealSlotDef>>\",\n (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = s.id) AS dietary_tags,\n s.meal_cancel_cutoff_minutes,\n s.branches AS \"branches: Json<Vec<String>>\",\n s.excuse_kinds AS \"excuse_kinds: Json<Vec<String>>\",\n s.max_excused_absent_days,\n s.max_unexcused_absent_days,\n s.timezone\n FROM settings s WHERE s.id = 'school'",
44 "describe": {
55 "columns": [
66 {
@@ -102,6 +102,61 @@
102102 "name": "meal_cancel_cutoff_minutes"
103103 }
104104 }
105+ },
106+ {
107+ "ordinal": 10,
108+ "name": "branches: Json<Vec<String>>",
109+ "type_info": "Jsonb",
110+ "origin": {
111+ "Table": {
112+ "table": "settings",
113+ "name": "branches"
114+ }
115+ }
116+ },
117+ {
118+ "ordinal": 11,
119+ "name": "excuse_kinds: Json<Vec<String>>",
120+ "type_info": "Jsonb",
121+ "origin": {
122+ "Table": {
123+ "table": "settings",
124+ "name": "excuse_kinds"
125+ }
126+ }
127+ },
128+ {
129+ "ordinal": 12,
130+ "name": "max_excused_absent_days",
131+ "type_info": "Int8",
132+ "origin": {
133+ "Table": {
134+ "table": "settings",
135+ "name": "max_excused_absent_days"
136+ }
137+ }
138+ },
139+ {
140+ "ordinal": 13,
141+ "name": "max_unexcused_absent_days",
142+ "type_info": "Int8",
143+ "origin": {
144+ "Table": {
145+ "table": "settings",
146+ "name": "max_unexcused_absent_days"
147+ }
148+ }
149+ },
150+ {
151+ "ordinal": 14,
152+ "name": "timezone",
153+ "type_info": "Text",
154+ "origin": {
155+ "Table": {
156+ "table": "settings",
157+ "name": "timezone"
158+ }
159+ }
105160 }
106161 ],
107162 "parameters": {
@@ -117,8 +172,13 @@
117172 true,
118173 true,
119174 null,
175+ true,
176+ true,
177+ true,
178+ true,
179+ true,
120180 true
121181 ]
122182 },
123- "hash": "fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e"
183+ "hash": "a16a5a66d59d7658e931ed1a9796a46317fd0820fa5eefc6fb4a3316948d9026"
124184 }
.sqlx/query-a4497c443cfa5d3f204d6e6828901739f328bad5f1c4ecb4e7a7973b7f0a5791.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "DELETE FROM exam_result WHERE exam = ANY($1)",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "UuidArray"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "a4497c443cfa5d3f204d6e6828901739f328bad5f1c4ecb4e7a7973b7f0a5791"
14-}
.sqlx/query-a4a9fe4a625d4ad55e5daf16c7d99791cd0002767262bef6b2520661c9da64b4.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH gone AS (\n DELETE FROM exam_question WHERE exam = ANY($1)\n RETURNING subject),\n subs AS (\n SELECT subject, count(*) AS n FROM gone GROUP BY subject)\n UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0)\n FROM subs c WHERE s.id = c.subject",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "UuidArray"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "a4a9fe4a625d4ad55e5daf16c7d99791cd0002767262bef6b2520661c9da64b4"
14+}
.sqlx/query-19a3c810ccfbf79cfc58404e2146eb5907c4f09ceb46b5c79e7c26cb1eb5988d.json → .sqlx/query-a7ca96bf0f9172c9c7ff2fc94a42dc7ee59d20419cf4cf3ebd90fcefeba21db0.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM homework_submission WHERE homework IN (\n SELECT id FROM homework WHERE course = $1)",
3+ "query": "DELETE FROM homework_submission WHERE homework IN (\n SELECT id FROM homework WHERE class_course = $1)",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -10,5 +10,5 @@
1010 },
1111 "nullable": []
1212 },
13- "hash": "19a3c810ccfbf79cfc58404e2146eb5907c4f09ceb46b5c79e7c26cb1eb5988d"
13+ "hash": "a7ca96bf0f9172c9c7ff2fc94a42dc7ee59d20419cf4cf3ebd90fcefeba21db0"
1414 }
.sqlx/query-5275fe61292bfb7d4e5ee166495d2fb149a7557d1aef52d35b8c91e4b9543cf5.json → .sqlx/query-a8a57bfd25073fc000010b532e400519cedea0c852d914156a90e774f3a23398.jsonrenamed+27 -28
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "INSERT INTO exam (id, creator, course, title, description, kind, mode,\n starts_at, ends_at, duration_ms, max_attempts,\n allow_rejoin, allow_review, draft)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n course AS \"course: CourseId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft",
3+ "query": "SELECT DISTINCT ON (e.id)\n e.id AS \"id: ExamId\", e.creator AS \"creator: UserId\",\n e.class_course AS \"class_course: ClassCourseId\",\n e.term AS \"term: TermId\", e.title AS \"title: ExamTitle\",\n e.description AS \"description: ExamDescription\",\n e.kind AS \"kind: ExamKind\", e.mode AS \"mode: ExamMode\",\n e.starts_at AS \"starts_at: Timestamp\",\n e.ends_at AS \"ends_at: Timestamp\",\n e.duration_ms AS \"duration_ms: ExamDuration\",\n e.max_attempts AS \"max_attempts: ExamAttemptLimit\",\n e.allow_rejoin, e.allow_review, e.draft\n FROM exam e\n JOIN exam_audience a ON a.exam = e.id\n JOIN class_course cc ON cc.id = a.class_course\n WHERE cc.course = ANY($1)\n ORDER BY e.id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -27,17 +27,28 @@
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "course: CourseId",
30+ "name": "class_course: ClassCourseId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
3434 "table": "exam",
35- "name": "course"
35+ "name": "class_course"
3636 }
3737 }
3838 },
3939 {
4040 "ordinal": 3,
41+ "name": "term: TermId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "exam",
46+ "name": "term"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
4152 "name": "title: ExamTitle",
4253 "type_info": "Text",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "description: ExamDescription",
5364 "type_info": "Text",
5465 "origin": {
@@ -59,7 +70,7 @@
5970 }
6071 },
6172 {
62- "ordinal": 5,
73+ "ordinal": 6,
6374 "name": "kind: ExamKind",
6475 "type_info": "Text",
6576 "origin": {
@@ -70,7 +81,7 @@
7081 }
7182 },
7283 {
73- "ordinal": 6,
84+ "ordinal": 7,
7485 "name": "mode: ExamMode",
7586 "type_info": "Text",
7687 "origin": {
@@ -81,7 +92,7 @@
8192 }
8293 },
8394 {
84- "ordinal": 7,
95+ "ordinal": 8,
8596 "name": "starts_at: Timestamp",
8697 "type_info": "Int8",
8798 "origin": {
@@ -92,7 +103,7 @@
92103 }
93104 },
94105 {
95- "ordinal": 8,
106+ "ordinal": 9,
96107 "name": "ends_at: Timestamp",
97108 "type_info": "Int8",
98109 "origin": {
@@ -103,7 +114,7 @@
103114 }
104115 },
105116 {
106- "ordinal": 9,
117+ "ordinal": 10,
107118 "name": "duration_ms: ExamDuration",
108119 "type_info": "Int8",
109120 "origin": {
@@ -114,7 +125,7 @@
114125 }
115126 },
116127 {
117- "ordinal": 10,
128+ "ordinal": 11,
118129 "name": "max_attempts: ExamAttemptLimit",
119130 "type_info": "Int8",
120131 "origin": {
@@ -125,7 +136,7 @@
125136 }
126137 },
127138 {
128- "ordinal": 11,
139+ "ordinal": 12,
129140 "name": "allow_rejoin",
130141 "type_info": "Bool",
131142 "origin": {
@@ -136,7 +147,7 @@
136147 }
137148 },
138149 {
139- "ordinal": 12,
150+ "ordinal": 13,
140151 "name": "allow_review",
141152 "type_info": "Bool",
142153 "origin": {
@@ -147,7 +158,7 @@
147158 }
148159 },
149160 {
150- "ordinal": 13,
161+ "ordinal": 14,
151162 "name": "draft",
152163 "type_info": "Bool",
153164 "origin": {
@@ -160,20 +171,7 @@
160171 ],
161172 "parameters": {
162173 "Left": [
163- "Uuid",
164- "Uuid",
165- "Uuid",
166- "Text",
167- "Text",
168- "Text",
169- "Text",
170- "Int8",
171- "Int8",
172- "Int8",
173- "Int8",
174- "Bool",
175- "Bool",
176- "Bool"
174+ "UuidArray"
177175 ]
178176 },
179177 "nullable": [
@@ -183,6 +181,7 @@
183181 false,
184182 false,
185183 false,
184+ false,
186185 true,
187186 true,
188187 true,
@@ -193,5 +192,5 @@
193192 false
194193 ]
195194 },
196- "hash": "5275fe61292bfb7d4e5ee166495d2fb149a7557d1aef52d35b8c91e4b9543cf5"
195+ "hash": "a8a57bfd25073fc000010b532e400519cedea0c852d914156a90e774f3a23398"
197196 }
.sqlx/query-a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3.jsonadded+119 -0
@@ -0,0 +1,119 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.id = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: ClassCourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course",
13+ "name": "id"
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+ "ordinal": 3,
41+ "name": "attached_by: UserId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "class_course",
46+ "name": "attached_by"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "source?: ClassBlueprintId",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "class_blueprint",
57+ "name": "grade"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "ders_saati!: DersSaati",
64+ "type_info": "Int8",
65+ "origin": "Expression"
66+ },
67+ {
68+ "ordinal": 6,
69+ "name": "counts_toward_karne",
70+ "type_info": "Bool",
71+ "origin": {
72+ "Table": {
73+ "table": "class_course",
74+ "name": "counts_toward_karne"
75+ }
76+ }
77+ },
78+ {
79+ "ordinal": 7,
80+ "name": "enrollment_count",
81+ "type_info": "Int8",
82+ "origin": {
83+ "Table": {
84+ "table": "class_course",
85+ "name": "enrollment_count"
86+ }
87+ }
88+ },
89+ {
90+ "ordinal": 8,
91+ "name": "attached_at: Timestamp",
92+ "type_info": "Int8",
93+ "origin": {
94+ "Table": {
95+ "table": "class_course",
96+ "name": "attached_at"
97+ }
98+ }
99+ }
100+ ],
101+ "parameters": {
102+ "Left": [
103+ "Uuid"
104+ ]
105+ },
106+ "nullable": [
107+ false,
108+ false,
109+ false,
110+ false,
111+ true,
112+ null,
113+ false,
114+ false,
115+ false
116+ ]
117+ },
118+ "hash": "a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3"
119+}
.sqlx/query-afbe9f23e7231c752aaf28226d82dade41124a5729a341956dd8360a408b7f2e.jsonadded+23 -0
@@ -0,0 +1,23 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT DISTINCT app_user AS \"user!: UserId\" FROM (\n SELECT e.app_user FROM enrollment e\n JOIN class_course cc ON cc.id = e.class_course\n WHERE cc.course = $1\n UNION ALL\n SELECT m.app_user FROM course_membership m WHERE m.course = $1\n ) people ORDER BY app_user",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "user!: UserId",
9+ "type_info": "Uuid",
10+ "origin": "Expression"
11+ }
12+ ],
13+ "parameters": {
14+ "Left": [
15+ "Uuid"
16+ ]
17+ },
18+ "nullable": [
19+ null
20+ ]
21+ },
22+ "hash": "afbe9f23e7231c752aaf28226d82dade41124a5729a341956dd8360a408b7f2e"
23+}
.sqlx/query-b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f.jsonadded+88 -0
@@ -0,0 +1,88 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE year = $1 ORDER BY id",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: ClassGroupId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_group",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "creator: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "class_group",
24+ "name": "creator"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "name: ClassName",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "class_group",
35+ "name": "name"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "grade: ClassGrade",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "class_group",
46+ "name": "grade"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "year: AcademicYearId",
53+ "type_info": "Uuid",
54+ "origin": {
55+ "Table": {
56+ "table": "class_group",
57+ "name": "year"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "teacher: UserId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "class_group",
68+ "name": "teacher"
69+ }
70+ }
71+ }
72+ ],
73+ "parameters": {
74+ "Left": [
75+ "Uuid"
76+ ]
77+ },
78+ "nullable": [
79+ false,
80+ false,
81+ false,
82+ true,
83+ true,
84+ true
85+ ]
86+ },
87+ "hash": "b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f"
88+}
.sqlx/query-09a4d21a85fc3b3fe59438874316ee35b4f80e3be898fa0f0f4dec4dde44bd4e.json → .sqlx/query-b1485b93a061e8735c6ec5eb2cbeb83e1f73ba2220d7e85e79904c26062dbffd.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT 1 AS \"one\" FROM class_member WHERE class = $1 AND app_user = $2",
3+ "query": "SELECT 1 AS \"one\" FROM enrollment WHERE class_course = $1 AND app_user = $2",
44 "describe": {
55 "columns": [
66 {
@@ -20,5 +20,5 @@
2020 null
2121 ]
2222 },
23- "hash": "09a4d21a85fc3b3fe59438874316ee35b4f80e3be898fa0f0f4dec4dde44bd4e"
23+ "hash": "b1485b93a061e8735c6ec5eb2cbeb83e1f73ba2220d7e85e79904c26062dbffd"
2424 }
.sqlx/query-b16588dd57a34e3647a1d5b87b2a477635f271ca98359faadfd9bb6b17c18bc9.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT class AS \"class: ClassGroupId\" FROM class_course WHERE id = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "class: ClassGroupId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course",
13+ "name": "class"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "b16588dd57a34e3647a1d5b87b2a477635f271ca98359faadfd9bb6b17c18bc9"
28+}
.sqlx/query-49ede4ebf9c7ab70d842755888e65aaf496d03b01d135459ccd9b99a3f51d49c.json → .sqlx/query-b1c1bb3f134a510cb5ccba24ce030ca195f78e51790efd07dc5b026938b41a63.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM exam WHERE course = $1",
3+ "query": "DELETE FROM class_group WHERE id = $1",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -10,5 +10,5 @@
1010 },
1111 "nullable": []
1212 },
13- "hash": "49ede4ebf9c7ab70d842755888e65aaf496d03b01d135459ccd9b99a3f51d49c"
13+ "hash": "b1c1bb3f134a510cb5ccba24ce030ca195f78e51790efd07dc5b026938b41a63"
1414 }
.sqlx/query-b2a05e29db69841f2a0d727e5b0f820722a33a939b88e40956092dbc20af9947.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "WITH gone AS (\n DELETE FROM enrollment WHERE app_user = $1 RETURNING course\n )\n UPDATE course\n SET enrollment_count = GREATEST(enrollment_count - 1, 0)\n WHERE id IN (SELECT gone.course FROM gone)",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "b2a05e29db69841f2a0d727e5b0f820722a33a939b88e40956092dbc20af9947"
14-}
.sqlx/query-59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5.json → .sqlx/query-b2c320ebdee88e24b250ece9fbe186401f010aa4e3119e9a7cc7491b8af8a80c.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "WITH seat AS (\n UPDATE subject SET homework_count = homework_count + 1\n WHERE id = $1\n RETURNING 1\n )\n INSERT INTO homework (id, course, subject, title, description, due_at, created_by, created_at)\n SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n NULL::uuid[] AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",
3+ "query": "WITH seat AS (\n UPDATE subject SET homework_count = homework_count + 1\n WHERE id = $1\n RETURNING 1\n )\n INSERT INTO homework (id, class_course, subject, title, description, due_at, created_by, created_at)\n SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n NULL::uuid[] AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "homework",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -122,5 +122,5 @@
122122 false
123123 ]
124124 },
125- "hash": "59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5"
125+ "hash": "b2c320ebdee88e24b250ece9fbe186401f010aa4e3119e9a7cc7491b8af8a80c"
126126 }
.sqlx/query-b2c9927ef99caca43fd99d7d733a6aa2fa38683560363486a80505005b5ef03d.jsonadded+77 -0
@@ -0,0 +1,77 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH gone AS (\n DELETE FROM enrollment\n WHERE class_course = $1 AND app_user = $2\n RETURNING class_course, app_user, enrolled_by, source, created_at),\n seated AS (\n UPDATE class_course\n SET enrollment_count = GREATEST(\n enrollment_count - (SELECT count(*) FROM gone), 0)\n WHERE id = $1\n RETURNING 1)\n SELECT class_course AS \"class_course: ClassCourseId\",\n app_user AS \"user: UserId\", enrolled_by AS \"enrolled_by: UserId\",\n source AS \"source: ClassGroupId\", created_at AS \"created_at: Timestamp\"\n FROM gone",
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+ "Uuid"
66+ ]
67+ },
68+ "nullable": [
69+ false,
70+ false,
71+ false,
72+ true,
73+ false
74+ ]
75+ },
76+ "hash": "b2c9927ef99caca43fd99d7d733a6aa2fa38683560363486a80505005b5ef03d"
77+}
.sqlx/query-b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681.jsonadded+88 -0
@@ -0,0 +1,88 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE teacher = $1 ORDER BY id DESC",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: ClassGroupId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_group",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "creator: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "class_group",
24+ "name": "creator"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "name: ClassName",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "class_group",
35+ "name": "name"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "grade: ClassGrade",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "class_group",
46+ "name": "grade"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "year: AcademicYearId",
53+ "type_info": "Uuid",
54+ "origin": {
55+ "Table": {
56+ "table": "class_group",
57+ "name": "year"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "teacher: UserId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "class_group",
68+ "name": "teacher"
69+ }
70+ }
71+ }
72+ ],
73+ "parameters": {
74+ "Left": [
75+ "Uuid"
76+ ]
77+ },
78+ "nullable": [
79+ false,
80+ false,
81+ false,
82+ true,
83+ true,
84+ true
85+ ]
86+ },
87+ "hash": "b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681"
88+}
.sqlx/query-a693d7fe95bd9da9fcd8ef12db5ba1aa133b09ccdcc25c07f6dd51e319b9f3e2.json → .sqlx/query-b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "WITH seat AS (\n UPDATE term SET class_count = class_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO class_group (id, creator, name, grade, term, teacher)\n SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n term AS \"term: TermId\", teacher AS \"teacher: UserId\"",
3+ "query": "WITH seat AS (\n UPDATE academic_year SET class_count = class_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO class_group (id, creator, name, grade, year, teacher)\n SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"",
44 "describe": {
55 "columns": [
66 {
@@ -49,12 +49,12 @@
4949 },
5050 {
5151 "ordinal": 4,
52- "name": "term: TermId",
52+ "name": "year: AcademicYearId",
5353 "type_info": "Uuid",
5454 "origin": {
5555 "Table": {
5656 "table": "class_group",
57- "name": "term"
57+ "name": "year"
5858 }
5959 }
6060 },
@@ -89,5 +89,5 @@
8989 true
9090 ]
9191 },
92- "hash": "a693d7fe95bd9da9fcd8ef12db5ba1aa133b09ccdcc25c07f6dd51e319b9f3e2"
92+ "hash": "b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59"
9393 }
.sqlx/query-33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d.json → .sqlx/query-b4deb88802c1d87668aab3480b64e7f3228f3d2f6ac284761d7e5ca8bd0df499.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM homework WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",
3+ "query": "DELETE FROM homework WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "homework",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -115,5 +115,5 @@
115115 false
116116 ]
117117 },
118- "hash": "33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d"
118+ "hash": "b4deb88802c1d87668aab3480b64e7f3228f3d2f6ac284761d7e5ca8bd0df499"
119119 }
.sqlx/query-9d97ae40f2a231fef7a322d0f55dc794d109326032412ae2e6b6582cc3d2e893.json → .sqlx/query-b564bc324da8ba9a7ee453cc85a6c187f98da879650f240ddec4ad11854f16d3.jsonrenamed+5 -3
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "WITH seat AS (\n UPDATE class_group SET class_member_count = class_member_count + 1\n WHERE id = $1 AND class_member_count < $2\n RETURNING 1)\n INSERT INTO class_member (class, app_user, added_by, added_at)\n SELECT $1, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"",
3+ "query": "WITH seat AS (\n UPDATE class_group SET class_member_count = class_member_count + 1\n WHERE id = $1 AND class_member_count < $2\n RETURNING 1)\n INSERT INTO class_member (id, class, app_user, added_by, joined_at, left_at,\n source_class_group)\n SELECT $3, $1, $4, $5, $6, NULL, $7 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,14 @@
1616 "Int8",
1717 "Uuid",
1818 "Uuid",
19- "Int8"
19+ "Uuid",
20+ "Int8",
21+ "Uuid"
2022 ]
2123 },
2224 "nullable": [
2325 null
2426 ]
2527 },
26- "hash": "9d97ae40f2a231fef7a322d0f55dc794d109326032412ae2e6b6582cc3d2e893"
28+ "hash": "b564bc324da8ba9a7ee453cc85a6c187f98da879650f240ddec4ad11854f16d3"
2729 }
.sqlx/query-4c38288787f424c39261947ba1f1097285ea04432869fef7fc411496a9087cd4.json → .sqlx/query-b859cdc3e09e10907ba2cc39ab90a96086a5bdd374250cc6677057dbc925f81d.jsonrenamed+26 -14
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\", course AS \"course: CourseId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam ORDER BY id DESC",
3+ "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\",\n class_course AS \"class_course: ClassCourseId\", term AS \"term: TermId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam ORDER BY id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -27,17 +27,28 @@
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "course: CourseId",
30+ "name": "class_course: ClassCourseId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
3434 "table": "exam",
35- "name": "course"
35+ "name": "class_course"
3636 }
3737 }
3838 },
3939 {
4040 "ordinal": 3,
41+ "name": "term: TermId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "exam",
46+ "name": "term"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
4152 "name": "title: ExamTitle",
4253 "type_info": "Text",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "description: ExamDescription",
5364 "type_info": "Text",
5465 "origin": {
@@ -59,7 +70,7 @@
5970 }
6071 },
6172 {
62- "ordinal": 5,
73+ "ordinal": 6,
6374 "name": "kind: ExamKind",
6475 "type_info": "Text",
6576 "origin": {
@@ -70,7 +81,7 @@
7081 }
7182 },
7283 {
73- "ordinal": 6,
84+ "ordinal": 7,
7485 "name": "mode: ExamMode",
7586 "type_info": "Text",
7687 "origin": {
@@ -81,7 +92,7 @@
8192 }
8293 },
8394 {
84- "ordinal": 7,
95+ "ordinal": 8,
8596 "name": "starts_at: Timestamp",
8697 "type_info": "Int8",
8798 "origin": {
@@ -92,7 +103,7 @@
92103 }
93104 },
94105 {
95- "ordinal": 8,
106+ "ordinal": 9,
96107 "name": "ends_at: Timestamp",
97108 "type_info": "Int8",
98109 "origin": {
@@ -103,7 +114,7 @@
103114 }
104115 },
105116 {
106- "ordinal": 9,
117+ "ordinal": 10,
107118 "name": "duration_ms: ExamDuration",
108119 "type_info": "Int8",
109120 "origin": {
@@ -114,7 +125,7 @@
114125 }
115126 },
116127 {
117- "ordinal": 10,
128+ "ordinal": 11,
118129 "name": "max_attempts: ExamAttemptLimit",
119130 "type_info": "Int8",
120131 "origin": {
@@ -125,7 +136,7 @@
125136 }
126137 },
127138 {
128- "ordinal": 11,
139+ "ordinal": 12,
129140 "name": "allow_rejoin",
130141 "type_info": "Bool",
131142 "origin": {
@@ -136,7 +147,7 @@
136147 }
137148 },
138149 {
139- "ordinal": 12,
150+ "ordinal": 13,
140151 "name": "allow_review",
141152 "type_info": "Bool",
142153 "origin": {
@@ -147,7 +158,7 @@
147158 }
148159 },
149160 {
150- "ordinal": 13,
161+ "ordinal": 14,
151162 "name": "draft",
152163 "type_info": "Bool",
153164 "origin": {
@@ -168,6 +179,7 @@
168179 false,
169180 false,
170181 false,
182+ false,
171183 true,
172184 true,
173185 true,
@@ -178,5 +190,5 @@
178190 false
179191 ]
180192 },
181- "hash": "4c38288787f424c39261947ba1f1097285ea04432869fef7fc411496a9087cd4"
193+ "hash": "b859cdc3e09e10907ba2cc39ab90a96086a5bdd374250cc6677057dbc925f81d"
182194 }
.sqlx/query-e2000c1bf26bc866f2bd0de9c15895b38a05e22b13b6db494a69d92eebeece76.json → .sqlx/query-b9237fa66d33731d7480f924978202890d7a2b39aefb09b00be6db9767af0264.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: CourseSessionId\", course AS \"course: CourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"\n FROM course_session WHERE id = $1",
3+ "query": "SELECT id AS \"id: CourseSessionId\",\n class_course AS \"class_course: ClassCourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"\n FROM course_session WHERE id = $1",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "course_session",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -84,5 +84,5 @@
8484 true
8585 ]
8686 },
87- "hash": "e2000c1bf26bc866f2bd0de9c15895b38a05e22b13b6db494a69d92eebeece76"
87+ "hash": "b9237fa66d33731d7480f924978202890d7a2b39aefb09b00be6db9767af0264"
8888 }
.sqlx/query-b9bd402798dd82f0b13e78b03ac9ba1278fcd5fe3d956d9996e1c615b346b1b8.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH gone AS (\n DELETE FROM exam_result WHERE exam = ANY($1)\n RETURNING exam),\n kinds AS (\n SELECT e.kind AS kind, count(*) AS n\n FROM gone g JOIN exam e ON e.id = g.exam\n GROUP BY e.kind)\n UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0)\n FROM kinds c WHERE k.name = c.kind",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "UuidArray"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "b9bd402798dd82f0b13e78b03ac9ba1278fcd5fe3d956d9996e1c615b346b1b8"
14+}
.sqlx/query-7035991f21ff426c7c9e7c9912c376a564002eb6013154a75c756df495ccf697.json → .sqlx/query-b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n term AS \"term: TermId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = $1",
3+ "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = $1",
44 "describe": {
55 "columns": [
66 {
@@ -49,12 +49,12 @@
4949 },
5050 {
5151 "ordinal": 4,
52- "name": "term: TermId",
52+ "name": "year: AcademicYearId",
5353 "type_info": "Uuid",
5454 "origin": {
5555 "Table": {
5656 "table": "class_group",
57- "name": "term"
57+ "name": "year"
5858 }
5959 }
6060 },
@@ -84,5 +84,5 @@
8484 true
8585 ]
8686 },
87- "hash": "7035991f21ff426c7c9e7c9912c376a564002eb6013154a75c756df495ccf697"
87+ "hash": "b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5"
8888 }
.sqlx/query-bbdea4fc1c294d8aff18288094153f6dc55cec1672a5761cd31cb1ea48d94423.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE kind_ref k\n SET count = GREATEST(k.count - s.n, 0)\n FROM (SELECT e.kind, count(*) AS n FROM exam_result r\n JOIN exam e ON r.exam = e.id\n WHERE r.exam = ANY($1) GROUP BY e.kind) s\n WHERE k.name = s.kind",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "UuidArray"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "bbdea4fc1c294d8aff18288094153f6dc55cec1672a5761cd31cb1ea48d94423"
14-}
.sqlx/query-bcdb9a4b449617cf405b3abb592e68ad4a6eb5e1715a773eeb1ec939338c6e2e.jsonadded+77 -0
@@ -0,0 +1,77 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT r.exam AS \"exam: ExamId\", r.app_user AS \"user: UserId\", r.seq,\n r.mark AS \"mark: Mark\", r.graded_by AS \"graded_by: UserId\"\n FROM exam_result r JOIN exam e ON e.id = r.exam\n WHERE r.app_user = $1 AND e.class_course = $2\n ORDER BY r.exam DESC, r.seq DESC",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "exam: ExamId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "exam_result",
13+ "name": "exam"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "exam_result",
24+ "name": "app_user"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "seq",
31+ "type_info": "Int8",
32+ "origin": {
33+ "Table": {
34+ "table": "exam_result",
35+ "name": "seq"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "mark: Mark",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "exam_result",
46+ "name": "mark"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "graded_by: UserId",
53+ "type_info": "Uuid",
54+ "origin": {
55+ "Table": {
56+ "table": "exam_result",
57+ "name": "graded_by"
58+ }
59+ }
60+ }
61+ ],
62+ "parameters": {
63+ "Left": [
64+ "Uuid",
65+ "Uuid"
66+ ]
67+ },
68+ "nullable": [
69+ false,
70+ false,
71+ false,
72+ false,
73+ false
74+ ]
75+ },
76+ "hash": "bcdb9a4b449617cf405b3abb592e68ad4a6eb5e1715a773eeb1ec939338c6e2e"
77+}
.sqlx/query-aacd58dae08eb43636a52ea734310e4d9bbd691bc75a61c6db1e62fc8cad77c3.json → .sqlx/query-c43cea61dd61df88dea3e87cc981a3d9750608bafa4306222afa42cff3d45230.jsonrenamed+17 -5
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "UPDATE term SET archived_at = NULL\n WHERE id = $1 AND archived_at IS NOT NULL\n RETURNING id AS \"id: TermId\", name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"",
3+ "query": "UPDATE term SET archived_at = NULL\n WHERE id = $1 AND archived_at IS NOT NULL\n RETURNING id AS \"id: TermId\", year AS \"year: AcademicYearId\",\n name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"",
44 "describe": {
55 "columns": [
66 {
@@ -16,6 +16,17 @@
1616 },
1717 {
1818 "ordinal": 1,
19+ "name": "year: AcademicYearId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "term",
24+ "name": "year"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
1930 "name": "name: TermName",
2031 "type_info": "Text",
2132 "origin": {
@@ -26,7 +37,7 @@
2637 }
2738 },
2839 {
29- "ordinal": 2,
40+ "ordinal": 3,
3041 "name": "starts_at: Timestamp",
3142 "type_info": "Int8",
3243 "origin": {
@@ -37,7 +48,7 @@
3748 }
3849 },
3950 {
40- "ordinal": 3,
51+ "ordinal": 4,
4152 "name": "ends_at: Timestamp",
4253 "type_info": "Int8",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "archived_at: Timestamp",
5364 "type_info": "Int8",
5465 "origin": {
@@ -69,8 +80,9 @@
6980 false,
7081 false,
7182 false,
83+ false,
7284 true
7385 ]
7486 },
75- "hash": "aacd58dae08eb43636a52ea734310e4d9bbd691bc75a61c6db1e62fc8cad77c3"
87+ "hash": "c43cea61dd61df88dea3e87cc981a3d9750608bafa4306222afa42cff3d45230"
7688 }
.sqlx/query-c7061a9a18a1da2cc178b22322cd1efd71d69681d050511d8c05e913ae6c62ae.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "DELETE FROM course_session WHERE course = $1",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "c7061a9a18a1da2cc178b22322cd1efd71d69681d050511d8c05e913ae6c62ae"
14-}
.sqlx/query-f77abe223a46882261b27bf5ac8f2c814c76e00836c1fd8a77483074fb2cd5eb.json → .sqlx/query-c9e8539ffc001f4fea89e28319703294b33a9312693ff2f9e795227ee1bb50db.jsonrenamed+8 -8
@@ -1,27 +1,27 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE",
3+ "query": "SELECT class_course_count, course_membership_count FROM course\n WHERE id = $1 FOR UPDATE",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "enrollment_count",
8+ "name": "class_course_count",
99 "type_info": "Int8",
1010 "origin": {
1111 "Table": {
1212 "table": "course",
13- "name": "enrollment_count"
13+ "name": "class_course_count"
1414 }
1515 }
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "term",
20- "type_info": "Uuid",
19+ "name": "course_membership_count",
20+ "type_info": "Int8",
2121 "origin": {
2222 "Table": {
2323 "table": "course",
24- "name": "term"
24+ "name": "course_membership_count"
2525 }
2626 }
2727 }
@@ -33,8 +33,8 @@
3333 },
3434 "nullable": [
3535 false,
36- true
36+ false
3737 ]
3838 },
39- "hash": "f77abe223a46882261b27bf5ac8f2c814c76e00836c1fd8a77483074fb2cd5eb"
39+ "hash": "c9e8539ffc001f4fea89e28319703294b33a9312693ff2f9e795227ee1bb50db"
4040 }
.sqlx/query-27bb824aa228c524d6ccfcd5fd13ff34c5a5e218f1b013021866d52a0f5d8474.json → .sqlx/query-ca6514056875c3acd3cf79f227cfb3b09093a0bf5c7708c65504e3fc60c7f118.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM session_attendance WHERE course = $1",
3+ "query": "DELETE FROM exam_audience WHERE class_course = $1",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -10,5 +10,5 @@
1010 },
1111 "nullable": []
1212 },
13- "hash": "27bb824aa228c524d6ccfcd5fd13ff34c5a5e218f1b013021866d52a0f5d8474"
13+ "hash": "ca6514056875c3acd3cf79f227cfb3b09093a0bf5c7708c65504e3fc60c7f118"
1414 }
.sqlx/query-425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695.json → .sqlx/query-caad4a6fe3555a38b1ac2f7dc3a4df74def95a0356454a07f9281103b19fdacc.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM course_teacher WHERE teacher = $1",
3+ "query": "DELETE FROM enrollment WHERE class_course = $1",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -10,5 +10,5 @@
1010 },
1111 "nullable": []
1212 },
13- "hash": "425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695"
13+ "hash": "caad4a6fe3555a38b1ac2f7dc3a4df74def95a0356454a07f9281103b19fdacc"
1414 }
.sqlx/query-ccb478d5d6140d28698b183ad905af36a014f483dc548b0068be808eb7b38df0.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM academic_year\n WHERE id = $1 AND class_count = 0 AND term_count = 0",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "ccb478d5d6140d28698b183ad905af36a014f483dc548b0068be808eb7b38df0"
14+}
.sqlx/query-e8a08dbbc2d58b7fd391beea26491ac2c61ac38d35a6805cc95dc2f370822b07.json → .sqlx/query-cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7.jsonrenamed+3 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "WITH seat AS (\n UPDATE class_group SET class_course_count = class_course_count + 1\n WHERE id = $1 AND class_course_count < $2\n RETURNING 1)\n INSERT INTO class_course (class, course, attached_by, attached_at, source)\n SELECT $1, $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"",
3+ "query": "WITH seat AS (\n UPDATE class_group SET class_course_count = class_course_count + 1\n WHERE id = $1 AND class_course_count < $2\n RETURNING 1)\n INSERT INTO class_course (id, class, course, attached_by, attached_at, source)\n SELECT $3, $1, $4, $5, $6, $7 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"",
44 "describe": {
55 "columns": [
66 {
@@ -16,6 +16,7 @@
1616 "Int8",
1717 "Uuid",
1818 "Uuid",
19+ "Uuid",
1920 "Int8",
2021 "Uuid"
2122 ]
@@ -24,5 +25,5 @@
2425 null
2526 ]
2627 },
27- "hash": "e8a08dbbc2d58b7fd391beea26491ac2c61ac38d35a6805cc95dc2f370822b07"
28+ "hash": "cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7"
2829 }
.sqlx/query-cd362195df1a2d07ac2c505cce03429f1a538e31d82e6ede3836d7f39c68efa4.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT enrollment_count AS \"count: i64\" FROM class_course WHERE id = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "count: i64",
9+ "type_info": "Int8",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course",
13+ "name": "enrollment_count"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "cd362195df1a2d07ac2c505cce03429f1a538e31d82e6ede3836d7f39c68efa4"
28+}
.sqlx/query-0d0c13c18d5098eb1c581ea5e6d51af848d59f79a590386f898d85900022f8b1.json → .sqlx/query-cf05e53c62f31d20f07e1f702e4f4d21bdbefaf19b3a14d8478ec3fdc8bcfc31.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM course_session WHERE id = $1\n RETURNING id AS \"id: CourseSessionId\", course AS \"course: CourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"",
3+ "query": "DELETE FROM course_session WHERE id = $1\n RETURNING id AS \"id: CourseSessionId\",\n class_course AS \"class_course: ClassCourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "course_session",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -84,5 +84,5 @@
8484 true
8585 ]
8686 },
87- "hash": "0d0c13c18d5098eb1c581ea5e6d51af848d59f79a590386f898d85900022f8b1"
87+ "hash": "cf05e53c62f31d20f07e1f702e4f4d21bdbefaf19b3a14d8478ec3fdc8bcfc31"
8888 }
.sqlx/query-cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4.jsondeleted+0 -21
@@ -1,21 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = EXCLUDED.exam_kinds,\n grade_bands = EXCLUDED.grade_bands,\n max_file_bytes = EXCLUDED.max_file_bytes,\n chatbot_history_turns = EXCLUDED.chatbot_history_turns,\n max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,\n max_chatbot_threads = EXCLUDED.max_chatbot_threads,\n meal_slots = EXCLUDED.meal_slots,\n meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Jsonb",
9- "Jsonb",
10- "Int8",
11- "Int8",
12- "Int8",
13- "Int8",
14- "Jsonb",
15- "Int8"
16- ]
17- },
18- "nullable": []
19- },
20- "hash": "cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4"
21-}
.sqlx/query-d06525ead7b0e7e9a589950826700212d313d65c3feab3aaa029723ee2bee7cf.jsonadded+29 -0
@@ -0,0 +1,29 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT payload AS \"payload: Json<serde_json::Value>\"\n FROM karne_snapshot WHERE term = $1 AND app_user = $2",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "payload: Json<serde_json::Value>",
9+ "type_info": "Jsonb",
10+ "origin": {
11+ "Table": {
12+ "table": "karne_snapshot",
13+ "name": "payload"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid",
21+ "Uuid"
22+ ]
23+ },
24+ "nullable": [
25+ false
26+ ]
27+ },
28+ "hash": "d06525ead7b0e7e9a589950826700212d313d65c3feab3aaa029723ee2bee7cf"
29+}
.sqlx/query-d1be78d4182f131ba6792925a4557e4b4d9d43197d1b013ce3e5b4eb08b05cf6.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "DELETE FROM term\n WHERE id = $1 AND course_count = 0 AND class_count = 0",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "d1be78d4182f131ba6792925a4557e4b4d9d43197d1b013ce3e5b4eb08b05cf6"
14-}
.sqlx/query-d227e7369f4eabea326711629151cf5ff0e114ee97fb681e9463703f2ac2fb64.jsonadded+24 -0
@@ -0,0 +1,24 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT 1 AS \"one\" FROM course_membership\n WHERE course = $1 AND app_user = $2",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "one",
9+ "type_info": "Int4",
10+ "origin": "Expression"
11+ }
12+ ],
13+ "parameters": {
14+ "Left": [
15+ "Uuid",
16+ "Uuid"
17+ ]
18+ },
19+ "nullable": [
20+ null
21+ ]
22+ },
23+ "hash": "d227e7369f4eabea326711629151cf5ff0e114ee97fb681e9463703f2ac2fb64"
24+}
.sqlx/query-27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1.json → .sqlx/query-d5744188d2347496462ff093b7a8d06d1be3c44cf25b8bc40403e26196feb6ae.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM course_teacher WHERE course = $1 AND teacher = $2",
3+ "query": "INSERT INTO exam_audience (exam, class_course) VALUES ($1, $2)",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -11,5 +11,5 @@
1111 },
1212 "nullable": []
1313 },
14- "hash": "27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1"
14+ "hash": "d5744188d2347496462ff093b7a8d06d1be3c44cf25b8bc40403e26196feb6ae"
1515 }
.sqlx/query-d8f2d5db166767ffdeedd219bf24f44ac8614fea1b45c3935082e511653e23dc.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM class_course_teacher WHERE teacher = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "d8f2d5db166767ffdeedd219bf24f44ac8614fea1b45c3935082e511653e23dc"
14+}
.sqlx/query-f60be76484071d1a16789dcc7b7d8eabcc179e9ce8efee2afe90635c6553fb1e.json → .sqlx/query-da4c055f25da6b0e2fae8a7ccc4c7e7f806e731ca5dbaffe3cfc83b2a548be9f.jsonrenamed+17 -5
@@ -1,16 +1,16 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "WITH gone AS (\n DELETE FROM enrollment\n WHERE course = $1 AND app_user = $2\n RETURNING course, app_user, enrolled_by, source),\n seated AS (\n UPDATE course\n SET enrollment_count = GREATEST(\n enrollment_count - (SELECT count(*) FROM gone), 0)\n WHERE id = $1\n RETURNING 1)\n SELECT course AS \"course: CourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\" FROM gone",
3+ "query": "SELECT class_course AS \"class_course: ClassCourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\",\n created_at AS \"created_at: Timestamp\"\n FROM enrollment WHERE class_course = $1 AND app_user = $2",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "course: CourseId",
8+ "name": "class_course: ClassCourseId",
99 "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
1212 "table": "enrollment",
13- "name": "course"
13+ "name": "class_course"
1414 }
1515 }
1616 },
@@ -46,6 +46,17 @@
4646 "name": "source"
4747 }
4848 }
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+ }
4960 }
5061 ],
5162 "parameters": {
@@ -58,8 +69,9 @@
5869 false,
5970 false,
6071 false,
61- true
72+ true,
73+ false
6274 ]
6375 },
64- "hash": "f60be76484071d1a16789dcc7b7d8eabcc179e9ce8efee2afe90635c6553fb1e"
76+ "hash": "da4c055f25da6b0e2fae8a7ccc4c7e7f806e731ca5dbaffe3cfc83b2a548be9f"
6577 }
.sqlx/query-b8279c8d5178f05cc4c3ee2afadd75e4759cf97aa94103d300dd19149c6c92f0.json → .sqlx/query-da8172853a9900e6572ec43020f316f9d034f53ba696a5c9ad300663e8e5db2c.jsonrenamed+26 -14
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM exam WHERE id = $1\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n course AS \"course: CourseId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft",
3+ "query": "DELETE FROM exam WHERE id = $1\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n term AS \"term: TermId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft",
44 "describe": {
55 "columns": [
66 {
@@ -27,17 +27,28 @@
2727 },
2828 {
2929 "ordinal": 2,
30- "name": "course: CourseId",
30+ "name": "class_course: ClassCourseId",
3131 "type_info": "Uuid",
3232 "origin": {
3333 "Table": {
3434 "table": "exam",
35- "name": "course"
35+ "name": "class_course"
3636 }
3737 }
3838 },
3939 {
4040 "ordinal": 3,
41+ "name": "term: TermId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "exam",
46+ "name": "term"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
4152 "name": "title: ExamTitle",
4253 "type_info": "Text",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "description: ExamDescription",
5364 "type_info": "Text",
5465 "origin": {
@@ -59,7 +70,7 @@
5970 }
6071 },
6172 {
62- "ordinal": 5,
73+ "ordinal": 6,
6374 "name": "kind: ExamKind",
6475 "type_info": "Text",
6576 "origin": {
@@ -70,7 +81,7 @@
7081 }
7182 },
7283 {
73- "ordinal": 6,
84+ "ordinal": 7,
7485 "name": "mode: ExamMode",
7586 "type_info": "Text",
7687 "origin": {
@@ -81,7 +92,7 @@
8192 }
8293 },
8394 {
84- "ordinal": 7,
95+ "ordinal": 8,
8596 "name": "starts_at: Timestamp",
8697 "type_info": "Int8",
8798 "origin": {
@@ -92,7 +103,7 @@
92103 }
93104 },
94105 {
95- "ordinal": 8,
106+ "ordinal": 9,
96107 "name": "ends_at: Timestamp",
97108 "type_info": "Int8",
98109 "origin": {
@@ -103,7 +114,7 @@
103114 }
104115 },
105116 {
106- "ordinal": 9,
117+ "ordinal": 10,
107118 "name": "duration_ms: ExamDuration",
108119 "type_info": "Int8",
109120 "origin": {
@@ -114,7 +125,7 @@
114125 }
115126 },
116127 {
117- "ordinal": 10,
128+ "ordinal": 11,
118129 "name": "max_attempts: ExamAttemptLimit",
119130 "type_info": "Int8",
120131 "origin": {
@@ -125,7 +136,7 @@
125136 }
126137 },
127138 {
128- "ordinal": 11,
139+ "ordinal": 12,
129140 "name": "allow_rejoin",
130141 "type_info": "Bool",
131142 "origin": {
@@ -136,7 +147,7 @@
136147 }
137148 },
138149 {
139- "ordinal": 12,
150+ "ordinal": 13,
140151 "name": "allow_review",
141152 "type_info": "Bool",
142153 "origin": {
@@ -147,7 +158,7 @@
147158 }
148159 },
149160 {
150- "ordinal": 13,
161+ "ordinal": 14,
151162 "name": "draft",
152163 "type_info": "Bool",
153164 "origin": {
@@ -170,6 +181,7 @@
170181 false,
171182 false,
172183 false,
184+ false,
173185 true,
174186 true,
175187 true,
@@ -180,5 +192,5 @@
180192 false
181193 ]
182194 },
183- "hash": "b8279c8d5178f05cc4c3ee2afadd75e4759cf97aa94103d300dd19149c6c92f0"
195+ "hash": "da8172853a9900e6572ec43020f316f9d034f53ba696a5c9ad300663e8e5db2c"
184196 }
.sqlx/query-dbcf7f63fb683407d48601841aab230a2323c676e7886509be184361747f9c8a.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE enrollment SET source = NULL WHERE source = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "dbcf7f63fb683407d48601841aab230a2323c676e7886509be184361747f9c8a"
14+}
.sqlx/query-dc4e699d21300e00e144794ce36ebe0a50ed9833393af07b727e69f3def66d42.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM session_attendance WHERE class_course = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "dc4e699d21300e00e144794ce36ebe0a50ed9833393af07b727e69f3def66d42"
14+}
.sqlx/query-e19b652daae920d9095b3485060cbf36828c7d4a794005fc5a5252c8b6af62ca.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "DELETE FROM homework_file WHERE submission IN (\n SELECT id FROM homework_submission\n WHERE homework IN (SELECT id FROM homework WHERE course = $1))",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "e19b652daae920d9095b3485060cbf36828c7d4a794005fc5a5252c8b6af62ca"
14-}
.sqlx/query-178ed4347a442f045bdfdab1153fd3b72c901f9278c37d4c9f5385f639a7fa1d.json → .sqlx/query-e50aac98a42832e61a62d8b1a7e3aef9758ddc0d246de5622473d9011897f363.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "INSERT INTO course_session (id, course, teacher, topic, starts_at, ends_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: CourseSessionId\", course AS \"course: CourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"",
3+ "query": "INSERT INTO course_session (id, class_course, teacher, topic, starts_at, ends_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: CourseSessionId\",\n class_course AS \"class_course: ClassCourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "course_session",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -89,5 +89,5 @@
8989 true
9090 ]
9191 },
92- "hash": "178ed4347a442f045bdfdab1153fd3b72c901f9278c37d4c9f5385f639a7fa1d"
92+ "hash": "e50aac98a42832e61a62d8b1a7e3aef9758ddc0d246de5622473d9011897f363"
9393 }
.sqlx/query-e61998707fa0030ed51a367b56e3a62bee785870b91d97998eaa7e3af29ae87e.jsonadded+128 -0
@@ -0,0 +1,128 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE academic_year\n SET name = COALESCE($2, name),\n starts_at = COALESCE($3, starts_at),\n ends_at = COALESCE($4, ends_at),\n grade_promotions = COALESCE($5, grade_promotions)\n WHERE id = $1\n AND COALESCE($4, ends_at) > COALESCE($3, starts_at)\n RETURNING id AS \"id: AcademicYearId\", name AS \"name: AcademicYearName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\", creator AS \"creator: UserId\",\n grade_promotions AS \"grade_promotions: Json<Vec<GradePromotion>>\",\n class_count, term_count",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: AcademicYearId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "academic_year",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "name: AcademicYearName",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "academic_year",
24+ "name": "name"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "starts_at: Timestamp",
31+ "type_info": "Int8",
32+ "origin": {
33+ "Table": {
34+ "table": "academic_year",
35+ "name": "starts_at"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "ends_at: Timestamp",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "academic_year",
46+ "name": "ends_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "archived_at: Timestamp",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "academic_year",
57+ "name": "archived_at"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "creator: UserId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "academic_year",
68+ "name": "creator"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "grade_promotions: Json<Vec<GradePromotion>>",
75+ "type_info": "Jsonb",
76+ "origin": {
77+ "Table": {
78+ "table": "academic_year",
79+ "name": "grade_promotions"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "class_count",
86+ "type_info": "Int8",
87+ "origin": {
88+ "Table": {
89+ "table": "academic_year",
90+ "name": "class_count"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "term_count",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "academic_year",
101+ "name": "term_count"
102+ }
103+ }
104+ }
105+ ],
106+ "parameters": {
107+ "Left": [
108+ "Uuid",
109+ "Text",
110+ "Int8",
111+ "Int8",
112+ "Jsonb"
113+ ]
114+ },
115+ "nullable": [
116+ false,
117+ false,
118+ false,
119+ false,
120+ true,
121+ false,
122+ false,
123+ false,
124+ false
125+ ]
126+ },
127+ "hash": "e61998707fa0030ed51a367b56e3a62bee785870b91d97998eaa7e3af29ae87e"
128+}
.sqlx/query-6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699.json → .sqlx/query-e7fd2e1221613ddef9bc36d6b2ed44b3e8b351471573a4f84e0ce06cb49aeebc.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework ORDER BY id DESC",
3+ "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework ORDER BY id DESC",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "homework",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -113,5 +113,5 @@
113113 false
114114 ]
115115 },
116- "hash": "6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699"
116+ "hash": "e7fd2e1221613ddef9bc36d6b2ed44b3e8b351471573a4f84e0ce06cb49aeebc"
117117 }
.sqlx/query-b99095e17c379fb32aea7db2926a9cc78bb3e7ed3200aca3e8019f4103c148d6.json → .sqlx/query-e9e9c3f5b35f35338501485a155be2784075bb0a5b29a270093da5e409ada3ed.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT qi.file FROM question_image qi\n JOIN exam e ON e.id = qi.exam WHERE e.course = $1",
3+ "query": "SELECT qi.file FROM question_image qi\n JOIN exam e ON e.id = qi.exam\n JOIN class_course cc ON cc.id = e.class_course\n WHERE cc.course = $1",
44 "describe": {
55 "columns": [
66 {
@@ -24,5 +24,5 @@
2424 false
2525 ]
2626 },
27- "hash": "b99095e17c379fb32aea7db2926a9cc78bb3e7ed3200aca3e8019f4103c148d6"
27+ "hash": "e9e9c3f5b35f35338501485a155be2784075bb0a5b29a270093da5e409ada3ed"
2828 }
.sqlx/query-0f4855352631239aaf9aac48ad4510afd1081f61c523106c60c62ae3c7ad9944.json → .sqlx/query-ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size\n FROM app_user WHERE id = ANY($1)",
3+ "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE id = ANY($1)",
44 "describe": {
55 "columns": [
66 {
@@ -181,6 +181,17 @@
181181 },
182182 {
183183 "ordinal": 16,
184+ "name": "branch",
185+ "type_info": "Text",
186+ "origin": {
187+ "Table": {
188+ "table": "app_user",
189+ "name": "branch"
190+ }
191+ }
192+ },
193+ {
194+ "ordinal": 17,
184195 "name": "avatar_size",
185196 "type_info": "Int8",
186197 "origin": {
@@ -213,8 +224,9 @@
213224 true,
214225 true,
215226 true,
227+ true,
216228 true
217229 ]
218230 },
219- "hash": "0f4855352631239aaf9aac48ad4510afd1081f61c523106c60c62ae3c7ad9944"
231+ "hash": "ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f"
220232 }
.sqlx/query-44493997240e532ba46452ef0222b2de5524cbf7ef435d7dd57a7e185a02891e.json → .sqlx/query-ea7346e8dcbf509401f3e89f0570b1c356222b02e85aa0571337f7a670792abb.jsonrenamed+4 -4
@@ -1,16 +1,16 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT course AS \"course: uuid::Uuid\", app_user AS \"app_user: uuid::Uuid\"\n FROM enrollment WHERE course = $1 AND source = $2",
3+ "query": "SELECT class_course AS \"class_course: uuid::Uuid\",\n app_user AS \"app_user: uuid::Uuid\"\n FROM enrollment WHERE app_user = $1 AND source = $2",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "course: uuid::Uuid",
8+ "name": "class_course: uuid::Uuid",
99 "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
1212 "table": "enrollment",
13- "name": "course"
13+ "name": "class_course"
1414 }
1515 }
1616 },
@@ -37,5 +37,5 @@
3737 false
3838 ]
3939 },
40- "hash": "44493997240e532ba46452ef0222b2de5524cbf7ef435d7dd57a7e185a02891e"
40+ "hash": "ea7346e8dcbf509401f3e89f0570b1c356222b02e85aa0571337f7a670792abb"
4141 }
.sqlx/query-eb3422e43b27e70b5b4eac909cb191ed8c89b0caeb2e2f27f93ea6a5469300e0.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "DELETE FROM exam_question WHERE exam = ANY($1)",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "UuidArray"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "eb3422e43b27e70b5b4eac909cb191ed8c89b0caeb2e2f27f93ea6a5469300e0"
14-}
.sqlx/query-f64594c9dd40fc944bcc77ae1bf62adc1a6d90c8cf53d4807dfa4db26d4faf41.json → .sqlx/query-eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "UPDATE app_user SET role = $2\n WHERE id = $1\n AND NOT (role = 'admin'\n AND $2 <> 'admin'\n AND (SELECT count(*) FROM app_user\n WHERE role = 'admin' AND id <> $1) = 0)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size",
3+ "query": "UPDATE app_user SET role = $2\n WHERE id = $1\n AND NOT (role = 'admin'\n AND $2 <> 'admin'\n AND (SELECT count(*) FROM app_user\n WHERE role = 'admin' AND id <> $1) = 0)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size",
44 "describe": {
55 "columns": [
66 {
@@ -181,6 +181,17 @@
181181 },
182182 {
183183 "ordinal": 16,
184+ "name": "branch",
185+ "type_info": "Text",
186+ "origin": {
187+ "Table": {
188+ "table": "app_user",
189+ "name": "branch"
190+ }
191+ }
192+ },
193+ {
194+ "ordinal": 17,
184195 "name": "avatar_size",
185196 "type_info": "Int8",
186197 "origin": {
@@ -214,8 +225,9 @@
214225 true,
215226 true,
216227 true,
228+ true,
217229 true
218230 ]
219231 },
220- "hash": "f64594c9dd40fc944bcc77ae1bf62adc1a6d90c8cf53d4807dfa4db26d4faf41"
232+ "hash": "eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712"
221233 }
.sqlx/query-ee474f7fcb2cd36d33ed13426c0f0ef265646de1ecb1f3f928ecaa6a9a36ea26.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH gone AS (\n DELETE FROM term\n WHERE id = $1 AND exam_count = 0\n AND NOT EXISTS (SELECT 1 FROM karne_snapshot WHERE term = $1)\n RETURNING year)\n UPDATE academic_year\n SET term_count = GREATEST(term_count - 1, 0)\n FROM gone\n WHERE academic_year.id = gone.year",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "ee474f7fcb2cd36d33ed13426c0f0ef265646de1ecb1f3f928ecaa6a9a36ea26"
14+}
.sqlx/query-c2dab6249cebf45a0a61c542700e05679a5bd6e335cc76767a167d00b3aa964d.json → .sqlx/query-eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n term AS \"term: TermId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE grade = $1",
3+ "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE grade = $1",
44 "describe": {
55 "columns": [
66 {
@@ -49,12 +49,12 @@
4949 },
5050 {
5151 "ordinal": 4,
52- "name": "term: TermId",
52+ "name": "year: AcademicYearId",
5353 "type_info": "Uuid",
5454 "origin": {
5555 "Table": {
5656 "table": "class_group",
57- "name": "term"
57+ "name": "year"
5858 }
5959 }
6060 },
@@ -84,5 +84,5 @@
8484 true
8585 ]
8686 },
87- "hash": "c2dab6249cebf45a0a61c542700e05679a5bd6e335cc76767a167d00b3aa964d"
87+ "hash": "eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e"
8888 }
.sqlx/query-2db4b9a7ae30282e36229c463126bfe5d8670dc1a44a326704c8a503f537ab2f.json → .sqlx/query-eeef9fa58c5f58e8758e184fa0b686b192a18463f4cb43e2334535861a372217.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM homework_result WHERE homework IN (\n SELECT id FROM homework WHERE course = $1)",
3+ "query": "DELETE FROM homework_result WHERE homework IN (\n SELECT id FROM homework WHERE class_course = $1)",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -10,5 +10,5 @@
1010 },
1111 "nullable": []
1212 },
13- "hash": "2db4b9a7ae30282e36229c463126bfe5d8670dc1a44a326704c8a503f537ab2f"
13+ "hash": "eeef9fa58c5f58e8758e184fa0b686b192a18463f4cb43e2334535861a372217"
1414 }
.sqlx/query-f0670cba23b45c7dd4e88531aed7c10ecbdf9f108165b055794a3c8ba5d7031b.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH gone AS (\n DELETE FROM homework WHERE class_course = $1\n RETURNING subject),\n subs AS (\n SELECT subject, count(*) AS n FROM gone GROUP BY subject)\n UPDATE subject s SET homework_count = GREATEST(s.homework_count - c.n, 0)\n FROM subs c WHERE s.id = c.subject",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "f0670cba23b45c7dd4e88531aed7c10ecbdf9f108165b055794a3c8ba5d7031b"
14+}
.sqlx/query-57ab52a67001f23abd0c94617d41d0a35ba6fee7fb71e0523c3c28862f2e7874.json → .sqlx/query-f0a41ad9450035b1fc8d52e4a4a4b1ada1998252bc516846e1d4f88b489e7c3c.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT EXISTS(SELECT 1 FROM class_member WHERE class = $1 AND app_user = $2)\n AS \"present!\"",
3+ "query": "SELECT EXISTS(SELECT 1 FROM class_member\n WHERE class = $1 AND app_user = $2 AND left_at IS NULL)\n AS \"present!\"",
44 "describe": {
55 "columns": [
66 {
@@ -20,5 +20,5 @@
2020 null
2121 ]
2222 },
23- "hash": "57ab52a67001f23abd0c94617d41d0a35ba6fee7fb71e0523c3c28862f2e7874"
23+ "hash": "f0a41ad9450035b1fc8d52e4a4a4b1ada1998252bc516846e1d4f88b489e7c3c"
2424 }
.sqlx/query-f12076e5b4bce06b50cc5923837f943560b4f8b9bc4f9bde9d3c4908513b8ae7.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM homework_file\n WHERE submission IN (SELECT id FROM homework_submission WHERE homework IN (\n SELECT id FROM homework WHERE class_course = $1))",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "f12076e5b4bce06b50cc5923837f943560b4f8b9bc4f9bde9d3c4908513b8ae7"
14+}
.sqlx/query-b12b099fc63ee82716606640bd2321aea103d8ec7cde10154c37aac7f5a0d429.json → .sqlx/query-f5547737eed659d69097999705426f0a827f9e7eeaeaf64c7a808784c6a95d95.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT 1 AS \"one\" FROM enrollment WHERE course = $1 AND app_user = $2",
3+ "query": "SELECT 1 AS \"one\" FROM course_membership WHERE course = $1 AND app_user = $2",
44 "describe": {
55 "columns": [
66 {
@@ -20,5 +20,5 @@
2020 null
2121 ]
2222 },
23- "hash": "b12b099fc63ee82716606640bd2321aea103d8ec7cde10154c37aac7f5a0d429"
23+ "hash": "f5547737eed659d69097999705426f0a827f9e7eeaeaf64c7a808784c6a95d95"
2424 }
.sqlx/query-1426cb1fc87d2e06ea919254bac9cb3403d07318c2bb43388a8dca245a952fc8.json → .sqlx/query-f6110c3d1f0e072aa0f0c62c631bb9846f1b6d509f4688f7e86e93c48a7f9d9f.jsonrenamed+18 -6
@@ -1,16 +1,16 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "WITH seat AS (\n UPDATE course\n SET enrollment_count = enrollment_count + 1\n WHERE id = $1\n AND enrollment_count < COALESCE(capacity, $2)\n RETURNING 1)\n INSERT INTO enrollment (course, app_user, enrolled_by, source, created_at)\n SELECT $1, $3, $4, NULL, $5 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING course AS \"course: CourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\"",
3+ "query": "WITH seat AS (\n UPDATE class_course\n SET enrollment_count = enrollment_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO enrollment (class_course, app_user, enrolled_by, source, created_at)\n SELECT $1, $2, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING class_course AS \"class_course: ClassCourseId\",\n app_user AS \"user: UserId\", enrolled_by AS \"enrolled_by: UserId\",\n source AS \"source: ClassGroupId\",\n created_at AS \"created_at: Timestamp\"",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "course: CourseId",
8+ "name": "class_course: ClassCourseId",
99 "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
1212 "table": "enrollment",
13- "name": "course"
13+ "name": "class_course"
1414 }
1515 }
1616 },
@@ -46,12 +46,23 @@
4646 "name": "source"
4747 }
4848 }
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+ }
4960 }
5061 ],
5162 "parameters": {
5263 "Left": [
5364 "Uuid",
54- "Int8",
65+ "Uuid",
5566 "Uuid",
5667 "Uuid",
5768 "Int8"
@@ -61,8 +72,9 @@
6172 false,
6273 false,
6374 false,
64- true
75+ true,
76+ false
6577 ]
6678 },
67- "hash": "1426cb1fc87d2e06ea919254bac9cb3403d07318c2bb43388a8dca245a952fc8"
79+ "hash": "f6110c3d1f0e072aa0f0c62c631bb9846f1b6d509f4688f7e86e93c48a7f9d9f"
6880 }
.sqlx/query-1df2ab45fdf2662a7d8b6a37eabf921e159e9a526b8a3f16086c2db3f390ae78.json → .sqlx/query-f72a0bb5098304333748ff839953de5e2f9bc6a7bb92295c4514026842c282a0.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "DELETE FROM homework WHERE course = $1",
3+ "query": "DELETE FROM class_course WHERE id = $1",
44 "describe": {
55 "columns": [],
66 "parameters": {
@@ -10,5 +10,5 @@
1010 },
1111 "nullable": []
1212 },
13- "hash": "1df2ab45fdf2662a7d8b6a37eabf921e159e9a526b8a3f16086c2db3f390ae78"
13+ "hash": "f72a0bb5098304333748ff839953de5e2f9bc6a7bb92295c4514026842c282a0"
1414 }
.sqlx/query-f8000bdc282afa0ebfc1c258f1478c504fc10234c6099f677a2cb3b59f001a67.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE course SET class_course_count = GREATEST(class_course_count - 1, 0)\n WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "f8000bdc282afa0ebfc1c258f1478c504fc10234c6099f677a2cb3b59f001a67"
14+}
.sqlx/query-9bb792ad62ed64306b9812bb3a049fe742604c0ad3162c9466869a1fe55e7463.json → .sqlx/query-f99618110767c8805bdbef2de1ba16f90a0430ee6ba734af80f90b8ab4527e71.jsonrenamed+17 -5
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "UPDATE term SET archived_at = $2\n WHERE id = $1 AND archived_at IS NULL\n RETURNING id AS \"id: TermId\", name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"",
3+ "query": "UPDATE term SET archived_at = $2\n WHERE id = $1 AND archived_at IS NULL\n RETURNING id AS \"id: TermId\", year AS \"year: AcademicYearId\",\n name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"",
44 "describe": {
55 "columns": [
66 {
@@ -16,6 +16,17 @@
1616 },
1717 {
1818 "ordinal": 1,
19+ "name": "year: AcademicYearId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "term",
24+ "name": "year"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
1930 "name": "name: TermName",
2031 "type_info": "Text",
2132 "origin": {
@@ -26,7 +37,7 @@
2637 }
2738 },
2839 {
29- "ordinal": 2,
40+ "ordinal": 3,
3041 "name": "starts_at: Timestamp",
3142 "type_info": "Int8",
3243 "origin": {
@@ -37,7 +48,7 @@
3748 }
3849 },
3950 {
40- "ordinal": 3,
51+ "ordinal": 4,
4152 "name": "ends_at: Timestamp",
4253 "type_info": "Int8",
4354 "origin": {
@@ -48,7 +59,7 @@
4859 }
4960 },
5061 {
51- "ordinal": 4,
62+ "ordinal": 5,
5263 "name": "archived_at: Timestamp",
5364 "type_info": "Int8",
5465 "origin": {
@@ -70,8 +81,9 @@
7081 false,
7182 false,
7283 false,
84+ false,
7385 true
7486 ]
7587 },
76- "hash": "9bb792ad62ed64306b9812bb3a049fe742604c0ad3162c9466869a1fe55e7463"
88+ "hash": "f99618110767c8805bdbef2de1ba16f90a0430ee6ba734af80f90b8ab4527e71"
7789 }
.sqlx/query-a9cffc647c52f9d65cae0c72f929ee49afac7e4d54606e6f084d2892b8a9d517.json → .sqlx/query-fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "INSERT INTO class_group (id, creator, name, grade, term, teacher)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n term AS \"term: TermId\", teacher AS \"teacher: UserId\"",
3+ "query": "INSERT INTO class_group (id, creator, name, grade, year, teacher)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"",
44 "describe": {
55 "columns": [
66 {
@@ -49,12 +49,12 @@
4949 },
5050 {
5151 "ordinal": 4,
52- "name": "term: TermId",
52+ "name": "year: AcademicYearId",
5353 "type_info": "Uuid",
5454 "origin": {
5555 "Table": {
5656 "table": "class_group",
57- "name": "term"
57+ "name": "year"
5858 }
5959 }
6060 },
@@ -89,5 +89,5 @@
8989 true
9090 ]
9191 },
92- "hash": "a9cffc647c52f9d65cae0c72f929ee49afac7e4d54606e6f084d2892b8a9d517"
92+ "hash": "fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee"
9393 }
.sqlx/query-fcfc67fdb7773a04fa9ebee659009b6b63ce8844a9ebdc4a4e8eb51c3b01eed1.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE class_member SET source_class_group = NULL WHERE source_class_group = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "fcfc67fdb7773a04fa9ebee659009b6b63ce8844a9ebdc4a4e8eb51c3b01eed1"
14+}
.sqlx/query-60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa.json → .sqlx/query-fe0ff8dba66bad35ba49676eb0c95eb348e85a428efed42e790b1e7b2d465677.jsonrenamed+4 -4
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "UPDATE homework SET subject = $2, title = $3, description = $4,\n due_at = $5\n WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",
3+ "query": "UPDATE homework SET subject = $2, title = $3, description = $4,\n due_at = $5\n WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",
44 "describe": {
55 "columns": [
66 {
@@ -16,12 +16,12 @@
1616 },
1717 {
1818 "ordinal": 1,
19- "name": "course: CourseId",
19+ "name": "class_course: ClassCourseId",
2020 "type_info": "Uuid",
2121 "origin": {
2222 "Table": {
2323 "table": "homework",
24- "name": "course"
24+ "name": "class_course"
2525 }
2626 }
2727 },
@@ -119,5 +119,5 @@
119119 false
120120 ]
121121 },
122- "hash": "60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa"
122+ "hash": "fe0ff8dba66bad35ba49676eb0c95eb348e85a428efed42e790b1e7b2d465677"
123123 }
.sqlx/query-ff85736b704c5450668adf038604d75ae4af5267133d088123eb8aace992cd2b.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE course SET class_course_count = class_course_count + 1 WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "ff85736b704c5450668adf038604d75ae4af5267133d088123eb8aace992cd2b"
14+}
README.mdmodified+399 -271
@@ -14,36 +14,43 @@ per-file size cap is school policy in settings (`max_file_bytes`, default
1414 body into the recipient's inbox, each side filing its own copy through
1515 archive/trash with a read flag the sender sees as a receipt (the only place a
1616 `parent` writes). Attendance is event + attendees: create an event with an **audience**
17-(the whole school, one role, a course's enrollment, a **class section's**
18-roster, or a **registration** signup list — omit for school-wide), then teachers mark the expected attendees
17+(the whole school, one role, a course **instance's** enrollment, a **class
18+section's** roster, or a **registration** signup list — omit for school-wide), then teachers mark the expected attendees
1919 present / absent / late / excused (students never self-mark), and a **roster
2020 report** shows who was expected and who missed. Registration lists fill seat
2121 by seat: teachers register students (never the other way round), staff
2222 register only themselves, an optional `capacity` caps the seats, and the list
2323 closes the moment the event starts (or, for an event with only an end time —
2424 a pure signup deadline — the moment that end passes). Every event stays visible to everyone —
25-the audience is a roster, not a wall. Marks are course-shaped
26-(Google Classroom style): a teacher creates a course — kind **`course`** (a
25+the audience is a roster, not a wall. Marks are **instance-shaped**. A **course** in `/courses` is a
26+school-wide catalog row — kind **`course`** (a
2727 regular taught course), **`study`** (a supervised study session — *etüt*), or
28-**`club`** (a student club — *kulüp*; same behavior, different label),
29-optionally capped by a `capacity` that refuses new enrolls once the roster is
30-full — lays out its **subjects** (curriculum topics —
28+**`club`** (a student club — *kulüp*; same behavior, different label) — and it
29+owns its **subjects** (curriculum topics —
3130 every exam question must be tagged with one of its course's subjects, so
32-results can later be read per topic), enrolls students, adds
33-exams inside it, and grades — enrolling, sitting exams, roll call, and marks are
34-all student-only, staff never take part. A course is run by whoever created it
35-plus any teachers a **manager assigns** to it (`POST /courses/{id}/teachers`):
36-an assigned teacher manages everything inside the course — exams, sessions,
37-subjects, roster, grading — but can't delete it or change who else teaches it,
38-and a demotion below `teacher` sweeps their assignments away. Students are
31+results can later be read per topic). Nobody is enrolled in a catalog course:
32+teaching happens in the **instance** — one class section × one course, created
33+when the course is attached to the section (`POST /classes/{id}/instances`) and
34+living at `/instances/{id}` with its own `ders_saati` (weekly lesson hours, its
35+weight in the karne average), `counts_toward_karne` flag, teachers, roster,
36+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 in
38+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 are
40+the exception — see "Courses (catalog)"), while an instance is run by the
41+teachers a **manager assigns** to it (`POST /instances/{id}/teachers`) plus the
42+section's homeroom teacher: an assigned teacher manages everything inside the
43+instance — exams, sessions, subjects, roster, grading — and a demotion below
44+`teacher` sweeps their assignments away. Students are
3945 grouped into a **class section** (*şube* — 9-A, 10-B) when a school teaches
40-that way: it is bulk enrollment, not a second kind of membership — attaching a
41-course to it enrolls the whole roster, adding a member enrolls them into every
42-course already attached, and what lands are ordinary enrollment rows tagged
43-with the section that pumped them (untagged = placed by hand, and hand-placed
44-rows are never adopted and never swept). A course without room for everyone
45-refuses the whole operation, naming it (see "Class sections (şube)"). A section
46-may also
46+that way; the şube belongs to an **academic year** (`/academic-years`), and a
47+term is a grading slice inside that year. Membership is a live stint: leaving
48+(`DELETE /classes/{id}/members/{user}`) stamps `left_at` and gives the seat
49+back, and re-adding inserts a fresh row — the section's history is never
50+erased. Attaching a course to a section enrolls the whole roster, adding a
51+member enrolls them into every instance already attached, and what lands are
52+ordinary enrollment rows tagged with the section that pumped them (untagged =
53+placed by hand; a şube sweep never adopts or removes those). A section may also
4754 name a **homeroom teacher** (*sınıf öğretmeni*, `teacher_id` — any teacher+
4855 account, cleared automatically when that account is demoted), and while every
4956 other class read is teacher+, a student reads their own section at
@@ -58,10 +65,15 @@ label (matched exactly, `?grade=` alone the ones carrying none), and
5865 `GET /classes/blueprints/{grade}/status` names, per section, the template
5966 courses it is still missing — which is how a partial pump is chased down after
6067 the response that reported it is gone. Students read a
61-per-course weighted average and
68+per-instance weighted average and
6269 an overall average from their mark report — each exam weighted by its **kind**
63-(midterms can count double, orals once: weights are set per kind in settings,
64-not per exam). Exams run **sync** (one
70+(a yazılı can count double, a sözlü once: weights are set per kind in settings,
71+not per exam) — and `GET /marks/karne` rolls the whole year up: per-instance
72+averages mapped to the school's grade bands, a year-to-date average weighting
73+each instance by its `ders_saati`, and a `gecti`/`kaldi` verdict read off the
74+band labelled `"2"`. Once a term is archived the karne serves the **frozen
75+snapshot** taken at archive time, so a past report never changes under a staff
76+edit. Exams run **sync** (one
6577 fixed window), **async** (start anytime inside the window, with a personal
6678 time budget), or **open** (sit anytime, optionally timed per attempt);
6779 students *sit* them via attempts — retakes metered by a per-exam limit
@@ -96,7 +108,8 @@ backend records the focus stints — every one of them, though only stints of at
96108 least 5 minutes and at most 16 a UTC day *count* towards the badges — and
97109 teachers can read any student's log),
98110 and every user has an
99-**attendance report** (event + per-course lesson tallies with rates).
111+**attendance report** (event + per-instance lesson tallies with rates, plus
112+the per-dönem devamsızlık day counts).
100113 A school-wide **question pool** runs on moderation: a student asks a question
101114 (optionally attaching one photo of the problem — raster only, same
102115 `max_file_bytes` cap), a teacher+ **approves** it into the pool (or deletes
@@ -704,7 +717,7 @@ drift from it**, which is enforced rather than asked for:
704717 and fails unless each one is either referenced by `src/web/limits.rs` or
705718 listed as a deliberate exclusion *with a reason*. A new constant breaks the
706719 suite until someone decides, consciously, whether clients need it.
707-- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 204 published
720+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 219 published
708721 bounds back out of the emitted JSON, and asserts each equals its constant.
709722 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal
710723 only** — a `const` there does not compile — so the annotations are
@@ -1036,30 +1049,36 @@ bought answers `403 {"error": "module disabled", …}` instead — see "Modules"
10361049
10371050 A course is a regular taught course (kind `course`, the default), an *etüt* (kind
10381051 `study` — a supervised study session), or a *kulüp* (kind `club` — a student
1039-club). The three kinds behave identically everywhere — enrollment, exams,
1040-sessions, marks — the kind is a label the UI renders differently, settable at
1041-creation and editable later. A course may also carry a `capacity`: once the
1042-roster reaches it, new enrolls are refused with `409` (members already on the
1043-roster are unaffected, even if the cap is later lowered below them; `null`
1044-lifts the cap).
1045-
1046-**Who runs a course.** Its **creator** owns it for good — only they (or a
1047-manager+) may delete it. On top of that, a manager can **assign** any
1048-`teacher`+ to the course with `POST /courses/{id}/teachers` (`{user_id}`,
1049-idempotent) and drop them again with `DELETE /courses/{id}/teachers/{user}`.
1050-An assigned teacher gets full **course-management rights** — edit the course,
1051-enroll and unenroll students, add exams, sessions and subjects, grade, take
1052-roll call — but *not* the two owner powers: they cannot delete the course, and
1053-they cannot change who else teaches it. Staffing is deliberately the office's
1054-call, so a course's own creator cannot hand rights to their peers; only
1055-manager+ may touch the list. Every course response carries its `teachers`
1056-array alongside `creator`, and a user demoted below `teacher` is swept off
1057-every course they were assigned to (the mirror of promotion dropping
1058-enrollments). That sweep runs once, so an assignment landing in the same
1059-instant would survive it: the assign call therefore re-reads the account's live
1060-role **after** its write and answers `409` — dropping the assignment again — if
1061-it has since fallen below `teacher`. Same guard, same wording, as a class's
1062-homeroom teacher.
1052+club). The three kinds behave identically everywhere, and the kind is a label
1053+the UI renders differently, settable at creation and editable later. A course
1054+is a **catalog row**: it owns its **subjects** (curriculum topics) and carries
1055+counters — `class_course_count`, `course_membership_count` — never a roster of
1056+its own. There is no `capacity` anywhere: no route refuses an enroll for room,
1057+and a counter is a count, not a cap. Teaching happens in the **instance**
1058+(`/instances`): one class × course row, minted by attaching the course to a
1059+section, carrying its own teachers, hours, roster, exams, sessions and homework.
1060+
1061+A catalog course is **office-owned**: only its **creator** (or a manager+) may
1062+edit or delete it. The two kinds a section does not teach are the exception —
1063+a *kulüp* or an *etüt* is joined directly, with `POST /courses/{id}/members`
1064+(the school-scoped membership a student may join and leave on their own). A
1065+`course`-kind row refuses that join (`409`): a ders is taken through a şube's
1066+instance, never directly.
1067+
1068+**Who runs an instance.** Its **teachers** — each a `teacher`+ account a
1069+manager assigned with `POST /instances/{id}/teachers` (`{user_id}`, idempotent;
1070+drop them with `DELETE /instances/{id}/teachers/{user}`) — plus the **homeroom
1071+teacher of its class**. Instance teachers manage everything inside it: its
1072+`ders_saati` and karne weight, its roster, its exams, sessions and homework,
1073+grading and roll call. Staffing is deliberately the office's call; a manager+
1074+caller may always do the same, and nobody else may touch the teacher list.
1075+Every instance response carries its `teachers` array. A user demoted below
1076+`teacher` is swept off every instance they were assigned to (the mirror of
1077+promotion dropping enrollments) and off every homeroom they held. That sweep
1078+runs once, so an assignment landing in the same instant would survive it: the
1079+assign call therefore re-reads the account's live role **after** its write and
1080+answers `409` — dropping the assignment again — if it has since fallen below
1081+`teacher`. Same guard, same wording, as a class's homeroom teacher.
10631082
10641083 Ownership is **not** a standing grant. `creator` is a historical column that no
10651084 demotion sweeps (unlike the assignment list above), so every course-management
@@ -1070,23 +1089,28 @@ manager+, who can hand it to someone else. Nothing below is a right a caller
10701089 holds while under `teacher`. The column is deliberately **not** swept the way
10711090 the assignment list is: it answers "who made this", which stays true after a
10721091 demotion — it is the *grant* that is role-gated, not the history. The same
1073-floor applies to the catalogs: a demoted creator's own course drops out of
1074-their `/courses`, `/exams` and `/homework` lists, and comes back only if they
1075-are enrolled in it, as any student would be. A session's `teacher` behaves
1092+floor applies to the catalogs: a demoted creator's own catalog row drops out
1093+of their `/courses` list, and comes back only if they are enrolled in one of
1094+its instances, as any student would be. A session's `teacher` behaves
10761095 identically — teaching a session grants no roll call, and no view of it, once
10771096 the account is below `teacher`.
10781097
1079-Course data is walled per course. A course, its exams, its sessions, and its
1080-subjects are
1081-**visible** only to its enrolled users, its creator, its assigned teachers,
1082-and manager+ — a student
1083-sees just the classes they were added to, and the `/courses` / `/exams`
1084-catalogs are filtered accordingly. Teacher-level reads *inside* a course
1098+Teaching data is walled **per instance**. An instance, its exams, its sessions,
1099+its homework and its rosters are
1100+**visible** only to its enrolled students, its assigned teachers, its class's
1101+homeroom teacher, and manager+ — a student
1102+sees just the instances their sections carry or they joined, and `/exams`,
1103+`/homework` and `/instances/me` are filtered accordingly. The catalog row, its
1104+subjects and its membership list are readable by that same audience (a student
1105+enrolled in any of its instances, a teacher assigned to one, a member of the
1106+catalog row itself, its creator, manager+). Teacher-level reads *inside* an
1107+instance
10851108 (roster, results, statistics, the question list, answer sheets, the live
1086-monitor) additionally need **course-management rights** (creator, an assigned
1087-teacher, or manager+ — each of them still `teacher`+ today):
1088-one teacher cannot look into another teacher's course, and the per-user
1089-marks/attendance reports narrow to the courses the caller manages.
1109+monitor) additionally need **instance-management rights** (manager+, one of its
1110+assigned teachers, or its class's homeroom teacher — each of them still
1111+`teacher`+ today):
1112+one teacher cannot look into another teacher's instance, and the per-user
1113+marks/attendance reports narrow to the instances the caller manages.
10901114
10911115 **Paging.** Every list endpoint below (the rows tagged **· paged**) accepts
10921116 `?limit=&offset=` and returns a `{ items, total, limit, offset }` envelope
@@ -1119,6 +1143,12 @@ window filtering, before paging; negative values are a `400` naming the field.
11191143 | Method | Path | Auth | Description |
11201144 |--------|------------------------------------------------------------------|---------|-------------|
11211145 | GET | `/` | no | Same as `/health` |
1146+| GET | `/academic-years` | teacher | List every academic year, newest first. Requires teacher+. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. |
1147+| POST | `/academic-years` | manager | Create an academic year. Requires manager+. Past dates are allowed — years are calendar structure, not schedules. `grade_promotions` is the sınıf-geçme policy the rollover applies. |
1148+| GET | `/academic-years/{id}` | teacher | Fetch a single academic year by id. Requires teacher+. |
1149+| PATCH | `/academic-years/{id}` | manager | Update an academic year. Requires manager+. Omitted fields keep their value; `grade_promotions` is replaced as a whole when sent. An archived year is read-only. |
1150+| DELETE | `/academic-years/{id}` | manager | Delete an academic year. Requires manager+. Refused with a 409 while any şube or dönem still links it — move or delete them first. An archived year must be re-opened (`PATCH` is not enough: there is no unarchive here, so the row is only deletable while open) like every other past-structure write. |
1151+| POST | `/academic-years/{id}/rollover` | manager | Carry another year's şubeler into this one. Requires manager+. Each şube of `from_year` whose grade the target year promotes is planted afresh here — same name, mapped grade, and copies of its instances (`ders_saati`, karne policy, teachers) and of every live member, who are also enrolled into the new instances. A grade with no promotion entry stays behind: that is graduation, and `graduated` names it. The target must be empty (a second rollover into it is a 409, which is what makes the command idempotent), open, and different from the source. |
11221152 | GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + SHA-256 fingerprint) for a service to pin; `404` when the bridge is off. |
11231153 | GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |
11241154 | GET | `/appointments` | student | List bookings, newest first. Students and parents see the ones they requested; teacher+ see the ones aimed at their own slots — their request inbox. Managers and admins read their own inbox too (they may still decide any booking by id). Paged via `?limit=&offset=` (omit `limit` for every booking); returns a `{items, total, limit, offset}` envelope. |
@@ -1133,8 +1163,8 @@ window filtering, before paging; negative values are a `400` naming the field.
11331163 | PATCH | `/appointments/{id}/reschedule` | teacher | Counter-propose another time for a booking, on the same row (the reason and the history stay in one place). Requires teacher+ and ownership of the slot (or manager/admin). |
11341164 | PATCH | `/appointments/{id}/reschedule/accept` | student | Accept the teacher's counter-proposal. The requester's call alone — it is their commitment. Accepting *is* approval at the proposed time, so the double-booking guard runs again for both sides (`409` if the moved time now collides with something else, or has already started — agreeing to a window that began would mint a meeting nobody can cancel). |
11351165 | PATCH | `/appointments/{id}/reschedule/decline` | student | Refuse the teacher's counter-proposal. The requester's call alone, and it **cancels the booking**: the proposal replaced the time that was asked for, so there is nothing left to fall back to — book another slot instead. The slot frees up, and the original request stays readable as `cancelled` with the refused proposal still on it. Declining is a cancel, so it answers to the same deadline: `409` once the meeting's effective window has started. |
1136-| GET | `/attendance/me` | student | The current user's attendance report: event tallies, lesson roll-call tallies, and a per-course breakdown with attendance rates. |
1137-| GET | `/attendance/{user}` | teacher | Any user's attendance report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every course; a teacher sees the event tallies plus only the roll-call blocks of the target's courses they manage. |
1166+| GET | `/attendance/me` | student | The current user's attendance report: event tallies, lesson roll-call tallies, a per-instance breakdown with attendance rates, and the per-dönem devamsızlık. |
1167+| GET | `/attendance/{user}` | teacher | Any user's attendance report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every instance; a teacher sees the event tallies plus only the roll-call blocks — and the devamsızlık days — of the instances they run. |
11381168 | POST | `/auth/login` | no | Log in with username + password — no school. Sets a `session` cookie on success: exactly one active membership enters that school right away (`<slug>.<token>` and the full [`UserResponse`], unchanged for single-school clients), several answer a [`SchoolChoiceResponse`] with a `person.<token>` cookie that `POST /auth/school` binds. |
11391169 | POST | `/auth/logout` | no | Log out: revoke the current session (if any) and clear the cookie. Idempotent — no session required; answers `204` either way. |
11401170 | GET | `/auth/me` | student | Return the currently authenticated user. |
@@ -1175,7 +1205,7 @@ window filtering, before paging; negative values are a `400` naming the field.
11751205 | GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn. The non-SSE fallback for `/stream`, reading the same row — including the projection that presents a long-stale `pending` as `failed`, so the two can never disagree about a turn's state. |
11761206 | GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a single `done` carrying the finished message, or one `error`. The stream closes after `done`/`error` — one stream per turn, not per thread. |
11771207 | GET | `/classes` | teacher | List every class, newest first. Requires teacher+. `?grade=` narrows to one grade label, matched exactly as written — the label a blueprint is keyed by, so this is the read that shows which sections a `POST /classes/blueprints` pump covered (and `?grade=` on its own lists the sections with no grade at all). An unknown label is an empty page, not a `404`. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope whose `total` counts every class under the same filter, not just this page. |
1178-| POST | `/classes` | manager | Create a class. Requires manager+ — a class is school structure, not a teacher's own room. `grade` is a free-text label for the year ("9", "10-A"), `term_id` links the school calendar, `teacher_id` names the homeroom teacher (sınıf öğretmeni, a teacher+ account); all optional. |
1208+| POST | `/classes` | manager | Create a class. Requires manager+ — a class is school structure, not a teacher's own room. `grade` is a free-text label for the year ("9", "10-A"), `year` links the academic year (which is what binds the şube to a karne and to the rollover), `teacher_id` names the homeroom teacher (sınıf öğretmeni, a teacher+ account); all optional. |
11791209 | GET | `/classes/blueprints` | manager | List every grade blueprint, by grade label. Requires manager+. Paged via `?limit=&offset=` (omit `limit` for all of them). |
11801210 | POST | `/classes/blueprints` | manager | Create a grade's course blueprint and stock every class section already at that grade with it. Requires manager+. |
11811211 | GET | `/classes/blueprints/{grade}` | manager | Fetch one grade's blueprint. Requires manager+. |
@@ -1185,17 +1215,17 @@ window filtering, before paging; negative values are a `400` naming the field.
11851215 | GET | `/classes/me` | student | The classes the caller is a member of, newest membership first. Any authenticated role — this is the one class read a student (or a parent, for themselves) can make, since every other `/classes` route is teacher+. Paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope. Staff, who are never class members, simply get an empty page. |
11861216 | GET | `/classes/user/{user}` | teacher | Another user's classes. Requires teacher+, or a parent tied to the target student — the same bar the per-student reports hold, and the same 403 for everyone else (a student reads their own at `GET /classes/me`). |
11871217 | GET | `/classes/{id}` | teacher | Fetch a single class by id. Requires teacher+. |
1188-| PATCH | `/classes/{id}` | manager | Update a class. Requires manager+. Omitted fields keep their value; `grade`, `term_id` and `teacher_id` are nullable, so an explicit `null` clears them. |
1218+| PATCH | `/classes/{id}` | manager | Update a class. Requires manager+. Omitted fields keep their value; `grade`, `year` and `teacher_id` are nullable, so an explicit `null` clears them. |
11891219 | DELETE | `/classes/{id}` | manager | Delete a class. Requires manager+. Refused with a 409 while it still holds students or courses — nothing cascades, because dropping the class silently would leave the enrollments it pumped with nothing left to sweep them. |
11901220 | POST | `/classes/{id}/blueprint` | manager | Stock one class section from its grade's blueprint. Requires manager+ — this writes the roster of every course in the template, which is the office's call, not one course owner's. |
1191-| GET | `/classes/{id}/courses` | teacher | List the courses a class is attached to, newest first, paged via `?limit=&offset=` (omit `limit` for all of them). Requires teacher+. Returns a `{items, total, limit, offset}` envelope. |
1192-| POST | `/classes/{id}/courses` | teacher | Attach a course to a class. Requires teacher+ and management rights **on that course** — attaching writes its roster, so it takes exactly the right enrolling into it does. The class's whole roster is enrolled in one go: a course that cannot hold all of them takes none (409), and students already enrolled by hand keep their own rows. Attaching the same course twice is a 409. |
1193-| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course from a class. Requires teacher+ and management rights on that course, like attaching. The enrollments the class pumped into it are swept — except rows another attached class still claims (re-tagged to it) and rows placed by hand (left standing). A course that was not attached is a 404 — but a course row that is *gone* is not: the link a deleted course left behind detaches (the rights check has nothing left to read, and no roster left to protect), or the class holding it could never be deleted. |
1221+| GET | `/classes/{id}/instances` | teacher | List the instances a class carries — each a catalog course as this section teaches it, with its hours, karne policy and teachers — newest first, paged via `?limit=&offset=` (omit `limit` for all of them). Requires teacher+. Returns a `{items, total, limit, offset}` envelope. `POST /instances/{id}` edits one; this is the read that names them. |
1222+| POST | `/classes/{id}/instances` | teacher | Attach a course to a class: this is what **mints the instance** — the class×course row every exam, session, lesson and roster under this class's course now keys on. Requires teacher+ and catalog rights on that course (its creator, or a manager/admin): attaching writes that course's roster for this section, and the weekly hours and karne policy the instance starts with. The class's whole roster is enrolled in one go, and students already enrolled by hand keep their own rows. Attaching the same course twice is a 409. |
1223+| DELETE | `/classes/{id}/instances/{instance}` | teacher | Detach an instance from a class: the instance and everything the class taught under it — exams (with results, questions and images), homework (with submissions and grades), sessions and roll call, the roster it pumped and its teacher links — are swept, and the uploaded files those rows named are unlinked from disk. Requires teacher+ and catalog rights on the course the instance teaches (its creator, or a manager/admin): this is the inverse of attaching. |
11941224 | GET | `/classes/{id}/members` | teacher | List a class's roster, newest first, paged via `?limit=&offset=` (omit `limit` for the whole roster). Requires teacher+. Returns a `{items, total, limit, offset}` envelope. |
1195-| POST | `/classes/{id}/members` | manager | Put a student in a class. Requires manager+. They are enrolled into every course the class already carries, in one go: a course with no free seat refuses the whole join with a 409 naming it, and a student already enrolled by hand keeps the row they have (no second seat, and it survives their removal from the class). Adding the same student twice is a 409. |
1196-| DELETE | `/classes/{id}/members/{user}` | manager | Take a student out of a class. Requires manager+. The enrollments the class pumped for them are swept with it — except rows another attached class still claims (re-tagged to it) and rows placed by hand (left standing). A student who was not in the class is a 404. |
1197-| GET | `/course-notes` | student | List a course's notes, newest first. Visible to whoever can view the course (its enrolled users, creator, assigned teachers, and managers/admins). Paged via `?limit=&offset=`. |
1198-| POST | `/course-notes` | teacher | Create a note on a course. Requires teacher+ and management rights over the course (its creator, an assigned teacher, or a manager/admin). |
1225+| POST | `/classes/{id}/members` | manager | Put a student in a class. Requires manager+. They are enrolled into every instance the class already carries, in one go, and a student already enrolled by hand keeps the row they have (and it survives their removal from the class). Adding the same student twice is a 409; a student who *left* is added afresh — the roster is a history, and the partial index only holds one live stint per pair. |
1226+| DELETE | `/classes/{id}/members/{user}` | manager | Take a student out of a class. Requires manager+. The enrollments the class pumped for them are swept with it — except rows placed by hand, which are left standing. There is no heir to hand a swept row to: a second section teaching the same course holds its **own** instance, so its roster is its own row and this one is released. A student who was not in the class is a 404. |
1227+| GET | `/course-notes` | student | List a course's notes, newest first. Visible to whoever can view the course (its creator, a manager/admin, or anyone the course reaches). Paged via `?limit=&offset=`. |
1228+| POST | `/course-notes` | teacher | Create a note on a course. Requires teacher+ and catalog rights over the course (its creator or a manager/admin). |
11991229 | GET | `/course-notes/{id}` | student | Fetch a single course note by id. Visible to whoever can view its course. |
12001230 | PATCH | `/course-notes/{id}` | teacher | Update a course note's title and/or content. Omitted fields keep their value. Requires teacher+ and management rights over the course. |
12011231 | DELETE | `/course-notes/{id}` | teacher | Delete a course note, along with its files. Requires teacher+ and management rights over the course. |
@@ -1205,25 +1235,17 @@ window filtering, before paging; negative values are a `400` naming the field.
12051235 | DELETE | `/course-notes/{id}/files/{file_id}` | teacher | Delete a course note file (row first, then its blob). Requires teacher+ and management rights over the course. |
12061236 | GET | `/course-notes/{id}/rag` | student | List a course note's AI outputs, newest first. Visible to whoever can view the course. Paged via `?limit=&offset=`. |
12071237 | DELETE | `/course-notes/{id}/rag/{output_id}` | teacher | Delete one stored AI output. Requires teacher+ and management rights over the course. Dropping an output does not stop the next note or file change from regenerating one. |
1208-| GET | `/courses` | student | List the courses visible to the caller: every course for manager+, otherwise the courses they created plus the ones they're enrolled in. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. |
1209-| POST | `/courses` | teacher | Create a course owned by the current user. Requires the `teacher` role or higher. `kind` picks the flavor — `course` (a regular class, the default), `study` (a supervised study session — etüt), or `club` (a student club — kulüp); all behave identically. `capacity` caps the roster at enroll time (omit for unlimited). |
1210-| GET | `/courses/me` | student | The courses the current user is enrolled in, paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope. |
1211-| GET | `/courses/{id}` | student | Fetch a single course by id. Visible to its enrolled users, and to its creator, its assigned teachers and managers/admins while those accounts are still `teacher`+ — a demoted creator sees it only if they are enrolled, like any other student (see [`can_manage_course`]). |
1212-| PATCH | `/courses/{id}` | teacher | Update a course. Requires teacher+ and course management rights — its creator, a teacher assigned to it, or a manager/admin. Omitted fields keep their value. |
1213-| DELETE | `/courses/{id}` | teacher | Delete a course. Requires teacher+; only its creator or a manager/admin may delete it — an assigned teacher runs the course but does not own it. Refused with a 409 while anyone is still enrolled — empty the roster first, so a course that carries students is never dropped by accident. Once empty, it cascades the course's exams (with their results, questions, answers, and question images), its homework (with submissions, submission files, and grades), its sessions and roll call, and its subjects. It also detaches the course from every class that carried it and strikes its id out of every class blueprint that named it — a template holding a course nothing can resolve is a stocking run that skips it and a `PATCH` that refuses the very list the template already holds. |
1214-| GET | `/courses/{id}/enrollments` | teacher | List a course's roster, paged via `?limit=&offset=` (omit `limit` for the whole roster). Requires teacher+ and course management rights — students see their own courses via `GET /courses/me`. Returns a `{items, total, limit, offset}` envelope. |
1215-| POST | `/courses/{id}/enrollments` | teacher | Enroll a user into a course (idempotent upsert). Requires teacher+ and course management rights. Only students can be enrolled — enrollment is student membership, and it gates sitting exams, being graded, and the class roster, all student-only. A course with a `capacity` refuses new members once the roster is full (someone already enrolled is returned as-is). Enrolling a student a class pumped in takes the row *off* that class — `source` comes back `null` — so a later class sweep can no longer undo a placement made by hand, the mirror of a manual unenroll winning permanently. |
1216-| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll a user from a course. Requires teacher+ and course management rights. Existing exam results are kept (they disappear from the user's marks report until re-enrolled). |
1217-| GET | `/courses/{id}/exams` | student | List a course's exams, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the course's enrolled users, its creator, and managers/admins — but drafts appear only to the course's managers. Returns a `{items, total, limit, offset}` envelope. |
1218-| POST | `/courses/{id}/exams` | teacher | Create an exam inside a course. Requires teacher+ and course management rights; the exam's marks count into the course average with its kind's weight (`GET /settings`). Omit `mode` for an offline-graded exam nobody can sit; `sync`/`async` take a window (async also `duration_ms`), `open` is sittable anytime with an optional per-attempt `duration_ms`. `max_attempts` (default 1, `0` = unlimited) meters retakes and `allow_rejoin` (default `true`) is the exam-room door — both stay editable while the exam runs. Send `draft: true` to keep the exam private while it's still being written: only the course's managers see it, and sitting and grading are blocked until it's published (`PATCH` `draft: false`). |
1219-| GET | `/courses/{id}/homework` | student | List a course's homework, newest first, paged via `?limit=&offset=` (omit `limit` for all of it). Visible to the course's enrolled users, its creator, its assigned teachers, and managers/admins — but a student sees only the homework they are assigned (whole-course ones plus subsets that name them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. |
1220-| POST | `/courses/{id}/homework` | teacher | Assign a homework inside a course. Requires teacher+ and course management rights. The homework is tagged with one of the course's subjects and given a future `due_at`; `assigned` optionally narrows it to a subset of the enrolled students (omit or empty = the whole course). |
1221-| GET | `/courses/{id}/sessions` | student | List a course's lesson sessions, most recent first, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the course's enrolled users, its creator, and managers/admins. Returns a `{items, total, limit, offset}` envelope. |
1222-| POST | `/courses/{id}/sessions` | teacher | Create a lesson session inside a course. Requires teacher+ and course management rights. The session's teacher defaults to the caller. |
1223-| GET | `/courses/{id}/subjects` | student | List a course's subjects in creation order, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the course's enrolled users, its creator, and managers/admins. Returns a `{items, total, limit, offset}` envelope. |
1224-| POST | `/courses/{id}/subjects` | teacher | Create a subject inside a course. Requires teacher+ and course management rights. Subjects are the course's curriculum topics — every exam question must be tagged with one of its course's subjects. |
1225-| POST | `/courses/{id}/teachers` | manager | Assign a teacher to a course (idempotent). Manager+ only — staffing is the office's call, so a course's own creator cannot hand management rights to their peers. The assignee must already hold the `teacher` role or higher; assigning gives them full management of the course (exams, sessions, subjects, roster, grading) but not the power to delete it or change this list. The course's assigned teachers are returned on every course response. |
1226-| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher from a course. Manager+ only. The course itself, its exams, sessions, and roster are untouched — the teacher just loses their management rights over it. A user who was never assigned is a 404. |
1238+| GET | `/courses` | student | List the catalog courses visible to the caller: every course for manager+, otherwise the courses they teach somewhere plus the ones they're enrolled in. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. |
1239+| POST | `/courses` | teacher | Create a catalog course owned by the current user. Requires the `teacher` role or higher. `kind` picks the flavor — `course` (a regular class, the default), `study` (a supervised study session — etüt), or `club` (a student club — kulüp). A catalog row teaches nobody by itself: a şube attaches it into an instance (`POST /classes/{id}/instances`), and a `study`/`club` is joined school-wide (`POST /courses/{id}/members`). |
1240+| GET | `/courses/me` | student | The catalog courses the current user is reached by, paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope. |
1241+| GET | `/courses/{id}` | student | Fetch a single catalog course by id. Visible to the people it reaches — students enrolled in any of its instances, members of the course itself — and to its creator and managers/admins while those accounts are still `teacher`+. |
1242+| PATCH | `/courses/{id}` | teacher | Update a catalog course. Requires teacher+ and catalog rights — its creator, or a manager/admin. Omitted fields keep their value. |
1243+| DELETE | `/courses/{id}` | teacher | Delete a catalog course. Requires teacher+; only its creator or a manager/admin may delete it. Refused with a 409 while the course is still taught anywhere — detach it from every şube (`DELETE /classes/{id}/instances/{instance}`) and remove its individual members first, so a course that carries teaching is never dropped by accident. Once free, it cascades the instances' exams (with their results, questions, answers, and question images), homework (with submissions, submission files, and grades), sessions and roll call, its individual memberships, its subjects, and the teacher links. It also strikes its id out of every class blueprint that named it — a template holding a course nothing can resolve is a stocking run that skips it and a `PATCH` that refuses the very list the template already holds. |
1244+| GET | `/courses/{id}/members` | teacher | List a club/etüt's members, newest first, paged via `?limit=&offset=` (omit `limit` for the whole list). Requires teacher+ and catalog rights. Returns a `{items, total, limit, offset}` envelope. An instance's roster is `GET /instances/{id}/enrollments`. |
1245+| POST | `/courses/{id}/members` | teacher | Add a user to a club or etüt — the **school-scoped** membership tier. Requires teacher+ and catalog rights (its creator, or a manager/admin). Only students can be added, and only to a `study` (etüt) or `club` (kulüp): a regular ders (`kind` `course`) has no school-wide roster — its students come from the şubeler that teach it, and that join is `POST /instances/{id}/enrollments` (400 here). Idempotent: a pair that already holds a membership is returned as-is. |
1246+| DELETE | `/courses/{id}/members/{user}` | teacher | Remove a user from a club or etüt. Requires teacher+ and catalog rights. Existing exam results and badges are untouched — the membership is a door, not a record of what happened inside. A pair holding no membership is a 404. |
1247+| GET | `/courses/{id}/subjects` | student | List a course's subjects in creation order, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to its creator, to managers/admins, and to anyone the course reaches (a student enrolled in one of its instances, or a member of it). Returns a `{items, total, limit, offset}` envelope. |
1248+| POST | `/courses/{id}/subjects` | teacher | Create a subject inside a course. Requires teacher+ and catalog rights (its creator, or a manager/admin). Subjects are the curriculum topics of the *catalog* row — every exam of every instance teaching it tags its questions with one of them. |
12271249 | GET | `/events` | student | List all events, newest first. Paged via `?limit=&offset=` (omit `limit` for every event); returns a `{items, total, limit, offset}` envelope. |
12281250 | POST | `/events` | teacher | Create an event owned by the current user. Requires the `teacher` role or higher. `audience` targets it at a role, a course's enrollment, a class section's roster, or a registration list (filled via `POST /events/{id}/register`); omitted it is school-wide. Everyone still sees every event — the audience is the expected-attendee roster, not a visibility wall. |
12291251 | GET | `/events/{id}` | student | Fetch a single event by id. |
@@ -1235,67 +1257,83 @@ window filtering, before paging; negative values are a `400` naming the field.
12351257 | POST | `/events/{id}/register` | teacher | Put a user on a registration-audience event's signup list. Requires teacher+. `user_id` must name a student — students are placed by staff and never register themselves; omit it to take a seat yourself (staff self-serve, so registering another teacher/manager is refused). Registering the same person twice is a no-op returning the existing seat. The list closes when the event starts (or its ends_at-only deadline passes) and refuses to grow past `capacity`. |
12361258 | 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. |
12371259 | 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). |
1238-| GET | `/exams` | student | List the exams visible to the caller: every exam for manager+, otherwise the exams of the courses they created or are enrolled in — minus other people's drafts (a draft shows only to its course's managers). Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. |
1239-| GET | `/exams/{id}` | student | Fetch a single exam by id. Visible to its course's enrolled users, the course creator, and managers/admins — except drafts, which only the course's managers see (everyone else gets a `404`, as if the exam doesn't exist yet — because it doesn't, officially). |
1240-| PATCH | `/exams/{id}` | teacher | Update an exam. Requires teacher+ and management rights over the exam's course (its creator, or manager/admin). Omitted fields keep their value; an explicit `null` clears a schedule field; the course itself is not updatable. 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. |
1241-| DELETE | `/exams/{id}` | teacher | Delete an exam. Requires teacher+ and management rights over the exam's course (its creator, or manager/admin). Cascades the exam's results, attempts, questions, answers, and question + answer images (blobs included). |
1260+| 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. |
1261+| 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). |
1262+| 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. |
1263+| 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). |
12421264 | 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. |
1243-| POST | `/exams/{id}/attempt` | student | Start, resume, or retake the caller's attempt. Requires the student role (staff run exams, they don't sit them), enrollment in the exam's course, a sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the window to be open. A still-running attempt is returned as-is (`200` instead of `201`), so a reconnecting client gets its original clock back — re-starting never resets the time. Once the latest attempt is submitted or expired, re-posting starts the next sitting (`201`, blank answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it. |
1244-| POST | `/exams/{id}/attempt/answers` | student | Save (or overwrite) one answer in the caller's in-progress attempt. `choice` questions take `selected`; `text` questions take `text`. Requires the student role and enrollment in the exam's course — an unenrollment (or a promotion out of `student`) mid-exam closes the sheet. Rejected once the attempt is submitted or its deadline has passed — the server clock, not the client's, is the judge — and rejected while the student has left the exam room with the rejoin door closed. |
1265+| POST | `/exams/{id}/attempt` | student | Start, resume, or retake the caller's attempt. Requires the student role (staff run exams, they don't sit them), enrollment in the exam's instance, a sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the window to be open. A still-running attempt is returned as-is (`200` instead of `201`), so a reconnecting client gets its original clock back — re-starting never resets the time. Once the latest attempt is submitted or expired, re-posting starts the next sitting (`201`, blank answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it. |
1266+| POST | `/exams/{id}/attempt/answers` | student | Save (or overwrite) one answer in the caller's in-progress attempt. `choice` questions take `selected`; `text` questions take `text`. Requires the student role and enrollment in the exam's instance — an unenrollment (or a promotion out of `student`) mid-exam closes the sheet. Rejected once the attempt is submitted or its deadline has passed — the server clock, not the client's, is the judge — and rejected while the student has left the exam room with the rejoin door closed. |
12451267 | GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes. Same visibility wall as the sitting question view — enrollment plus a started attempt (404 before that). |
12461268 | POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach (or replace) the caller's drawn answer to a question inside their in-progress attempt. `multipart/form-data` with the drawing under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes`. Rides the exact `POST /exams/{id}/attempt/answers` gate chain: the student role, an in-progress attempt, current enrollment, and the rejoin door. |
12471269 | DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's drawn answer to a question. Same writable-attempt gate chain as the upload. |
12481270 | POST | `/exams/{id}/attempt/finish` | student | Submit the caller's attempt. Allowed while the deadline hasn't passed; after it, the attempt is already `expired` (a valid terminal state — the student used their full time) and submitting is a `409`. |
1249-| GET | `/exams/{id}/attempt/questions` | student | The exam's questions as the sitting student sees them: `correct` stripped, their own saved answers embedded — the latest sitting's, since a retake starts from a blank sheet. Requires enrollment in the exam's course (the questions are course content — leaving the course closes them) and an attempt — start one with `POST /exams/{id}/attempt` first (404 until then). Readable in every attempt state, so a submitted student can still review what they wrote. |
1271+| GET | `/exams/{id}/attempt/questions` | student | The exam's questions as the sitting student sees them: `correct` stripped, their own saved answers embedded — the latest sitting's, since a retake starts from a blank sheet. Requires enrollment in the exam's instance (the questions are the instance's content — leaving it closes them) and an attempt — start one with `POST /exams/{id}/attempt` first (404 until then). Readable in every attempt state, so a submitted student can still review what they wrote. |
12501272 | 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") |
1251-| 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 course. |
1252-| 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 course — the `attempt_answers` gate. |
1253-| 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 course. Poll it to keep a monitor up to date. |
1254-| 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 course. Students read questions through `GET /exams/{id}/attempt/questions`. Returns a `{items, total, limit, offset}` envelope. |
1255-| POST | `/exams/{id}/questions` | teacher | Add a question to an exam. Requires teacher+ and management rights over the exam's course. `subject_id` must name one of the course's subjects (`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. |
1256-| 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 course, 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 course's subjects — 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. |
1257-| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question. Requires teacher+ and management rights over the exam's course. Omitted fields keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so a kind switch must bring the matching fields along. `subject_id` re-tags within the course's subjects. Locked once attempts exist. An omitted `subject_id` is filled from the stored row, so any edit here — not just a re-tag — is refused with a `409` when someone else moved the question's subject after the caller read it. |
1258-| DELETE | `/exams/{id}/questions/{qid}` | teacher | Remove a question (and every answer to it). Requires teacher+ and management rights over the exam's course. Locked once attempts exist. |
1273+| 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. |
1274+| 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. |
1275+| 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. |
1276+| 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. |
1277+| 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. |
1278+| 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. |
1279+| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question. Requires teacher+ and management rights over the exam's instance. Omitted fields keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so a kind switch must bring the matching fields along. `subject_id` re-tags within the instance's catalog course. Locked once attempts exist. An omitted `subject_id` is filled from the stored row, so any edit here — not just a re-tag — is refused with a `409` when someone else moved the question's subject after the caller read it. |
1280+| DELETE | `/exams/{id}/questions/{qid}` | teacher | Remove a question (and every answer to it). Requires teacher+ and management rights over the exam's instance. Locked once attempts exist. |
12591281 | GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | One option's picture bytes. Same access wall as the question-image read. |
12601282 | POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach (or replace) one option's picture on a `choice` question — so the options themselves can be images (four map crops, pick the right one). Same form, limits, and rights as the question-image upload; `choice_id` is the `id` carried on that choice, as returned in the question's `choices` (not a position — an unknown id is a `400`). Replacing the question's `choices` list drops all its option pictures — re-upload against the new list. |
1261-| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option's picture. Requires teacher+ and management rights over the exam's course; frozen once attempts exist. |
1262-| GET | `/exams/{id}/questions/{qid}/image` | student | The question's illustration bytes. Course managers read anytime; students through the same wall as the sitting view — enrollment plus a started attempt (404 before that, like the question list itself). |
1263-| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach (or replace) a question's illustration — any question kind may carry one, e.g. the map the prompt asks about. `multipart/form-data` with the image under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes` (settings). Requires teacher+ and management rights over the exam's course; frozen once attempts exist, like every other question edit. |
1264-| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove a question's illustration. Requires teacher+ and management rights over the exam's course; frozen once attempts exist. |
1265-| 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 course, and a template the caller may still see. |
1266-| 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 course. 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. |
1283+| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option's picture. Requires teacher+ and management rights over the exam's instance; frozen once attempts exist. |
1284+| GET | `/exams/{id}/questions/{qid}/image` | student | The question's illustration bytes. Instance managers read anytime; students through the same wall as the sitting view — enrollment plus a started attempt (404 before that, like the question list itself). |
1285+| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach (or replace) a question's illustration — any question kind may carry one, e.g. the map the prompt asks about. `multipart/form-data` with the image under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes` (settings). Requires teacher+ and management rights over the exam's instance; frozen once attempts exist, like every other question edit. |
1286+| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove a question's illustration. Requires teacher+ and management rights over the exam's instance; frozen once attempts exist. |
1287+| 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. |
1288+| 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. |
12671289 | 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). |
1268-| 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 course — students read only their own via `GET /exams/{id}/result`. Returns a `{items, total, limit, offset}` envelope. |
1269-| POST | `/exams/{id}/results` | teacher | Record (or overwrite) a student's mark for an exam. Requires teacher+ and management rights over the exam's course; 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. |
1270-| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result from an exam. Requires teacher+ and management rights over the exam's course. |
1290+| 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. |
1291+| 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. |
1292+| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result from an exam. Requires teacher+ and management rights over the exam's instance. |
12711293 | 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. |
12721294 | 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. |
12731295 | 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. |
12741296 | 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=`. |
1275-| GET | `/exams/{id}/statistics` | teacher | Summary statistics for an exam's graded results. Requires teacher+ and management rights over the exam's course. |
1276-| 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 course. Drives the FE's attempt-by-attempt picker. |
1277-| 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 course. Serves an empty sheet for a seq the student never wrote in. |
1278-| 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 course — the seq-scoped mirror of the grader's latest-sitting drawing read. |
1279-| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full mark history at an exam — every sitting's mark, oldest first (the grade-of-record is the latest). Requires teacher+ and management rights over the exam's course. |
1297+| GET | `/exams/{id}/statistics` | teacher | Summary statistics for an exam's graded results. Requires teacher+ and management rights over the exam's instance. |
1298+| 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. |
1299+| 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. |
1300+| 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. |
1301+| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full mark history at an exam — every sitting's mark, oldest first (the grade-of-record is the latest). Requires teacher+ and management rights over the exam's instance. |
12801302 | GET | `/health` | no | Health probe: the database verdict and the AI bridge, `503` when degraded. |
1281-| GET | `/homework` | student | List the homework across the caller's courses — their "my homework" view — paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every course's homework; a teacher sees the homework of courses they run; a student sees only the homework they are assigned (whole-course ones plus any subset that names them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. |
1282-| GET | `/homework/report/{user}` | teacher | A student's homework report across their enrolled courses, paged via `?limit=&offset=` (omit `limit` for all of it): one row per homework in their audience — submitted/late/missing state plus the grade once one exists. Statuses and marks, never the submitted files (observers get the report, not the bytes). Requires teacher+, or a parent linked to the target student. Managers, admins, and parents see every course; a teacher sees only the target's courses they manage. Returns a `{items, total, limit, offset}` envelope. |
1283-| GET | `/homework/{id}` | student | Fetch a single homework by id. Visible to whoever can view its course (its enrolled users, creator, assigned teachers, and managers/admins). A student the homework is *not* assigned to gets a 404 — the same no-leak an unseen exam draft gets, so a subset assignment never reveals itself to the students left out of it. To a caller without course-management rights the `assigned` subset comes back narrowed to their own id: being named is theirs to know, the rest of the roster is not. |
1284-| PATCH | `/homework/{id}` | teacher | Edit a homework's title, description, due date, subject, or assigned subset. Requires teacher+ and management rights over its course. Omitted fields keep their value; a newly set `due_at` is re-checked against now and a new `subject_id` re-checked against the course. Narrowing `assigned` is refused (409) while it would orphan an existing submission or result. |
1285-| DELETE | `/homework/{id}` | teacher | Delete a homework and everything under it — submissions, their files, and results — then unlink the file blobs from disk. Requires teacher+ and management rights over its course. The cascade is one transaction whose homework-row lock keeps a submission from landing under the homework mid-delete; the blob names are collected inside that transaction, before the rows are wiped, and removed after, so a crash in between strands at worst an unreachable file. |
1303+| GET | `/homework` | student | List the homework across the caller's instances — their "my homework" view — paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every instance's homework; a teacher sees the homework of instances they run; a student sees only the homework they are assigned (whole-roster ones plus any subset that names them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. |
1304+| GET | `/homework/report/{user}` | teacher | A student's homework report across the instances their şube carries, paged via `?limit=&offset=` (omit `limit` for all of it): one row per homework in their audience — submitted/late/missing state plus the grade once one exists. Statuses and marks, never the submitted files (observers get the report, not the bytes). Requires teacher+, or a parent linked to the target student. Managers, admins, and parents see every instance; a teacher sees only the target's instances they manage. Returns a `{items, total, limit, offset}` envelope. |
1305+| GET | `/homework/{id}` | student | Fetch a single homework by id. Visible to whoever can view its instance (its enrolled students, its teachers, its şube's homeroom teacher, and managers/admins). A student the homework is *not* assigned to gets a 404 — the same no-leak an unseen exam draft gets, so a subset assignment never reveals itself to the students left out of it. To a caller without instance-management rights the `assigned` subset comes back narrowed to their own id: being named is theirs to know, the rest of the roster is not. |
1306+| PATCH | `/homework/{id}` | teacher | Edit a homework's title, description, due date, subject, or assigned subset. Requires teacher+ and management rights over its instance. Omitted fields keep their value; a newly set `due_at` is re-checked against now and a new `subject_id` re-checked against the instance's course. Narrowing `assigned` is refused (409) while it would orphan an existing submission or result. |
1307+| DELETE | `/homework/{id}` | teacher | Delete a homework and everything under it — submissions, their files, and results — then unlink the file blobs from disk. Requires teacher+ and management rights over its instance. The cascade is one transaction whose homework-row lock keeps a submission from landing under the homework mid-delete; the blob names are collected inside that transaction, before the rows are wiped, and removed after, so a crash in between strands at worst an unreachable file. |
12861308 | GET | `/homework/{id}/result` | student | The caller's own grade for a homework. Any authenticated user may read their own; `404` while ungraded (or when the homework doesn't exist). This is the one read a student graded `missing` *without* ever submitting has — their submission endpoints 404 while nothing is submitted. |
1287-| POST | `/homework/{id}/results` | teacher | Record (or overwrite) a student's grade for a homework: a status (`done`/`incomplete`/`missing`) plus an optional 0–100 mark. Requires teacher+ and management rights over the homework's course; the target must be a live student, enrolled in the course, and in the homework's audience. Nobody grades themselves. Grading before the due date, or before any submission exists (`missing` for work never handed in), is allowed. A stored grade freezes the student's submission until it is removed. |
1288-| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade from a homework — un-grading, which unfreezes the student's submission and files for further edits. Requires teacher+ and management rights over the homework's course. |
1309+| POST | `/homework/{id}/results` | teacher | Record (or overwrite) a student's grade for a homework: a status (`done`/`incomplete`/`missing`) plus an optional 0–100 mark. Requires teacher+ and management rights over the homework's instance; the target must be a live student, enrolled in the instance, and in the homework's audience. Nobody grades themselves. Grading before the due date, or before any submission exists (`missing` for work never handed in), is allowed. A stored grade freezes the student's submission until it is removed. |
1310+| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade from a homework — un-grading, which unfreezes the student's submission and files for further edits. Requires teacher+ and management rights over the homework's instance. |
12891311 | GET | `/homework/{id}/submission` | student | Read the caller's own submission to a homework: their text, files, the computed late flag, and the grade if one exists. Same visibility gates as submitting (student, enrolled, assigned). `404` until they have submitted. |
1290-| POST | `/homework/{id}/submission` | student | Submit (or re-submit) the caller's own work for a homework: optional text, files added separately. Requires the student role, enrollment in the course, and that the homework is assigned to the caller (a subset it doesn't name 404s, never leaking the assignment). Text replaces the previous text; the first-submit stamp is pinned once and `updated_at` moves to now. `201` on the first submit, `200` on a later edit. Refused (409) once the work is graded — ask the teacher to remove the grade to reopen it. |
1312+| POST | `/homework/{id}/submission` | student | Submit (or re-submit) the caller's own work for a homework: optional text, files added separately. Requires the student role, enrollment in the instance, and that the homework is assigned to the caller (a subset it doesn't name 404s, never leaking the assignment). Text replaces the previous text; the first-submit stamp is pinned once and `updated_at` moves to now. `201` on the first submit, `200` on a later edit. Refused (409) once the work is graded — ask the teacher to remove the grade to reopen it. |
12911313 | DELETE | `/homework/{id}/submission` | student | Withdraw the caller's own submission — its text, its file rows, and their blobs. Same visibility gates as submitting. Refused (409) once the work is graded. The file rows fall in one transaction with the submission (children first); their blob names are collected before the wipe and unlinked after. |
12921314 | POST | `/homework/{id}/submission/files` | student | Attach a file to the caller's own submission. `multipart/form-data` with the bytes under a `file` field (its `filename` required); any content type, at most the school's `max_file_bytes`, up to 10 files per submission. Same visibility gates as submitting. A submission need not exist first — a photo-only homework never types text, so this auto-creates an empty submission to hang the file off (an existing one's text is preserved). Adding a file re-stamps the submission's `updated_at`. Refused (409) once graded, or once the 10-file cap is reached. |
1293-| GET | `/homework/{id}/submission/files/{fid}` | student | Download a submission file's bytes. Two callers, one handler: a student reads their own file (behind the submission gate), or a teacher who manages the homework's course reads any file under it. A parent never reaches here — observers get the report, never the bytes. The file is scoped to the homework in the path, so a managed homework's id can't be used to pull a file from another one. |
1315+| GET | `/homework/{id}/submission/files/{fid}` | student | Download a submission file's bytes. Two callers, one handler: a student reads their own file (behind the submission gate), or a teacher who manages the homework's instance reads any file under it. A parent never reaches here — observers get the report, never the bytes. The file is scoped to the homework in the path, so a managed homework's id can't be used to pull a file from another one. |
12941316 | DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove a file from the caller's own submission — row first, then its blob. Same visibility gates as submitting. Refused (409) once graded. Removing a file re-stamps the submission's `updated_at`. |
1295-| GET | `/homework/{id}/submissions` | teacher | The teacher's roster for a homework, paged via `?limit=&offset=` (omit `limit` for all of it): one row per student in the audience — the assigned subset, or every currently enrolled student for a whole-course homework — plus any student outside it who still owns a submission or grade (an unenrollment or an audience change leaves work behind; it stays visible here, flagged). Each row carries the submission with its files and computed late flag, the grade, a computed `missing`, and a computed `unenrolled`. Requires teacher+ and management rights over the homework's course. Returns a `{items, total, limit, offset}` envelope. |
1317+| GET | `/homework/{id}/submissions` | teacher | The teacher's roster for a homework, paged via `?limit=&offset=` (omit `limit` for all of it): one row per student in the audience — the assigned subset, or every student currently enrolled in the instance when the homework carries none — plus any student outside it who still owns a submission or grade (an unenrollment or an audience change leaves work behind; it stays visible here, flagged). Each row carries the submission with its files and computed late flag, the grade, a computed `missing`, and a computed `unenrolled`. Requires teacher+ and management rights over the homework's instance. Returns a `{items, total, limit, offset}` envelope. |
1318+| GET | `/instances/me` | student | The instances the caller is a live member of, newest first, paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope. The route a student reads to find the courses their section is being taught. |
1319+| GET | `/instances/{id}` | student | Fetch one instance by id. Visible to its enrolled students, its assigned teachers, its şube's homeroom teacher, and managers/admins. |
1320+| PATCH | `/instances/{id}` | teacher | Update one instance's own policy. Requires teacher+ and a right over this instance: manager+, one of its assigned teachers, or its şube's homeroom teacher. Omitted fields keep their value; both are non-clearable. |
1321+| GET | `/instances/{id}/enrollments` | teacher | List this instance's roster, paged via `?limit=&offset=` (omit `limit` for the whole roster). Requires teacher+ and a right over the instance — students see their own instances via `GET /instances/me`. Returns a `{items, total, limit, offset}` envelope. |
1322+| POST | `/instances/{id}/enrollments` | teacher | Enroll a student into this instance (idempotent upsert). Requires teacher+ and a right over the instance. Only students can be enrolled — enrollment is student membership, and it gates sitting exams, being graded, and the roster. The row is hand-placed (`source` `null`), so no şube sweep can take it back. |
1323+| DELETE | `/instances/{id}/enrollments/{user}` | teacher | Unenroll a student from this instance. Requires teacher+ and a right over the instance. Existing exam results are kept (they disappear from the student's marks report until re-enrolled). |
1324+| GET | `/instances/{id}/exams` | student | List one instance's exams, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the instance's enrolled students, its teachers, its şube's homeroom teacher, and managers/admins — but drafts appear only to the instance's managers. Returns a `{items, total, limit, offset}` envelope. |
1325+| POST | `/instances/{id}/exams` | teacher | Create an exam inside one instance. Requires teacher+ and a right over the instance; the exam's marks count into the instance's average with its kind's weight (`GET /settings`) and into the dönem's karne named by `term`. Omit `mode` for an offline-graded exam nobody can sit; `sync`/`async` take a window (async also `duration_ms`), `open` is sittable anytime with an optional per-attempt `duration_ms`. `max_attempts` (default 1, `0` = unlimited) meters retakes and `allow_rejoin` (default `true`) is the exam-room door — both stay editable while the exam runs. Send `draft: true` to keep the exam private while it's still being written: only the instance's managers see it, and sitting and grading are blocked until it's published (`PATCH` `draft: false`). Only a class-delivered course (`kind` `course`) carries exams. |
1326+| GET | `/instances/{id}/homework` | student | List one instance's homework, newest first, paged via `?limit=&offset=` (omit `limit` for all of it). Visible to the instance's enrolled students, its teachers, and managers/admins — but a student sees only the homework they are assigned (whole-roster ones plus subsets that name them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. |
1327+| POST | `/instances/{id}/homework` | teacher | Assign homework inside one instance. Requires teacher+ and a right over the instance. The homework is tagged with one of the catalog course's subjects and given a future `due_at`; `assigned` optionally narrows it to a subset of the enrolled students (omit or empty = the whole roster). |
1328+| GET | `/instances/{id}/sessions` | student | List one instance's lesson sessions, most recent first, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the instance's enrolled students, its teachers, and managers/admins. Returns a `{items, total, limit, offset}` envelope. |
1329+| POST | `/instances/{id}/sessions` | teacher | Create a lesson session inside one instance. Requires teacher+ and a right over the instance. The session's teacher defaults to the caller. |
1330+| POST | `/instances/{id}/teachers` | manager | Assign a teacher to this instance (idempotent). Manager+ only — staffing is the office's call. The assignee must already hold the `teacher` role or higher; the assignment gives them full management of the instance (exams, sessions, homework, roster, grading) but they keep no catalog rights over the course itself. |
1331+| DELETE | `/instances/{id}/teachers/{user}` | manager | Unassign a teacher from this instance. Manager+ only. The instance, its exams, sessions, and roster are untouched — the teacher just loses their management rights over it. A user who was never assigned is a 404. |
12961332 | GET | `/limits` | no | Every fixed validation bound the API enforces. Unauthenticated: the registration and login forms need the username and password bounds before a session exists, and none of these values are secrets — they are the same rules a 400 would spell out. |
1297-| GET | `/marks/me` | student | The current user's mark report: every enrolled course with its graded exams, weighted course averages, and the overall average. |
1298-| GET | `/marks/{user}` | teacher | Any user's mark report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every course; a teacher sees only the target's courses they manage — the rest of the report (other teachers' courses) stays out of reach. |
1333+| GET | `/marks/karne` | student | The current user's karne for one dönem: every instance of their şubeler that counts toward the karne, the `ders_saati`-weighted average across them, and the verdict. An archived dönem serves the snapshot the school froze when it was closed; an open one computes live. |
1334+| GET | `/marks/karne/{user}` | teacher | Any user's karne for one dönem. Requires teacher+, or a parent tied to the target student. A linked parent and manager+ read the whole karne; an exactly-teacher caller sees only the lines of the instances they run, with the dönem average recomputed over those and no verdict (see [`narrow_karne`]). |
1335+| GET | `/marks/me` | student | The current user's mark report: every instance they sit, with its graded exams, weighted instance averages, and the overall average. |
1336+| GET | `/marks/{user}` | teacher | Any user's mark report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every instance; a teacher sees only the target's instances they run — the rest of the report (other sections) stays out of reach. |
12991337 | GET | `/meals/attendance/{user}` | teacher | One student's meal-attendance history, newest mark first. Requires teacher+, or a parent linked to them — the caller's own id always passes, like the balance and ledger reads. Narrow to a date range with `?from=&to=` (inclusive `YYYY-MM-DD` bounds on the menu's day, each held to the same real-calendar-day rule the menu's own date is). Paged via `?limit=&offset=`. |
13001338 | GET | `/meals/balance/me` | student | What the caller owes or has on account, in minor units (negative = owes). |
13011339 | GET | `/meals/balance/{user}` | manager | One student's meal balance. Requires manager+, or a parent link to them — the caller's own id always passes. A teacher gets a `403`: canteen debt is family debt, gated exactly like `/payments`. |
@@ -1378,24 +1416,24 @@ window filtering, before paging; negative values are a `400` naming the field.
13781416 | PATCH | `/schools/{slug}/modules` | builder | Re-sell a school's whole shelf in one call: any mix of modules and packages, in either direction. Every list is optional and an empty body is a no-op. |
13791417 | POST | `/schools/{slug}/modules/{module}` | builder | Sell a school one module. Idempotent: a module it already has is a `200` with the unchanged set. Refused while what the module structurally needs is off — enable those in the same `PATCH` instead. |
13801418 | DELETE | `/schools/{slug}/modules/{module}` | builder | Take one module back. Idempotent, and refused while a module the school still has depends on it — the mirror of the enable direction. |
1381-| GET | `/sessions/{id}` | student | Fetch a single session by id. Visible to its course's enrolled users, the session's teacher, the course's own teachers, and managers/admins. |
1382-| PATCH | `/sessions/{id}` | teacher | Update a session. Requires teacher+ with course-management rights. Omitted fields keep their value; an explicit `null` clears `ends_at`. |
1383-| DELETE | `/sessions/{id}` | teacher | Delete a session and its roll-call rows. Requires teacher+ with course-management rights. |
1384-| GET | `/sessions/{id}/attendance` | teacher | List a session's roll call, paged via `?limit=&offset=` (omit `limit` for the whole roster). Same rights as taking it: the session's teacher or a course manager — students see their own tallies via `GET /attendance/me`. Returns a `{items, total, limit, offset}` envelope. |
1385-| POST | `/sessions/{id}/attendance` | teacher | Record a user's roll-call state for a session. The session's teacher or a course manager marks **enrolled students** (only students attend classes); marking the **session's teacher** requires manager+ (staff presence is management's call, so a teacher can't mark themselves present). Students never self-mark a lesson. |
1386-| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a user's roll-call row from a session. Same rights as marking: session teacher or course manager for students, manager+ for a staff row (any target holding teacher or higher). |
1419+| GET | `/sessions/{id}` | student | Fetch a single session by id. Visible to the instance's enrolled students, the session's own teacher, the instance's teachers, and managers/admins. |
1420+| PATCH | `/sessions/{id}` | teacher | Update a session. Requires teacher+ with instance-management rights. Omitted fields keep their value; an explicit `null` clears `ends_at`. |
1421+| DELETE | `/sessions/{id}` | teacher | Delete a session and its roll-call rows. Requires teacher+ with instance-management rights. |
1422+| GET | `/sessions/{id}/attendance` | teacher | List a session's roll call, paged via `?limit=&offset=` (omit `limit` for the whole roster). Same rights as taking it: the session's teacher or a manager of its instance — students see their own tallies via `GET /attendance/me`. Returns a `{items, total, limit, offset}` envelope. |
1423+| POST | `/sessions/{id}/attendance` | teacher | Record a user's roll-call state for a session. The session's teacher or a manager of its instance marks **enrolled students** (only students attend classes); marking the **session's teacher** requires manager+ (staff presence is management's call, so a teacher can't mark themselves present). Students never self-mark a lesson. |
1424+| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a user's roll-call row from a session. Same rights as marking: the session's teacher or a manager of its instance for students, manager+ for a staff row (any target holding teacher or higher). |
13871425 | GET | `/settings` | student | The school's current policy. Any authenticated user — clients need it to render pickers and grades. Falls back to the built-in defaults until a manager edits it. |
13881426 | PATCH | `/settings` | manager | Update the school's policy. Requires manager+. Omitted fields keep their value; a present field replaces its list wholesale. Existing rows are untouched — a removed exam kind or status lives on in old records; only new writes are held to the new lists. Kind weights, though, apply live: mark reports read them at request time, so editing a weight re-weights every exam of that kind. For that reason a kind whose exams already carry marks cannot be dropped from the list (409) — those marks would silently re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is gone counts with weight 1 but cannot be graded (409) until the kind returns — the other end of the same rule. `max_file_bytes` likewise applies at upload time only — already-stored files keep their size, and the chatbot knobs apply to the next chat request only. `meal_slots` follows the exam-kind rule: a slot a menu was already published for cannot be dropped (409), because the menu snapshotted its name. Slot names must not contain `/ \ ? # %` (400) — a menu's id carries the name into a URL — but a name already on the school's stored list is exempt, so a list written before that rule can still be edited around it. |
1389-| GET | `/subjects/{id}` | student | Fetch a single subject by id. Visible to whoever can view its course: the course's enrolled users, its creator, its assigned teachers, and managers/admins. |
1427+| GET | `/subjects/{id}` | student | Fetch a single subject by id. Visible to whoever can view its course: its creator, a manager/admin, or anyone the course reaches. |
13901428 | PATCH | `/subjects/{id}` | teacher | Update a subject's name or description. Requires teacher+ and management rights over its course. Omitted fields keep their value; the course link is fixed at creation. |
13911429 | DELETE | `/subjects/{id}` | teacher | Delete a subject. Requires teacher+ and management rights over its course. Refused with a 409 while any exam question or homework still references it — re-tag or delete those first, so nothing is left pointing at a subject that no longer exists. |
13921430 | GET | `/swagger` | no | Interactive API docs (Swagger UI) |
13931431 | GET | `/terms` | student | List every term, newest first. Any authenticated user — students need the calendar to make sense of their courses. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. |
1394-| POST | `/terms` | manager | Create an academic term. Requires manager+. Past dates are allowed — terms are calendar structure, not schedules. |
1432+| POST | `/terms` | manager | Create a dönem inside an academic year. Requires manager+. Past dates are allowed — dönemler are calendar structure, not schedules; an *archived* year refuses the new dönem (`409`), because past years take no new structure. |
13951433 | GET | `/terms/{id}` | student | Fetch a single term by id. |
13961434 | PATCH | `/terms/{id}` | manager | Update a term. Requires manager+. Omitted fields keep their value; the merged range must stay ordered. |
1397-| DELETE | `/terms/{id}` | manager | Delete a term. Requires manager+. Refused with a 409 while any course still links to it — unlink those courses (`PATCH /courses/{id}` with `"term_id": null`) or delete them first, so a term is never dropped out from under the calendar its courses hang on. |
1398-| POST | `/terms/{id}/archive` | manager | Archive a term. Requires manager+. An archived term is frozen: it takes no edits, no delete, and no new course or class link. Idempotent — archiving an already-archived term answers `200` with the stamp it already had. |
1435+| DELETE | `/terms/{id}` | manager | Delete a dönem. Requires manager+. Refused with a 409 while anything still hangs off it — an exam filed in it, or a karne frozen for it — so a dönem is never dropped out from under marks that name it; move or delete those first. The dönem's own academic year is untouched (that is `DELETE /academic-years/{id}`, which refuses while a dönem still links it). |
1436+| POST | `/terms/{id}/archive` | manager | Archive a dönem. Requires manager+. Archiving **freezes the karnes**: every student with a roster row under the dönem's year gets a snapshot of their report, and from then on `GET /marks/karne` serves that record instead of recomputing — a mark corrected after the fact no longer rewrites what a family holds. An archived dönem takes no edits and no delete; exams may still be created in it while its *year* is open (the archive is a record, not a wall). Idempotent — archiving an already-archived dönem answers `200` with the stamp it already had and never re-freezes. |
13991437 | POST | `/terms/{id}/unarchive` | manager | Re-open an archived term. Requires manager+. Idempotent the same way as archiving: an already-open term answers `200`. |
14001438 | GET | `/time` | no | Server clock: `{now}` UTC unix-millis, for a frontend to sync against. |
14011439 | GET | `/users` | admin | List every user with their role, newest first. Admin only. Paged: pass `?limit=&offset=` to take a window (omit `limit` for the whole list); the response is a `{items, total, limit, offset}` envelope where `total` counts every user. |
@@ -1431,13 +1469,16 @@ window filtering, before paging; negative values are a `400` naming the field.
14311469 the core four `present | absent | late | excused` always exist, plus whatever
14321470 the school added.
14331471 `kind` must be one of the school's exam kinds (`GET /settings`; defaults:
1434-`homework | quiz | midterm | final | project | oral`). The kind carries the
1435-exam's weight in the course average — an integer `1`–`100` set per **kind** in
1472+`yazili | sozlu | uygulama`). The kind carries the
1473+exam's weight in the instance average — an integer `1`–`100` set per **kind** in
14361474 settings (defaults all `1`), resolved when a report is read; an exam whose
14371475 kind was later removed from settings counts with weight `1`.
1438-A course may carry a `term_id` (`null` = unassigned); on `PATCH
1439-/courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`
1440-clears it.
1476+A course carries **no** term — the calendar hangs off the class instead. The
1477+academic stack is three levels: an **academic year** (`/academic-years`) holds
1478+the terms (`/terms`), and a **class section** names the year it runs in
1479+(`year`), so every instance under it and every exam filed in one of that year's
1480+terms shares one calendar. On `PATCH /classes/{id}`, an omitted `year` keeps the
1481+link and an explicit `null` clears it.
14411482 `role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are
14421483 hyphenated UUIDv7s. `parent` accounts are made by an admin (register as `student`, then
14431484 `PATCH /users/{id}/role`) and observe only the students an admin tied to them
@@ -1503,8 +1544,9 @@ free their own, and a closed list is never rewritten. Pre-existing hand-picked (
15031544 audiences convert on boot: each listed user becomes a signup row credited to
15041545 the event's creator, and the audience becomes an uncapped registration list.
15051546 Reading a child collection of a missing parent (`/events/{id}/attendance`,
1506-`/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`,
1507-`/courses/{id}/sessions`, `/courses/{id}/subjects`, `/courses/{id}/homework`,
1547+`/exams/{id}/results`, `/instances/{id}/enrollments`, `/instances/{id}/exams`,
1548+`/instances/{id}/sessions`, `/instances/{id}/homework`,
1549+`/courses/{id}/subjects`, `/classes/{id}/members`, `/classes/{id}/instances`,
15081550 `/homework/{id}/submissions`, `/sessions/{id}/attendance`) is a `404`, not an
15091551 empty list.
15101552 Personal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same
@@ -2149,13 +2191,17 @@ why grading an exam whose kind has left the list is refused).
21492191
21502192 The kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see "Food program: menus, dishes, bookings & the ledger"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it.
21512193
2152-Academic structure is data too. **Terms** (`/terms`) model whatever calendar
2153-the school runs — semester, trimester, quarter systems are just rows with a
2154-name and a date range. Courses *and classes* may link to one via `term_id` (nullable),
2155-and deleting a term is refused with a `409` while any of them still links to
2156-it — unlink them (`PATCH /courses/{id}` or `PATCH /classes/{id}` with
2157-`"term_id": null`) or delete them first, so the calendar never disappears
2158-under them. Term dates may lie in the past,
2194+Academic structure is data too, in three levels. An **academic year**
2195+(`/academic-years`) carries the school's year — a name, a date range, the
2196+sınıf-geçme policy (`grade_promotions`) the next rollover applies, and, once
2197+you ask for one, `POST /academic-years/{id}/rollover` plants the previous
2198+year's şubeler into it. A **class section** names the year it runs in (`year`),
2199+and **terms** (`/terms`) hang off that year: semester, trimester and quarter
2200+systems are all just rows with a name, a date range and their `year`.
2201+A year refuses deletion with a `409` while any şube or dönem still belongs to
2202+it, and a term refuses it while any exam is filed in it — move or delete those
2203+first, so the calendar never disappears
2204+under the structure. Term dates may lie in the past,
21592205 deliberately: a school adopting the app mid-year backfills its calendar —
21602206 unlike exam/lesson/event times, which reject backdating.
21612207
@@ -2633,7 +2679,9 @@ a new plan instead.
26332679 That freeze is a **counter on the plan row** (`assignment_count`), incremented
26342680 in the *same transaction* as the assignment row it counts, and the edit and the
26352681 delete are single-record conditional writes against it — the same shape as a
2636-term's `course_count`. It used to be a `SELECT` taken before the write, which a
2682+term's `exam_count` (the term's own delete is one `DELETE … WHERE
2683+exam_count = 0 AND NOT EXISTS (SELECT 1 FROM karne_snapshot WHERE term = $1)`,
2684+with the year's reference handed back in the same statement). It used to be a `SELECT` taken before the write, which a
26372685 concurrent assign could land behind, leaving a plan edited *and* assigned, or
26382686 deleted with a live assignment naming it. Now the two contend on one record: an
26392687 assign either freezes the plan first (and the edit or delete is a `409`) or
@@ -3149,8 +3197,8 @@ half-applied refresh.
31493197
31503198 ## Homework
31513199
3152-A course hands out **homework**: `POST /courses/{id}/homework` with a title,
3153-an optional description, a **required subject** (one of the course's own — and
3200+An **instance** hands out **homework**: `POST /instances/{id}/homework` with a title,
3201+an optional description, a **required subject** (one of the instance's course's subjects — and
31543202 the same delete guard questions have: a subject with homework refuses deletion
31553203 with a `409` until the homework is re-tagged via `PATCH /homework/{id}` or
31563204 deleted), and a **required `due_at`** that must not lie in the past (same 60s
@@ -3222,7 +3270,7 @@ grades.
32223270
32233271 ## Lesson sessions, roll call, the work log, pomodoro & attendance reports
32243272
3225-Events cover ad-hoc gatherings; **sessions** are a course's lessons. A session
3273+Events cover ad-hoc gatherings; **sessions** are an instance's lessons. A session
32263274 belongs to a course and carries a `teacher` (defaults to whoever creates it;
32273275 any explicit `teacher_id` must hold teacher+ — a student cannot teach), an
32283276 optional `topic`, a required `starts_at`, and an optional `ends_at` (when both
@@ -3300,135 +3348,167 @@ as the longest run ever held (see "Badges").
33003348
33013349 **Attendance reports** mirror the marks report: `GET /attendance/me` for any
33023350 logged-in user, `GET /attendance/{user}` for teacher+ — narrowed to the
3303-courses the caller manages (manager+ sees every course; event tallies are
3351+instances the caller manages (manager+ sees every instance; event tallies are
33043352 school-wide either way). The report tallies event attendance and lesson roll
3305-call separately, plus a per-course breakdown:
3353+call separately, plus a per-instance breakdown and the per-dönem devamsızlık
3354+counts:
33063355
33073356 ```json
33083357 {
33093358 "user": "01J…",
33103359 "events": { "present": 4, "absent": 1, "late": 0, "excused": 1, "total": 6, "rate": 0.8 },
33113360 "sessions": { "present": 9, "absent": 2, "late": 1, "excused": 0, "total": 12, "rate": 0.8333 },
3312- "courses": [ { "course": { "id": "01J…", "title": "algebra", … }, "counts": { … } } ]
3361+ "courses": [ { "instance": "01J…", "course": { "id": "01J…", "title": "algebra", … }, "counts": { … } } ],
3362+ "devamsizlik": [
3363+ { "term": "01J…", "name": "1. Dönem", "absent_days": 3, "excused_days": 1,
3364+ "unexcused_days": 3,
3365+ "limits": { "max_excused_days": 10, "max_unexcused_days": 20 },
3366+ "over_limit": false }
3367+ ]
33133368 }
33143369 ```
33153370
33163371 `rate = (present + late) / (present + absent + late)`: arriving late still
33173372 counts as attending, and an excused absence counts against no one (`rate` is
3318-`null` when every row is excused, or there are none). Per-course blocks appear
3319-for every course the user has roll-call rows in — attendance is a historical
3373+`null` when every row is excused, or there are none). Per-instance blocks appear
3374+for every instance the user has roll-call rows in — attendance is a historical
33203375 record, so unenrolling hides marks from the marks report but never hides an
33213376 absence.
33223377
3378+**Devamsızlık (the legal absence tally).** The same report carries a
3379+`devamsizlik` block, one entry per **term**: `absent_days` (distinct calendar
3380+days the student has at least one `absent` roll-call row on), `excused_days`
3381+(idem for `excused`), `unexcused_days` (the `absent` count — the two are one
3382+bucket in the schema), the school's `limits`
3383+(`max_excused_absent_days`, `max_unexcused_absent_days`, each `null` when
3384+unset), and `over_limit`. Days are bucketed in the school's **timezone**
3385+(`GET /settings`, `timezone`, default `Europe/Istanbul`), so a 23:30 and a
3386+00:30 lesson are two days or one depending on where the school is — never on
3387+where the server runs. Two absences on one day count once, because veli
3388+excuses and the yönetmelik count days, not lessons. The limits are advisory
3389+here: nothing refuses a roll-call row that pushes a student past them.
3390+
33233391 ## Class sections (şube)
33243392
33253393 A **class section** is the group a school actually teaches in — 9-A, 10-B — and
3326-here it is a bulk-enrollment tool rather than a second kind of membership. Its
3327-row carries a name, an optional free-text `grade` label in the school's own
3328-vocabulary (`"9"`, `"Lise 2"`; `""` means no grade, exactly like omitting it)
3329-and an optional `term_id`; nothing else about a course changes because a class
3330-exists. Schools that run electives or a college-style timetable simply never
3331-create one — individual enrollment is untouched, and classes are a
3332-convenience.
3394+it is the **academic anchor**: a student's membership, the courses it carries,
3395+their exams and their homework all hang off it. Its row carries a name, an
3396+optional free-text `grade` label in the school's own vocabulary (`"9"`,
3397+`"Lise 2"`; `""` means no grade, exactly like omitting it) and the **academic
3398+year** it runs in (`year`, nullable while a section is being prepared). A
3399+section does not teach a course directly: attaching one mints an **instance**
3400+(`/instances`) — its own row, with its own teachers, `ders_saati`, karne weight,
3401+roster, exams, sessions and homework — and two sections that attach the same
3402+course share nothing at all. Schools that run electives or a college-style
3403+timetable simply never create one — individual enrollment and the school-scoped
3404+course membership are untouched, and classes are a convenience.
33333405
33343406 **The homeroom teacher.** A class may also name one — the *sınıf öğretmeni* —
33353407 with `teacher_id` on create or `PATCH`, and it rides back out as a `teacher`
33363408 person block (`null` when there is none, exactly like `grade`; both `null` and
33373409 `""` clear it). The account must exist and hold **teacher, manager or admin**
33383410 (anything else is a `400` naming `teacher_id`, the same shape a non-student
3339-member gets). It is a label and nothing more: it grants no rights over the
3340-class, is not counted, and is not a second teacher assignment — courses keep
3341-their own `teachers` list. A role change that takes the account below `teacher`
3411+member gets). It is a **teaching right**, not a label: the homeroom teacher
3412+manages every **instance** their section carries — its hours and karne weight,
3413+its roster, its exams, sessions, homework and grading — under the same rule an
3414+assigned instance teacher gets (manager+, one of the instance's assigned
3415+teachers, or the section's homeroom teacher). It is not counted as a teacher
3416+assignment of its own and grants nothing on the catalog: instances keep their
3417+own `teachers` list, and editing a section is still manager+. A role change
3418+that takes the account below `teacher`
33423419 clears the column on **every** class it held, in the same sweep that drops
3343-their course assignments, so no section ever lists a demoted account.
3420+their instance assignments, so no section ever lists a demoted account.
33443421
33453422 That sweep runs once, over the rows that exist when it runs — so a demotion
33463423 that lands *between* a request's role check and its write would sweep nothing
33473424 and leave the assignment standing forever. Both writers close it from the other
3348-end: `POST /classes`, `PATCH /classes/{id}` and `POST /courses/{id}/teachers`
3425+end: `POST /classes`, `PATCH /classes/{id}` and `POST /instances/{id}/teachers`
33493426 re-read the account's live role **after** their write and answer `409` if it
33503427 has since dropped below `teacher`, taking the assignment back (a create is
33513428 rolled back whole — no half-made class is left behind). Whichever side is
33523429 second catches it; the ordinary path costs one extra read and no extra write.
33533430
3354-**The pump.** A class holds **members** (students) and **attached courses**,
3355-and owes the product of the two: every member enrolled in every attached
3356-course. So both writes push the same way — attaching a course
3357-(`POST /classes/{id}/courses`) enrolls the whole roster into it, adding a
3358-member (`POST /classes/{id}/members`) enrolls them into every course the class
3431+**The pump.** A class holds **members** (students) and **instances** (the
3432+courses it teaches), and owes the product of the two: every member enrolled in
3433+every instance. So both writes push the same way — attaching a course
3434+(`POST /classes/{id}/instances`, body `{"course_id": …}`) enrolls the whole
3435+roster into the new instance, adding a
3436+member (`POST /classes/{id}/members`) enrolls them into every instance the class
33593437 already carries — and what gets written is an ordinary `enrollment` row, the
3360-same one `POST /courses/{id}/enrollments` writes, counted against the same
3438+same one `POST /instances/{id}/enrollments` writes, counted against the same
33613439 `enrollment_count`. Each row a class writes is tagged with it as the row's
33623440 `source`; **no `source` means placed by hand**, and that one bit is what makes
33633441 the sweeps below safe. It rides back out on every enrollment response
3364-(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a
3442+(`GET /instances/{id}/enrollments`) as the class's id, or `null` for a
33653443 hand-placed row — without it no client could tell which of the roster rows it
33663444 is showing a class change is about to remove.
33673445
3368-**Already enrolled is skipped.** A pair that already has an enrollment row is
3369-left exactly as it stands — no second seat charged, no `source` rewritten. A
3446+**Already enrolled is skipped.** An (instance, student) pair that already has
3447+an enrollment row is
3448+left exactly as it stands — no second row, no `source` rewritten. A
33703449 student a teacher enrolled by hand *stays* hand-placed when the class later
33713450 attaches that course, so the class never quietly adopts someone else's roster
33723451 decision.
33733452
3374-**Capacity is all-or-nothing.** Attaching a course, or adding a member, claims
3375-one seat per pair that needs a new row, each against its own course's
3376-`capacity` — and if any single course has no room the whole call is a `409`
3377-naming it (`course:<key> is full, so the class cannot take this student`,
3378-`course:<key> cannot hold the whole class`). Nothing lands, not even the seats
3379-claimed earlier in the same run: a half-enrolled class is worse than a refused
3380-one, and the refusal names the course whose capacity to raise.
3381-
3382-A second `409` reads off the same claim and is deliberately told apart from it:
3383-one of the class's attached courses **no longer exists**
3384-(`course:<key> no longer exists — detach it from this class first`). A seat
3385-claim that matches nothing means "full" *or* "no such row", and reporting a
3386-stale attachment as a full course would send staff off to raise a capacity that
3387-is not there — on a class every member-add now fails on. Detach the link and
3388-the class works again.
3389-
3390-**Removals take back only what the class pumped, and repair before they
3391-delete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or
3392-detaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the
3453+**A link to a course that no longer exists blocks the pump.** Adding a member
3454+walks every instance the class carries, and one of them may point at a course
3455+row that is gone: the call is a `409` and names it
3456+(`course:<key> no longer exists — detach it from this class first`, code
3457+`linked_course_missing`). Reporting it as anything else would send staff off to
3458+raise a cap that does not exist — on a class every member-add now fails on.
3459+Detach the link and the class works again.
3460+
3461+**Removing a member ends the stint; the row stays.** `DELETE
3462+/classes/{id}/members/{user}` is a **soft leave**: it stamps `left_at`, gives
3463+the class its seat back (the counter counts live members only), and sweeps the
3464+instance enrollments the class pumped for that student. The history is not
3465+erased — a second `POST /classes/{id}/members` inserts a **fresh** row for the
3466+same pair (the live-pair index is partial, so both can exist), and
3467+`class_member_count` never exceeds the live rows. Removing the wrong student
3468+from a class mid-year is therefore something the product can undo without
3469+losing who was there when.
3470+
3471+**Removals take back only what the class pumped.** A leave, or detaching an
3472+instance (`DELETE /classes/{id}/instances/{instance}`) sweeps the
33933473 enrollment rows whose `source` is *this* class and no others — hand-placed
3394-rows survive every class operation. Even a tagged row is not automatically
3395-deleted: if a **second class** still claims that pair (it holds the same
3396-student *and* that course attached), the row is re-tagged to that class
3397-instead, because the row it skipped writing is the row now being swept and the
3398-student is still owed the seat. The heir is the lowest class id among the
3399-claimants, so repeating a sweep lands on the same class. Only a row nobody is
3400-left to claim is deleted and its seat handed back. Sweeps also tolerate rows
3401-that are already gone — deleting a course wipes its enrollments wholesale
3474+rows survive every class operation, and every swept row's seat is handed back
3475+to its instance's counter. There is no heir to consider: a second section
3476+teaching the same course holds its **own** instance and therefore its own
3477+roster row, so this class's row is released outright. Sweeps also tolerate rows
3478+that are already gone — deleting a course or detaching an instance wipes its
3479+enrollments wholesale
34023480 while the class memberships survive — so "this class has a member" and "that
34033481 member holds a pumped row" are independent facts.
34043482
3405-**A manual unenroll wins, permanently.** `DELETE /courses/{id}/enrollments/{user}`
3483+**A manual unenroll wins, permanently.** `DELETE /instances/{id}/enrollments/{user}`
34063484 on a pumped student is allowed and sticks: nothing re-pumps them while they
34073485 remain a member, because the pump runs on writes, never on a schedule. Staff
34083486 put them back by enrolling them by hand (which makes the row hand-placed) or
34093487 by detaching and re-attaching the course.
34103488
3411-**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments`
3489+**And a manual enroll wins too, permanently.** `POST /instances/{id}/enrollments`
34123490 landing on a row a class pumped takes the row *off* that class — its `source`
34133491 is cleared, the response comes back with `"source": null` — so no later class
34143492 sweep can undo a placement an operator made on purpose. That is the mirror of
34153493 the rule above: hand-placed beats pumped in both directions, and without it
34163494 "hand-placed" was a state only a *first* enroll could ever reach.
34173495
3418-**Delete guards.** A class still holding members or attached courses refuses
3419-deletion with a `409` ("remove its members and detach its courses first") —
3496+**Delete guards.** A class still holding live members or instances refuses
3497+deletion with a `409` ("remove its members and detach its instances first") —
34203498 the roster it owes is never dropped out from under the courses silently. A
3421-term linked by any class refuses deletion the same way courses make it refuse.
3422-Deleting a **course** detaches it from every class it was on (its enrollments
3423-go with it), and a role change that takes a user off `student` drops their
3499+**term** carrying exams refuses deletion, and an **academic year** refuses while
3500+any class or term still belongs to it: the calendar never disappears under the
3501+structure. Deleting a **course** detaches it from every class it was on (its
3502+instances and their enrollments go with it, and the files those rows held are
3503+unlinked), and a role change that takes a user off `student` drops their
34243504 class memberships exactly as it drops their enrollments — in one transaction,
3425-because a membership left behind would keep pumping them back into courses,
3505+because a membership left behind would keep pumping them back into instances,
34263506 while an enrollment left behind would stay tagged with a class the released
34273507 counters had already made deletable, and nothing could ever sweep it again.
34283508
34293509 **A link to a deleted course detaches instead of refusing.** Should a
34303510 `class_course` row ever be left pointing at a course row that is gone,
3431-`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights
3511+`DELETE /classes/{id}/instances/{instance}` still answers `204`: management rights
34323512 are read *off* the course, so a stale link had no readable owner and the detach
34333513 used to `404` forever — which also left the class permanently undeletable, its
34343514 attachment counter counting a row nothing could sweep. There is no roster left
@@ -3436,11 +3516,13 @@ to protect, and the caller is already teacher+.
34363516
34373517 **Who may.** Creating, editing and deleting a class, and adding or removing
34383518 its members, is **manager+** — a class is school structure, not classroom
3439-work. Attaching or detaching a course takes management rights on **that
3440-course** (its creator, a teacher assigned to it, or manager+), since the call
3441-writes that course's roster and nothing else: the same right enrolling one
3442-student takes. Every read (`GET /classes`, `/classes/{id}`, its members and
3443-its courses, all paged, newest first) is **teacher+** — and "newest" here means
3519+work. Attaching or detaching a course takes catalog rights on **that
3520+course** (its creator, or manager+), since the call writes that course's roster
3521+for this section and nothing else. Editing an instance's own policy
3522+(`PATCH /instances/{id}`) and its roster take instance rights (manager+, an
3523+assigned teacher, or the section's homeroom teacher). Every read
3524+(`GET /classes`, `/classes/{id}`, its members and its instances, all paged,
3525+newest first) is **teacher+** — and "newest" here means
34443526 when the student was *added* or the course *attached*, not the student's or the
34453527 course's own id, which is what a link row keyed on the pair would otherwise
34463528 sort by. Rows written before that stamp existed carry none, and sort last.
@@ -3501,8 +3583,9 @@ grade's template — idempotent, so it is safe on a class that already carries
35013583 some of the courses.
35023584
35033585 The blueprint is a template, not a new kind of membership. Applying it calls
3504-the same attach a manager's own `POST /classes/{id}/courses` does, so what
3505-lands is ordinary `class_course` links and ordinary `enrollment` rows, and an
3586+the same attach a manager's own `POST /classes/{id}/instances` does, so what
3587+lands is ordinary `class_course` **instances** and the ordinary `enrollment`
3588+rows each implies, and an
35063589 elective a student takes alone stays an individual enrollment nothing here can
35073590 see.
35083591
@@ -3626,8 +3709,8 @@ so the skip is reported once for the whole grade — the sections after the firs
36263709 one are not asked again — and never again on a later pump),
36273710 `class_at_course_ceiling`, `class_roster_too_large`
36283711 (the section holds more students than one attach may enroll at once),
3629-`course_full` (no free
3630-seat for the whole section), and
3712+`linked_course_missing` (an instance the section already carries points at a
3713+course that no longer exists), and
36313714 `blueprint_deleted` (the template itself was deleted while the pump ran —
36323715 nothing was attached, and there is nothing left to retry). That last one **ends
36333716 the run**: it says nothing about the (section, course) pair it names, so every
@@ -3641,8 +3724,8 @@ code out of:
36413724
36423725 | route | codes |
36433726 | --- | --- |
3644-| `POST /classes/{id}/courses` | `duplicate`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full` |
3645-| `POST /classes/{id}/members` | `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full`, `linked_course_missing` |
3727+| `POST /classes/{id}/instances` | `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` |
3728+| `POST /classes/{id}/members` | `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `linked_course_missing` |
36463729
36473730 The three *deleted* codes are a pump's alone: on a manual attach a deleted class
36483731 or course is a `404`, and `blueprint_deleted` needs a blueprint nobody handed
@@ -3662,14 +3745,18 @@ pump, which only ever attaches courses, reports that second pair. One cause
36623745 therefore reads the same whether a manager hit it by hand or a pump hit it in
36633746 bulk, which is what lets a bilingual client branch and word it once. `code` is
36643747 published on those two routes only and is simply **absent** from every other
3665-error body.
3748+error body — with one addition since the instance model: `linked_course_missing`,
3749+which only a member add can meet, is published on that route.
36663750
3667-**Removal spares what a human placed.** Every attachment a blueprint makes is
3751+**Removal spares what a human placed.** Every instance a blueprint mints is
36683752 tagged with it. Dropping a course from the list detaches it only where the
3669-blueprint attached it (sweeping the enrollments it pumped, repairing to a rival
3670-class first exactly as a manual detach does), and a course a human attached to
3753+blueprint attached it — sweeping the enrollments it pumped, repairing to a rival
3754+class first exactly as a manual detach does, and **unlinking the files** the
3755+detached instances' exams, homework and submissions held (the sweep returns
3756+their blob keys, and the route unlinks them the way a manual detach does) — and
3757+a course a human attached to
36713758 that class by hand carries no tag and is left exactly where it is. Deleting a
3672-blueprint applies that to its whole list.
3759+blueprint applies that to its whole list, and unlinks those files too.
36733760
36743761 **Deleting the course itself takes it out of every template naming it**, in the
36753762 same transaction that detaches it from the sections. A template holds its
@@ -3687,7 +3774,8 @@ and pumps it while the delete runs would otherwise leave rows tagged with a
36873774 blueprint that no longer exists, and since the grade label *is* the record id,
36883775 nothing could ever reach them again. The pump carries the other half of that —
36893776 an attach whose blueprint was deleted mid-run writes nothing and is reported as
3690-`blueprint_deleted`. The attach's in-transaction claim is a `FOR KEY SHARE`
3777+`blueprint_deleted`. The delete returns the swept subtree's blob keys and the
3778+route unlinks them. The attach's in-transaction claim is a `FOR KEY SHARE`
36913779 row lock on `class_blueprint` — the one strength a `DELETE` of the row
36923780 cannot take — so a sourced attach that started first holds the row and the
36933781 delete waits behind it; an attach starting after the delete finds no row
@@ -3699,9 +3787,12 @@ recreated at the same grade with the same list satisfies that comparison, which
36993787 is accepted, since the end state is the one the caller asked for. The remaining
37003788 cost is a **process crash** between the delete and its sweep, which no lock
37013789 survives: it leaves inert tagged attachments behind, still detachable one at a
3702-time at `DELETE /classes/{id}/courses/{course}`, with every counter exact.
3790+time at `DELETE /classes/{id}/instances/{instance}`, with every counter exact —
3791+the crash window's files outlive their rows, which is the one leak the model
3792+cannot close from here.
37033793
3704-A blueprint names no term — the class names its own. The grade label is the
3794+A blueprint names no year — the class names its own, and the year is what the
3795+exam calendar hangs off. The grade label is the
37053796 blueprint's id, so there is one per grade (a second is a `409`), and it must be
37063797 non-empty and contain none of `/ \ ? # %`.
37073798
@@ -3742,27 +3833,50 @@ curl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json'
37423833 -d '{"status":"present"}'
37433834 curl -s -b $JAR $BASE/events/$EV/attendance
37443835
3745-# courses + weighted marks (as a teacher)
3746-# optional, manager+: weigh midterms triple — school policy, per kind
3747-curl -s -b $JAR -X PATCH $BASE/settings -H 'content-type: application/json' \
3748- -d '{"exam_kinds":[{"name":"midterm","weight":3},{"name":"quiz","weight":1}]}'
3836+# the academic calendar: a year, then a term inside it (manager+)
3837+YR=$(curl -s -b $JAR $BASE/academic-years -H 'content-type: application/json' \
3838+ -d '{"name":"2026-2027","starts_at":1788000000000,"ends_at":1811000000000}' \
3839+ | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
3840+TE=$(curl -s -b $JAR $BASE/terms -H 'content-type: application/json' \
3841+ -d '{"name":"1. Dönem","year":"'$YR'","starts_at":1788000000000,"ends_at":1794000000000}' \
3842+ | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
3843+
3844+# the class section: the academic anchor, in that year. Naming yourself as the
3845+# homeroom teacher is what gives this teacher rights over its instances (D10) —
3846+# a manager could assign an instance teacher afterwards instead.
3847+ME=$(curl -s -b $JAR $BASE/users/me | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
3848+CL=$(curl -s -b $JAR $BASE/classes -H 'content-type: application/json' \
3849+ -d '{"name":"9-A","grade":"9","year":"'$YR'","teacher_id":"'$ME'"}' \
3850+ | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
3851+
3852+# the catalog course, then the instance this section teaches it in
3853+CO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \
3854+ -d '{"title":"Matematik"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
3855+IN=$(curl -s -b $JAR $BASE/classes/$CL/instances -H 'content-type: application/json' \
3856+ -d '{"course_id":"'$CO'"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
3857+curl -s -b $JAR $BASE/instances/$IN # hours, karne weight, teachers
3858+
3859+# roster: adding a member to the section enrolls them into $IN (the pump);
3860+# a teacher can also enroll one student by hand
37493861 # find the student to enroll (here: a registered user "veli"): fragment
37503862 # search over username/name, role-narrowed (teacher+)
37513863 SID=$(curl -s -b $JAR "$BASE/users/search?q=vel&role=student" \
37523864 | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
3753-CO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \
3754- -d '{"title":"algebra"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
3755-curl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \
3865+curl -s -b $JAR $BASE/classes/$CL/members -H 'content-type: application/json' \
37563866 -d "{\"user_id\":\"$SID\"}"
3757-EX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \
3758- -d '{"title":"midterm","kind":"midterm"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
3867+curl -s -b $JAR $BASE/instances/$IN/enrollments # lists the pumped row
3868+
3869+# exams live on the instance and are filed in a dönem; weighted marks
3870+EX=$(curl -s -b $JAR $BASE/instances/$IN/exams -H 'content-type: application/json' \
3871+ -d '{"title":"1. Yazılı","kind":"yazili","term":"'$TE'"}' \
3872+ | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
37593873 curl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \
37603874 -d "{\"mark\":90,\"user_id\":\"$SID\"}"
37613875 curl -s -b $JAR $BASE/exams/$EX/statistics
37623876
3763-# lesson sessions + roll call (course manager creates; the session's teacher
3764-# or a course manager marks enrolled students)
3765-SE=$(curl -s -b $JAR $BASE/courses/$CO/sessions -H 'content-type: application/json' \
3877+# lesson sessions + roll call (instance teacher creates; the session's teacher
3878+# or an instance manager marks the enrolled students)
3879+SE=$(curl -s -b $JAR $BASE/instances/$IN/sessions -H 'content-type: application/json' \
37663880 -d '{"topic":"limits","starts_at":1900000000000}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
37673881 curl -s -b $JAR $BASE/sessions/$SE/attendance -H 'content-type: application/json' \
37683882 -d "{\"status\":\"present\",\"user_id\":\"$SID\"}"
@@ -3773,7 +3887,9 @@ curl -s -b $JAR -X POST $BASE/work/check-out
37733887 curl -s -b $JAR $BASE/work/me
37743888
37753889 # ...and as the student:
3890+curl -s -b $STUDENT_JAR $BASE/instances/me # the sections' instances
37763891 curl -s -b $STUDENT_JAR $BASE/marks/me
3892+curl -s -b $STUDENT_JAR "$BASE/marks/karne?term=$TE" # the report card
37773893 curl -s -b $STUDENT_JAR $BASE/attendance/me
37783894 # pomodoro: start when the timer starts, finish when it rings
37793895 curl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/start
@@ -4438,8 +4554,9 @@ which half of a class gets to draw.
44384554
44394555 **Inviting a group discloses that group.** A board's roster is visible to every
44404556 participant, so each source carries the gate its own listing route carries —
4441-teacher+ for a class (`GET /classes/{id}/members`), the course's creator, an
4442-assigned teacher or a manager+ for a course (`GET /courses/{id}/enrollments`),
4557+teacher+ for a class (`GET /classes/{id}/members`), a manager+, one of the
4558+instance's assigned teachers or its class's homeroom teacher for an instance
4559+(`GET /instances/{id}/enrollments`),
44434560 teacher+ for an event (`GET /events/{id}/roster`). A student may still build a
44444561 board one id at a time; they cannot pour a class roster into one. A source that
44454562 does not exist is a `400` naming the field, never a `404` — on these routes a
@@ -4657,11 +4774,14 @@ database itself decides the winner. Three tiers:
46574774 `INSERT … SELECT … WHERE EXISTS` behind a real `FOREIGN KEY` (the
46584775 existence proofs), the CTE recipes in `db::cap`. Used where
46594776 the rule reads the row being written (state machines, delete guards).
4660- "Is anything still attached?" is answered the same way, by a counter on the
4777+ "Is anything still attached?" is answered the same way, by counters on the
46614778 row being deleted rather than a `SELECT` over the children: a course is
4662- deletable while its `enrollment_count` is zero, a term while its
4663- `course_count` is (courses claim that reference *before* they write the
4664- link, and give it back when the link moves or the course is deleted). A fee
4779+ deletable while its `class_course_count` **and** `course_membership_count`
4780+ are zero (a şube attach or a club/etüt join claims that reference *before* it
4781+ writes the link, and gives it back when the link moves or is deleted), and a
4782+ term while its `exam_count` is zero and no `karne_snapshot` names it — the
4783+ count is the fast path, the snapshot `NOT EXISTS` is the record a `DELETE`
4784+ must not take with it. A fee
46654785 plan reads the same way — editable *and* deletable while its
46664786 `assignment_count` is zero, and frozen for good once it is not, since an
46674787 assignment is never taken back.
@@ -4776,17 +4896,25 @@ src/
47764896 disk under FILES_PATH; FileName/FileContentType shared with note_file.rs)
47774897 rag_output.rs RagOutputId · RagOutput (what an AI service produced for a
47784898 course note; derived, disposable, cascaded from note and file)
4779- course_session.rs CourseSessionId · SessionTopic · CourseSession (a course's lesson)
4899+ course_session.rs CourseSessionId · SessionTopic · CourseSession (an instance's lesson)
47804900 session_attendance.rs SessionAttendanceId · SessionAttendance (roll call; one row per session+user)
47814901 work_entry.rs WorkEntryId · WorkEntry (staff stint; one open per user by construction)
4782- enrollment.rs EnrollmentId · Enrollment (one row per course+user; `source`
4902+ enrollment.rs EnrollmentId · Enrollment (one row per instance+student; `source`
47834903 names the class that pumped it, absent when hand-placed)
4784- class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a class section;
4785- deletable only with no members and no attached courses)
4786- class_member.rs ClassMember (one student in a class; adding them enrolls
4787- them into every course the class holds)
4788- class_course.rs ClassCourse (one course on a class; attaching it enrolls
4789- the class's whole roster)
4904+ course_membership.rs CourseMembershipId · CourseMembership (one row per
4905+ catalog course+user: the club/etüt join a student makes alone)
4906+ academic_year.rs AcademicYearId · GradePromotion · AcademicYear (the school
4907+ year: its terms, its sınıf geçme policy, its rollover)
4908+ class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a class
4909+ section; belongs to an academic year; deletable only with no
4910+ live members and no instances)
4911+ class_member.rs ClassMemberId · ClassMember (one student's stint in a class;
4912+ `left_at` ends it — the row stays, the seat comes back, and a
4913+ re-add is a fresh row)
4914+ class_course.rs ClassCourseId · DersSaati · ClassCourse (the **instance**:
4915+ one course as one class teaches it — hours, karne weight,
4916+ teachers, roster, and the key every exam/session/homework
4917+ under it carries)
47904918 class_blueprint.rs ClassBlueprintId · ClassBlueprint (a grade's course list;
47914919 applying it stocks every section at that grade, best-effort)
47924920 class_pump.rs attach/detach (the shared transaction behind both of those:
@@ -4869,7 +4997,7 @@ src/
48694997 solution.rs SolutionId · SolutionBody · Solution (discussion thread on an
48704998 approved pool question; dies with the question)
48714999 homework.rs HomeworkId · HomeworkTitle · HomeworkDescription · Homework
4872- (per-course assignment; required subject; optional `assigned`
5000+ (per-instance assignment; required subject; optional `assigned`
48735001 student subset — absent/empty = the whole enrolled course)
48745002 homework_submission.rs HomeworkSubmissionId · SubmissionText ·
48755003 HomeworkSubmission (one row per homework+user; immutable
@@ -4914,7 +5042,7 @@ src/
49145042 images.rs · review.rs (prior sittings)
49155043 bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs
49165044 settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs
4917- boards.rs classes.rs
5045+ boards.rs classes.rs instances.rs academic_years.rs
49185046 limits.rs GET /limits: every constant.rs bound served as JSON
49195047 ```
49205048
migrations/school/20260916000001_k12_remodel.sqladded+457 -0
@@ -0,0 +1,457 @@
1+-- School-database schema, part 5: the Turkish-K12 remodel — the class×course
2+-- *instance* (`class_course`) becomes the academic anchor.
3+--
4+-- Before this migration `course` was a school-wide singleton and every
5+-- downstream row keyed off it (`enrollment (course, app_user)`,
6+-- `exam.course`, `course_session.course`, `session_attendance.course`,
7+-- `homework.course`), while `class_course` was a hollow join carrying only
8+-- (`class`, `course`, `attached_by`, `source`). Two şubeler attaching the
9+-- same course therefore shared one roster, one exam set and one timetable.
10+--
11+-- After it: `class_course` is the instance (it carries the teachers, the
12+-- weekly `ders_saati` and the karne weight), exams/sessions/roll-call/
13+-- homework/enrollment re-key onto it, a şube belongs to an `academic_year`
14+-- (a dönem is a grading slice inside the year), and `course` is a pure
15+-- catalog.
16+--
17+-- Compatibility is waived (pre-customer): the identity-changing tables below
18+-- are dropped and recreated empty rather than backfilled, which keeps every
19+-- refcount seeded in this file consistent at 0. The drop list therefore also
20+-- includes the tables that merely *reference* a dropped one (bank_question,
21+-- question_image, answer_image, homework_assignment) so their foreign keys
22+-- are recreated instead of silently lost to CASCADE.
23+--
24+-- Same translation rules as parts 1-4: entity ids are app-minted UUID v7 (no
25+-- DB default), timestamps stay BIGINT unix-ms, counter columns are BIGINT
26+-- NOT NULL DEFAULT 0 and stay out of the Rust structs, all FKs ON DELETE NO
27+-- ACTION.
28+
29+-- ---------------------------------------------------------------------------
30+-- 1. Academic year, above Term.
31+-- ---------------------------------------------------------------------------
32+CREATE TABLE academic_year (
33+ id uuid PRIMARY KEY,
34+ name TEXT NOT NULL CONSTRAINT academic_year_name_key UNIQUE,
35+ starts_at BIGINT NOT NULL,
36+ ends_at BIGINT NOT NULL,
37+ archived_at BIGINT NULL,
38+ creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
39+ -- Sınıf geçme policy: [{from_grade, to_grade}, …]. A grade absent from
40+ -- this list is not rolled over — that is how graduation is expressed.
41+ grade_promotions JSONB NOT NULL DEFAULT '[]',
42+ class_count BIGINT NOT NULL DEFAULT 0,
43+ term_count BIGINT NOT NULL DEFAULT 0
44+);
45+
46+-- ---------------------------------------------------------------------------
47+-- 2. Backfill one default year, bind term to it, move the class counter and
48+-- drop the term's course counter (course.term is removed in §6).
49+-- ---------------------------------------------------------------------------
50+-- Only on a database that already has terms: a fresh one needs no synthetic
51+-- year, and `creator` is NOT NULL so the row needs a real app_user to name.
52+INSERT INTO academic_year (id, name, starts_at, ends_at, creator, grade_promotions)
53+SELECT '00000000-0000-0000-0000-000000000001', 'Varsayılan Eğitim Yılı',
54+ COALESCE((SELECT min(starts_at) FROM term), 0),
55+ COALESCE((SELECT max(ends_at) FROM term), 0),
56+ (SELECT id FROM app_user ORDER BY created_at LIMIT 1),
57+ '[]'
58+WHERE EXISTS (SELECT 1 FROM term);
59+
60+ALTER TABLE term ADD COLUMN year uuid REFERENCES academic_year(id) ON DELETE NO ACTION;
61+UPDATE term SET year = '00000000-0000-0000-0000-000000000001';
62+ALTER TABLE term ALTER COLUMN year SET NOT NULL;
63+
64+-- The term now tracks how many exams sit in it; the class counter moves to
65+-- the academic year (§3) and the course counter had no referent.
66+ALTER TABLE term ADD COLUMN exam_count BIGINT NOT NULL DEFAULT 0;
67+ALTER TABLE term DROP COLUMN course_count;
68+ALTER TABLE term DROP COLUMN class_count;
69+
70+UPDATE academic_year SET term_count = (SELECT count(*) FROM term);
71+
72+-- ---------------------------------------------------------------------------
73+-- 3. Şube belongs to the year, not to a term.
74+-- ---------------------------------------------------------------------------
75+ALTER TABLE class_group ADD COLUMN year uuid REFERENCES academic_year(id) ON DELETE NO ACTION;
76+UPDATE class_group c SET year = t.year FROM term t WHERE t.id = c.term;
77+ALTER TABLE class_group DROP COLUMN term;
78+
79+UPDATE academic_year SET class_count = (SELECT count(*) FROM class_group WHERE year = academic_year.id);
80+
81+-- ---------------------------------------------------------------------------
82+-- 4. course is a pure catalog: no capacity, no seat count, no term.
83+-- ---------------------------------------------------------------------------
84+ALTER TABLE course DROP COLUMN capacity;
85+ALTER TABLE course DROP COLUMN enrollment_count;
86+ALTER TABLE course DROP COLUMN term;
87+ALTER TABLE course ADD COLUMN class_course_count BIGINT NOT NULL DEFAULT 0;
88+ALTER TABLE course ADD COLUMN course_membership_count BIGINT NOT NULL DEFAULT 0;
89+
90+-- ---------------------------------------------------------------------------
91+-- 5. Drop the identity-changing tables (and every table that references one),
92+-- then recreate them empty against the instance key.
93+-- ---------------------------------------------------------------------------
94+DROP TABLE IF EXISTS
95+ exam_audience,
96+ exam_answer,
97+ answer_image,
98+ exam_attempt,
99+ exam_result,
100+ question_image,
101+ exam_question,
102+ bank_question_image,
103+ bank_question,
104+ exam,
105+ homework_assignment,
106+ homework_file,
107+ homework_submission,
108+ homework_result,
109+ homework,
110+ session_attendance,
111+ course_session,
112+ enrollment,
113+ course_membership,
114+ class_course_teacher,
115+ class_course,
116+ class_member,
117+ course_teacher
118+CASCADE;
119+
120+-- ---------------------------------------------------------------------------
121+-- 5b. The emptied tables leave phantom counts on the KEPT ones.
122+-- Every counter below lives on a table this migration keeps but counts rows
123+-- in a table that was just emptied. Left alone on a non-empty database, the
124+-- phantom blocks the guard that reads it: a class_group would refuse its own
125+-- `class_member_count = 0 AND class_course_count = 0` delete guard (and eat
126+-- MAX_CLASS_MEMBERS seats) over members that no longer exist, a subject would
127+-- refuse its delete over questions/homework that are gone, and a kind_ref
128+-- would refuse its kind's retirement over marks that went with exam_result.
129+-- Counters on columns this migration *adds* (`course.class_course_count`,
130+-- `course.course_membership_count`, `term.exam_count`) are not listed: they
131+-- are born with DEFAULT 0.
132+-- ---------------------------------------------------------------------------
133+UPDATE class_group SET class_member_count = 0, class_course_count = 0;
134+UPDATE subject SET exam_question_count = 0, homework_count = 0;
135+UPDATE kind_ref SET count = 0;
136+
137+-- The instance. It now carries the teachers (a junction), the weekly hours
138+-- and whether it counts toward the karne; `source` still marks blueprint vs
139+-- hand-placed. `enrollment_count` is the instance roster size — a counter,
140+-- not a capacity gate (the seat-claim 409 is deleted with D4/D5).
141+CREATE TABLE class_course (
142+ id uuid PRIMARY KEY,
143+ class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION,
144+ course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION,
145+ attached_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
146+ source uuid NULL REFERENCES class_blueprint(id) ON DELETE NO ACTION,
147+ ders_saati SMALLINT NOT NULL DEFAULT 1,
148+ counts_toward_karne BOOLEAN NOT NULL DEFAULT TRUE,
149+ enrollment_count BIGINT NOT NULL DEFAULT 0,
150+ attached_at BIGINT NOT NULL,
151+ CONSTRAINT class_course_class_course UNIQUE (class, course)
152+);
153+
154+CREATE INDEX class_course_course ON class_course (course);
155+CREATE INDEX class_course_class ON class_course (class);
156+
157+-- D6: teacher assignment moves off the catalog course onto the instance.
158+CREATE TABLE class_course_teacher (
159+ class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION,
160+ teacher uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
161+ CONSTRAINT class_course_teacher_pk PRIMARY KEY (class_course, teacher)
162+);
163+
164+CREATE INDEX class_course_teacher_teacher ON class_course_teacher (teacher);
165+
166+-- D11: a history table with a surrogate id. `left_at` NULL is the live stint;
167+-- the partial unique index enforces one live stint per (class, user) pair
168+-- while preserving rejoin history. A soft-left row holds no seat, so the
169+-- roster read and MAX_CLASS_MEMBERS always filter on `left_at IS NULL`.
170+CREATE TABLE class_member (
171+ id uuid PRIMARY KEY,
172+ class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION,
173+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
174+ added_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
175+ joined_at BIGINT NOT NULL,
176+ left_at BIGINT NULL,
177+ source_class_group uuid NULL REFERENCES class_group(id) ON DELETE NO ACTION
178+);
179+
180+CREATE UNIQUE INDEX class_member_live_pair ON class_member (class, app_user) WHERE left_at IS NULL;
181+CREATE INDEX class_member_user ON class_member (app_user);
182+
183+-- D4: the roster is pumped per instance; individual (seçmeli) enrollment is
184+-- the same row shape, hand-placed (`source` NULL).
185+CREATE TABLE enrollment (
186+ class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION,
187+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
188+ enrolled_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
189+ source uuid NULL REFERENCES class_group(id) ON DELETE NO ACTION,
190+ created_at BIGINT NOT NULL,
191+ CONSTRAINT enrollment_class_course_user PRIMARY KEY (class_course, app_user)
192+);
193+
194+-- D9: clubs/etüt are school-scoped memberships, not class-delivered.
195+CREATE TABLE course_membership (
196+ course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION,
197+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
198+ added_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
199+ created_at BIGINT NOT NULL,
200+ CONSTRAINT course_membership_course_user PRIMARY KEY (course, app_user)
201+);
202+
203+-- Exam now hangs off the instance and the dönem it belongs to.
204+CREATE TABLE exam (
205+ id uuid PRIMARY KEY,
206+ creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
207+ class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION,
208+ term uuid NOT NULL REFERENCES term(id) ON DELETE NO ACTION,
209+ title TEXT NOT NULL,
210+ description TEXT NOT NULL,
211+ kind TEXT NOT NULL,
212+ mode TEXT NULL,
213+ starts_at BIGINT NULL,
214+ ends_at BIGINT NULL,
215+ duration_ms BIGINT NULL,
216+ max_attempts BIGINT NOT NULL,
217+ allow_rejoin BOOLEAN NOT NULL,
218+ allow_review BOOLEAN NOT NULL,
219+ draft BOOLEAN NOT NULL,
220+ result_count BIGINT NOT NULL DEFAULT 0
221+);
222+
223+CREATE INDEX exam_class_course ON exam (class_course);
224+CREATE INDEX exam_term ON exam (term);
225+
226+-- The sitting instances of one exam. The owning instance always gets a row,
227+-- so every exam read is one path: JOIN exam_audience.
228+CREATE TABLE exam_audience (
229+ exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION,
230+ class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION,
231+ CONSTRAINT exam_audience_pk PRIMARY KEY (exam, class_course)
232+);
233+
234+-- ---------------------------------------------------------------------------
235+-- 6. Recreate the exam / question-bank subtree verbatim (no key change: it
236+-- keys on exam, which now carries the instance).
237+-- ---------------------------------------------------------------------------
238+CREATE TABLE bank_question (
239+ id uuid PRIMARY KEY,
240+ owner uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
241+ subject uuid NULL REFERENCES subject(id) ON DELETE NO ACTION,
242+ text TEXT NOT NULL,
243+ kind TEXT NOT NULL,
244+ points BIGINT NOT NULL,
245+ choices JSONB NULL,
246+ correct TEXT NULL,
247+ source_exam uuid NULL REFERENCES exam(id) ON DELETE NO ACTION,
248+ visibility TEXT NOT NULL DEFAULT 'private',
249+ created_at BIGINT NOT NULL
250+);
251+
252+CREATE INDEX bank_question_owner ON bank_question (owner);
253+CREATE INDEX bank_question_subject ON bank_question (subject);
254+
255+CREATE TABLE bank_question_image (
256+ bank_question uuid NOT NULL REFERENCES bank_question(id) ON DELETE NO ACTION,
257+ slot TEXT NULL,
258+ file TEXT NOT NULL,
259+ content_type TEXT NOT NULL,
260+ size BIGINT NOT NULL,
261+ CONSTRAINT bank_question_image_question_slot UNIQUE NULLS NOT DISTINCT (bank_question, slot)
262+);
263+
264+CREATE TABLE exam_question (
265+ id uuid PRIMARY KEY,
266+ exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION,
267+ text TEXT NOT NULL,
268+ kind TEXT NOT NULL,
269+ points BIGINT NOT NULL,
270+ choices JSONB NULL,
271+ correct TEXT NULL,
272+ subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION,
273+ from_bank uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION,
274+ banked_as uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION,
275+ CONSTRAINT exam_question_id_exam UNIQUE (id, exam)
276+);
277+
278+CREATE INDEX exam_question_exam ON exam_question (exam);
279+CREATE INDEX exam_question_subject ON exam_question (subject);
280+
281+CREATE TABLE question_image (
282+ exam uuid NOT NULL,
283+ question uuid NOT NULL,
284+ slot TEXT NULL,
285+ file TEXT NOT NULL,
286+ content_type TEXT NOT NULL,
287+ size BIGINT NOT NULL,
288+ CONSTRAINT question_image_question_slot UNIQUE NULLS NOT DISTINCT (question, slot),
289+ CONSTRAINT question_image_exam_question_fkey FOREIGN KEY (exam, question)
290+ REFERENCES exam_question (exam, id) ON DELETE NO ACTION
291+);
292+
293+CREATE INDEX question_image_exam ON question_image (exam);
294+CREATE INDEX question_image_question ON question_image (question);
295+
296+CREATE TABLE exam_attempt (
297+ exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION,
298+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
299+ seq BIGINT NOT NULL DEFAULT 1,
300+ started_at BIGINT NOT NULL,
301+ finished_at BIGINT NULL,
302+ left_at BIGINT NULL,
303+ CONSTRAINT exam_attempt_exam_user_seq PRIMARY KEY (exam, app_user, seq)
304+);
305+
306+CREATE TABLE exam_answer (
307+ exam uuid NOT NULL,
308+ question uuid NOT NULL,
309+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
310+ selected TEXT NULL,
311+ text TEXT NULL,
312+ updated_at BIGINT NOT NULL,
313+ seq BIGINT NOT NULL DEFAULT 1,
314+ CONSTRAINT exam_answer_question_user_seq PRIMARY KEY (question, app_user, seq),
315+ CONSTRAINT exam_answer_exam_question_fkey FOREIGN KEY (exam, question)
316+ REFERENCES exam_question (exam, id) ON DELETE NO ACTION
317+);
318+
319+CREATE INDEX exam_answer_exam_user ON exam_answer (exam, app_user);
320+
321+CREATE TABLE answer_image (
322+ exam uuid NOT NULL,
323+ question uuid NOT NULL,
324+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
325+ file TEXT NOT NULL,
326+ content_type TEXT NOT NULL,
327+ size BIGINT NOT NULL,
328+ seq BIGINT NOT NULL DEFAULT 1,
329+ CONSTRAINT answer_image_question_user_seq PRIMARY KEY (question, app_user, seq),
330+ CONSTRAINT answer_image_exam_question_fkey FOREIGN KEY (exam, question)
331+ REFERENCES exam_question (exam, id) ON DELETE NO ACTION
332+);
333+
334+CREATE INDEX answer_image_exam ON answer_image (exam);
335+CREATE INDEX answer_image_user ON answer_image (app_user);
336+
337+CREATE TABLE exam_result (
338+ exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION,
339+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
340+ mark BIGINT NOT NULL,
341+ graded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
342+ graded_at BIGINT NOT NULL,
343+ seq BIGINT NOT NULL DEFAULT 1,
344+ CONSTRAINT exam_result_exam_user_seq PRIMARY KEY (exam, app_user, seq)
345+);
346+
347+-- ---------------------------------------------------------------------------
348+-- 7. Sessions, roll-call and homework re-key onto the instance.
349+-- ---------------------------------------------------------------------------
350+CREATE TABLE course_session (
351+ id uuid PRIMARY KEY,
352+ class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION,
353+ teacher uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
354+ topic TEXT NOT NULL,
355+ starts_at BIGINT NOT NULL,
356+ ends_at BIGINT NULL,
357+ held_counted_at BIGINT NULL
358+);
359+
360+CREATE INDEX course_session_class_course ON course_session (class_course);
361+
362+CREATE TABLE session_attendance (
363+ session uuid NOT NULL REFERENCES course_session(id) ON DELETE NO ACTION,
364+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
365+ class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION,
366+ status TEXT NOT NULL,
367+ marked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
368+ marked_at BIGINT NOT NULL,
369+ CONSTRAINT session_attendance_session_user PRIMARY KEY (session, app_user)
370+);
371+
372+CREATE INDEX session_attendance_user ON session_attendance (app_user);
373+CREATE INDEX session_attendance_class_course ON session_attendance (class_course);
374+
375+CREATE TABLE homework (
376+ id uuid PRIMARY KEY,
377+ class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION,
378+ subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION,
379+ title TEXT NOT NULL,
380+ description TEXT NULL,
381+ due_at BIGINT NOT NULL,
382+ created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
383+ created_at BIGINT NOT NULL
384+);
385+
386+CREATE INDEX homework_class_course ON homework (class_course);
387+
388+CREATE TABLE homework_assignment (
389+ homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION,
390+ student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
391+ CONSTRAINT homework_assignment_homework_student PRIMARY KEY (homework, student)
392+);
393+
394+CREATE INDEX homework_assignment_student ON homework_assignment (student);
395+
396+CREATE TABLE homework_result (
397+ id uuid PRIMARY KEY,
398+ homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION,
399+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
400+ status TEXT NOT NULL,
401+ mark BIGINT NULL,
402+ graded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
403+ created_at BIGINT NOT NULL,
404+ CONSTRAINT homework_result_homework_user UNIQUE (homework, app_user)
405+);
406+
407+CREATE INDEX homework_result_homework ON homework_result (homework);
408+
409+CREATE TABLE homework_submission (
410+ id uuid PRIMARY KEY,
411+ homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION,
412+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
413+ text TEXT NULL,
414+ submitted_at BIGINT NOT NULL,
415+ updated_at BIGINT NOT NULL,
416+ file_count BIGINT NOT NULL DEFAULT 0,
417+ counted_on_time BOOLEAN NULL,
418+ graded_by_result uuid NULL REFERENCES homework_result(id) ON DELETE NO ACTION,
419+ CONSTRAINT homework_submission_homework_user UNIQUE (homework, app_user)
420+);
421+
422+CREATE INDEX homework_submission_homework ON homework_submission (homework);
423+
424+CREATE TABLE homework_file (
425+ id uuid PRIMARY KEY,
426+ submission uuid NOT NULL REFERENCES homework_submission(id) ON DELETE NO ACTION,
427+ name TEXT NOT NULL,
428+ content_type TEXT NOT NULL,
429+ size BIGINT NOT NULL,
430+ file TEXT NOT NULL,
431+ created_at BIGINT NOT NULL
432+);
433+
434+CREATE INDEX homework_file_submission ON homework_file (submission);
435+
436+-- ---------------------------------------------------------------------------
437+-- 8. Karne snapshot: the frozen per-student per-dönem report written when the
438+-- dönem is archived (karne is otherwise a computed read).
439+-- ---------------------------------------------------------------------------
440+CREATE TABLE karne_snapshot (
441+ term uuid NOT NULL REFERENCES term(id) ON DELETE NO ACTION,
442+ app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
443+ payload JSONB NOT NULL,
444+ created_at BIGINT NOT NULL,
445+ CONSTRAINT karne_snapshot_term_user PRIMARY KEY (term, app_user)
446+);
447+
448+-- ---------------------------------------------------------------------------
449+-- 9. Settings and profile additions (branş, absence limits, timezone).
450+-- ---------------------------------------------------------------------------
451+ALTER TABLE settings ADD COLUMN branches JSONB NULL;
452+ALTER TABLE settings ADD COLUMN excuse_kinds JSONB NULL;
453+ALTER TABLE settings ADD COLUMN max_excused_absent_days BIGINT NULL;
454+ALTER TABLE settings ADD COLUMN max_unexcused_absent_days BIGINT NULL;
455+ALTER TABLE settings ADD COLUMN timezone TEXT NULL;
456+
457+ALTER TABLE app_user ADD COLUMN branch TEXT NULL;
src/config.rsmodified+3 -2
@@ -59,8 +59,9 @@ impl Config {
5959 Self {
6060 host: env::var("HOST").unwrap_or_else(|_| "127.0.0.1".into()),
6161 port: parse_port(env::var("PORT").ok()),
62- database_url: env::var("DATABASE_URL")
63- .unwrap_or_else(|_| "postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control".into()),
62+ database_url: env::var("DATABASE_URL").unwrap_or_else(|_| {
63+ "postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control".into()
64+ }),
6465 files_path: env::var("FILES_PATH").unwrap_or_else(|_| "./data/files".into()),
6566 cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()),
6667 rate_limit: RateLimitConfig {
src/constant.rsmodified+34 -18
@@ -135,6 +135,17 @@ pub const MAX_CLASS_GRADE_LEN: usize = 20;
135135 pub const MAX_CLASS_MEMBERS: i64 = 200;
136136 pub const MAX_CLASS_COURSES: i64 = 50;
137137
138+/// Weekly lesson hours of a class×course instance (D8's karne weight). Bounded
139+/// so a typo cannot make one instance dominate the year average.
140+pub const MIN_DERS_SAATI: i64 = 1;
141+pub const MAX_DERS_SAATI: i64 = 40;
142+
143+/// The default grade-display bands: the Türkiye 5-point scale (85–100 = 5,
144+/// … 0–44 = 1). Schools edit the list via `PATCH /settings`; the karne verdict
145+/// reads the band labelled `"2"` as the pass boundary.
146+pub const DEFAULT_GRADE_BANDS: [(i64, &str); 5] =
147+ [(85, "5"), (70, "4"), (55, "3"), (45, "2"), (0, "1")];
148+
138149 pub const MAX_SUBJECT_NAME_LEN: usize = 200;
139150 pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000;
140151
@@ -161,15 +172,9 @@ pub const MAX_SESSION_TOPIC_LEN: usize = 200;
161172 /// The default exam kinds with their weights; schools replace the list via
162173 /// `PATCH /settings`. An exam's kind decides how heavily it counts into the
163174 /// course average — the defaults all weigh 1 (a plain average) so weighting
164-/// is opt-in policy, not baked-in opinion.
165-pub const DEFAULT_EXAM_KINDS: [(&str, i64); 6] = [
166- ("homework", 1),
167- ("quiz", 1),
168- ("midterm", 1),
169- ("final", 1),
170- ("project", 1),
171- ("oral", 1),
172-];
175+/// is opt-in policy, not baked-in opinion. The defaults are the Turkish K12
176+/// classroom's own: yazılı, sözlü, uygulama.
177+pub const DEFAULT_EXAM_KINDS: [(&str, i64); 3] = [("yazili", 1), ("sozlu", 1), ("uygulama", 1)];
173178
174179 /// Bounds for the school-editable lists in settings (exam kinds, attendance
175180 /// statuses): entry count and per-entry character length.
@@ -189,6 +194,22 @@ pub const CAS_UPDATE_RETRIES: usize = 3;
189194
190195 pub const MAX_TERM_NAME_LEN: usize = 100;
191196
197+/// An academic year is named like a term ("2026-2027").
198+pub const MAX_ACADEMIC_YEAR_NAME_LEN: usize = 100;
199+
200+/// The per-dönem devamsızlık limits a school may configure; a bound so a typo
201+/// cannot disable the rule or make it absurd.
202+pub const MAX_ABSENCE_DAYS: i64 = 365;
203+
204+/// The timezone a school's day-bucketing falls back to when none is set, and
205+/// the one the default deployment runs in.
206+pub const DEFAULT_TIMEZONE: &str = "Europe/Istanbul";
207+
208+/// The timezones a school may configure. A short allow-list on purpose: the
209+/// backend has no timezone database of its own, and day-bucketing needs the
210+/// offset to be trustworthy.
211+pub const TIMEZONES: [&str; 2] = ["Europe/Istanbul", "UTC"];
212+
192213 /// A published availability slot's optional note ("bring your report card").
193214 pub const MAX_APPOINTMENT_NOTE_LEN: usize = 500;
194215
@@ -908,19 +929,14 @@ pub const SLOT_REF_TABLE: &str = "slot_ref";
908929 /// SCHEMAFULL refusing the write.
909930 pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count";
910931 pub const REGISTRATION_COUNT_FIELD: &str = "registration_count";
911-/// Not a cap — a refcount, and the whole of the term delete guard: how many
912-/// courses link this term. A term may only be dropped at zero, and the count
913-/// is claimed before a course's link is written, so the two decisions contend
914-/// on the term row instead of on a cross-table `SELECT` no transaction orders.
915-pub const COURSE_COUNT_FIELD: &str = "course_count";
916932 /// The two refcounts on a class row: how many students it holds and how many
917933 /// courses it is attached to. A class may only be dropped at zero on both.
918934 pub const CLASS_MEMBER_COUNT_FIELD: &str = "class_member_count";
919935 pub const CLASS_COURSE_COUNT_FIELD: &str = "class_course_count";
920-/// Classes linking a term, the second half of the term delete guard. Deliberately
921-/// *not* `COURSE_COUNT_FIELD`: boot recounts that one from the course rows alone,
922-/// so a class claiming into it would be wiped on the next migration.
923-pub const TERM_CLASS_COUNT_FIELD: &str = "class_count";
936+/// Classes belonging to an academic year, the second half of the year's delete
937+/// guard. Its own column: a class's share is never confused with another
938+/// roster's count.
939+pub const ACADEMIC_YEAR_CLASS_COUNT_FIELD: &str = "class_count";
924940 /// A refcount too, and the whole of the fee-plan edit *and* delete guard: how
925941 /// many students are on this plan. A plan may only be edited or deleted at
926942 /// zero, and the count is claimed in the same transaction as the assignment
src/db/academic_year.rsadded+213 -0
@@ -0,0 +1,213 @@
1+//! The `academic_year` table: the row mint, the paged calendar listing, the
2+//! field-scoped PATCH whose `WHERE` re-checks the merged range, and the 0/0
3+//! delete guard.
4+//!
5+//! The year is the top of the academic calendar (D3): a şube belongs to a year
6+//! and a dönem ([`crate::db::term`]) is a grading slice inside it. Its two
7+//! counters are the delete guard — a year that still carries a şube or a dönem
8+//! is refused outright, because dropping it silently would strand the year's
9+//! structure. The rollover that reads and writes the şubeler lives one layer
10+//! up ([`crate::service::academic_year::rollover`]).
11+
12+use sqlx::types::Json;
13+
14+use crate::database::Database;
15+use crate::db::page::PagedList;
16+use crate::domain::academic_year::{
17+ AcademicYear, AcademicYearId, AcademicYearName, GradePromotion,
18+};
19+use crate::domain::timestamp::Timestamp;
20+use crate::domain::user::UserId;
21+use crate::error::AppError;
22+
23+/// Mint one year. The creator is a foreign key: a gone account is the same
24+/// `NotFound` the web layer's own read answers with, never an orphan row.
25+pub async fn create(
26+ db: &Database,
27+ creator: &UserId,
28+ name: AcademicYearName,
29+ starts_at: Timestamp,
30+ ends_at: Timestamp,
31+ grade_promotions: Vec<GradePromotion>,
32+) -> Result<AcademicYear, AppError> {
33+ let promotions = Json(grade_promotions);
34+ let created = sqlx::query_as!(
35+ AcademicYear,
36+ r#"INSERT INTO academic_year (id, name, starts_at, ends_at, creator, grade_promotions)
37+ VALUES ($1, $2, $3, $4, $5, $6)
38+ RETURNING id AS "id: AcademicYearId", name AS "name: AcademicYearName",
39+ starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
40+ archived_at AS "archived_at: Timestamp", creator AS "creator: UserId",
41+ grade_promotions AS "grade_promotions: Json<Vec<GradePromotion>>",
42+ class_count, term_count"#,
43+ AcademicYearId::generate().uuid(),
44+ name.as_str(),
45+ starts_at.as_millis(),
46+ ends_at.as_millis(),
47+ creator.uuid(),
48+ promotions as _,
49+ )
50+ .fetch_one(db)
51+ .await;
52+ match created {
53+ Ok(year) => Ok(year),
54+ Err(err) if crate::database::foreign_key_violation(&err) => Err(AppError::NotFound),
55+ // The name carries a UNIQUE constraint; a duplicate is a legacy-year
56+ // naming clash. The web layer pre-checks it and answers 409 with a
57+ // readable message, so reaching here is a race — reported as the same
58+ // conflict rather than a 500.
59+ Err(err) if crate::database::unique_violation(&err).is_some() => Err(AppError::Conflict(
60+ "an academic year with that name already exists",
61+ )),
62+ Err(err) => Err(err.into()),
63+ }
64+}
65+
66+pub async fn read(db: &Database, id: &AcademicYearId) -> Result<Option<AcademicYear>, AppError> {
67+ let year = sqlx::query_as!(
68+ AcademicYear,
69+ r#"SELECT id AS "id: AcademicYearId", name AS "name: AcademicYearName",
70+ starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
71+ archived_at AS "archived_at: Timestamp", creator AS "creator: UserId",
72+ grade_promotions AS "grade_promotions: Json<Vec<GradePromotion>>",
73+ class_count, term_count
74+ FROM academic_year WHERE id = $1"#,
75+ id.uuid(),
76+ )
77+ .fetch_optional(db)
78+ .await?;
79+ Ok(year)
80+}
81+
82+/// Every year, newest first — the calendar is small by nature.
83+pub async fn list_all(
84+ db: &Database,
85+ limit: Option<i64>,
86+ offset: i64,
87+) -> Result<(Vec<AcademicYear>, i64), AppError> {
88+ PagedList::new("academic_year", "ORDER BY starts_at DESC, id DESC")
89+ .run::<AcademicYear>(limit, offset, db)
90+ .await
91+}
92+
93+/// Write only the fields the PATCH carried — `None` means the request omitted
94+/// it, so the column keeps the value it holds rather than being re-stated from
95+/// the snapshot the handler read. Every column here is non-clearable, so
96+/// `COALESCE` is the whole rule: absent = keep.
97+///
98+/// The merged range is re-checked by the `WHERE` (`ends_at > starts_at` on the
99+/// values this write will leave behind), so two PATCHes each moving one end
100+/// cannot commit an inverted year between them. `Err(NotFound)` when the row
101+/// is gone.
102+pub async fn update(
103+ db: &Database,
104+ id: &AcademicYearId,
105+ name: Option<AcademicYearName>,
106+ starts_at: Option<Timestamp>,
107+ ends_at: Option<Timestamp>,
108+ grade_promotions: Option<Vec<GradePromotion>>,
109+) -> Result<AcademicYear, AppError> {
110+ let promotions = grade_promotions.map(Json);
111+ let starts_millis = starts_at.map(|at| at.as_millis());
112+ let ends_millis = ends_at.map(|at| at.as_millis());
113+ let updated = sqlx::query_as!(
114+ AcademicYear,
115+ r#"UPDATE academic_year
116+ SET name = COALESCE($2, name),
117+ starts_at = COALESCE($3, starts_at),
118+ ends_at = COALESCE($4, ends_at),
119+ grade_promotions = COALESCE($5, grade_promotions)
120+ WHERE id = $1
121+ AND COALESCE($4, ends_at) > COALESCE($3, starts_at)
122+ RETURNING id AS "id: AcademicYearId", name AS "name: AcademicYearName",
123+ starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
124+ archived_at AS "archived_at: Timestamp", creator AS "creator: UserId",
125+ grade_promotions AS "grade_promotions: Json<Vec<GradePromotion>>",
126+ class_count, term_count"#,
127+ id.uuid(),
128+ name.as_ref().map(AcademicYearName::as_str),
129+ starts_millis,
130+ ends_millis,
131+ promotions as _,
132+ )
133+ .fetch_optional(db)
134+ .await?;
135+ match updated {
136+ Some(year) => Ok(year),
137+ // Either the row is gone or the merged range is inverted — the same
138+ // shape the caller's own pre-flight range check answers, one instant
139+ // later. Only the refusal path pays for the read that tells them
140+ // apart.
141+ None => match read(db, id).await? {
142+ Some(_) => Err(AppError::Validation(
143+ crate::error::ValidationError::Invalid {
144+ field: "ends_at",
145+ reason: "must be after starts_at",
146+ },
147+ )),
148+ None => Err(AppError::NotFound),
149+ },
150+ }
151+}
152+
153+/// Delete the year, but only while no şube and no dönem links it — nothing
154+/// here unlinks or cascades. `false` = refused, nothing was written.
155+///
156+/// Both counts are read off the year's own row, so the check and the delete
157+/// are one conditional write on one record: a class or term write racing this
158+/// either claims first (and the delete is refused) or finds the row gone (and
159+/// is refused itself). The referencing foreign keys (`class_group.year`,
160+/// `term.year`, both `NO ACTION`) are the backstop behind the counters, not a
161+/// second guard. The `Err(NotFound)` keeps the answer a concurrent *delete*
162+/// used to get.
163+pub async fn delete(db: &Database, year: AcademicYear) -> Result<bool, AppError> {
164+ let gone = sqlx::query!(
165+ r#"DELETE FROM academic_year
166+ WHERE id = $1 AND class_count = 0 AND term_count = 0"#,
167+ year.get_id().uuid(),
168+ )
169+ .execute(db)
170+ .await?;
171+ if gone.rows_affected() > 0 {
172+ return Ok(true);
173+ }
174+ // Still linked or already gone: the one statement cannot tell those apart,
175+ // and only the refusal path pays for the read that can.
176+ match read(db, year.get_id()).await? {
177+ Some(_) => Ok(false),
178+ None => Err(AppError::NotFound),
179+ }
180+}
181+
182+/// A real academic year for the fixtures of the tables that hang off one: a
183+/// dönem ([`crate::db::term::a_test_term`]) and, through it, every exam. Minted
184+/// per call — the name is unique — with a creator that is a real `app_user`
185+/// row, because `creator` is a foreign key.
186+#[cfg(test)]
187+pub(crate) async fn a_test_year(db: &Database) -> AcademicYearId {
188+ let creator = UserId::generate();
189+ // The last six hex digits of the uuid, not a fixed-width byte range: a
190+ // `key()` is 36 characters, so `[30..38]` — the range a `[30..]` suffix
191+ // suggests — panics before the fixture ever reaches the store.
192+ let suffix = &creator.key()[30..];
193+ sqlx::query(
194+ "INSERT INTO app_user (id, username, created_at, role) \
195+ VALUES ($1, $2, 0, 'manager')",
196+ )
197+ .bind(creator.uuid())
198+ .bind(format!("year-fixture-{suffix}"))
199+ .execute(db)
200+ .await
201+ .unwrap();
202+ let year = crate::db::academic_year::create(
203+ db,
204+ &creator,
205+ AcademicYearName::try_new(&format!("year-{suffix}")).unwrap(),
206+ Timestamp::from_millis(0),
207+ Timestamp::from_millis(1),
208+ Vec::new(),
209+ )
210+ .await
211+ .unwrap();
212+ *year.get_id()
213+}
src/db/answer_image.rsmodified+9 -4
@@ -179,7 +179,9 @@ pub async fn file_keys_for_course(
179179 ) -> Result<Vec<String>, AppError> {
180180 let rows = sqlx::query!(
181181 r#"SELECT ai.file FROM answer_image ai
182- JOIN exam e ON e.id = ai.exam WHERE e.course = $1"#,
182+ JOIN exam e ON e.id = ai.exam
183+ JOIN class_course cc ON cc.id = e.class_course
184+ WHERE cc.course = $1"#,
183185 course.uuid(),
184186 )
185187 .fetch_all(db)
@@ -346,9 +348,12 @@ mod tests {
346348 let exam_b = exam_row(&db).await;
347349 let user = a_student(&db).await;
348350 let question = a_question(&db, &exam_a).await;
349- upsert(&db, AnswerImage::new(&exam_a, &question, &user, 1, png(), 1))
350- .await
351- .unwrap();
351+ upsert(
352+ &db,
353+ AnswerImage::new(&exam_a, &question, &user, 1, png(), 1),
354+ )
355+ .await
356+ .unwrap();
352357 assert_eq!(
353358 list_for_exam_user(&db, &exam_a, &user, 1)
354359 .await
src/db/appointment.rsmodified+9 -7
@@ -9,12 +9,14 @@
99 use crate::database::{Database, tx_with_retry};
1010 use crate::db::cap::Claimed;
1111 use crate::db::page::PagedList;
12-use crate::domain::appointment::{Appointment, AppointmentId, AppointmentReason, AppointmentStatus};
12+use crate::domain::appointment::{
13+ Appointment, AppointmentId, AppointmentReason, AppointmentStatus,
14+};
1315 use crate::domain::appointment_slot::AppointmentSlotId;
1416 use crate::domain::timestamp::Timestamp;
1517 use crate::domain::user::UserId;
1618 use crate::error::AppError;
17-use sqlx::{query, query_as, PgConnection, Postgres};
19+use sqlx::{PgConnection, Postgres, query, query_as};
1820
1921 /// Is `[starts_at, ends_at)` already taken for either party? Both sides are
2022 /// checked: a teacher can't be in two meetings at once, and neither can a
@@ -80,7 +82,10 @@ where
8082 }))
8183 }
8284
83-pub(crate) async fn read_on<'e, E>(executor: E, id: &AppointmentId) -> Result<Option<Appointment>, AppError>
85+pub(crate) async fn read_on<'e, E>(
86+ executor: E,
87+ id: &AppointmentId,
88+) -> Result<Option<Appointment>, AppError>
8489 where
8590 E: sqlx::Executor<'e, Database = Postgres>,
8691 {
@@ -103,10 +108,7 @@ where
103108 Ok(appointment)
104109 }
105110
106-pub async fn read(
107- db: &Database,
108- id: &AppointmentId,
109-) -> Result<Option<Appointment>, AppError> {
111+pub async fn read(db: &Database, id: &AppointmentId) -> Result<Option<Appointment>, AppError> {
110112 read_on(db, id).await
111113 }
112114
src/db/appointment_slot.rsmodified+6 -1
@@ -138,7 +138,12 @@ pub async fn windows_in_span(
138138 .await?;
139139 Ok(rows
140140 .into_iter()
141- .map(|row| (Timestamp::from_millis(row.starts_at), Timestamp::from_millis(row.ends_at)))
141+ .map(|row| {
142+ (
143+ Timestamp::from_millis(row.starts_at),
144+ Timestamp::from_millis(row.ends_at),
145+ )
146+ })
142147 .collect())
143148 }
144149
src/db/badge.rsmodified+1 -1
@@ -111,7 +111,7 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> {
111111 SET earned_at = badge_award.earned_at \
112112 WHERE badge_award.earned_at IS NULL"
113113 )))
114-.bind(user.uuid())
114+ .bind(user.uuid())
115115 .bind(badge)
116116 .bind(now)
117117 .execute(db)
src/db/bank_question.rsmodified+1 -5
@@ -589,11 +589,7 @@ mod tests {
589589 let (db, _leases) = crate::database::init_test_db().await;
590590 let owner = a_person(&db, "owner").await;
591591 let other = a_person(&db, "other").await;
592- async fn mine(
593- db: &Database,
594- owner: &UserId,
595- text: &str,
596- ) -> Result<BankQuestion, AppError> {
592+ async fn mine(db: &Database, owner: &UserId, text: &str) -> Result<BankQuestion, AppError> {
597593 create(
598594 db,
599595 *owner,
src/db/board.rsmodified+9 -9
@@ -356,9 +356,12 @@ pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> {
356356 /// longer exists.
357357 pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> {
358358 tx_with_retry(db, true, async move |conn| {
359- sqlx::query!("DELETE FROM board_participant WHERE board = $1", board.id.uuid())
360- .execute(&mut *conn)
361- .await?;
359+ sqlx::query!(
360+ "DELETE FROM board_participant WHERE board = $1",
361+ board.id.uuid()
362+ )
363+ .execute(&mut *conn)
364+ .await?;
362365 sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id.uuid())
363366 .execute(&mut *conn)
364367 .await?;
@@ -407,8 +410,7 @@ mod tests {
407410 #[tokio::test]
408411 async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() {
409412 let (db, _leases) = crate::database::init_test_db().await;
410- let creator =
411- crate::db::class_member::tests::fixture_user(&db, "board-creator").await;
413+ let creator = crate::db::class_member::tests::fixture_user(&db, "board-creator").await;
412414 let board = create(
413415 &db,
414416 &creator,
@@ -425,8 +427,7 @@ mod tests {
425427
426428 let locked = set_locked(&db, &board, true, &creator).await.unwrap();
427429 assert!(locked.is_locked());
428- let member =
429- crate::db::class_member::tests::fixture_user(&db, "board-member").await;
430+ let member = crate::db::class_member::tests::fixture_user(&db, "board-member").await;
430431 let roster = vec![member];
431432 let re_rostered = set_participants(&db, &board, roster).await.unwrap();
432433 assert_eq!(re_rostered.get_participants().len(), 1);
@@ -440,8 +441,7 @@ mod tests {
440441 #[tokio::test]
441442 async fn the_cap_refuses_and_delete_releases_the_seat() {
442443 let (db, _leases) = crate::database::init_test_db().await;
443- let creator =
444- crate::db::class_member::tests::fixture_user(&db, "board-creator").await;
444+ let creator = crate::db::class_member::tests::fixture_user(&db, "board-creator").await;
445445 for index in 0..MAX_BOARDS_PER_CREATOR {
446446 create(
447447 &db,
src/db/cap.rsmodified+6 -1
@@ -236,7 +236,12 @@ pub(crate) enum FullKind {
236236 /// guard/gone case, folds into [`FullKind::Hard`], whose contract already
237237 /// covers it. This is the old claim order (hard claim, guard attached, before
238238 /// the soft one) expressed as a re-read.
239-pub(crate) fn full_kind(soft_count: i64, soft_cap: i64, hard_count: i64, hard_cap: i64) -> FullKind {
239+pub(crate) fn full_kind(
240+ soft_count: i64,
241+ soft_cap: i64,
242+ hard_count: i64,
243+ hard_cap: i64,
244+) -> FullKind {
240245 if soft_count >= soft_cap && hard_count < hard_cap {
241246 FullKind::Soft
242247 } else {
src/db/chatbot_thread.rsmodified+7 -8
@@ -205,14 +205,13 @@ mod tests {
205205 /// The owner's counter and the threads it counts, both re-read out of the
206206 /// store — never off a return value.
207207 async fn stored(db: &Database) -> (i64, usize) {
208- let counter =
209- sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1")
210- .bind(UserId::from_key(U).uuid())
211- .fetch_one(db)
212- .await
213- .unwrap()
214- .try_get::<i64, _>(0)
215- .unwrap();
208+ let counter = sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1")
209+ .bind(UserId::from_key(U).uuid())
210+ .fetch_one(db)
211+ .await
212+ .unwrap()
213+ .try_get::<i64, _>(0)
214+ .unwrap();
216215 let rows = sqlx::query("SELECT count(*) FROM chatbot_thread")
217216 .fetch_one(db)
218217 .await
src/db/class_blueprint.rsmodified+24 -6
@@ -375,9 +375,12 @@ async fn delete_claimed(
375375 if stored != held {
376376 return Ok(false);
377377 }
378- sqlx::query!(r#"DELETE FROM blueprint_course WHERE blueprint = $1"#, row.key)
379- .execute(&mut *tx)
380- .await?;
378+ sqlx::query!(
379+ r#"DELETE FROM blueprint_course WHERE blueprint = $1"#,
380+ row.key
381+ )
382+ .execute(&mut *tx)
383+ .await?;
381384 sqlx::query!(r#"DELETE FROM class_blueprint WHERE id = $1"#, row.key)
382385 .execute(&mut *tx)
383386 .await?;
@@ -533,13 +536,28 @@ pub async fn sourced_links(
533536 /// detached detached, each with its counter released and its enrollments
534537 /// swept, and the rest exactly as they were: a partial removal the next call
535538 /// finishes.
539+///
540+/// Answers the **blob keys** every detach's cascade removed — the
541+/// question/answer images and homework files of each swept instance subtree —
542+/// for the caller's route to unlink after the commits. Each detach commits its
543+/// own transaction, so the keys of the rows already swept come back even when
544+/// a later link refuses ([`crate::db::class_pump::detach_course`] answers
545+/// `None` for a pair that held no instance, which contributes nothing); a
546+/// failure before a link's detach returns the Err and drops the keys gathered
547+/// so far, which is the same accepted window
548+/// [`crate::service::course::delete`] documents: at worst an unreachable blob.
536549 pub async fn drop_links(
537550 db: &Database,
538551 id: &ClassBlueprintId,
539552 links: Vec<Held>,
540-) -> Result<(), AppError> {
553+) -> Result<Vec<String>, AppError> {
554+ let mut blobs = Vec::new();
541555 for link in links {
542- class_pump::detach_course(db, &link.class, &link.course, Some(id)).await?;
556+ if let Some(keys) =
557+ class_pump::detach_course(db, &link.class, &link.course, Some(id)).await?
558+ {
559+ blobs.extend(keys);
560+ }
543561 }
544- Ok(())
562+ Ok(blobs)
545563 }
src/db/class_course.rsmodified+188 -15
@@ -1,19 +1,39 @@
11 //! The `class_course` table: the course-axis attach entry point and the
2-//! attachment listing. The refusals-to-errors policy and the detach that turns
3-//! a zero-row sweep into a 404 live in [`crate::service::class_course`]; the
4-//! transaction itself is the pump's, [`crate::db::class_pump`].
2+//! instance reads behind `/instances`. The refusals-to-errors policy and the
3+//! detach that turns a zero-row sweep into a 404 live in
4+//! [`crate::service::class_course`]; the transaction itself is the pump's,
5+//! [`crate::db::class_pump`].
6+//!
7+//! An instance is the academic anchor now: it carries the weekly hours
8+//! (`ders_saati`), whether it counts toward the karne, the roster counter and
9+//! its own teachers ([`crate::db::class_course_teacher`]). Reads speak the
10+//! *bare uuid* id of the instance; the (class, course) pair survives as the
11+//! UNIQUE key the attach gates on.
512
613 use crate::constant::CLASS_COURSE_TABLE;
714 use crate::database::Database;
815 use crate::db::class_pump::Attached;
916 use crate::db::page::PagedList;
1017 use crate::domain::class_blueprint::ClassBlueprintId;
11-use crate::domain::class_course::ClassCourse;
18+use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati};
1219 use crate::domain::class_group::ClassGroupId;
1320 use crate::domain::course::CourseId;
21+use crate::domain::timestamp::Timestamp;
1422 use crate::domain::user::UserId;
1523 use crate::error::AppError;
1624
25+/// The projection every instance read shares.
26+///
27+/// Two translations ride it: `source` is stored as the blueprint's surrogate
28+/// uuid while the domain speaks the grade label the API does (a hand attach,
29+/// source NULL, survives the LEFT JOIN as NULL), and `ders_saati` is a
30+/// `SMALLINT` column while [`DersSaati`] is an `i64` newtype — decoded
31+/// through a `bigint` cast so the type the driver checks is the one the
32+/// newtype names.
33+const INSTANCE_COLUMNS: &str = "cc.id, cc.class, cc.course, cc.attached_by, \
34+ b.grade AS source, cc.ders_saati::bigint AS ders_saati, \
35+ cc.counts_toward_karne, cc.enrollment_count, cc.attached_at";
36+
1737 /// The attach itself, with the refusals left *unmapped*.
1838 ///
1939 /// A hand attach ([`crate::service::class_course::attach`]) turns each of them
@@ -39,30 +59,183 @@ pub(crate) async fn attach_sourced(
3959 crate::db::class_pump::attach_course(db, class, course, attached_by, source).await
4060 }
4161
42-/// The courses a class is attached to, newest first — by when they were
43-/// attached. The composite primary key is the tiebreaker (class, then course:
44-/// the two halves of the id this order used to sort), which makes the order
45-/// total.
62+/// The instances a class carries, newest first — by when they were attached,
63+/// the instance id breaking the tie (v7 ids sort in mint order, so the order
64+/// is total and reads as creation order within one instant).
4665 pub async fn list_for_class(
4766 db: &Database,
4867 class: &ClassGroupId,
4968 limit: Option<i64>,
5069 offset: i64,
5170 ) -> Result<(Vec<ClassCourse>, i64), AppError> {
52- // The stored `source` is the blueprint's surrogate uuid; the domain row
53- // speaks the grade label, so the projection joins it back (a hand attach,
54- // source NULL, survives the LEFT JOIN as NULL).
5571 PagedList::new(
5672 format!(
57- "(SELECT cc.class, cc.course, cc.attached_by, cc.attached_at, \
58- b.grade AS source \
59- FROM {CLASS_COURSE_TABLE} cc \
73+ "(SELECT {INSTANCE_COLUMNS} FROM {CLASS_COURSE_TABLE} cc \
6074 LEFT JOIN class_blueprint b ON b.id = cc.source) \
6175 AS {CLASS_COURSE_TABLE} WHERE class = $1"
6276 ),
63- "ORDER BY attached_at DESC NULLS LAST, class DESC, course DESC",
77+ "ORDER BY attached_at DESC, id DESC",
6478 )
6579 .bind(class.uuid())
6680 .run(limit, offset, db)
6781 .await
6882 }
83+
84+/// The instances one catalog course is taught in, newest first — the read
85+/// behind "which şubeler run this course".
86+pub async fn list_for_course(
87+ db: &Database,
88+ course: &CourseId,
89+ limit: Option<i64>,
90+ offset: i64,
91+) -> Result<(Vec<ClassCourse>, i64), AppError> {
92+ PagedList::new(
93+ format!(
94+ "(SELECT {INSTANCE_COLUMNS} FROM {CLASS_COURSE_TABLE} cc \
95+ LEFT JOIN class_blueprint b ON b.id = cc.source) \
96+ AS {CLASS_COURSE_TABLE} WHERE course = $1"
97+ ),
98+ "ORDER BY attached_at DESC, id DESC",
99+ )
100+ .bind(course.uuid())
101+ .run(limit, offset, db)
102+ .await
103+}
104+
105+/// Every instance held by any of `classes` (one query, unpaged) — the join
106+/// half of the class-layer reads that already hold class ids (a roster read,
107+/// a blueprint status diff). Ids that name no class are simply absent from
108+/// the result.
109+pub async fn list_for_class_ids(
110+ db: &Database,
111+ classes: &[ClassGroupId],
112+) -> Result<Vec<ClassCourse>, AppError> {
113+ if classes.is_empty() {
114+ return Ok(Vec::new());
115+ }
116+ let ids: Vec<uuid::Uuid> = classes.iter().map(ClassGroupId::uuid).collect();
117+ let rows = sqlx::query_as!(
118+ ClassCourse,
119+ r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId",
120+ cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId",
121+ b.grade AS "source?: ClassBlueprintId",
122+ cc.ders_saati::bigint AS "ders_saati!: DersSaati",
123+ cc.counts_toward_karne, cc.enrollment_count,
124+ cc.attached_at AS "attached_at: Timestamp"
125+ FROM class_course cc
126+ LEFT JOIN class_blueprint b ON b.id = cc.source
127+ WHERE cc.class = ANY($1)
128+ ORDER BY cc.attached_at DESC, cc.id DESC"#,
129+ &ids,
130+ )
131+ .fetch_all(db)
132+ .await?;
133+ Ok(rows)
134+}
135+
136+/// Load every instance behind `ids` (one query) — the join half of the reads
137+/// that already hold instance ids (a marks report's per-instance blocks).
138+pub async fn list_by_ids(
139+ db: &Database,
140+ ids: &[ClassCourseId],
141+) -> Result<Vec<ClassCourse>, AppError> {
142+ if ids.is_empty() {
143+ return Ok(Vec::new());
144+ }
145+ let keys: Vec<uuid::Uuid> = ids.iter().map(ClassCourseId::uuid).collect();
146+ let rows = sqlx::query_as!(
147+ ClassCourse,
148+ r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId",
149+ cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId",
150+ b.grade AS "source?: ClassBlueprintId",
151+ cc.ders_saati::bigint AS "ders_saati!: DersSaati",
152+ cc.counts_toward_karne, cc.enrollment_count,
153+ cc.attached_at AS "attached_at: Timestamp"
154+ FROM class_course cc
155+ LEFT JOIN class_blueprint b ON b.id = cc.source
156+ WHERE cc.id = ANY($1)
157+ ORDER BY cc.attached_at DESC, cc.id DESC"#,
158+ &keys,
159+ )
160+ .fetch_all(db)
161+ .await?;
162+ Ok(rows)
163+}
164+
165+/// One instance, or `None` when the id names no row.
166+pub async fn read(db: &Database, id: &ClassCourseId) -> Result<Option<ClassCourse>, AppError> {
167+ let row = sqlx::query_as!(
168+ ClassCourse,
169+ r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId",
170+ cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId",
171+ b.grade AS "source?: ClassBlueprintId",
172+ cc.ders_saati::bigint AS "ders_saati!: DersSaati",
173+ cc.counts_toward_karne, cc.enrollment_count,
174+ cc.attached_at AS "attached_at: Timestamp"
175+ FROM class_course cc
176+ LEFT JOIN class_blueprint b ON b.id = cc.source
177+ WHERE cc.id = $1"#,
178+ id.uuid(),
179+ )
180+ .fetch_optional(db)
181+ .await?;
182+ Ok(row)
183+}
184+
185+/// The class this instance belongs to, or `None` when the id names no row —
186+/// the seam every instance-scoped route reads the şube (and, through it, the
187+/// year) off.
188+pub async fn class_of(db: &Database, id: &ClassCourseId) -> Result<Option<ClassGroupId>, AppError> {
189+ let row = sqlx::query!(
190+ r#"SELECT class AS "class: ClassGroupId" FROM class_course WHERE id = $1"#,
191+ id.uuid(),
192+ )
193+ .fetch_optional(db)
194+ .await?;
195+ Ok(row.map(|row| row.class))
196+}
197+
198+/// Write only the fields the PATCH carried — `None` means the request omitted
199+/// it, so the column keeps the value it holds rather than being re-stated
200+/// from the snapshot the handler read. Both fields are non-clearable, so
201+/// `COALESCE` is the whole rule: absent = keep the stored value.
202+///
203+/// No counter moves and no compare-and-set is needed: neither field is
204+/// refcounted, and each is an independent scalar, so two PATCHes touching
205+/// different ones cannot revert each other. `Err(NotFound)` when the instance
206+/// is gone — the same answer the caller's own read gives one instant earlier.
207+pub async fn update(
208+ db: &Database,
209+ id: &ClassCourseId,
210+ staff: Option<DersSaati>,
211+ counts: Option<bool>,
212+) -> Result<ClassCourse, AppError> {
213+ // `i64`, cast down by the statement itself: the column is a `SMALLINT`
214+ // and the newtype wraps an `i64`, so naming both types explicitly is what
215+ // keeps the driver's type check honest in either direction.
216+ let hours = staff.map(|hours| hours.as_i64());
217+ let row = sqlx::query_as!(
218+ ClassCourse,
219+ r#"WITH updated AS (
220+ UPDATE class_course
221+ SET ders_saati = COALESCE($2::bigint, ders_saati::bigint)::smallint,
222+ counts_toward_karne = COALESCE($3, counts_toward_karne)
223+ WHERE id = $1
224+ RETURNING *)
225+ SELECT u.id AS "id: ClassCourseId", u.class AS "class: ClassGroupId",
226+ u.course AS "course: CourseId", u.attached_by AS "attached_by: UserId",
227+ b.grade AS "source?: ClassBlueprintId",
228+ u.ders_saati::bigint AS "ders_saati!: DersSaati",
229+ u.counts_toward_karne, u.enrollment_count,
230+ u.attached_at AS "attached_at: Timestamp"
231+ FROM updated u
232+ LEFT JOIN class_blueprint b ON b.id = u.source"#,
233+ id.uuid(),
234+ hours,
235+ counts,
236+ )
237+ .fetch_optional(db)
238+ .await?
239+ .ok_or(AppError::NotFound)?;
240+ Ok(row)
241+}
src/db/class_course_teacher.rsadded+139 -0
@@ -0,0 +1,139 @@
1+//! The `class_course_teacher` junction: who teaches one instance.
2+//!
3+//! D6 moved teacher assignment off the catalog course and onto the instance —
4+//! two şubeler teaching the same course may legitimately have different
5+//! teachers — so this is the table every instance-membership gate reads
6+//! ([`crate::service::class_course::ensure_instance_teacher`]) and the one the
7+//! demotion sweep strips ([`crate::db::user::set_role_cascade`]).
8+//!
9+//! The shape is the `course_teacher` junction's, keyed on the instance:
10+//! assignment is an idempotent `INSERT` whose `(class_course, teacher)` key
11+//! answers a duplicate with `DO NOTHING`, so two requests naming the same
12+//! teacher at once land one row.
13+
14+use crate::database::{Database, foreign_key_violation};
15+use crate::domain::class_course::{ClassCourse, ClassCourseId};
16+use crate::domain::user::UserId;
17+use crate::error::AppError;
18+
19+use std::collections::HashMap;
20+
21+/// Assign `teacher` to teach this instance. `false` when they already did
22+/// (assignment is idempotent, so a repeat is a no-op rather than an error);
23+/// `Err(NotFound)` when the instance is gone — the same answer the caller's
24+/// own read gives one instant earlier.
25+pub async fn assign(
26+ db: &Database,
27+ instance: &ClassCourseId,
28+ teacher: &UserId,
29+) -> Result<bool, AppError> {
30+ let written = match sqlx::query!(
31+ r#"INSERT INTO class_course_teacher (class_course, teacher)
32+ SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM class_course WHERE id = $1)
33+ ON CONFLICT DO NOTHING"#,
34+ instance.uuid(),
35+ teacher.uuid(),
36+ )
37+ .execute(db)
38+ .await
39+ {
40+ Ok(result) => result.rows_affected(),
41+ // The teacher row (or the instance) vanished mid-write: a foreign key
42+ // answers, and a gone target is the `NotFound` the read below gives.
43+ Err(e) if foreign_key_violation(&e) => return Err(AppError::NotFound),
44+ Err(e) => return Err(e.into()),
45+ };
46+ if written == 0
47+ && crate::db::class_course::class_of(db, instance)
48+ .await?
49+ .is_none()
50+ {
51+ // Zero rows and no instance: the conditional select matched nothing,
52+ // rather than the pair already holding its row.
53+ return Err(AppError::NotFound);
54+ }
55+ Ok(written > 0)
56+}
57+
58+/// Drop `teacher` from this instance. `false` when they were not assigned to
59+/// it, so the web layer can answer 404 instead of pretending it removed
60+/// someone.
61+pub async fn unassign(
62+ db: &Database,
63+ instance: &ClassCourseId,
64+ teacher: &UserId,
65+) -> Result<bool, AppError> {
66+ let deleted = sqlx::query!(
67+ r#"DELETE FROM class_course_teacher WHERE class_course = $1 AND teacher = $2"#,
68+ instance.uuid(),
69+ teacher.uuid(),
70+ )
71+ .execute(db)
72+ .await?;
73+ Ok(deleted.rows_affected() > 0)
74+}
75+
76+/// Strip `user` from every instance they were assigned to — the sweep for a
77+/// user demoted below `teacher`, who may no longer run anything.
78+pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
79+ sqlx::query!(
80+ r#"DELETE FROM class_course_teacher WHERE teacher = $1"#,
81+ user.uuid(),
82+ )
83+ .execute(db)
84+ .await?;
85+ Ok(())
86+}
87+
88+/// The teachers of one instance, by uuid — the read behind a single
89+/// `/instances/{id}` response.
90+pub async fn list_for_instance(
91+ db: &Database,
92+ instance: &ClassCourseId,
93+) -> Result<Vec<UserId>, AppError> {
94+ let rows = sqlx::query!(
95+ r#"SELECT teacher AS "teacher: UserId" FROM class_course_teacher
96+ WHERE class_course = $1 ORDER BY teacher"#,
97+ instance.uuid(),
98+ )
99+ .fetch_all(db)
100+ .await?;
101+ Ok(rows.into_iter().map(|row| row.teacher).collect())
102+}
103+
104+/// Assemble `(instance, teachers)` pairs out of a batch of instance reads:
105+/// one `class_course_teacher` query for the whole batch, so a page of `n`
106+/// instances costs one extra statement rather than `n`. An instance nobody is
107+/// assigned to reads an empty list, the shape
108+/// [`crate::db::course`]'s old `into_courses` gave a course.
109+pub async fn into_instances(
110+ db: &Database,
111+ rows: Vec<ClassCourse>,
112+) -> Result<Vec<(ClassCourse, Vec<UserId>)>, AppError> {
113+ if rows.is_empty() {
114+ return Ok(Vec::new());
115+ }
116+ let ids: Vec<uuid::Uuid> = rows.iter().map(|row| row.get_id().uuid()).collect();
117+ let links = sqlx::query!(
118+ r#"SELECT class_course AS "class_course: ClassCourseId", teacher AS "teacher: UserId"
119+ FROM class_course_teacher WHERE class_course = ANY($1)
120+ ORDER BY class_course, teacher"#,
121+ &ids,
122+ )
123+ .fetch_all(db)
124+ .await?;
125+ let mut by_instance: HashMap<uuid::Uuid, Vec<UserId>> = HashMap::new();
126+ for link in links {
127+ by_instance
128+ .entry(link.class_course.uuid())
129+ .or_default()
130+ .push(link.teacher);
131+ }
132+ Ok(rows
133+ .into_iter()
134+ .map(|row| {
135+ let teachers = by_instance.remove(&row.get_id().uuid()).unwrap_or_default();
136+ (row, teachers)
137+ })
138+ .collect())
139+}
src/db/class_group.rsmodified+368 -248
@@ -1,50 +1,75 @@
1-//! The `class_group` table: the row, its term reference claimed through the
2-//! [`crate::db::cap`] shapes in the same statement as the link, and the 0/0
3-//! delete guard. The archived-term guard and the route-facing wrappers live in
4-//! [`crate::service::class_group`].
1+//! The `class_group` table: the row, its academic-year reference claimed
2+//! through the [`crate::db::cap`] shapes in the same statement as the link,
3+//! and the 0/0 delete guard. The archived-year guard and the route-facing
4+//! wrappers live in [`crate::service::class_group`].
55
6-use crate::constant::{CLASS_GROUP_TABLE, TERM_CLASS_COUNT_FIELD};
6+use crate::constant::{ACADEMIC_YEAR_CLASS_COUNT_FIELD, CLASS_GROUP_TABLE};
77 use crate::database::{Database, tx_with_retry};
88 use crate::db::field_update::{FieldUpdate, Refcount};
99 use crate::db::page::PagedList;
10+use crate::domain::academic_year::AcademicYearId;
1011 use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName};
11-use crate::domain::term::{self, TermId};
1212 use crate::domain::user::UserId;
13-use crate::error::AppError;
14-
15-/// Create the class, claiming a reference on the term it links (if any) in
16-/// the *same statement* as the row, exactly as
17-/// [`crate::db::course::create`] does: the claim is a
18-/// conditional write on the term row, so it fails when the term is already
19-/// gone, it makes the term undeletable the instant this link exists, and — the
20-/// claim and the insert being one CTE — no crash and no refused claim can
21-/// leave either half without the other.
13+use crate::error::{AppError, ValidationError};
14+
15+/// The refusal a şube write naming a year that is not there gets — the mirror
16+/// of [`crate::domain::term::gone_error`], one layer up the calendar.
17+fn year_gone() -> AppError {
18+ AppError::Validation(ValidationError::Invalid {
19+ field: "year",
20+ reason: "academic year does not exist",
21+ })
22+}
23+
24+/// What a PATCH's `year` field owes the refcounts: the year to claim and the
25+/// one to give back. Covers all three moves — set (none→some), move
26+/// (some→other) and clear (some→none) — and moves nothing for a PATCH that
27+/// omitted the field or re-stated the link it already had. The same shape
28+/// [`crate::domain::term::ref_move`] gives the term link.
29+fn year_ref_move(
30+ current: Option<&AcademicYearId>,
31+ patch: &Option<Option<AcademicYearId>>,
32+) -> (Option<AcademicYearId>, Option<AcademicYearId>) {
33+ match patch {
34+ None => (None, None),
35+ Some(next) if next.as_ref() == current => (None, None),
36+ Some(next) => (*next, current.copied()),
37+ }
38+}
39+
40+/// Create the class, claiming a reference on the academic year it links (if
41+/// any) in the *same statement* as the row, exactly as
42+/// [`crate::db::course::create`] did for the term: the claim is a conditional
43+/// write on the year row, so it fails when the year is already gone, it makes
44+/// the year undeletable the instant this link exists, and — the claim and the
45+/// insert being one CTE — no crash and no refused claim can leave either half
46+/// without the other.
2247 pub async fn create(
2348 db: &Database,
2449 creator: &UserId,
2550 name: ClassName,
2651 grade: Option<ClassGrade>,
27- term: Option<TermId>,
52+ year: Option<AcademicYearId>,
2853 teacher: Option<UserId>,
2954 ) -> Result<ClassGroup, AppError> {
3055 let id = ClassGroupId::generate();
31- match &term {
32- Some(term) => {
56+ match &year {
57+ Some(year) => {
3358 // The claim and the insert are one statement: atomic without an
3459 // explicit transaction, exactly like every other
3560 // single-statement guard.
3661 let written = sqlx::query_as!(
3762 ClassGroup,
3863 r#"WITH seat AS (
39- UPDATE term SET class_count = class_count + 1
64+ UPDATE academic_year SET class_count = class_count + 1
4065 WHERE id = $1
4166 RETURNING 1)
42- INSERT INTO class_group (id, creator, name, grade, term, teacher)
67+ INSERT INTO class_group (id, creator, name, grade, year, teacher)
4368 SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat)
4469 RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId",
4570 name AS "name: ClassName", grade AS "grade: ClassGrade",
46- term AS "term: TermId", teacher AS "teacher: UserId""#,
47- term.uuid(),
71+ year AS "year: AcademicYearId", teacher AS "teacher: UserId""#,
72+ year.uuid(),
4873 id.uuid(),
4974 creator.uuid(),
5075 name.as_str(),
@@ -56,12 +81,12 @@ pub async fn create(
5681 match written {
5782 Ok(Some(created)) => Ok(created),
5883 // Uncapped, so a zero-row claim can only mean the conditional
59- // write matched no term row at all — the claim doubles as the
84+ // write matched no year row at all — the claim doubles as the
6085 // existence check.
61- Ok(None) => Err(term::gone_error()),
62- // The term row is locked by the claim's own UPDATE, so this
86+ Ok(None) => Err(year_gone()),
87+ // The year row is locked by the claim's own UPDATE, so this
6388 // is unreachable; a defensible answer beats a 500.
64- Err(e) if crate::database::foreign_key_violation(&e) => Err(term::gone_error()),
89+ Err(e) if crate::database::foreign_key_violation(&e) => Err(year_gone()),
6590 // Unreachable: the id was minted one line above.
6691 Err(e) if crate::database::unique_violation(&e).is_some() => {
6792 Err(AppError::Internal("failed to create class".into()))
@@ -72,16 +97,16 @@ pub async fn create(
7297 None => {
7398 let created = sqlx::query_as!(
7499 ClassGroup,
75- r#"INSERT INTO class_group (id, creator, name, grade, term, teacher)
100+ r#"INSERT INTO class_group (id, creator, name, grade, year, teacher)
76101 VALUES ($1, $2, $3, $4, $5, $6)
77102 RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId",
78103 name AS "name: ClassName", grade AS "grade: ClassGrade",
79- term AS "term: TermId", teacher AS "teacher: UserId""#,
104+ year AS "year: AcademicYearId", teacher AS "teacher: UserId""#,
80105 id.uuid(),
81106 creator.uuid(),
82107 name.as_str(),
83108 grade.as_ref().map(ClassGrade::as_str),
84- term.as_ref().map(TermId::uuid),
109+ year.as_ref().map(AcademicYearId::uuid),
85110 teacher.as_ref().map(UserId::uuid)
86111 )
87112 .fetch_optional(db)
@@ -97,7 +122,7 @@ pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup>
97122 ClassGroup,
98123 r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId",
99124 name AS "name: ClassName", grade AS "grade: ClassGrade",
100- term AS "term: TermId", teacher AS "teacher: UserId"
125+ year AS "year: AcademicYearId", teacher AS "teacher: UserId"
101126 FROM class_group WHERE id = $1"#,
102127 id.uuid()
103128 )
@@ -137,45 +162,45 @@ pub async fn list_all(
137162
138163 /// Write only the fields the PATCH carried — `None` means the request
139164 /// omitted it, so the column is left alone rather than re-stated from the
140-/// snapshot this struct was read into. `grade`, `term` and `teacher` are
165+/// snapshot this struct was read into. `grade`, `year` and `teacher` are
141166 /// nullable, so they take the outer/inner `Option<Option<_>>`: `None` =
142167 /// omitted (keep), `Some(None)` = clear.
143168 ///
144-/// A term move claims the new term and releases the old one inside the very
169+/// A year move claims the new year and releases the old one inside the very
145170 /// transaction that moves the link, exactly as in
146-/// [`crate::db::course::update`]: both counters and the link
147-/// commit together, so no crash can strand a count on a term nothing links.
171+/// [`crate::db::course::update`] did for the term: both counters and the link
172+/// commit together, so no crash can strand a count on a year nothing links.
148173 pub async fn update(
149174 db: &Database,
150175 class: ClassGroup,
151176 name: Option<ClassName>,
152177 grade: Option<Option<ClassGrade>>,
153- term: Option<Option<TermId>>,
178+ year: Option<Option<AcademicYearId>>,
154179 teacher: Option<Option<UserId>>,
155180 ) -> Result<ClassGroup, AppError> {
156- let (claim, release) = term::ref_move(class.term.as_ref(), &term);
157- let expected = class.term.as_ref().map(TermId::uuid);
181+ let (claim, release) = year_ref_move(class.year.as_ref(), &year);
182+ let expected = class.year.as_ref().map(AcademicYearId::uuid);
158183 FieldUpdate::new(CLASS_GROUP_TABLE, class.id.uuid())
159184 .set("name", name.map(|name| name.as_str().to_string()))
160185 .set(
161186 "grade",
162187 grade.map(|grade| grade.map(|grade| grade.as_str().to_string())),
163188 )
164- .set("term", term.map(|term| term.map(|term| term.uuid())))
189+ .set("year", year.map(|year| year.map(|year| year.uuid())))
165190 // Not refcounted: a homeroom assignment is a label, so it rides the
166- // plain `set` path and never arms the term CAS.
191+ // plain `set` path and never arms the year CAS.
167192 .set(
168193 "teacher",
169194 teacher.map(|teacher| teacher.map(|teacher| teacher.uuid())),
170195 )
171196 .refcount(Refcount {
172- counter_table: "term",
173- counter_field: TERM_CLASS_COUNT_FIELD,
174- link: "term",
197+ counter_table: "academic_year",
198+ counter_field: ACADEMIC_YEAR_CLASS_COUNT_FIELD,
199+ link: "year",
175200 expected,
176- claim: claim.map(|term| term.uuid()),
177- release: release.map(|term| term.uuid()),
178- refused: term::gone_error(),
201+ claim: claim.map(|year| year.uuid()),
202+ release: release.map(|year| year.uuid()),
203+ refused: year_gone(),
179204 })
180205 .run::<ClassGroup>(db)
181206 .await
@@ -194,7 +219,7 @@ pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result<Vec<Clas
194219 ClassGroup,
195220 r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId",
196221 name AS "name: ClassName", grade AS "grade: ClassGrade",
197- term AS "term: TermId", teacher AS "teacher: UserId"
222+ year AS "year: AcademicYearId", teacher AS "teacher: UserId"
198223 FROM class_group WHERE id = ANY($1)"#,
199224 &ids
200225 )
@@ -214,7 +239,7 @@ pub async fn list_for_grade(
214239 ClassGroup,
215240 r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId",
216241 name AS "name: ClassName", grade AS "grade: ClassGrade",
217- term AS "term: TermId", teacher AS "teacher: UserId"
242+ year AS "year: AcademicYearId", teacher AS "teacher: UserId"
218243 FROM class_group WHERE grade = $1"#,
219244 grade.as_str()
220245 )
@@ -223,6 +248,55 @@ pub async fn list_for_grade(
223248 Ok(classes)
224249 }
225250
251+/// Every class of one academic year, newest first — the rollover's input list
252+/// ([`crate::service::academic_year::rollover`]). Unpaged for the same reason
253+/// [`list_for_grade`] is: the caller reconciles all of them.
254+pub async fn list_for_year(
255+ db: &Database,
256+ year: &AcademicYearId,
257+) -> Result<Vec<ClassGroup>, AppError> {
258+ let classes = sqlx::query_as!(
259+ ClassGroup,
260+ r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId",
261+ name AS "name: ClassName", grade AS "grade: ClassGrade",
262+ year AS "year: AcademicYearId", teacher AS "teacher: UserId"
263+ FROM class_group WHERE year = $1 ORDER BY id"#,
264+ year.uuid()
265+ )
266+ .fetch_all(db)
267+ .await?;
268+ Ok(classes)
269+}
270+
271+/// Every class `user` is the homeroom teacher (sınıf öğretmeni) of, newest
272+/// first — the same order [`list_all`] gives, since this is a narrowing of
273+/// that list and not a second one.
274+///
275+/// It is the read behind "which şubeler do I run": the homeroom teacher of a
276+/// section may act on every instance of it (D10, the third arm of
277+/// [`crate::service::class_course::ensure_instance_teacher`]) without being a
278+/// member of it or assigned to the instance — and without a read like this the
279+/// section would be invisible to them, so their own instances' exams,
280+/// sessions and homework could not be listed at all.
281+///
282+/// Unpaged like [`list_for_grade`] and [`list_for_year`]: the caller resolves
283+/// a *visible set*, and a page would silently hide the sections past the
284+/// window. A user who homerooms nothing — including one every sweep has
285+/// cleared (`unassign_everywhere`) — simply gets an empty list.
286+pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<ClassGroup>, AppError> {
287+ let classes = sqlx::query_as!(
288+ ClassGroup,
289+ r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId",
290+ name AS "name: ClassName", grade AS "grade: ClassGrade",
291+ year AS "year: AcademicYearId", teacher AS "teacher: UserId"
292+ FROM class_group WHERE teacher = $1 ORDER BY id DESC"#,
293+ user.uuid()
294+ )
295+ .fetch_all(db)
296+ .await?;
297+ Ok(classes)
298+}
299+
226300 /// Clear the homeroom teacher everywhere `user` held one — the
227301 /// sweep for a user demoted below `teacher`, who may no longer hold one.
228302 /// The mirror of [`crate::db::course::unassign_everywhere`];
@@ -237,20 +311,49 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
237311 Ok(())
238312 }
239313
240-/// Delete the class and give its term reference back. Nothing else cascades:
241-/// a class that still holds students or courses is refused outright, because
242-/// dropping it silently would leave the enrollments it pumped behind with
243-/// nothing left to sweep them. An event aimed at the class keeps standing
244-/// with `audience_class` cleared — the course twin's documented outcome
314+/// Delete the class and give its academic-year reference back. A class that
315+/// still holds students or courses is refused outright, because dropping it
316+/// silently would leave the enrollments it pumped behind with nothing left to
317+/// sweep them. What the guard cannot see is the *history* standing beside the
318+/// live rows, and that is what this delete sweeps first: every `class_member`
319+/// stint of the class (a soft-left student holds no seat, so the 0/0 guard
320+/// passes while their row still stands, and `class_member.class` would refuse
321+/// the delete as a `23503`), plus the provenance tags naming it from rows that
322+/// outlive it — a rollover copy's `source_class_group` and a handed-over
323+/// enrollment's `source`, both hard foreign keys into this table. Dropping a
324+/// şube takes its own history with it; a row that merely *remembers* the şube
325+/// keeps standing, untagged. An event aimed at the class keeps standing with
326+/// `audience_class` cleared — the course twin's documented outcome
245327 /// (`db::course::delete`): the roster resolves live, so it simply reads empty.
246328 ///
247-/// `false` = refused, nothing was written. Both counts are read off the
248-/// class's own row, so the check and the delete are one conditional write on
249-/// one record — a member or attach racing this either claims first (and the
250-/// delete is refused) or finds the row gone (and is refused itself). The
251-/// `Err(NotFound)` keeps the answer a concurrent *delete* used to get.
329+/// `false` = refused, nothing was written — not even the sweeps below. The
330+/// guard locks the class row (`FOR UPDATE`) and reads its own two counters, so
331+/// a member or an attach racing this either claims first (and the delete is
332+/// refused, untouched) or finds the row gone (and is refused itself).
333+/// `Err(NotFound)` keeps the answer a concurrent *delete* used to get — and
334+/// unlike the old one-statement guard, this one tells the two apart without a
335+/// second read. The row lock is what makes the sweeps safe to run before the
336+/// final delete: no counter can move under this transaction, so the verdict
337+/// this read settled is still the verdict when the children are gone.
252338 pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> {
253339 tx_with_retry(db, false, async move |tx| {
340+ // The guard and the lock, in one read — the shape
341+ // [`crate::db::course::delete`] uses. A refused delete must leave the
342+ // class's history exactly as it found it, so nothing may be swept
343+ // until this verdict is in.
344+ let guard = sqlx::query!(
345+ r#"SELECT class_member_count, class_course_count, year AS "year: uuid::Uuid"
346+ FROM class_group WHERE id = $1 FOR UPDATE"#,
347+ class.id.uuid()
348+ )
349+ .fetch_optional(&mut *tx)
350+ .await?;
351+ let Some(guard) = guard else {
352+ return Err(AppError::NotFound);
353+ };
354+ if guard.class_member_count != 0 || guard.class_course_count != 0 {
355+ return Ok(false);
356+ }
254357 // Events aimed at this class keep standing, audience cleared — the
255358 // hard FK on `event.audience_class` would otherwise refuse the delete
256359 // outright, and a dangling audience resolves to an empty roster.
@@ -260,37 +363,45 @@ pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError>
260363 )
261364 .execute(&mut *tx)
262365 .await?;
263- let gone = sqlx::query!(
264- r#"DELETE FROM class_group
265- WHERE id = $1
266- AND class_member_count = 0 AND class_course_count = 0
267- RETURNING term AS "term: uuid::Uuid""#,
366+ // The roster history goes with the şube. The 0/0 guard counts *live*
367+ // stints, so a class whose last student soft-left passes it with the
368+ // history row still standing — and `class_member.class` is a hard
369+ // foreign key, which would answer the delete below as a `23503`.
370+ sqlx::query!(
371+ r#"DELETE FROM class_member WHERE class = $1"#,
268372 class.id.uuid()
269373 )
270- .fetch_optional(&mut *tx)
374+ .execute(&mut *tx)
271375 .await?;
272- let Some(row) = gone else {
273- // Still linked or already gone: the guard cannot tell those
274- // apart, and only the refusal path pays for the extra read that
275- // can.
276- let standing = sqlx::query_scalar!(
277- r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#,
278- class.id.uuid()
279- )
280- .fetch_optional(&mut *tx)
281- .await?
282- .is_some();
283- return if standing {
284- Ok(false)
285- } else {
286- Err(AppError::NotFound)
287- };
288- };
289- if let Some(term) = row.term {
376+ // …and the same key from the *other* side: a stint another şube holds
377+ // remembers where it came from (a rollover copy's `source_class_group`)
378+ // and an enrollment a class wrote remembers which class pumped it
379+ // (its `source`). Both are hard keys into this row, so both would
380+ // refuse the delete. The rows outlive the şube and stay; only the tag
381+ // goes.
382+ sqlx::query!(
383+ r#"UPDATE class_member SET source_class_group = NULL WHERE source_class_group = $1"#,
384+ class.id.uuid()
385+ )
386+ .execute(&mut *tx)
387+ .await?;
388+ sqlx::query!(
389+ r#"UPDATE enrollment SET source = NULL WHERE source = $1"#,
390+ class.id.uuid()
391+ )
392+ .execute(&mut *tx)
393+ .await?;
394+ // Last, and FK-silent: every child row whose key names this class is
395+ // either taken or untagged by now.
396+ sqlx::query!(r#"DELETE FROM class_group WHERE id = $1"#, class.id.uuid())
397+ .execute(&mut *tx)
398+ .await?;
399+ if let Some(year) = guard.year {
290400 sqlx::query!(
291- r#"UPDATE term SET class_count = GREATEST(class_count - 1, 0)
292- WHERE id = $1"#,
293- term
401+ r#"UPDATE academic_year
402+ SET class_count = GREATEST(class_count - 1, 0)
403+ WHERE id = $1"#,
404+ year
294405 )
295406 .execute(&mut *tx)
296407 .await?;
@@ -305,7 +416,7 @@ mod tests {
305416 use super::*;
306417 use sqlx::Row as _;
307418
308- use crate::domain::term::{Term, TermName};
419+ use crate::domain::academic_year::{AcademicYear, AcademicYearName};
309420
310421 /// A real `app_user` row: creator, teacher, and attached-by are foreign
311422 /// keys now, so every fixture participant is a row, not a fabricated id.
@@ -321,32 +432,47 @@ mod tests {
321432 .execute(db)
322433 .await
323434 .unwrap();
324- let id: uuid::Uuid =
325- sqlx::query("SELECT id FROM app_user WHERE username = $1")
326- .bind(username)
327- .fetch_one(db)
328- .await
329- .unwrap()
330- .try_get(0)
331- .unwrap();
435+ let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1")
436+ .bind(username)
437+ .fetch_one(db)
438+ .await
439+ .unwrap()
440+ .try_get(0)
441+ .unwrap();
332442 UserId::from_key(&id.to_string())
333443 }
334444
335- async fn class_on(term: Option<TermId>, db: &Database) -> ClassGroup {
445+ /// A real academic year: the şube's year link is a foreign key now, and
446+ /// the class-count claim it carries is what these tests are about.
447+ async fn a_year(name: &str, db: &Database) -> AcademicYear {
448+ let at = crate::domain::timestamp::Timestamp::from_millis;
449+ crate::db::academic_year::create(
450+ db,
451+ &a_named_user(db, "manager").await,
452+ AcademicYearName::try_new(name).unwrap(),
453+ at(100),
454+ at(200),
455+ Vec::new(),
456+ )
457+ .await
458+ .unwrap()
459+ }
460+
461+ async fn class_on(year: Option<AcademicYearId>, db: &Database) -> ClassGroup {
336462 let manager = a_named_user(db, "manager").await;
337463 create(
338464 db,
339465 &manager,
340466 ClassName::try_new("9-A").unwrap(),
341467 None,
342- term,
468+ year,
343469 None,
344470 )
345471 .await
346472 .unwrap()
347473 }
348474
349- /// A class with a homeroom teacher, no term.
475+ /// A class with a homeroom teacher, no year.
350476 async fn class_of(teacher: Option<UserId>, db: &Database) -> ClassGroup {
351477 let manager = a_named_user(db, "manager").await;
352478 create(
@@ -371,13 +497,6 @@ mod tests {
371497 .cloned()
372498 }
373499
374- async fn a_term(db: &Database) -> Term {
375- let at = crate::domain::timestamp::Timestamp::from_millis;
376- crate::db::term::create(db, TermName::try_new("2026").unwrap(), at(100), at(200))
377- .await
378- .unwrap()
379- }
380-
381500 /// The single integer `sql` selects — the stored counter, re-read, never
382501 /// off a return value. The SQL is built from literals in this module, so
383502 /// the audit wrapper is a formality.
@@ -390,11 +509,14 @@ mod tests {
390509 .unwrap()
391510 }
392511
393- /// The stored `class_count` on one term, absent counting as zero.
394- async fn count_on(term: &TermId, db: &Database) -> i64 {
512+ /// The stored `class_count` on one academic year, absent counting as zero.
513+ async fn count_on(year: &AcademicYearId, db: &Database) -> i64 {
395514 one_i64(
396515 db,
397- format!("SELECT COALESCE(class_count, 0) FROM term WHERE id = '{}'", term.uuid()),
516+ format!(
517+ "SELECT COALESCE(class_count, 0) FROM academic_year WHERE id = '{}'",
518+ year.uuid()
519+ ),
398520 )
399521 .await
400522 }
@@ -494,29 +616,40 @@ mod tests {
494616 assert_eq!(teacher_of(none.get_id(), &db).await, None);
495617 }
496618
497- /// The bite test for the class half of the term delete guard: a term is
498- /// undeletable while a *class* links it, on its own column, and every way
499- /// that link can end gives the reference back. Claiming into `course_count`
500- /// instead would pass the first assert and fail the roundtrip through boot.
619+ /// The bite test for the class half of the academic-year delete guard
620+ /// (D3): a year is undeletable while a *şube* links it, on its own
621+ /// column, and every way that link can end gives the reference back.
622+ /// Claiming into `term_count` instead would pass the first assert and
623+ /// fail the roundtrip through the year's own delete.
501624 #[tokio::test]
502- async fn a_term_is_deletable_only_once_no_class_links_it() {
625+ async fn a_year_is_deletable_only_once_no_class_links_it() {
503626 let (db, _leases) = crate::database::init_test_db().await;
504- let term = a_term(&db).await;
627+ let year = a_year("2026-2027", &db).await;
505628
506- let linked = class_on(Some(*term.get_id()), &db).await;
507- let patched = class_on(Some(*term.get_id()), &db).await;
629+ let linked = class_on(Some(*year.get_id()), &db).await;
630+ let patched = class_on(Some(*year.get_id()), &db).await;
508631 assert_eq!(
509- one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await,
632+ one_i64(
633+ &db,
634+ "SELECT COALESCE(class_count, 0) FROM academic_year".to_string()
635+ )
636+ .await,
510637 2,
511- "classes must count on class_count, not course_count"
638+ "classes must count on class_count, not term_count"
512639 );
513640 assert_eq!(
514- one_i64(&db, "SELECT COALESCE(course_count, 0) FROM term".to_string()).await,
641+ one_i64(
642+ &db,
643+ "SELECT COALESCE(term_count, 0) FROM academic_year".to_string()
644+ )
645+ .await,
515646 0,
516- "the courses' counter is seeded from course rows and must stay untouched"
647+ "the terms' counter is seeded from term rows and must stay untouched"
517648 );
518649 assert!(
519- !crate::db::term::delete(&db, term.clone()).await.unwrap(),
650+ !crate::db::academic_year::delete(&db, year.clone())
651+ .await
652+ .unwrap(),
520653 "two linked classes must refuse the delete"
521654 );
522655
@@ -524,33 +657,42 @@ mod tests {
524657 .await
525658 .unwrap();
526659 assert!(
527- !crate::db::term::delete(&db, term.clone()).await.unwrap(),
660+ !crate::db::academic_year::delete(&db, year.clone())
661+ .await
662+ .unwrap(),
528663 "one link is still one link"
529664 );
530665
531666 assert!(delete(&db, linked).await.unwrap());
532667 assert!(
533- crate::db::term::delete(&db, term.clone()).await.unwrap(),
534- "the last link gone, the term may go"
668+ crate::db::academic_year::delete(&db, year.clone())
669+ .await
670+ .unwrap(),
671+ "the last link gone, the year may go"
672+ );
673+ let again = crate::db::academic_year::delete(&db, year).await;
674+ assert!(
675+ matches!(again, Err(AppError::NotFound)),
676+ "a second delete is a 404, not a refusal: {again:?}"
535677 );
536678 }
537679
538680 /// The bite test for the class delete guard, both arms: either count above
539- /// zero refuses, having written nothing — the term reference least of all,
681+ /// zero refuses, having written nothing — the year reference least of all,
540682 /// which a refusal that released it would strand.
541683 #[tokio::test]
542684 async fn a_class_with_members_or_courses_refuses_to_delete() {
543685 for field in ["class_member_count", "class_course_count"] {
544686 let (db, _leases) = crate::database::init_test_db().await;
545- let term = a_term(&db).await;
546- let class = class_on(Some(*term.get_id()), &db).await;
687+ let year = a_year("2026-2027", &db).await;
688+ let class = class_on(Some(*year.get_id()), &db).await;
547689 sqlx::query(sqlx::AssertSqlSafe(format!(
548690 "UPDATE class_group SET {field} = 1 WHERE id = $1"
549691 )))
550- .bind(class.get_id().uuid())
551- .execute(&db)
552- .await
553- .unwrap();
692+ .bind(class.get_id().uuid())
693+ .execute(&db)
694+ .await
695+ .unwrap();
554696
555697 assert!(
556698 !delete(&db, class.clone()).await.unwrap(),
@@ -561,24 +703,21 @@ mod tests {
561703 "a refused delete may write nothing"
562704 );
563705 assert_eq!(
564- one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await,
706+ count_on(year.get_id(), &db).await,
565707 1,
566- "…the term reference least of all"
708+ "…the year reference least of all"
567709 );
568710
569- // Back to zero, and the same class deletes and releases the term.
711+ // Back to zero, and the same class deletes and releases the year.
570712 sqlx::query(sqlx::AssertSqlSafe(format!(
571713 "UPDATE class_group SET {field} = 0 WHERE id = $1"
572714 )))
573- .bind(class.get_id().uuid())
574- .execute(&db)
575- .await
576- .unwrap();
715+ .bind(class.get_id().uuid())
716+ .execute(&db)
717+ .await
718+ .unwrap();
577719 assert!(delete(&db, class.clone()).await.unwrap());
578- assert_eq!(
579- one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await,
580- 0
581- );
720+ assert_eq!(count_on(year.get_id(), &db).await, 0);
582721 let again = delete(&db, class).await;
583722 assert!(
584723 matches!(again, Err(AppError::NotFound)),
@@ -588,14 +727,14 @@ mod tests {
588727 }
589728
590729 /// The class half of the invariant on the create path: a refused create
591- /// leaves neither the row nor a count stranded on a term (which the term's
730+ /// leaves neither the row nor a count stranded on a year (which the year's
592731 /// delete guard reads, so a stray one would make it undeletable forever).
593732 #[tokio::test]
594733 async fn a_refused_create_writes_neither_row_nor_count() {
595734 let (db, _leases) = crate::database::init_test_db().await;
596- let term = a_term(&db).await;
597- let id = *term.get_id();
598- assert!(crate::db::term::delete(&db, term).await.unwrap());
735+ let year = a_year("2026-2027", &db).await;
736+ let id = *year.get_id();
737+ assert!(crate::db::academic_year::delete(&db, year).await.unwrap());
599738
600739 let error = create(
601740 &db,
@@ -606,39 +745,33 @@ mod tests {
606745 None,
607746 )
608747 .await
609- .expect_err("a term that is gone must not be linkable");
610- assert!(error.to_string().contains("term does not exist"));
748+ .expect_err("a year that is gone must not be linkable");
749+ assert!(error.to_string().contains("academic year does not exist"));
611750 assert_eq!(
612751 row_count(&db, "class_group").await,
613752 0,
614753 "a refused create may write no row"
615754 );
616755 assert_eq!(
617- row_count(&db, "term").await,
756+ row_count(&db, "academic_year").await,
618757 0,
619- "…and least of all a count on a term it just brought back"
758+ "…and least of all a count on a year it just brought back"
620759 );
621760 }
622761
623762 /// The class mirror of
624- /// [`crate::db::course`]'s move tests: a term move carries both
625- /// counters with the link, and a move to a term that is gone rolls the
626- /// release back with the abort (the transaction releases before it claims,
627- /// so the old count would be 0 if the abort did not undo it).
763+ /// [`crate::db::course`]'s move tests: a year move carries the count with
764+ /// the link, and a move to a year that is gone rolls the release back with
765+ /// the abort (the transaction releases before it claims, so the old count
766+ /// would be 0 if the abort did not undo it).
628767 #[tokio::test]
629- async fn a_class_term_move_moves_both_counts_or_neither() {
768+ async fn a_class_year_move_moves_the_count_or_neither() {
630769 let (db, _leases) = crate::database::init_test_db().await;
631- let at = crate::domain::timestamp::Timestamp::from_millis;
632- let from = a_term(&db).await;
633- let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))
634- .await
635- .unwrap();
636- let dead =
637- crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200))
638- .await
639- .unwrap();
770+ let from = a_year("2026-2027", &db).await;
771+ let to = a_year("2027-2028", &db).await;
772+ let dead = a_year("2028-2029", &db).await;
640773 let dead_id = *dead.get_id();
641- assert!(crate::db::term::delete(&db, dead).await.unwrap());
774+ assert!(crate::db::academic_year::delete(&db, dead).await.unwrap());
642775 let class = class_on(Some(*from.get_id()), &db).await;
643776
644777 let error = update(
@@ -650,10 +783,10 @@ mod tests {
650783 None,
651784 )
652785 .await
653- .expect_err("a term that is gone must not be linkable");
654- assert!(error.to_string().contains("term does not exist"));
786+ .expect_err("a year that is gone must not be linkable");
787+ assert!(error.to_string().contains("academic year does not exist"));
655788 let stored = read(&db, class.get_id()).await.unwrap().unwrap();
656- assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put");
789+ assert_eq!(stored.get_year(), Some(from.get_id()), "the link stays put");
657790 assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row");
658791 assert_eq!(
659792 count_on(from.get_id(), &db).await,
@@ -661,28 +794,21 @@ mod tests {
661794 "the release must roll back with the abort"
662795 );
663796
664- let moved = update(
665- &db,
666- class,
667- None,
668- None,
669- Some(Some(*to.get_id())),
670- None,
671- )
672- .await
673- .unwrap();
674- assert_eq!(moved.get_term(), Some(to.get_id()));
797+ let moved = update(&db, class, None, None, Some(Some(*to.get_id())), None)
798+ .await
799+ .unwrap();
800+ assert_eq!(moved.get_year(), Some(to.get_id()));
675801 assert_eq!(
676802 count_on(from.get_id(), &db).await,
677803 0,
678- "the old term is free"
804+ "the old year is free"
679805 );
680806 assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
681807 }
682808
683- /// The class twin of
684- /// [`crate::domain::course`]'s `a_stale_mover_is_refused_and_claims_nothing`
685- /// and `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both
809+ /// The class twin of [`crate::db::course`]'s
810+ /// `a_stale_mover_is_refused_and_claims_nothing` and
811+ /// `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both
686812 /// PATCHes compute their counter move from the row as *they* read it, so a
687813 /// second one running on the pre-move struct would claim a second seat for
688814 /// one link (the mover) or drag the link back and strand the winner's claim
@@ -690,29 +816,16 @@ mod tests {
690816 /// stopped by a guard armed off the *carried column*). Both must be refused
691817 /// with the counts reading as if they never ran.
692818 #[tokio::test]
693- async fn a_stale_class_term_write_is_refused_and_moves_no_count() {
819+ async fn a_stale_class_year_write_is_refused_and_moves_no_count() {
694820 let (db, _leases) = crate::database::init_test_db().await;
695- let at = crate::domain::timestamp::Timestamp::from_millis;
696- let from = a_term(&db).await;
697- let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))
698- .await
699- .unwrap();
700- let other =
701- crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200))
702- .await
703- .unwrap();
821+ let from = a_year("2026-2027", &db).await;
822+ let to = a_year("2027-2028", &db).await;
823+ let other = a_year("2028-2029", &db).await;
704824 let class = class_on(Some(*from.get_id()), &db).await;
705825 let stale = class.clone();
706- update(
707- &db,
708- class,
709- None,
710- None,
711- Some(Some(*to.get_id())),
712- None,
713- )
714- .await
715- .unwrap();
826+ update(&db, class, None, None, Some(Some(*to.get_id())), None)
827+ .await
828+ .unwrap();
716829
717830 // The mover: its snapshot says `from`, so it would release `from` and
718831 // claim `other` on top of the winner's claim on `to`.
@@ -741,73 +854,80 @@ mod tests {
741854 assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
742855
743856 let stored = read(&db, stale.get_id()).await.unwrap().unwrap();
744- assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link");
857+ assert_eq!(stored.get_year(), Some(to.get_id()), "the winner's link");
745858 assert_eq!(count_on(from.get_id(), &db).await, 0, "released once");
746859 assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once");
747860 assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed");
748861
749862 // A genuine no-op re-state still lands and still moves nothing.
750- let same = update(
751- &db,
752- stored,
753- None,
754- None,
755- Some(Some(*to.get_id())),
756- None,
757- )
758- .await
759- .expect("re-stating the link the row really holds is not a conflict");
760- assert_eq!(same.get_term(), Some(to.get_id()));
863+ let same = update(&db, stored, None, None, Some(Some(*to.get_id())), None)
864+ .await
865+ .expect("re-stating the link the row really holds is not a conflict");
866+ assert_eq!(same.get_year(), Some(to.get_id()));
761867 assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat");
762868 }
763869
764- /// [`crate::db::course::delete`]'s class sweep: deleting a course
765- /// takes its `class_course` attachments with it and gives each class its
766- /// count back, or the classes would be undeletable forever over rows that
767- /// point at nothing.
870+ /// The delete guard counts *live* stints, and a soft-left student holds
871+ /// none — so the class passes it with the history row still standing, and
872+ /// `class_member.class` (a hard foreign key) is what used to answer this
873+ /// delete, as a `23503` the route turns into a 500. The roster history
874+ /// goes with the şube it belongs to.
768875 #[tokio::test]
769- async fn deleting_a_course_sweeps_its_class_attachments() {
770- use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
876+ async fn a_soft_left_member_does_not_block_the_delete_and_goes_with_it() {
877+ use crate::db::class_pump::{self, Attached};
771878
772879 let (db, _leases) = crate::database::init_test_db().await;
773880 let manager = a_named_user(&db, "manager").await;
774- let course = crate::db::course::create(
775- &db,
776- &manager,
777- CourseTitle::try_new("algebra").unwrap(),
778- CourseDescription::try_new("").unwrap(),
779- CourseKind::course(),
780- None,
781- None,
782- )
783- .await
784- .unwrap();
785- let class = class_on(None, &db).await;
786- sqlx::query("INSERT INTO class_course (class, course, attached_by) VALUES ($1, $2, $3)")
787- .bind(class.get_id().uuid())
788- .bind(course.get_id().uuid())
789- .bind(manager.uuid())
790- .execute(&db)
791- .await
792- .unwrap();
793- sqlx::query("UPDATE class_group SET class_course_count = 1 WHERE id = $1")
794- .bind(class.get_id().uuid())
881+ let class = class_of(None, &db).await;
882+ // The pump's member axis claims the `student` role on the user row,
883+ // and a stint is a real write, not a row fabricated into place.
884+ let student = a_named_user(&db, "ada").await;
885+ sqlx::query("UPDATE app_user SET role = 'student' WHERE id = $1")
886+ .bind(student.uuid())
795887 .execute(&db)
796888 .await
797889 .unwrap();
890+ assert!(matches!(
891+ class_pump::add_member(&db, class.get_id(), &student, &manager)
892+ .await
893+ .unwrap(),
894+ Attached::Made(_)
895+ ));
798896
799- assert!(crate::db::course::delete(&db, course).await.unwrap());
800897 assert_eq!(
801- row_count(&db, "class_course").await,
802- 0,
803- "the attachment rows must go with the course"
898+ class_pump::leave_member(&db, class.get_id(), &student)
899+ .await
900+ .unwrap(),
901+ 1,
902+ "the one live stint is the one the leave ends"
804903 );
904+ // Exactly what the guard is blind to: the counters read zero, the
905+ // history does not.
805906 assert_eq!(
806- one_i64(&db, "SELECT COALESCE(class_course_count, 0) FROM class_group".to_string()).await,
907+ one_i64(
908+ &db,
909+ format!(
910+ "SELECT class_member_count FROM class_group WHERE id = '{}'",
911+ class.get_id().uuid()
912+ )
913+ )
914+ .await,
915+ 0
916+ );
917+ assert_eq!(row_count(&db, "class_member").await, 1);
918+
919+ assert!(
920+ delete(&db, class.clone()).await.unwrap(),
921+ "a soft-left member must not block the delete"
922+ );
923+ assert_eq!(
924+ row_count(&db, "class_member").await,
807925 0,
808- "…and each class must get its count back"
926+ "…and the roster history goes with the şube"
927+ );
928+ assert!(
929+ matches!(delete(&db, class).await, Err(AppError::NotFound)),
930+ "a second delete is still a 404"
809931 );
810- // Which is the whole point: the class is deletable again.
811- assert!(delete(&db, class).await.unwrap());
812932 }
813933 }
src/db/class_member.rsmodified+64 -28
@@ -2,6 +2,11 @@
22 //! pump's, along the member axis ([`crate::db::class_pump`]); the
33 //! refusals-to-errors policy and the detach live in
44 //! [`crate::service::class_member`].
5+//!
6+//! The table is a history: `left_at` NULL is the live stint, and every read
7+//! here filters on it — a student who left the şube holds no seat and appears
8+//! on no roster, while their earlier row survives for the record (and for the
9+//! karne's attribution).
510
611 use crate::constant::CLASS_MEMBER_TABLE;
712 use crate::database::Database;
@@ -11,9 +16,8 @@ use crate::domain::class_member::ClassMember;
1116 use crate::domain::user::UserId;
1217 use crate::error::AppError;
1318
14-/// The class's roster, newest first — by when the student was added. The
15-/// composite primary key is the tiebreaker (class, then user: the two halves
16-/// of the id this order used to sort), which makes the order total.
19+/// The class's live roster, newest first — by when the student joined. The
20+/// surrogate id breaks the tie, so the order is total.
1721 pub async fn list_for_class(
1822 db: &Database,
1923 class: &ClassGroupId,
@@ -21,17 +25,17 @@ pub async fn list_for_class(
2125 offset: i64,
2226 ) -> Result<(Vec<ClassMember>, i64), AppError> {
2327 PagedList::new(
24- format!("{CLASS_MEMBER_TABLE} WHERE class = $1"),
25- "ORDER BY added_at DESC NULLS LAST, class DESC, app_user DESC",
28+ format!("{CLASS_MEMBER_TABLE} WHERE class = $1 AND left_at IS NULL"),
29+ "ORDER BY joined_at DESC, id DESC",
2630 )
2731 .bind(class.uuid())
2832 .run(limit, offset, db)
2933 .await
3034 }
3135
32-/// The classes one student belongs to, newest membership first — the read
33-/// behind "which class section (şube) am I in". Same ordering story as
34-/// [`list_for_class`], along the other axis of the same index.
36+/// The classes one student is currently in, newest stint first — the read
37+/// behind "which class section (şube) am I in". A left stint is history and
38+/// does not appear.
3539 pub async fn list_for_user(
3640 db: &Database,
3741 user: &UserId,
@@ -39,14 +43,32 @@ pub async fn list_for_user(
3943 offset: i64,
4044 ) -> Result<(Vec<ClassMember>, i64), AppError> {
4145 PagedList::new(
42- format!("{CLASS_MEMBER_TABLE} WHERE app_user = $1"),
43- "ORDER BY added_at DESC NULLS LAST, class DESC, app_user DESC",
46+ format!("{CLASS_MEMBER_TABLE} WHERE app_user = $1 AND left_at IS NULL"),
47+ "ORDER BY joined_at DESC, id DESC",
4448 )
4549 .bind(user.uuid())
4650 .run(limit, offset, db)
4751 .await
4852 }
4953
54+/// Whether `user` holds a live stint in `class` right now — the membership
55+/// gate a class-scoped route reads before it writes.
56+pub async fn is_live_member(
57+ db: &Database,
58+ class: &ClassGroupId,
59+ user: &UserId,
60+) -> Result<bool, AppError> {
61+ let row = sqlx::query!(
62+ r#"SELECT 1 AS "one" FROM class_member
63+ WHERE class = $1 AND app_user = $2 AND left_at IS NULL"#,
64+ class.uuid(),
65+ user.uuid(),
66+ )
67+ .fetch_optional(db)
68+ .await?;
69+ Ok(row.is_some())
70+}
71+
5072 #[cfg(test)]
5173 pub(crate) mod tests {
5274 use super::*;
@@ -80,6 +102,8 @@ pub(crate) mod tests {
80102 UserId::from_key(&id.to_string())
81103 }
82104
105+ /// A class with no year and no grade: the shape most fixtures want, since
106+ /// the year only matters to the academic-calendar reads.
83107 pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId {
84108 let manager = fixture_user(db, "manager").await;
85109 crate::db::class_group::create(
@@ -96,7 +120,9 @@ pub(crate) mod tests {
96120 .clone()
97121 }
98122
99- pub(crate) async fn a_course(title: &str, capacity: Option<i64>, db: &Database) -> CourseId {
123+ /// A catalog course. Capacity is gone from the catalog (D5): the instance
124+ /// carries the roster counter and there is no seat gate to trip.
125+ pub(crate) async fn a_course(title: &str, db: &Database) -> CourseId {
100126 let manager = fixture_user(db, "manager").await;
101127 crate::db::course::create(
102128 db,
@@ -104,8 +130,6 @@ pub(crate) mod tests {
104130 CourseTitle::try_new(title).unwrap(),
105131 CourseDescription::try_new("").unwrap(),
106132 CourseKind::course(),
107- None,
108- capacity,
109133 )
110134 .await
111135 .unwrap()
@@ -114,23 +138,34 @@ pub(crate) mod tests {
114138 }
115139
116140 /// A counter column on its row, re-read out of the store — never off a
117- /// return value. The column name picks the table: every `*_count` these
118- /// suites read lives on exactly one.
141+ /// return value. The field picks the table for the counters whose home is
142+ /// unambiguous; `class_course_count` now exists on *both* the class (how
143+ /// many courses it carries) and the catalog course (how many instances are
144+ /// taught in), so that one names the class here and
145+ /// [`counter_on`] is the way to read the course's.
119146 pub(crate) async fn counter(field: &str, of: uuid::Uuid, db: &Database) -> i64 {
120147 let table = match field {
121- "enrollment_count" => "course",
148+ // The roster counter is the *instance's* (the catalog course has
149+ // no roster since D4/D5).
150+ "enrollment_count" => "class_course",
122151 "class_member_count" | "class_course_count" => "class_group",
123152 other => panic!("no table known for the counter {other}"),
124153 };
154+ counter_on(table, field, of, db).await
155+ }
156+
157+ /// [`counter`] with the table named outright, for the columns two tables
158+ /// share.
159+ pub(crate) async fn counter_on(table: &str, field: &str, of: uuid::Uuid, db: &Database) -> i64 {
125160 sqlx::query(sqlx::AssertSqlSafe(format!(
126161 "SELECT COALESCE({field}, 0) FROM {table} WHERE id = $1"
127162 )))
128- .bind(of)
129- .fetch_one(db)
130- .await
131- .unwrap()
132- .try_get::<i64, _>(0)
133- .unwrap()
163+ .bind(of)
164+ .fetch_one(db)
165+ .await
166+ .unwrap()
167+ .try_get::<i64, _>(0)
168+ .unwrap()
134169 }
135170
136171 /// How many rows `table` holds.
@@ -155,12 +190,12 @@ pub(crate) mod tests {
155190
156191 /// Whether the enrollment pair still has its row.
157192 pub(crate) async fn enrollment_exists(
158- course: &CourseId,
193+ class_course: &crate::domain::class_course::ClassCourseId,
159194 user: &UserId,
160195 db: &Database,
161196 ) -> bool {
162- sqlx::query("SELECT 1 FROM enrollment WHERE course = $1 AND app_user = $2")
163- .bind(course.uuid())
197+ sqlx::query("SELECT 1 FROM enrollment WHERE class_course = $1 AND app_user = $2")
198+ .bind(class_course.uuid())
164199 .bind(user.uuid())
165200 .fetch_optional(db)
166201 .await
@@ -183,13 +218,14 @@ pub(crate) mod tests {
183218 .is_some()
184219 }
185220
186- /// The class that wrote an enrollment, or `None` for a hand-placed row.
221+ /// The class that wrote an instance's enrollment, or `None` for a
222+ /// hand-placed row.
187223 pub(crate) async fn source_of(
188- course: &CourseId,
224+ class_course: &crate::domain::class_course::ClassCourseId,
189225 user: &UserId,
190226 db: &Database,
191227 ) -> Option<Option<ClassGroupId>> {
192- crate::db::enrollment::read_for_user(db, course, user)
228+ crate::db::enrollment::read_for_user(db, class_course, user)
193229 .await
194230 .unwrap()
195231 .map(|row| row.get_source().cloned())
src/db/class_pump.rsmodified+357 -333
@@ -2,37 +2,41 @@
22 //! `enrollment` row that link implies reconciled with it, in one transaction.
33 //!
44 //! A class section (şube) has two link tables — `class_member` (a student in
5-//! it) and `class_course` (a course attached to it) — and the *product* of the
6-//! two is the roster it owes: every member is enrolled in every attached
7-//! course, in real `enrollment` rows tagged [`source`](crate::domain::enrollment)
8-//! with the class that wrote them. Adding a member and attaching a course are
9-//! therefore the same operation seen along its two axes, and so are removing
5+//! it) and `class_course` (a course attached to it, as that class×course
6+//! *instance*) — and the *product* of the two is the roster it owes: every
7+//! live member is enrolled in every instance the class carries, in real
8+//! `enrollment` rows tagged [`source`](crate::domain::enrollment) with the
9+//! class that wrote them. Adding a member and attaching a course are
10+//! therefore the same operation seen along its two axes, and so are ending
1011 //! one and detaching the other.
1112 //!
1213 //! What is *not* one primitive is attach and detach. They share no statement:
1314 //! one gates on "this pair already holds a row" and claims a counter upwards,
14-//! the other gates on nothing, releases, and has to decide per enrollment row
15-//! whether a *rival* class still claims it.
15+//! the other takes the instance and everything the class taught under it, and
16+//! the member exits release the enrollment rows the ended stint owned — one
17+//! row per *instance*, so a section's exit never touches the seat the student
18+//! holds in another section.
1619 //!
1720 //! Every invariant is one Postgres statement or one row lock, in the shapes
1821 //! [`crate::db::cap`] documents: the class counter is claimed by a conditional
1922 //! `UPDATE` fused with the link's `INSERT` (one CTE — a refused insert takes
20-//! its own seat bump back), a duplicate is the link table's natural composite
21-//! primary key answering as `23505`, a gone parent is a real `FOREIGN KEY`
22-//! answering as `23503`, and the row locks (`FOR KEY SHARE` / `FOR NO KEY
23-//! UPDATE`) put each transaction on the very record a racing writer must
24-//! touch. A refusal is an early `Err` (or an `Ok` verdict) from the
23+//! its own bump back), a duplicate live stint is the partial unique index
24+//! `class_member_live_pair` answering as `23505` (and enrollment's natural
25+//! `(class_course, app_user)` key doing the same job through `ON CONFLICT`),
26+//! a gone parent is a real `FOREIGN KEY` answering as `23503`, and the row
27+//! locks (`FOR KEY SHARE` / `FOR NO KEY UPDATE` / `FOR UPDATE`) put each
28+//! transaction on the very record a racing writer must touch. A refusal is an
29+//! early `Err` (or an `Ok` verdict) from the
2530 //! [`crate::database::tx_with_retry`] closure — a decision, never a retry.
2631
2732 use sqlx::postgres::PgConnection;
2833
2934 use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
3035 use crate::database::{Database, foreign_key_violation, tx_with_retry, unique_violation};
31-use crate::db::cap;
3236 use crate::domain::class_blueprint::ClassBlueprintId;
33-use crate::domain::class_course::ClassCourse;
37+use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati};
3438 use crate::domain::class_group::ClassGroupId;
35-use crate::domain::class_member::ClassMember;
39+use crate::domain::class_member::{ClassMember, ClassMemberId};
3640 use crate::domain::course::CourseId;
3741 use crate::domain::role::Role;
3842 use crate::domain::timestamp::Timestamp;
@@ -72,13 +76,12 @@ pub(crate) enum Attached<T> {
7276 /// be. Only a class predating the ceilings can be here, and only its own
7377 /// axis can make room — which is why it is not [`Attached::ClassFull`].
7478 ClassOverloaded,
75- /// One of the courses had no free seat, named by its key. Nothing was
76- /// written — not one of the earlier seats in the same run, which is the
77- /// whole point of doing this in a transaction.
78- Full(String),
79- /// One of the courses the class carries no longer exists, named by its id:
80- /// a stale `class_course` link. Nothing was written, and no capacity anyone
81- /// can raise will change that answer.
79+ /// One of the class's instances no longer exists, named by its id: a
80+ /// `class_course` row a concurrent detach took while this pump was walking
81+ /// its pairs. Nothing was written — not one of the earlier rows in the
82+ /// same run, which is the whole point of doing this in a transaction. No
83+ /// capacity anyone can raise will change that answer; the attach must be
84+ /// retried against the class as it now stands.
8285 CourseGone(String),
8386 /// The blueprint this attach was sourced from is gone — a delete landed
8487 /// between the pump reading the template and this transaction running.
@@ -105,8 +108,9 @@ impl<T> Attached<T> {
105108 /// *course* delete ([`Attached::PivotGone`] → `course_deleted`) — and
106109 /// telling a manager the class vanished when the course did sends them to
107110 /// look at a section that is standing right there. `linked_course_missing`
108- /// is a third: *another* course already attached to this class no longer
109- /// exists, and it must be detached before this attach can be retried.
111+ /// is a third: one of the class's *instances* vanished while the pump was
112+ /// walking its pairs (a concurrent detach), so the attach must be retried
113+ /// against the class as it now stands.
110114 /// `blueprint_deleted` is a pump losing the template itself mid-run — the
111115 /// only refusal that says nothing about the (class, course) pair it names.
112116 ///
@@ -124,7 +128,6 @@ impl<T> Attached<T> {
124128 Attached::PivotGone => Some("course_deleted"),
125129 Attached::ClassFull => Some(axis.at_ceiling_code()),
126130 Attached::ClassOverloaded => Some(axis.other().over_ceiling_code()),
127- Attached::Full(_) => Some("course_full"),
128131 Attached::CourseGone(_) => Some("linked_course_missing"),
129132 Attached::SourceGone => Some("blueprint_deleted"),
130133 }
@@ -228,11 +231,14 @@ fn refusal_of<T>(early: Early) -> Attached<T> {
228231 /// The gates that run before any counter moves, in the order their answers
229232 /// outrank each other:
230233 ///
231-/// 1. **Duplicate** — "you are already in" outranks "there is no room": a
232-/// caller whose row a rival placed a moment ago must not be told a course
233-/// is full about seats they already hold. (The link table's own primary key
234-/// re-answers this below as `23505` for a rival landing inside the window —
235-/// same verdict, no second seat.)
234+/// 1. **Duplicate** — "you are already in" outranks every other answer: a
235+/// caller whose row a rival placed a moment ago must be told they are in,
236+/// not refused for a class ceiling they are not near. The member axis reads
237+/// a **live** stint (a left one claims nothing, so rejoining is not a
238+/// duplicate); the course axis reads the (class, course) pair. (The link
239+/// tables re-answer this below — `23505` on the live-stint partial index,
240+/// `ON CONFLICT DO NOTHING` on the enrollment pair — for a rival landing
241+/// inside the window: same verdict, no second count.)
236242 /// 2. **Source** — the blueprint that asked for this attach is still there. A
237243 /// `FOR KEY SHARE` row lock on the blueprint row: it serializes the attach
238244 /// against the blueprint's own delete — the closure the old process-wide
@@ -265,7 +271,8 @@ async fn early_verdicts(
265271 ) -> Result<(Option<Early>, Option<uuid::Uuid>), AppError> {
266272 let held = match pivot {
267273 Pivot::User(user) => sqlx::query_scalar!(
268- r#"SELECT 1 AS "one" FROM class_member WHERE class = $1 AND app_user = $2"#,
274+ r#"SELECT 1 AS "one" FROM class_member
275+ WHERE class = $1 AND app_user = $2 AND left_at IS NULL"#,
269276 class as _,
270277 user as _
271278 )
@@ -350,13 +357,12 @@ async fn early_verdicts(
350357 Ok((over.then_some(Early::Overloaded), source_id))
351358 }
352359
353-/// Write the member link and enroll the student into every course the class is
354-/// already attached to, or write nothing at all.
360+/// Write the member stint and enroll the student into every instance the
361+/// class already carries, or write nothing at all.
355362 ///
356-/// A student already enrolled in one of those courses keeps the row they
357-/// have — no seat is charged, and the existing row's `source` is left exactly
363+/// A student already enrolled in one of those instances keeps the row they
364+/// have — no count charged, and the existing row's `source` is left exactly
358365 /// as it was, so a hand-placed student is never quietly adopted by a class.
359-/// A course with no free seat refuses the *whole* join rather than half of it.
360366 ///
361367 /// The class counter is claimed by the conditional half of the CTE below
362368 /// rather than a bare increment, so a class deleted out from under this run
@@ -366,18 +372,45 @@ async fn early_verdicts(
366372 /// this transaction — finite: [`Attached::ClassFull`] once the class is at its
367373 /// ceiling. Claim and insert are one statement, so a refused insert takes its
368374 /// own seat bump back.
375+///
376+/// The stint is live (`left_at` NULL) by construction, which is the row the
377+/// partial unique index `class_member_live_pair` guards: a rival landing in
378+/// the window is answered as [`Attached::Duplicate`] rather than a second
379+/// live stint for the same pair. A student who left earlier keeps their
380+/// history row — it claims nothing.
369381 pub(crate) async fn add_member(
370382 db: &Database,
371383 class: &ClassGroupId,
372384 user: &UserId,
373385 by: &UserId,
374386 ) -> Result<Attached<ClassMember>, AppError> {
375- let added_at = Timestamp::now();
387+ add_member_sourced(db, class, user, by, None).await
388+}
389+
390+/// [`add_member`] carrying the stint's *provenance*: the şube the student was
391+/// copied from, written into `source_class_group` in the same statement as
392+/// the row. `None` is the hand add — a student someone put here, who came
393+/// from nowhere (the pump is the only writer of this column, and a rollover
394+/// is the only caller that has a source to name).
395+///
396+/// Everything else — the claim, the cap, the duplicate verdict, the pair loop
397+/// — is identical, and deliberately so: the tag rides the member axis's own
398+/// single statement rather than a follow-up write, so a crash cannot leave a
399+/// copied stint that lost its provenance.
400+pub(crate) async fn add_member_sourced(
401+ db: &Database,
402+ class: &ClassGroupId,
403+ user: &UserId,
404+ by: &UserId,
405+ source: Option<&ClassGroupId>,
406+) -> Result<Attached<ClassMember>, AppError> {
407+ let joined_at = Timestamp::now();
376408 let class = class.clone();
409+ let source = source.cloned();
377410 let (user, by) = (*user, *by);
411+ let id = ClassMemberId::generate();
378412 let outcome = tx_with_retry(db, false, async move |tx| {
379- let (early, _) =
380- early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?;
413+ let (early, _) = early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?;
381414 if let Some(early) = early {
382415 return Ok(refusal_of(early));
383416 }
@@ -389,23 +422,27 @@ pub(crate) async fn add_member(
389422 UPDATE class_group SET class_member_count = class_member_count + 1
390423 WHERE id = $1 AND class_member_count < $2
391424 RETURNING 1)
392- INSERT INTO class_member (class, app_user, added_by, added_at)
393- SELECT $1, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat)
425+ INSERT INTO class_member (id, class, app_user, added_by, joined_at, left_at,
426+ source_class_group)
427+ SELECT $3, $1, $4, $5, $6, NULL, $7 WHERE EXISTS (SELECT 1 FROM seat)
394428 RETURNING 1 AS "one""#,
395429 class as _,
396430 Axis::Member.cap(),
431+ id.uuid(),
397432 user as _,
398433 by as _,
399- added_at as _
434+ joined_at as _,
435+ source.as_ref().map(ClassGroupId::uuid),
400436 )
401437 .fetch_optional(&mut *tx)
402438 .await
403439 {
404440 Ok(result) => result,
405441 // A rival landed in the window between the gate and the insert:
406- // the link table's own primary key answers, same verdict as the
407- // gate, no second seat.
408- Err(e) if unique_violation(&e) == Some("class_member_class_user") => {
442+ // the live-stint partial index answers, same verdict as the gate,
443+ // no second seat. (A left row is not in that index, so a rejoin
444+ // after a leave is never a duplicate.)
445+ Err(e) if unique_violation(&e) == Some("class_member_live_pair") => {
409446 return Ok(Attached::Duplicate);
410447 }
411448 // The student row vanished mid-run despite the locked pivot claim.
@@ -428,36 +465,59 @@ pub(crate) async fn add_member(
428465 Attached::Gone
429466 });
430467 }
431- let courses: Vec<uuid::Uuid> = sqlx::query_scalar!(
432- r#"SELECT course AS "course: uuid::Uuid" FROM class_course WHERE class = $1"#,
468+ // The pairs are the class's *instances*, one per attached course: the
469+ // member axis now enrolls into the class×course instance, not into a
470+ // school-wide course row.
471+ let instances: Vec<uuid::Uuid> = sqlx::query_scalar!(
472+ r#"SELECT id AS "id: uuid::Uuid" FROM class_course WHERE class = $1"#,
433473 class as _
434474 )
435475 .fetch_all(&mut *tx)
436476 .await?;
437- let pairs = courses.into_iter().map(|course| (course, user.uuid()));
477+ let pairs = instances
478+ .into_iter()
479+ .map(|instance| (instance, user.uuid()));
438480 enroll_pairs(tx, &class, pairs, &by).await?;
439481 Ok(Attached::Made(ClassMember {
482+ id: id.clone(),
440483 class: class.clone(),
441484 user,
442485 added_by: by,
486+ joined_at,
487+ left_at: None,
488+ source_class_group: source.clone(),
443489 }))
444490 })
445491 .await;
446492 map_sweep_abort(outcome)
447493 }
448494
449-/// Write the course link and enroll the class's whole roster into it, or
495+/// Write the instance and enroll the class's whole live roster into it, or
450496 /// write nothing at all.
451497 ///
452-/// Students already in the course keep the rows they have — no seat charged,
453-/// `source` untouched — and a roster that does not fit refuses the whole
454-/// attach rather than filling the course to its cap and stopping.
498+/// Students already enrolled in it keep the rows they have — no count charged,
499+/// `source` untouched. There is no roster-size gate any more (D5: the
500+/// counter is a count, not a capacity), so the only refusals left are the
501+/// class's own ceilings and a vanished pivot.
455502 ///
456503 /// `source` is the blueprint whose behalf this attach runs on, and supplying
457504 /// it adds one more claim: that it is still there when the transaction runs
458505 /// ([`Attached::SourceGone`]) — the `FOR KEY SHARE` lock that serializes this
459506 /// transaction against the blueprint's own delete. A hand attach owns itself
460507 /// and passes `None`.
508+///
509+/// The instance's own id is minted here (v7, so a class's instances list in
510+/// creation order) and its policy columns take the schema defaults: one weekly
511+/// hour, counted toward the karne, an empty roster. A PATCH on `/instances`
512+/// changes them afterwards.
513+///
514+/// Two counters ride the write, both in this one transaction: the class's
515+/// `class_course_count` (claimed by the conditional CTE, so a full or gone
516+/// class writes nothing) and the *catalog's* `class_course_count` — how many
517+/// şubeler teach this course, which is what [`crate::db::course::delete`]'s
518+/// guard reads. This is the only insert path into `class_course`; every layer
519+/// above it (hand attach, blueprint pump, rollover copy) reaches the counter
520+/// through here.
461521 pub(crate) async fn attach_course(
462522 db: &Database,
463523 class: &ClassGroupId,
@@ -470,6 +530,7 @@ pub(crate) async fn attach_course(
470530 let course = course.clone();
471531 let by = *by;
472532 let source = source.cloned();
533+ let id = ClassCourseId::generate();
473534 let outcome = tx_with_retry(db, false, async move |tx| {
474535 let (early, source_id) = early_verdicts(
475536 tx,
@@ -487,11 +548,12 @@ pub(crate) async fn attach_course(
487548 UPDATE class_group SET class_course_count = class_course_count + 1
488549 WHERE id = $1 AND class_course_count < $2
489550 RETURNING 1)
490- INSERT INTO class_course (class, course, attached_by, attached_at, source)
491- SELECT $1, $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)
551+ INSERT INTO class_course (id, class, course, attached_by, attached_at, source)
552+ SELECT $3, $1, $4, $5, $6, $7 WHERE EXISTS (SELECT 1 FROM seat)
492553 RETURNING 1 AS "one""#,
493554 class as _,
494555 Axis::Course.cap(),
556+ id.uuid(),
495557 course as _,
496558 by as _,
497559 attached_at as _,
@@ -521,19 +583,51 @@ pub(crate) async fn attach_course(
521583 Attached::Gone
522584 });
523585 }
586+ // The catalog's own counter: how many şubeler teach this course. It is
587+ // what [`crate::db::course::delete`]'s guard reads — a course a class
588+ // still teaches may not go — and this insert is the only place it can
589+ // be claimed. It is a *count*, not a capacity (D5: nothing is refused
590+ // for being near it), so it is a plain increment in the same
591+ // transaction as the row: the link and its count commit together, and
592+ // the early refusals above (a full or gone class, a lost insert) have
593+ // already returned, so no give-back path exists to get wrong.
594+ sqlx::query!(
595+ r#"UPDATE course SET class_course_count = class_course_count + 1 WHERE id = $1"#,
596+ course as _
597+ )
598+ .execute(&mut *tx)
599+ .await?;
600+ // The roster is the class's *live* stints: a student who left holds no
601+ // seat and is enrolled in nothing the class attaches afterwards.
524602 let members: Vec<uuid::Uuid> = sqlx::query_scalar!(
525- r#"SELECT app_user AS "app_user: uuid::Uuid" FROM class_member WHERE class = $1"#,
603+ r#"SELECT app_user AS "app_user: uuid::Uuid" FROM class_member
604+ WHERE class = $1 AND left_at IS NULL"#,
526605 class as _
527606 )
528607 .fetch_all(&mut *tx)
529608 .await?;
530- let pairs = members.into_iter().map(|user| (course.uuid(), user));
609+ let pairs = members.into_iter().map(|user| (id.uuid(), user));
531610 enroll_pairs(tx, &class, pairs, &by).await?;
611+ // The counter the pair loop just moved, read back inside the
612+ // transaction so the returned row reports the roster it now has
613+ // rather than the empty one it was inserted with.
614+ let enrollment_count = sqlx::query_scalar!(
615+ r#"SELECT enrollment_count AS "count: i64" FROM class_course WHERE id = $1"#,
616+ id.uuid()
617+ )
618+ .fetch_one(&mut *tx)
619+ .await?;
532620 Ok(Attached::Made(ClassCourse {
621+ id: id.clone(),
533622 class: class.clone(),
534623 course: course.clone(),
535624 attached_by: by,
536625 source: source.clone(),
626+ ders_saati: DersSaati::try_new(crate::constant::MIN_DERS_SAATI)
627+ .expect("the schema default is a valid weekly-hours count"),
628+ counts_toward_karne: true,
629+ enrollment_count,
630+ attached_at,
537631 }))
538632 })
539633 .await;
@@ -543,11 +637,10 @@ pub(crate) async fn attach_course(
543637 /// Abort markers the pair loop raises where the old transaction `THROW` did,
544638 /// in the [`crate::db::field_update`] style: a refusal found *after* earlier
545639 /// pairs wrote must take the whole run down with it — returning it as `Ok`
546-/// would COMMIT the partial enrollment. The marker carries the course's key
640+/// would COMMIT the partial enrollment. The marker carries the instance's id
547641 /// and is mapped back to [`Attached`] right after [`tx_with_retry`] returns
548642 /// ([`map_sweep_abort`]); it never reaches the wire.
549643 const COURSE_GONE_MARK: &str = "class_pump_course_gone:";
550-const COURSE_FULL_MARK: &str = "class_pump_course_full:";
551644
552645 /// The pair loop's abort markers back into their [`Attached`] refusals —
553646 /// every other outcome passes through untouched.
@@ -556,28 +649,24 @@ fn map_sweep_abort<T>(outcome: Result<Attached<T>, AppError>) -> Result<Attached
556649 Err(AppError::Internal(m)) if m.starts_with(COURSE_GONE_MARK) => Ok(Attached::CourseGone(
557650 m[COURSE_GONE_MARK.len()..].to_string(),
558651 )),
559- Err(AppError::Internal(m)) if m.starts_with(COURSE_FULL_MARK) => {
560- Ok(Attached::Full(m[COURSE_FULL_MARK.len()..].to_string()))
561- }
562652 other => other,
563653 }
564654 }
565655
566-/// Enroll every `(course, user)` pair that has no row yet, each against its
567-/// own course's capacity, skipping — never charging — the pairs that do.
656+/// Enroll every `(instance, user)` pair that has no row yet, and charge the
657+/// instance's roster counter only for the rows actually written.
568658 ///
569-/// Per pair, in the order the refusals outrank each other: the pair's own row
570-/// answers "already enrolled" (skip, no seat); the course row answers "gone"
571-/// *before* the seat claim, so a stale link is never mis-reported as a
572-/// capacity problem; the seat claim is a conditional `UPDATE` on the course
573-/// row (live cap — `capacity` as it stands at write time, `NULL` reading as
574-/// unlimited); and the insert rides the seat it claimed. A rival that lands
575-/// between the gate and the insert answers `23505`, and the bump is given
576-/// back before the skip — the outcome a re-sent transaction used to reach by
577-/// seeing the rival's row at its gate.
659+/// Per pair, in the order the answers outrank each other: the pair's own row
660+/// answers "already enrolled" (skip, no count moved); the counter claim is a
661+/// plain increment on the instance row, so it doubles as the existence check —
662+/// a claim matching nothing is an instance a concurrent detach took, which is
663+/// the abort marker rather than a refusal of this pair alone; and then the
664+/// row is inserted with `ON CONFLICT DO NOTHING`, so a rival landing between
665+/// the gate and the insert leaves *their* row standing and this run gives its
666+/// own claim back before the skip.
578667 ///
579668 /// Every abort stops the loop inside the caller's transaction: not one of the
580-/// earlier seats in the same run survives, which is the whole point of doing
669+/// earlier rows in the same run survives, which is the whole point of doing
581670 /// this in a transaction.
582671 async fn enroll_pairs(
583672 tx: &mut PgConnection,
@@ -586,10 +675,10 @@ async fn enroll_pairs(
586675 by: &UserId,
587676 ) -> Result<(), AppError> {
588677 let now = Timestamp::now();
589- for (course, user) in pairs {
678+ for (instance, user) in pairs {
590679 let held = sqlx::query_scalar!(
591- r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
592- course,
680+ r#"SELECT 1 AS "one" FROM enrollment WHERE class_course = $1 AND app_user = $2"#,
681+ instance,
593682 user
594683 )
595684 .fetch_optional(&mut *tx)
@@ -598,32 +687,27 @@ async fn enroll_pairs(
598687 if held {
599688 continue;
600689 }
601- let alive = sqlx::query_scalar!(r#"SELECT 1 AS "one" FROM course WHERE id = $1"#, course)
602- .fetch_optional(&mut *tx)
603- .await?
604- .is_some();
605- if !alive {
606- return Err(AppError::Internal(format!("{COURSE_GONE_MARK}{course}")));
607- }
608- let seat = sqlx::query_scalar!(
609- r#"UPDATE course SET enrollment_count = enrollment_count + 1
610- WHERE id = $1 AND enrollment_count < COALESCE(capacity, $2)
690+ // The claim doubles as the existence check: there is no capacity to
691+ // refuse on, so an increment that matches no row means the instance is
692+ // gone — a stale link, never a full roster.
693+ let claimed = sqlx::query_scalar!(
694+ r#"UPDATE class_course SET enrollment_count = enrollment_count + 1
695+ WHERE id = $1
611696 RETURNING 1 AS "one""#,
612- course,
613- cap::UNLIMITED,
697+ instance,
614698 )
615699 .fetch_optional(&mut *tx)
616700 .await?
617701 .is_some();
618- if !seat {
619- return Err(AppError::Internal(format!("{COURSE_FULL_MARK}{course}")));
702+ if !claimed {
703+ return Err(AppError::Internal(format!("{COURSE_GONE_MARK}{instance}")));
620704 }
621705 let wrote = sqlx::query_scalar!(
622- r#"INSERT INTO enrollment (course, app_user, enrolled_by, source, created_at)
706+ r#"INSERT INTO enrollment (class_course, app_user, enrolled_by, source, created_at)
623707 VALUES ($1, $2, $3, $4, $5)
624- ON CONFLICT (course, app_user) DO NOTHING
708+ ON CONFLICT (class_course, app_user) DO NOTHING
625709 RETURNING 1 AS "one""#,
626- course,
710+ instance,
627711 user,
628712 by as _,
629713 class as _,
@@ -634,23 +718,15 @@ async fn enroll_pairs(
634718 match wrote {
635719 Ok(Some(_)) => {}
636720 // A rival placed the pair in the window: their row stands, no
637- // second seat, and the claim this run took is given back — the
638- // skip wins over the capacity answer, exactly as a re-sent
639- // transaction found the row at its gate.
721+ // second count, and the claim this run took is given back — the
722+ // skip wins, exactly as a re-sent transaction found the row at its
723+ // gate.
640724 Ok(None) => {
641725 sqlx::query!(
642- r#"UPDATE course SET enrollment_count = enrollment_count - 1
643- WHERE id = $1"#,
644- course
645- )
646- .execute(&mut *tx)
647- .await?;
648- }
649- Err(e) if unique_violation(&e) == Some("enrollment_course_user") => {
650- sqlx::query!(
651- r#"UPDATE course SET enrollment_count = enrollment_count - 1
652- WHERE id = $1"#,
653- course
726+ r#"UPDATE class_course
727+ SET enrollment_count = GREATEST(enrollment_count - 1, 0)
728+ WHERE id = $1"#,
729+ instance
654730 )
655731 .execute(&mut *tx)
656732 .await?;
@@ -672,54 +748,106 @@ async fn enroll_pairs(
672748 // were left pointing at a class no sweep could ever reach again.
673749
674750 /// Take a student out of a class and sweep the enrollments the class pumped
675-/// for them. Answers how many link rows went (0 or 1), so the caller can turn
751+/// for them. Answers how many stints went (0 or 1), so the caller can turn
676752 /// zero into a 404.
677753 ///
678-/// The sweep is *repair-first*: an enrollment this class wrote is only deleted
679-/// once no other class still claims it. Two classes attached to the same
680-/// course share a student — the second attach skipped the row the first had
681-/// already written, so the row carries only the first class's name — and
682-/// deleting it on the first class's way out would unenroll a student the
683-/// second class is still responsible for. So the row is re-tagged to that
684-/// rival instead, and only a row nobody is left to claim is deleted and its
685-/// seat given back. The heir is the lowest class id among the claimants: a
686-/// deterministic pick (uuid order is mint order), so a repeat of the same
687-/// sweep lands on the same class.
754+/// This is the hard form — the row is deleted — and it is kept only for the
755+/// transfer rollback path, where the stint being undone must leave no trace.
756+/// The route uses [`leave_member`], which stamps `left_at` and keeps the
757+/// history.
758+pub(crate) async fn remove_member(
759+ db: &Database,
760+ class: &ClassGroupId,
761+ user: &UserId,
762+) -> Result<i64, AppError> {
763+ drop_member(db, class, user, false).await
764+}
765+
766+/// The same exit, soft: `left_at` is stamped and the row stays as history.
767+/// The roster read and the cap both filter on `left_at IS NULL`, so the
768+/// student holds no seat from this moment — and a rejoin later inserts a
769+/// fresh live row beside this one (the partial unique index only guards the
770+/// live stint), which is how "left in October, came back in January" is
771+/// represented.
772+///
773+/// Both exits take the user row `FOR NO KEY UPDATE` first — the same lock the
774+/// pump's pivot claim and a role-change sweep take — so a demotion cannot
775+/// interleave with this write in either direction.
776+pub(crate) async fn leave_member(
777+ db: &Database,
778+ class: &ClassGroupId,
779+ user: &UserId,
780+) -> Result<i64, AppError> {
781+ drop_member(db, class, user, true).await
782+}
783+
784+/// The one body both exits run: find the live stint, end it, give the class
785+/// its seat back, and release the enrollments the class pumped for the
786+/// student.
688787 ///
689-/// That pick is then **claimed** — a `FOR NO KEY UPDATE` read of the heir's
690-/// class row, no counter moved — before the row is handed over. Both reads
691-/// behind it are pure, and this sweep is long — one pass per enrollment row
692-/// the link implies — so `DELETE /classes/{heir}/members/{user}` and
693-/// `DELETE /classes/{heir}/courses/{course}` could both commit inside it and
694-/// leave the row tagged with a class holding neither link: a `class_group`
695-/// whose own 0/0 delete guard then passes, stranding an enrollment nothing can
696-/// ever sweep. Every one of those writers moves a counter on the heir's own
697-/// row, so the row lock here puts this transaction on the record they write
698-/// and the two settle in either order. A claim that matches nothing is an
699-/// heir whose class row is gone — a stale link outliving its class — and it
700-/// takes the release arm rather than tagging the row with an id no route can
701-/// reach.
788+/// The sweep's rule, and it is the whole rule: **every row the ended stint
789+/// owned goes, and each instance gets its roster count back**. An enrollment
790+/// is keyed `(class_course, app_user)` — one row per *instance* — so a student
791+/// in two şubeler that teach the same course holds two rows, one on each
792+/// section's instance, and the seat they keep is the other section's own row,
793+/// written when they joined it. Handing this row over to a rival class (the
794+/// pre-remodel rule, when one school-wide course carried one roster) would
795+/// leave the leaving section's roster, exams and roll-call still listing a
796+/// student who left it, with its `enrollment_count` inflated on top — a
797+/// "repair" that repairs nothing, because there was never a shortage of rows
798+/// to repair.
702799 ///
703-/// Sweeps tolerate rows that are already gone. A course delete wipes a
704-/// course's enrollments wholesale while the `class_member` rows survive it, so
800+/// Only the rows *this class* wrote are in the list ([`drop_member`] reads
801+/// `source = <class>`), so a hand-placed enrollment — the operator's own, or
802+/// one a section handed over before this rule — is never touched.
803+///
804+/// Sweeps tolerate rows that are already gone: an instance detach wipes its
805+/// own enrollments wholesale while the `class_member` rows survive it, so
705806 /// "this class has a member" and "that member has a live pumped row" are
706-/// independent facts and the loop simply finds nothing to sweep.
707-pub(crate) async fn remove_member(
807+/// independent facts and the loop simply finds nothing to sweep (and, because
808+/// [`release`] only gives a count back for a row it actually deleted, takes
809+/// nothing back twice).
810+async fn drop_member(
708811 db: &Database,
709812 class: &ClassGroupId,
710813 user: &UserId,
814+ soft: bool,
711815 ) -> Result<i64, AppError> {
712816 let class = class.clone();
713817 let user = *user;
818+ let now = Timestamp::now();
714819 tx_with_retry(db, true, async move |tx| {
715- let gone = sqlx::query_scalar!(
716- r#"DELETE FROM class_member WHERE class = $1 AND app_user = $2
717- RETURNING 1 AS "one""#,
718- class as _,
820+ // The role-claim handshake: the same `FOR NO KEY UPDATE` the pump's
821+ // pivot takes, so a demotion's sweep and this exit serialize on the
822+ // user row rather than interleaving.
823+ sqlx::query!(
824+ r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#,
719825 user as _
720826 )
721827 .fetch_optional(&mut *tx)
722828 .await?;
829+ let gone = if soft {
830+ sqlx::query_scalar!(
831+ r#"UPDATE class_member SET left_at = $3
832+ WHERE class = $1 AND app_user = $2 AND left_at IS NULL
833+ RETURNING 1 AS "one""#,
834+ class as _,
835+ user as _,
836+ now as _
837+ )
838+ .fetch_optional(&mut *tx)
839+ .await?
840+ } else {
841+ sqlx::query_scalar!(
842+ r#"DELETE FROM class_member
843+ WHERE class = $1 AND app_user = $2 AND left_at IS NULL
844+ RETURNING 1 AS "one""#,
845+ class as _,
846+ user as _
847+ )
848+ .fetch_optional(&mut *tx)
849+ .await?
850+ };
723851 let Some(_) = gone else {
724852 return Ok(0);
725853 };
@@ -731,8 +859,11 @@ pub(crate) async fn remove_member(
731859 )
732860 .execute(&mut *tx)
733861 .await?;
862+ // Only the rows *this class* wrote: a hand-placed enrollment is the
863+ // operator's and is never taken back by a class sweep.
734864 let rows = sqlx::query!(
735- r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid"
865+ r#"SELECT class_course AS "class_course: uuid::Uuid",
866+ app_user AS "app_user: uuid::Uuid"
736867 FROM enrollment WHERE app_user = $1 AND source = $2"#,
737868 user as _,
738869 class as _
@@ -740,36 +871,70 @@ pub(crate) async fn remove_member(
740871 .fetch_all(&mut *tx)
741872 .await?
742873 .into_iter()
743- .map(|row| (row.course, row.app_user))
874+ .map(|row| (row.class_course, row.app_user))
744875 .collect::<Vec<_>>();
745- sweep_enrollments(tx, &class, rows).await?;
876+ // Every row this class's tag owns goes, and each instance gets its
877+ // roster count back — see the doc above: the student's seat in a
878+ // second şube teaching the same course is that şube's *own* row, so
879+ // there is no heir to hand this one over to.
880+ for (instance, member) in rows {
881+ release(tx, instance, member).await?;
882+ }
746883 Ok(1)
747884 })
748885 .await
749886 }
750887
751-/// Detach `course` from `class` and sweep the enrollments the class pumped
752-/// into it. `source`, when given, re-asserts the provenance tag on the link's
753-/// own delete — a blueprint sweep may only take back rows its own tag owns.
754-/// Answers how many link rows went, so a caller whose link was a single pair
755-/// can turn zero into a 404. The sweep underneath is the shared one: a student
756-/// a second class still claims is re-tagged rather than unenrolled.
888+/// Detach one instance from its class and sweep what hangs off it. `source`,
889+/// when given, re-asserts the provenance tag on the link's own delete — a
890+/// blueprint sweep may only take back rows its own tag owns. Answers the blob
891+/// keys of the image and homework-file rows the sweep removed, or `None` when
892+/// the pair held no instance at all (nothing written), so a caller whose link
893+/// was a single pair can turn `None` into a 404 while a detach that removed an
894+/// instance carrying no uploads still reads as one that went.
895+///
896+/// The instance is the anchor now, so detaching it takes everything the class
897+/// taught under it: its exams (with their results and questions), its sessions
898+/// with their roll call, its homework with its submissions, its roster and its
899+/// teacher links. That is the same cascade a course delete runs
900+/// ([`crate::db::course::sweep_instance_subtree`]), scoped to one instance —
901+/// and it has to be, because every one of those rows names the instance as its
902+/// parent key (`ON DELETE NO ACTION`), so deleting the instance while they
903+/// stand is refused by the store itself.
904+///
905+/// The sweep runs behind a `FOR UPDATE` claim on the instance row: a rival
906+/// detach waits here and finds nothing left to sweep, so exactly one
907+/// transaction unlinks the pair and gives the class its counter back — and
908+/// with it the catalog's `class_course_count`, the count
909+/// [`crate::db::course::delete`]'s guard reads (`course::delete` needs no
910+/// release of its own: it deletes the course row the counter lives on).
911+/// This is the only delete path for an instance that does *not* remove the
912+/// course: the hand detach and the blueprint sweep both come through it.
913+///
914+/// The image and homework-file *blobs* the cascade removes come back as keys
915+/// and are unlinked by the caller, after the commit — the same shape
916+/// [`crate::service::course::delete`] has. The rows are gone the moment this
917+/// returns, so a caller that drops the list strands the bytes on disk with
918+/// nothing left pointing at them.
757919 pub(crate) async fn detach_course(
758920 db: &Database,
759921 class: &ClassGroupId,
760922 course: &CourseId,
761923 source: Option<&ClassBlueprintId>,
762-) -> Result<i64, AppError> {
924+) -> Result<Option<Vec<String>>, AppError> {
763925 let class = class.clone();
764926 let course = course.clone();
765927 let source = source.cloned();
766928 tx_with_retry(db, true, async move |tx| {
767- let gone = match &source {
929+ // The claim and the resolution in one read: the row this returns is
930+ // the very row the lock holds against a rival detach.
931+ let target = match &source {
768932 Some(source) => {
769933 sqlx::query_scalar!(
770- r#"DELETE FROM class_course WHERE class = $1 AND course = $2
934+ r#"SELECT id AS "id: uuid::Uuid" FROM class_course
935+ WHERE class = $1 AND course = $2
771936 AND source = (SELECT id FROM class_blueprint WHERE grade = $3)
772- RETURNING 1 AS "one""#,
937+ FOR UPDATE"#,
773938 class as _,
774939 course as _,
775940 source as _
@@ -779,8 +944,8 @@ pub(crate) async fn detach_course(
779944 }
780945 None => {
781946 sqlx::query_scalar!(
782- r#"DELETE FROM class_course WHERE class = $1 AND course = $2
783- RETURNING 1 AS "one""#,
947+ r#"SELECT id AS "id: uuid::Uuid" FROM class_course
948+ WHERE class = $1 AND course = $2 FOR UPDATE"#,
784949 class as _,
785950 course as _
786951 )
@@ -788,9 +953,13 @@ pub(crate) async fn detach_course(
788953 .await?
789954 }
790955 };
791- let Some(_) = gone else {
792- return Ok(0);
956+ let Some(instance) = target else {
957+ return Ok(None);
793958 };
959+ let blobs = crate::db::course::sweep_instance_subtree(&mut *tx, instance).await?;
960+ sqlx::query!(r#"DELETE FROM class_course WHERE id = $1"#, instance)
961+ .execute(&mut *tx)
962+ .await?;
794963 sqlx::query!(
795964 r#"UPDATE class_group
796965 SET class_course_count = GREATEST(class_course_count - 1, 0)
@@ -799,92 +968,41 @@ pub(crate) async fn detach_course(
799968 )
800969 .execute(&mut *tx)
801970 .await?;
802- let rows = sqlx::query!(
803- r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid"
804- FROM enrollment WHERE course = $1 AND source = $2"#,
805- course as _,
806- class as _
807- )
808- .fetch_all(&mut *tx)
809- .await?
810- .into_iter()
811- .map(|row| (row.course, row.app_user))
812- .collect::<Vec<_>>();
813- sweep_enrollments(tx, &class, rows).await?;
814- Ok(1)
815- })
816- .await
817-}
818-
819-/// The repair-first tail both detaches share: for every enrollment row the
820-/// deleted link owned, hand it to a rival class that still claims it, or
821-/// delete it and give the course its seat back.
822-///
823-/// The heir is the lowest class id among the rivals that carry both this
824-/// course *and* the student — the same deterministic pick on every repeat. Its
825-/// class row is read `FOR NO KEY UPDATE` (a claim that moves no counter: the
826-/// class_member row already covers the student, and the enrollment is counted
827-/// on the course) so a concurrent member/course write on the heir serializes
828-/// behind this transaction; a claim matching nothing is a gone heir, and the
829-/// row takes the release arm.
830-async fn sweep_enrollments(
831- tx: &mut PgConnection,
832- class: &ClassGroupId,
833- rows: Vec<(uuid::Uuid, uuid::Uuid)>,
834-) -> Result<(), AppError> {
835- for (course, user) in rows {
836- let heir = sqlx::query_scalar!(
837- r#"SELECT cm.class AS "class: uuid::Uuid"
838- FROM class_member cm
839- JOIN class_course cc ON cc.class = cm.class AND cc.course = $1
840- WHERE cm.app_user = $2 AND cm.class <> $3
841- ORDER BY cm.class
842- LIMIT 1"#,
843- course,
844- user,
845- class as _
846- )
847- .fetch_optional(&mut *tx)
848- .await?;
849- let Some(heir) = heir else {
850- release(tx, course, user).await?;
851- continue;
852- };
853- let claimed = sqlx::query_scalar!(
854- r#"SELECT class_member_count AS "heir_count: i64" FROM class_group
855- WHERE id = $1 FOR NO KEY UPDATE"#,
856- heir
857- )
858- .fetch_optional(&mut *tx)
859- .await?;
860- if claimed.is_none() {
861- release(tx, course, user).await?;
862- continue;
863- }
971+ // …and the catalog's own counter: the course is taught in one fewer
972+ // şube from this commit. Same transaction as the delete, so the link
973+ // and its count move together — `course::delete`'s guard reads this,
974+ // and a course whose last instance was just detached is deletable the
975+ // moment this lands. `GREATEST` for the same reason the class counter
976+ // uses it: a drift can only ever be repaired downward, never refused.
864977 sqlx::query!(
865- r#"UPDATE enrollment SET source = $1 WHERE course = $2 AND app_user = $3"#,
866- heir,
867- course,
868- user
978+ r#"UPDATE course SET class_course_count = GREATEST(class_course_count - 1, 0)
979+ WHERE id = $1"#,
980+ course as _
869981 )
870982 .execute(&mut *tx)
871983 .await?;
872- }
873- Ok(())
984+ Ok(Some(blobs))
985+ })
986+ .await
874987 }
875988
876-/// Nobody is left to claim the row: it goes, and its seat with it. The seat
877-/// is only given back when the delete actually took the row — a course
878-/// delete's wholesale sweep may have taken both while this transaction read
879-/// them, and both halves vanish together there.
989+/// The row goes, and the instance's roster count with it. It is the *only*
990+/// fate for an enrollment a section's exit owns: the roster is per instance
991+/// (D4), so a student who is also in another şube teaching the same course
992+/// keeps their seat there through that section's own row — see
993+/// [`drop_member`].
994+///
995+/// The count is only given back when the delete actually took the row — an
996+/// instance detach's wholesale sweep may have taken both while this
997+/// transaction read them, and both halves vanish together there.
880998 async fn release(
881999 tx: &mut PgConnection,
882- course: uuid::Uuid,
1000+ instance: uuid::Uuid,
8831001 user: uuid::Uuid,
8841002 ) -> Result<(), AppError> {
8851003 let deleted = sqlx::query!(
886- r#"DELETE FROM enrollment WHERE course = $1 AND app_user = $2"#,
887- course,
1004+ r#"DELETE FROM enrollment WHERE class_course = $1 AND app_user = $2"#,
1005+ instance,
8881006 user
8891007 )
8901008 .execute(&mut *tx)
@@ -892,22 +1010,24 @@ async fn release(
8921010 .rows_affected();
8931011 if deleted > 0 {
8941012 sqlx::query!(
895- r#"UPDATE course SET enrollment_count = GREATEST(enrollment_count - 1, 0)
896- WHERE id = $1"#,
897- course
1013+ r#"UPDATE class_course
1014+ SET enrollment_count = GREATEST(enrollment_count - 1, 0)
1015+ WHERE id = $1"#,
1016+ instance
8981017 )
8991018 .execute(&mut *tx)
9001019 .await?;
9011020 }
9021021 Ok(())
9031022 }
1023+
9041024 #[cfg(test)]
9051025 mod tests {
906-
1026+
9071027 use crate::db::class_member::tests::{a_class, counter, fixture_user, rows};
9081028 use crate::domain::class_group::ClassGroupId;
9091029 use crate::error::AppError;
910- use crate::service::{class_course, class_member};
1030+ use crate::service::class_member;
9111031
9121032 /// The class counter is claimed conditionally, so a class that is not there
9131033 /// stops the cascade before anything is written — rather than leaving a
@@ -971,100 +1091,4 @@ mod tests {
9711091 "a second removal is a 404, not a silent no-op: {again:?}"
9721092 );
9731093 }
974-
975- /// The heir a sweep hands a shared enrollment to must still hold *both*
976- /// links when the transaction commits — not merely when it read them.
977- ///
978- /// Two classes carry one course and one student, so the row names the first
979- /// and the second is its heir. While that first class's detach sweeps — a
980- /// pass per enrollment row, up to a full roster long — the heir drops the
981- /// student and detaches the course, both committed. Its two reads see an
982- /// heir that is already gone, and its write set (its own class, its own
983- /// link, the enrollment) touches nothing the heir's two deletes wrote: with
984- /// no read-set conflict detection, both sides commit and the row is left
985- /// tagged with a class holding neither link, which then passes its own 0/0
986- /// delete guard. The claim on the heir's counter is what puts the two
987- /// transactions on one record.
988- ///
989- /// Real server, and `#[ignore]`d for it, exactly like
990- /// [`crate::domain::class_course`]'s course-delete twin: the subject *is*
991- /// the store's conflict detection, which `init_mem`'s embedded engine does
992- /// not have — it commits both sides and answers `Ok` to each, so this passes
993- /// there on broken code.
994- ///
995- /// The window the old engine needed a schema event to open is the row
996- /// lock now: the owner's sweep claims the heir's class row before it
997- /// chooses the heir, so the heir's own member/course writes either land
998- /// wholly before the sweep reads them or wait behind it — and the
999- /// invariant below must hold in both orders. A barrier start lets every
1000- /// interleaving happen instead of pinning one.
1001- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1002- async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() {
1003- use crate::db::class_member::tests::{a_course, fixture_user, source_of};
1004-
1005- let (db, _leases) = crate::database::init_test_db().await;
1006- let manager = fixture_user(&db, "manager").await;
1007- let student = fixture_user(&db, "student").await;
1008- let (mut raced, mut stranded) = (0, 0);
1009- for round in 0..4 {
1010- let algebra = a_course(&format!("algebra{round}"), None, &db).await;
1011- let owner = a_class(&format!("9-{round}-owner"), &db).await;
1012- let heir = a_class(&format!("9-{round}-heir"), &db).await;
1013- for class in [&owner, &heir] {
1014- class_member::add(&db, class, &student, &manager)
1015- .await
1016- .unwrap();
1017- class_course::attach(&db, class, &algebra, &manager)
1018- .await
1019- .unwrap();
1020- }
1021- assert_eq!(
1022- source_of(&algebra, &student, &db).await,
1023- Some(Some(owner.clone())),
1024- "round {round}: the row must start out owned by the first class"
1025- );
1026-
1027- let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
1028- let detaching = {
1029- let (db, owner, algebra, gate) =
1030- (db.clone(), owner.clone(), algebra.clone(), gate.clone());
1031- tokio::spawn(async move {
1032- gate.wait().await;
1033- class_course::detach(&db, &owner, &algebra).await
1034- })
1035- };
1036- // The heir lets the row go, twice over, while the sweep is racing
1037- // it for the same enrollment row.
1038- let heir_moves = {
1039- let (db, heir, algebra, gate) =
1040- (db.clone(), heir.clone(), algebra.clone(), gate);
1041- tokio::spawn(async move {
1042- gate.wait().await;
1043- class_member::remove(&db, &heir, &student).await?;
1044- class_course::detach(&db, &heir, &algebra).await
1045- })
1046- };
1047- let swept = detaching.await.unwrap();
1048- heir_moves.await.unwrap().unwrap();
1049- assert!(
1050- !matches!(swept, Err(AppError::Db(_))),
1051- "round {round}: a raced detach must be answered, not 500: {swept:?}"
1052- );
1053-
1054- // Stored state is the whole verdict; a return value is not evidence.
1055- if swept.is_ok() {
1056- raced += 1;
1057- }
1058- if source_of(&algebra, &student, &db).await == Some(Some(heir.clone())) {
1059- stranded += 1;
1060- }
1061- }
1062- eprintln!("a detach raced by its heir: {raced}/4 rounds swept");
1063- assert!(raced > 0, "no round ever committed its sweep");
1064- assert_eq!(
1065- stranded, 0,
1066- "an enrollment was left tagged with a class holding neither link"
1067- );
1068- }
1069-
10701094 }
src/db/course.rsmodified+555 -843
@@ -1,25 +1,25 @@
1-//! The `course` table: the unit exams, sessions, subjects and enrollments
2-//! hang off. Listed newest first; deleted with its whole subtree in one
3-//! guarded cascade.
1+//! The `course` table: the school-level catalog exams, sessions, subjects and
2+//! enrollments hang off *through their instances* ([`crate::db::class_course`]).
3+//! Listed newest first; deleted with its whole subtree in one guarded cascade.
4+//!
5+//! The catalog is a template since the K12 remodel (D1): the academic work —
6+//! roster, exams, timetable, teachers — lives on the instances a şube attaches,
7+//! so this row carries only what every instance shares (title, description,
8+//! kind) and two counters. The catalog is Manager+-owned (D6): there is no
9+//! per-teacher ownership list, and the two counters are the delete guard.
410
511 use crate::constant::COURSE_TABLE;
612 use crate::database::{Database, tx_with_retry, unique_violation};
7-use crate::db::cap;
8-use crate::db::field_update::{FieldUpdate, Refcount};
913 use crate::db::page::PagedList;
1014 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
11-use crate::domain::term::{self, TermId};
1215 use crate::domain::user::UserId;
1316 use crate::error::AppError;
17+use sqlx::PgConnection;
1418
15-use std::collections::HashMap;
16-
17-/// The stored columns of a `course` row. The assigned teachers live across
18-/// the `course_teacher` junction, not on this row, so every read joins them
19-/// on in one batch afterwards ([`into_courses`]) — the two generic readers
20-/// below (the paged list and the field-scoped PATCH) both read whole rows
21-/// (`SELECT *` / `RETURNING *`), which is a shape no aggregate column can
22-/// ride.
19+/// The stored columns of a `course` row — the whole row. The assigned-teacher
20+/// list this struct used to join on moved to the instances
21+/// ([`crate::db::class_course_teacher`]), so a course read is one statement
22+/// again.
2323 #[derive(Debug, sqlx::FromRow)]
2424 struct CourseRow {
2525 id: CourseId,
@@ -27,131 +27,56 @@ struct CourseRow {
2727 title: CourseTitle,
2828 description: CourseDescription,
2929 kind: CourseKind,
30- term: Option<TermId>,
31- capacity: Option<i64>,
30+ class_course_count: i64,
31+ course_membership_count: i64,
3232 }
3333
3434 impl CourseRow {
35- fn into_course(self, teachers: Vec<UserId>) -> Course {
35+ fn into_course(self) -> Course {
3636 Course {
3737 id: self.id,
3838 creator: self.creator,
39- teachers,
4039 title: self.title,
4140 description: self.description,
4241 kind: self.kind,
43- term: self.term,
44- capacity: self.capacity,
42+ class_course_count: self.class_course_count,
43+ course_membership_count: self.course_membership_count,
4544 }
4645 }
4746 }
4847
49-/// Assemble [`Course`]s (their assigned teachers included) out of row reads:
50-/// one `course_teacher` query for the whole batch, a course nobody is
51-/// assigned to reading an empty list.
52-async fn into_courses(db: &Database, rows: Vec<CourseRow>) -> Result<Vec<Course>, AppError> {
53- if rows.is_empty() {
54- return Ok(Vec::new());
55- }
56- let ids: Vec<uuid::Uuid> = rows.iter().map(|row| row.id.uuid()).collect();
57- let links = sqlx::query!(
58- r#"SELECT course AS "course: CourseId", teacher AS "teacher: UserId"
59- FROM course_teacher WHERE course = ANY($1)"#,
60- &ids,
61- )
62- .fetch_all(db)
63- .await?;
64- let mut by_course: HashMap<uuid::Uuid, Vec<UserId>> = HashMap::new();
65- for link in links {
66- by_course
67- .entry(link.course.uuid())
68- .or_default()
69- .push(link.teacher);
70- }
71- Ok(rows
72- .into_iter()
73- .map(|row| {
74- let teachers = by_course.remove(&row.id.uuid()).unwrap_or_default();
75- row.into_course(teachers)
76- })
77- .collect())
78-}
79-
80-/// [`into_courses`] for a single row.
81-async fn one_course(db: &Database, row: CourseRow) -> Result<Course, AppError> {
82- let course = into_courses(db, vec![row])
83- .await?
84- .pop()
85- .expect("one row in, one course out");
86- Ok(course)
87-}
88-
48+/// Mint a catalog course. No term is claimed any more: the catalog is not
49+/// bound to a dönem (exams are, through their instance), and no capacity is
50+/// stored — the roster counter lives on the instance and gates nothing.
8951 pub async fn create(
9052 db: &Database,
9153 creator: &UserId,
9254 title: CourseTitle,
9355 description: CourseDescription,
9456 kind: CourseKind,
95- term: Option<TermId>,
96- capacity: Option<i64>,
9757 ) -> Result<Course, AppError> {
9858 let id = CourseId::generate();
99- let Some(term) = term else {
100- let created = sqlx::query_as!(
101- CourseRow,
102- r#"INSERT INTO course (id, creator, title, description, kind, term, capacity)
103- VALUES ($1, $2, $3, $4, $5, NULL, $6)
104- RETURNING id AS "id: CourseId", creator AS "creator: UserId",
105- title AS "title: CourseTitle",
106- description AS "description: CourseDescription",
107- kind AS "kind: CourseKind", term AS "term: TermId", capacity"#,
108- id.uuid(),
109- creator.uuid(),
110- title.as_str(),
111- description.as_str(),
112- kind.as_str(),
113- capacity,
114- )
115- .fetch_one(db)
116- .await?;
117- // A new course has no assigned teachers; the join reads an empty list.
118- return one_course(db, created).await;
119- };
120- // Claim a reference on the term in the *same statement* as the row: the
121- // claim is a conditional write on the term row, so it fails when the
122- // term is already gone and it makes the term undeletable the instant
123- // this link exists — and a crash can never leave one without the other,
124- // which a claim sent as its own query could (the count would strand and
125- // the term be undeletable forever).
12659 let created = sqlx::query_as!(
12760 CourseRow,
128- r#"WITH seat AS (
129- UPDATE term
130- SET course_count = course_count + 1
131- WHERE id = $7 AND course_count < $8
132- RETURNING 1)
133- INSERT INTO course (id, creator, title, description, kind, term, capacity)
134- SELECT $1, $2, $3, $4, $5, $7, $6 WHERE EXISTS (SELECT 1 FROM seat)
61+ r#"INSERT INTO course (id, creator, title, description, kind)
62+ VALUES ($1, $2, $3, $4, $5)
13563 RETURNING id AS "id: CourseId", creator AS "creator: UserId",
136- title AS "title: CourseTitle",
137- description AS "description: CourseDescription",
138- kind AS "kind: CourseKind", term AS "term: TermId", capacity"#,
64+ title AS "title: CourseTitle",
65+ description AS "description: CourseDescription",
66+ kind AS "kind: CourseKind", class_course_count, course_membership_count"#,
13967 id.uuid(),
14068 creator.uuid(),
14169 title.as_str(),
14270 description.as_str(),
14371 kind.as_str(),
144- capacity,
145- term.uuid(),
146- cap::UNLIMITED,
14772 )
14873 .fetch_one(db)
14974 .await;
15075 match created {
151- Ok(created) => one_course(db, created).await,
152- // Uncapped, so "full" can only mean the conditional write matched no
153- // term row at all — the existence check the pre-flight lookup makes.
154- Err(sqlx::Error::RowNotFound) => Err(term::gone_error()),
76+ Ok(created) => Ok(created.into_course()),
77+ // The creator is a foreign key: a gone account is the same `NotFound`
78+ // the web layer's own read answers with, never an orphan row.
79+ Err(err) if crate::database::foreign_key_violation(&err) => Err(AppError::NotFound),
15580 // Unreachable: the id was minted above.
15681 Err(err) if unique_violation(&err).is_some() => {
15782 Err(AppError::Internal("failed to create course".into()))
@@ -166,7 +91,7 @@ async fn read_row(db: &Database, id: &CourseId) -> Result<Option<CourseRow>, App
16691 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
16792 title AS "title: CourseTitle",
16893 description AS "description: CourseDescription",
169- kind AS "kind: CourseKind", term AS "term: TermId", capacity
94+ kind AS "kind: CourseKind", class_course_count, course_membership_count
17095 FROM course WHERE id = $1"#,
17196 id.uuid(),
17297 )
@@ -176,10 +101,7 @@ async fn read_row(db: &Database, id: &CourseId) -> Result<Option<CourseRow>, App
176101 }
177102
178103 pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> {
179- match read_row(db, id).await? {
180- Some(row) => Ok(Some(one_course(db, row).await?)),
181- None => Ok(None),
182- }
104+ Ok(read_row(db, id).await?.map(CourseRow::into_course))
183105 }
184106
185107 pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {
@@ -188,16 +110,17 @@ pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {
188110 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
189111 title AS "title: CourseTitle",
190112 description AS "description: CourseDescription",
191- kind AS "kind: CourseKind", term AS "term: TermId", capacity
113+ kind AS "kind: CourseKind", class_course_count, course_membership_count
192114 FROM course ORDER BY id DESC"#,
193115 )
194116 .fetch_all(db)
195117 .await?;
196- into_courses(db, rows).await
118+ Ok(rows.into_iter().map(CourseRow::into_course).collect())
197119 }
198120
199-/// The courses `user` is enrolled in — the spine of `/courses/me` and the
200-/// marks report.
121+/// The courses `user` is enrolled in — read through the *instances* their
122+/// enrollments name, since an enrollment keys on the class×course instance.
123+/// The spine of `/courses/me` and the marks report.
201124 pub async fn list_enrolled(
202125 db: &Database,
203126 user: &UserId,
@@ -205,42 +128,49 @@ pub async fn list_enrolled(
205128 offset: i64,
206129 ) -> Result<(Vec<Course>, i64), AppError> {
207130 let (rows, total) = PagedList::new(
208- "course WHERE id IN (SELECT course FROM enrollment WHERE app_user = $1)",
131+ "course WHERE id IN (
132+ SELECT cc.course FROM enrollment e
133+ JOIN class_course cc ON cc.id = e.class_course
134+ WHERE e.app_user = $1)",
209135 "ORDER BY id DESC",
210136 )
211137 .bind(user.uuid())
212138 .run::<CourseRow>(limit, offset, db)
213139 .await?;
214- Ok((into_courses(db, rows).await?, total))
140+ Ok((
141+ rows.into_iter().map(CourseRow::into_course).collect(),
142+ total,
143+ ))
215144 }
216145
217-/// The courses `user` runs — the ones they created plus the ones a manager
218-/// assigned them to. A teacher's slice of the catalog.
146+/// The courses `user` teaches somewhere — the ones a manager assigned them to
147+/// on some instance. A teacher's slice of the catalog.
219148 ///
220-/// The assigned half reads `course_teacher` by its `teacher` index (the
221-/// shape `enrollment` already has) instead of an array membership test —
222-/// that test was the corner-cut here once, and the junction is exactly the
223-/// upgrade path the old comment called structural.
149+/// It reads `class_course_teacher` by its `teacher` index and follows each
150+/// assignment to the catalog course its instance teaches: a teacher who runs
151+/// 5-A's Matematik sees Matematik. The old creator-membership half is gone
152+/// with D6 — the catalog is Manager+ owned.
224153 pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {
225154 let rows = sqlx::query_as!(
226155 CourseRow,
227156 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
228157 title AS "title: CourseTitle",
229158 description AS "description: CourseDescription",
230- kind AS "kind: CourseKind", term AS "term: TermId", capacity
231- FROM course WHERE creator = $1 OR id IN (
232- SELECT course FROM course_teacher WHERE teacher = $2)
159+ kind AS "kind: CourseKind", class_course_count, course_membership_count
160+ FROM course WHERE id IN (
161+ SELECT cc.course FROM class_course_teacher t
162+ JOIN class_course cc ON cc.id = t.class_course
163+ WHERE t.teacher = $1)
233164 ORDER BY id DESC"#,
234165 user.uuid(),
235- user.uuid(),
236166 )
237167 .fetch_all(db)
238168 .await?;
239- into_courses(db, rows).await
169+ Ok(rows.into_iter().map(CourseRow::into_course).collect())
240170 }
241171
242172 /// Load every course behind `ids` (one query) — the join half of the
243-/// attendance report's per-course blocks.
173+/// attendance and marks reports' per-course blocks.
244174 pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>, AppError> {
245175 if ids.is_empty() {
246176 return Ok(Vec::new());
@@ -251,144 +181,58 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>,
251181 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
252182 title AS "title: CourseTitle",
253183 description AS "description: CourseDescription",
254- kind AS "kind: CourseKind", term AS "term: TermId", capacity
184+ kind AS "kind: CourseKind", class_course_count, course_membership_count
255185 FROM course WHERE id = ANY($1)"#,
256186 &keys,
257187 )
258188 .fetch_all(db)
259189 .await?;
260- into_courses(db, rows).await
190+ Ok(rows.into_iter().map(CourseRow::into_course).collect())
261191 }
262192
263-/// Field-scoped: nothing guards the course row across the handler's read
264-/// and this write (the term it links is guarded by its own refcount write,
265-/// and the assign path takes no lock at all) — so a field the request omitted
266-/// (`None`) is not written at all. Sending the snapshot's value back
267-/// instead would revert a concurrent edit of that field; scoping the `SET`
268-/// alone does not stop that, the values have to come from the request.
269-/// `term` and `capacity` are nullable, so they take the outer/inner
270-/// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear.
193+/// Field-scoped: a field the request omitted (`None`) is not written at all.
194+/// Sending the snapshot's value back instead would revert a concurrent edit of
195+/// that field; scoping the `SET` alone does not stop that, the values have to
196+/// come from the request.
271197 ///
272-/// The assigned teachers are not fields of this row — they are
273-/// `course_teacher` rows, written only by [`assign_teacher`],
274-/// [`unassign_teacher`] and the demotion sweep — so a PATCH can neither
275-/// carry nor clobber them.
198+/// The two counters and `creator` are not editable: the counters are what the
199+/// delete guard reads (a PATCH is not a roster change), and the creator is the
200+/// catalog's of record.
276201 pub async fn update(
277202 db: &Database,
278203 course: Course,
279204 title: Option<CourseTitle>,
280205 description: Option<CourseDescription>,
281206 kind: Option<CourseKind>,
282- term: Option<Option<TermId>>,
283- capacity: Option<Option<i64>>,
284207 ) -> Result<Course, AppError> {
285- // A term move claims the new term and releases the old one inside the
286- // very transaction that moves the link, so no crash can leave a count
287- // without its link (the term would be undeletable forever) or a link
288- // without its count. A PATCH that carried no `term_id`, or re-stated the
289- // link it already had, moves neither counter.
290- let (claim, release) = term::ref_move(course.term.as_ref(), &term);
291- let row = FieldUpdate::new(COURSE_TABLE, course.id.uuid())
208+ let row = crate::db::field_update::FieldUpdate::new(COURSE_TABLE, course.id.uuid())
292209 .set("title", title.map(|title| title.as_str().to_owned()))
293210 .set(
294211 "description",
295212 description.map(|description| description.as_str().to_owned()),
296213 )
297214 .set("kind", kind.map(|kind| kind.as_str().to_owned()))
298- .set(
299- "term",
300- term.map(|term| crate::db::page::Param::OptUuid(term.map(|term| term.uuid()))),
301- )
302- .set("capacity", capacity.map(crate::db::page::Param::OptI64))
303- .refcount(Refcount {
304- counter_table: "term",
305- counter_field: "course_count",
306- link: "term",
307- expected: course.term.as_ref().map(|term| term.uuid()),
308- claim: claim.map(|term| term.uuid()),
309- release: release.map(|term| term.uuid()),
310- refused: term::gone_error(),
311- })
312215 .run::<CourseRow>(db)
313216 .await?;
314- // The teachers are joined on after the write, off the junction.
315- one_course(db, row).await
217+ Ok(row.into_course())
316218 }
317219
318-/// Assign `teacher` to run this course, or return the course untouched if
319-/// they already run it — assignment is idempotent, like enrollment: the
320-/// link is an `INSERT` whose `(course, teacher)` key answers a duplicate
321-/// with `DO NOTHING`, so two requests naming the same teacher at once land
322-/// one row (the early return only sees a stale snapshot).
323-pub async fn assign_teacher(
324- db: &Database,
325- course: Course,
326- teacher: &UserId,
327-) -> Result<Course, AppError> {
328- if course.is_assigned(teacher) {
329- return Ok(course);
330- }
331- // `WHERE EXISTS` keeps the insert a no-op when the course went between
332- // the caller's read and this write — the answer is the `NotFound` the
333- // fresh read below gives, not a foreign-key 500.
334- sqlx::query!(
335- r#"INSERT INTO course_teacher (course, teacher)
336- SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM course WHERE id = $1)
337- ON CONFLICT DO NOTHING"#,
338- course.id.uuid(),
339- teacher.uuid(),
340- )
341- .execute(db)
342- .await?;
343- // Fresh read, like the `RETURNING` this replaced: the snapshot's
344- // teacher list can be stale (a concurrent assign).
345- let row = read_row(db, &course.id).await?.ok_or(AppError::NotFound)?;
346- one_course(db, row).await
347-}
348-
349-/// Drop `teacher` from this course. `None` when they weren't assigned, so
350-/// the web layer can answer 404 instead of pretending it removed someone.
351-pub async fn unassign_teacher(
352- db: &Database,
353- course: Course,
354- teacher: &UserId,
355-) -> Result<Option<Course>, AppError> {
356- if !course.is_assigned(teacher) {
357- return Ok(None);
358- }
359- let deleted = sqlx::query!(
360- r#"DELETE FROM course_teacher WHERE course = $1 AND teacher = $2"#,
361- course.id.uuid(),
362- teacher.uuid(),
363- )
364- .execute(db)
365- .await?;
366- if deleted.rows_affected() == 0 {
367- // Unassigned under the caller's feet — nothing was removed.
368- return Ok(None);
369- }
370- read(db, &course.id).await
371-}
372-
373-/// Strip `user` from every course they were assigned to — the sweep for a
374-/// user demoted below `teacher`, who may no longer run anything.
375-pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
376- sqlx::query!(r#"DELETE FROM course_teacher WHERE teacher = $1"#, user.uuid(),)
377- .execute(db)
378- .await?;
379- Ok(())
380-}
381-
382-/// Delete the course and cascade-remove everything inside it: results,
383-/// attempts, answers, and question/answer images of its exams, its
384-/// homework with their submissions, submission files, and grades, its
385-/// enrollments, the class attachments that pumped some of them (each class
386-/// gets its count back, or it would be undeletable over rows pointing at
387-/// nothing), its sessions with their roll call, its subjects, and the
388-/// exams themselves. The children go in one transaction so a crash can't
389-/// leave an exam pointing at a deleted course. The image and
390-/// homework-file *blobs* are the web layer's to remove — it collects
391-/// their names before calling this.
220+/// Delete the course and cascade-remove everything inside it *through its
221+/// instances*: results, attempts, answers, and question/answer images of
222+/// their exams, their homework with submissions, submission files, and
223+/// grades, their enrollments, their sessions with their roll call, their
224+/// teachers, and — last — the `class_course` rows themselves (each class
225+/// getting its attachment counter back, or it would be undeletable over rows
226+/// pointing at nothing). The children go in one transaction so a crash can't
227+/// leave an exam pointing at a deleted course. The image and homework-file
228+/// *blobs* are the web layer's to remove — it collects their names before
229+/// calling this.
230+///
231+/// The guard is the two counters on the locked row (D5/D6): an instance still
232+/// teaching this course refuses the delete, and so does an individual club
233+/// membership, because nothing here unlinks either. Detach the instances and
234+/// empty the memberships first — a catalog course whose last instance goes is
235+/// then deletable, which is the whole point of the catalog being a template.
392236 ///
393237 /// **Bank templates** survive it — they are a separate, reusable library
394238 /// spanning every course — so their `source_exam` and `subject` links are
@@ -405,46 +249,48 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
405249 /// here like any other link, so a template stops naming a course the
406250 /// instant that course goes (the old `teachers`-style array made the id a
407251 /// permanent dangling value only the pump's [`crate::db::class_blueprint::
408-/// prune`] could chase). The same transaction takes the course's
409-/// `course_teacher` assignment rows: an assigned teacher loses the course
410-/// with it.
252+/// prune`] could chase). The same transaction takes the instances'
253+/// `class_course_teacher` assignment rows: an assigned teacher loses the
254+/// instance with it.
411255 ///
412256 /// The **derived AI rows** (`rag_output` carries a denormalized `course`
413257 /// besides its note link) and the event **audience links** are FK children
414258 /// the old store let dangle: `rag_output` is disposable and dies here, and
415259 /// an event whose audience was "this course's students" keeps standing with
416260 /// `audience_course` cleared — an empty roster, exactly the documented
417-/// outcome of the class twin (`Course::delete` never touched `event`; it
418-/// still doesn't delete one).
261+/// outcome of the class twin (`ClassGroup::delete` never touched `event`;
262+/// it still doesn't delete one).
419263 ///
420264 /// The marks going with it give their exam kinds' references back, counted
421265 /// per kind inside this same transaction — the mirror of `Exam::delete`.
422266 /// Skipping it would leave every kind the course graded under counted
423267 /// forever, and a counted kind can never leave the school's settings.
424268 ///
425-/// **Order is the foreign-key graph, children first** (the old store had
426-/// no FKs, so its order was free): exam results/attempts/answers/images
427-/// and question images before `exam_question`; `exam_question` before
428-/// `exam`; homework files before submissions before results before
429-/// `homework`; roll-call rows before `course_session`; note files and
430-/// rag rows before `course_note`; `blueprint_course` and `course_teacher`
431-/// before the `course` row itself, whose `NO ACTION` FKs are checked the
432-/// moment the final `DELETE` runs.
269+/// **Order is the foreign-key graph, children first**: exam results/attempts/
270+/// answers/audiences/images and question images before `exam_question`;
271+/// `exam_question` before `exam`; homework files before submissions before
272+/// results before `homework`; roll-call rows before `course_session`;
273+/// enrollment / teacher / audience rows before `class_course`; note files and
274+/// rag rows before `course_note`; `blueprint_course`, `course_membership` and
275+/// `class_course` before the `course` row itself, whose `NO ACTION` FKs are
276+/// checked the moment the final `DELETE` runs.
433277 ///
434-/// `false` = refused, nothing was written: someone is still enrolled. The
435-/// guard locks the course row (`FOR UPDATE`) and reads its own
436-/// `enrollment_count`, so an enroll racing this either takes its seat
437-/// first (and the delete is refused) or finds the row gone (and is refused
438-/// itself). `Err(NotFound)` keeps the answer a concurrent *delete* used
439-/// to get — and unlike the old one-statement guard, this one tells the two
440-/// apart without a second read.
278+/// `false` = refused, nothing was written: a class still teaches it, or
279+/// someone still holds a membership. The guard locks the course row
280+/// (`FOR UPDATE`) and reads its own counters, so an attach or a join racing
281+/// this either claims first (and the delete is refused) or finds the row gone
282+/// (and is refused itself). `Err(NotFound)` keeps the answer a concurrent
283+/// *delete* used to get — and unlike the old one-statement guard, this one
284+/// tells the two apart without a second read.
441285 pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
442286 tx_with_retry(db, true, async move |tx| {
443- // The guard and the lock: the row (and its roster count) cannot
444- // change under this transaction, and every enroll claim contends on
445- // this very row, so check and cascade are one decision.
287+ // The guard and the lock: the row (and its two counters) cannot
288+ // change under this transaction, and every attach or membership
289+ // claim contends on this very row, so check and cascade are one
290+ // decision.
446291 let guard = sqlx::query!(
447- r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#,
292+ r#"SELECT class_course_count, course_membership_count FROM course
293+ WHERE id = $1 FOR UPDATE"#,
448294 course.id.uuid(),
449295 )
450296 .fetch_optional(&mut *tx)
@@ -452,43 +298,9 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
452298 let Some(guard) = guard else {
453299 return Err(AppError::NotFound);
454300 };
455- if guard.enrollment_count != 0 {
301+ if guard.class_course_count != 0 || guard.course_membership_count != 0 {
456302 return Ok(false);
457303 }
458- // The exam ids are needed twice — the kind_ref refund and the bank's
459- // source_exam clear — and must be collected before the sweeps take
460- // the rows they name.
461- let exams: Vec<uuid::Uuid> =
462- sqlx::query!(r#"SELECT id FROM exam WHERE course = $1"#, course.id.uuid(),)
463- .fetch_all(&mut *tx)
464- .await?
465- .into_iter()
466- .map(|row| row.id)
467- .collect();
468- // Every mark the course ever gave gives its exam kind's reference
469- // back, counted per kind (mirrors `Exam::delete`). The kind rides
470- // the exam row — `exam_result` names its exam, not its kind.
471- sqlx::query!(
472- r#"UPDATE kind_ref k
473- SET count = GREATEST(k.count - s.n, 0)
474- FROM (SELECT e.kind, count(*) AS n FROM exam_result r
475- JOIN exam e ON r.exam = e.id
476- WHERE r.exam = ANY($1) GROUP BY e.kind) s
477- WHERE k.name = s.kind"#,
478- &exams,
479- )
480- .execute(&mut *tx)
481- .await?;
482- // The term gets its reference back inside the same transaction.
483- if let Some(term) = guard.term {
484- sqlx::query!(
485- r#"UPDATE term SET course_count = GREATEST(course_count - 1, 0)
486- WHERE id = $1"#,
487- term,
488- )
489- .execute(&mut *tx)
490- .await?;
491- }
492304 // Events aimed at this course keep standing, audience cleared.
493305 sqlx::query!(
494306 r#"UPDATE event SET audience_course = NULL WHERE audience_course = $1"#,
@@ -496,49 +308,21 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
496308 )
497309 .execute(&mut *tx)
498310 .await?;
499- // The exam subtree, deepest children first.
500- sqlx::query!(r#"DELETE FROM exam_result WHERE exam = ANY($1)"#, &exams)
501- .execute(&mut *tx)
502- .await?;
503- sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, &exams)
504- .execute(&mut *tx)
505- .await?;
506- sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, &exams)
507- .execute(&mut *tx)
508- .await?;
509- sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, &exams)
510- .execute(&mut *tx)
511- .await?;
512- sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, &exams)
513- .execute(&mut *tx)
514- .await?;
515- sqlx::query!(r#"DELETE FROM exam_question WHERE exam = ANY($1)"#, &exams)
516- .execute(&mut *tx)
517- .await?;
518- // The homework subtree: files, then submissions (whose graded_by
519- // link names a result deleted after them), then results.
520- sqlx::query!(
521- r#"DELETE FROM homework_file WHERE submission IN (
522- SELECT id FROM homework_submission
523- WHERE homework IN (SELECT id FROM homework WHERE course = $1))"#,
311+ // The instances and everything under them. The guard above refuses a
312+ // course that still carries one, so this sweep is defensive: a counter
313+ // is the guard's *input*, and a guard reading a stale number is
314+ // exactly the shape this exists to survive. The blob keys it returns
315+ // are already collected by the caller (`file_keys_for_course`), which
316+ // reads them before the rows go, so they are dropped here.
317+ let instances: Vec<uuid::Uuid> = sqlx::query_scalar!(
318+ r#"SELECT id AS "id: uuid::Uuid" FROM class_course WHERE course = $1"#,
524319 course.id.uuid(),
525320 )
526- .execute(&mut *tx)
527- .await?;
528- sqlx::query!(
529- r#"DELETE FROM homework_submission WHERE homework IN (
530- SELECT id FROM homework WHERE course = $1)"#,
531- course.id.uuid(),
532- )
533- .execute(&mut *tx)
534- .await?;
535- sqlx::query!(
536- r#"DELETE FROM homework_result WHERE homework IN (
537- SELECT id FROM homework WHERE course = $1)"#,
538- course.id.uuid(),
539- )
540- .execute(&mut *tx)
321+ .fetch_all(&mut *tx)
541322 .await?;
323+ for instance in &instances {
324+ let _blobs = sweep_instance_subtree(&mut *tx, *instance).await?;
325+ }
542326 // Derived AI rows for this course's notes — links before the rows
543327 // (`ON DELETE NO ACTION`).
544328 sqlx::query!(
@@ -568,8 +352,8 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
568352 )
569353 .execute(&mut *tx)
570354 .await?;
571- // Class attachments: detach and hand each class its count back in
572- // one statement, then strike the course out of every blueprint.
355+ // The instances, each class handed its attachment counter back in
356+ // the same statement.
573357 sqlx::query!(
574358 r#"WITH detached AS (
575359 DELETE FROM class_course WHERE course = $1 RETURNING class)
@@ -581,40 +365,20 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
581365 .execute(&mut *tx)
582366 .await?;
583367 sqlx::query!(
584- r#"DELETE FROM blueprint_course WHERE course = $1"#,
585- course.id.uuid(),
586- )
587- .execute(&mut *tx)
588- .await?;
589- // The assignment links die with the course, before the row itself.
590- sqlx::query!(
591- r#"DELETE FROM course_teacher WHERE course = $1"#,
368+ r#"DELETE FROM course_membership WHERE course = $1"#,
592369 course.id.uuid(),
593370 )
594371 .execute(&mut *tx)
595372 .await?;
596- // Sessions with their roll call, then the roster itself.
597373 sqlx::query!(
598- r#"DELETE FROM session_attendance WHERE course = $1"#,
374+ r#"DELETE FROM blueprint_course WHERE course = $1"#,
599375 course.id.uuid(),
600376 )
601377 .execute(&mut *tx)
602378 .await?;
603- sqlx::query!(
604- r#"DELETE FROM course_session WHERE course = $1"#,
605- course.id.uuid()
606- )
607- .execute(&mut *tx)
608- .await?;
609- sqlx::query!(
610- r#"DELETE FROM enrollment WHERE course = $1"#,
611- course.id.uuid()
612- )
613- .execute(&mut *tx)
614- .await?;
615379 // The bank keeps its templates; their links to this course's
616- // content go first, so the subject/exam deletes below cannot trip
617- // a foreign key behind them.
380+ // content go first, so the subject delete below cannot trip a
381+ // foreign key behind them.
618382 sqlx::query!(
619383 r#"UPDATE bank_question SET subject = NULL
620384 WHERE subject IN (SELECT id FROM subject WHERE course = $1)"#,
@@ -622,29 +386,6 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
622386 )
623387 .execute(&mut *tx)
624388 .await?;
625- sqlx::query!(
626- r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#,
627- &exams,
628- )
629- .execute(&mut *tx)
630- .await?;
631- // Subjects before exams would trip `exam.subject` — exams go first.
632- sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id.uuid())
633- .execute(&mut *tx)
634- .await?;
635- sqlx::query!(
636- r#"DELETE FROM homework_assignment WHERE homework IN (
637- SELECT id FROM homework WHERE course = $1)"#,
638- course.id.uuid(),
639- )
640- .execute(&mut *tx)
641- .await?;
642- sqlx::query!(
643- r#"DELETE FROM homework WHERE course = $1"#,
644- course.id.uuid()
645- )
646- .execute(&mut *tx)
647- .await?;
648389 sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id.uuid())
649390 .execute(&mut *tx)
650391 .await?;
@@ -657,10 +398,237 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
657398 .await
658399 }
659400
401+/// Everything hanging off one instance, deleted children-first with the
402+/// counters it holds refunded — the sweep both [`crate::db::class_pump::
403+/// detach_course`] and [`delete`] run, and the only place the instance's
404+/// foreign-key graph is spelled.
405+///
406+/// The order is the graph: exam results/attempts/answers/audiences and
407+/// question/answer images before `exam_question`; the question rows give their
408+/// subjects' `exam_question_count` back and the results their kinds'
409+/// `kind_ref` count; bank templates keep standing with `source_exam` cleared;
410+/// homework files before submissions (whose `grad_by_result` stamp points at a
411+/// result row) before results before assignments before `homework`; roll-call
412+/// rows before `course_session`; then the roster, the teacher links and the
413+/// audience rows, and the caller takes the instance row itself last.
414+///
415+/// Returns the blob keys of the image and homework-file rows it removed, so a
416+/// caller whose web route unlinks bytes can do it after the commit; a caller
417+/// that collected them beforehand ([`crate::service::course::delete`]) drops
418+/// them.
419+///
420+/// **Every reference counter it gives back is driven by the rows a
421+/// `DELETE … RETURNING` actually removed** — `exam`→`term.exam_count`,
422+/// `exam_result`→`kind_ref.count`, `exam_question`→`subject.exam_question_count`,
423+/// `homework`→`subject.homework_count` — never by a count taken off a
424+/// statement-start snapshot. The difference is a race: `Exam::delete` and
425+/// `remove_result` release some of these counters themselves, so a
426+/// count-then-subtract pair would hand one row's reference back twice (a
427+/// counter one low, permanently — `GREATEST` only floors at zero), and a kind
428+/// still carrying marks could then be retired from settings. Fused this way an
429+/// interleaving is exact from either side: the loser's `DELETE` simply does
430+/// not return the row the winner took.
431+///
432+/// The row locks it takes are the ones the children's own writers take (the
433+/// instance row `FOR UPDATE` is the caller's, before this runs), so a grade or
434+/// an upload racing the sweep either lands before it (and is swept) or finds
435+/// its parent gone and is refused.
436+pub(crate) async fn sweep_instance_subtree(
437+ tx: &mut PgConnection,
438+ instance: uuid::Uuid,
439+) -> Result<Vec<String>, AppError> {
440+ let exams: Vec<uuid::Uuid> = sqlx::query_scalar!(
441+ r#"SELECT id AS "id: uuid::Uuid" FROM exam WHERE class_course = $1"#,
442+ instance,
443+ )
444+ .fetch_all(&mut *tx)
445+ .await?;
446+ // Every release below is driven by the rows a `DELETE … RETURNING`
447+ // actually removed, in the shape [`crate::db::exam_result::remove`] uses,
448+ // and never by a count taken off a statement-start snapshot: a concurrent
449+ // `Exam::delete` or `remove_result` releases the same counters itself, so
450+ // a count-then-subtract pair would release its row twice — a `kind_ref`
451+ // one low permanently (GREATEST only floors at zero), which then lets a
452+ // kind still carrying marks be retired from settings.
453+ let image_files: Vec<String> = sqlx::query_scalar!(
454+ r#"SELECT file FROM question_image WHERE exam = ANY($1)"#,
455+ &exams,
456+ )
457+ .fetch_all(&mut *tx)
458+ .await?;
459+ let answer_image_files: Vec<String> = sqlx::query_scalar!(
460+ r#"SELECT file FROM answer_image WHERE exam = ANY($1)"#,
461+ &exams,
462+ )
463+ .fetch_all(&mut *tx)
464+ .await?;
465+ sqlx::query!(
466+ r#"DELETE FROM exam_audience WHERE class_course = $1"#,
467+ instance
468+ )
469+ .execute(&mut *tx)
470+ .await?;
471+ // Every mark this sweep takes gives its exam kind's reference back, per
472+ // kind, off the rows this statement removed. The kind rides the exam row —
473+ // `exam_result` names its exam, not its kind — so the deleted rows are
474+ // joined back to the exam they named *before* it goes (the exam row is
475+ // still there: this runs ahead of the `DELETE FROM exam` at the end).
476+ sqlx::query!(
477+ r#"WITH gone AS (
478+ DELETE FROM exam_result WHERE exam = ANY($1)
479+ RETURNING exam),
480+ kinds AS (
481+ SELECT e.kind AS kind, count(*) AS n
482+ FROM gone g JOIN exam e ON e.id = g.exam
483+ GROUP BY e.kind)
484+ UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0)
485+ FROM kinds c WHERE k.name = c.kind"#,
486+ &exams,
487+ )
488+ .execute(&mut *tx)
489+ .await?;
490+ sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, &exams)
491+ .execute(&mut *tx)
492+ .await?;
493+ sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, &exams)
494+ .execute(&mut *tx)
495+ .await?;
496+ sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, &exams)
497+ .execute(&mut *tx)
498+ .await?;
499+ sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, &exams)
500+ .execute(&mut *tx)
501+ .await?;
502+ // The cascaded questions give their subject references back off the rows
503+ // this statement removed, per subject — released with the delete, never
504+ // counted ahead of it.
505+ sqlx::query!(
506+ r#"WITH gone AS (
507+ DELETE FROM exam_question WHERE exam = ANY($1)
508+ RETURNING subject),
509+ subs AS (
510+ SELECT subject, count(*) AS n FROM gone GROUP BY subject)
511+ UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0)
512+ FROM subs c WHERE s.id = c.subject"#,
513+ &exams,
514+ )
515+ .execute(&mut *tx)
516+ .await?;
517+ // Bank templates survive the exam they were saved from — only the
518+ // provenance link is cleared.
519+ sqlx::query!(
520+ r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#,
521+ &exams,
522+ )
523+ .execute(&mut *tx)
524+ .await?;
525+ // The swept exams give their dönem's reference back off the rows this
526+ // statement removed, per term (the mirror of `Exam::delete`'s
527+ // single-exam release): `db::exam::create` claimed `term.exam_count` for
528+ // each of them, and a claim nothing releases leaves the dönem's
529+ // `exam_count = 0` delete guard permanently failing — which takes the
530+ // term, and the academic year whose own guard counts its dönems, down
531+ // with it. Fused with the delete for the same reason the two releases
532+ // above are: a concurrent single-exam delete releases its own claim, so a
533+ // count taken before this statement could give one back twice.
534+ sqlx::query!(
535+ r#"WITH gone AS (
536+ DELETE FROM exam WHERE class_course = $1
537+ RETURNING term),
538+ terms AS (
539+ SELECT term, count(*) AS n FROM gone GROUP BY term)
540+ UPDATE term t SET exam_count = GREATEST(t.exam_count - c.n, 0)
541+ FROM terms c WHERE t.id = c.term"#,
542+ instance,
543+ )
544+ .execute(&mut *tx)
545+ .await?;
546+ let homework_files: Vec<String> = sqlx::query_scalar!(
547+ r#"SELECT file FROM homework_file
548+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework IN (
549+ SELECT id FROM homework WHERE class_course = $1))"#,
550+ instance,
551+ )
552+ .fetch_all(&mut *tx)
553+ .await?;
554+ sqlx::query!(
555+ r#"DELETE FROM homework_file
556+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework IN (
557+ SELECT id FROM homework WHERE class_course = $1))"#,
558+ instance,
559+ )
560+ .execute(&mut *tx)
561+ .await?;
562+ sqlx::query!(
563+ r#"DELETE FROM homework_submission WHERE homework IN (
564+ SELECT id FROM homework WHERE class_course = $1)"#,
565+ instance,
566+ )
567+ .execute(&mut *tx)
568+ .await?;
569+ sqlx::query!(
570+ r#"DELETE FROM homework_result WHERE homework IN (
571+ SELECT id FROM homework WHERE class_course = $1)"#,
572+ instance,
573+ )
574+ .execute(&mut *tx)
575+ .await?;
576+ sqlx::query!(
577+ r#"DELETE FROM homework_assignment WHERE homework IN (
578+ SELECT id FROM homework WHERE class_course = $1)"#,
579+ instance,
580+ )
581+ .execute(&mut *tx)
582+ .await?;
583+ // The homework rows give their subjects' counters back off the rows this
584+ // statement removed, per subject — the same fused shape as the two above.
585+ sqlx::query!(
586+ r#"WITH gone AS (
587+ DELETE FROM homework WHERE class_course = $1
588+ RETURNING subject),
589+ subs AS (
590+ SELECT subject, count(*) AS n FROM gone GROUP BY subject)
591+ UPDATE subject s SET homework_count = GREATEST(s.homework_count - c.n, 0)
592+ FROM subs c WHERE s.id = c.subject"#,
593+ instance,
594+ )
595+ .execute(&mut *tx)
596+ .await?;
597+ sqlx::query!(
598+ r#"DELETE FROM session_attendance WHERE class_course = $1"#,
599+ instance
600+ )
601+ .execute(&mut *tx)
602+ .await?;
603+ sqlx::query!(
604+ r#"DELETE FROM course_session WHERE class_course = $1"#,
605+ instance
606+ )
607+ .execute(&mut *tx)
608+ .await?;
609+ // The roster: every enrollment row of the instance, hand-placed included —
610+ // the instance is the row's own parent key, so none can outlive it.
611+ sqlx::query!(
612+ r#"DELETE FROM enrollment WHERE class_course = $1"#,
613+ instance
614+ )
615+ .execute(&mut *tx)
616+ .await?;
617+ sqlx::query!(
618+ r#"DELETE FROM class_course_teacher WHERE class_course = $1"#,
619+ instance
620+ )
621+ .execute(&mut *tx)
622+ .await?;
623+ let mut blobs = image_files;
624+ blobs.extend(answer_image_files);
625+ blobs.extend(homework_files);
626+ Ok(blobs)
627+}
628+
660629 /// A real course row, for the tests of every child that must now prove its
661-/// parent exists (`Exam`, `CourseSession`, `Subject` — see
662-/// [`cap::touch_and_create`]). A minted id nothing wrote is a 404 there, the
663-/// way a minted subject id already is for an exam question.
630+/// parent exists. A minted id nothing wrote is a 404 there, the way a minted
631+/// subject id already is for an exam question.
664632 #[cfg(test)]
665633 pub(crate) async fn a_test_course(db: &Database) -> CourseId {
666634 // The creator is a foreign key now: a real row, minted per call so
@@ -681,17 +649,55 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId {
681649 CourseTitle::try_new("test course").unwrap(),
682650 CourseDescription::try_new("").unwrap(),
683651 CourseKind::course(),
684- None,
685- None,
686652 )
687653 .await
688654 .unwrap()
689655 .id
690656 }
691657
658+/// A real *instance* of that course, attached to a fresh class — the parent
659+/// every re-keyed child (exam, session, homework, enrollment) now hangs off,
660+/// for the tests of those children.
661+///
662+/// Returned as a pair because a child write that names the instance usually
663+/// also wants the catalog course (a subject's `course`, a marks read's
664+/// course grouping); both are real rows, minted per call.
665+#[cfg(test)]
666+pub(crate) async fn a_test_instance(
667+ db: &Database,
668+) -> (crate::domain::class_course::ClassCourseId, CourseId) {
669+ use crate::domain::class_group::ClassName;
670+
671+ let manager = UserId::generate();
672+ sqlx::query(
673+ "INSERT INTO app_user (id, username, created_at, role) \
674+ VALUES ($1, $2, 0, 'manager')",
675+ )
676+ .bind(manager.uuid())
677+ .bind(format!("instance-fixture-{}", &manager.key()[30..]))
678+ .execute(db)
679+ .await
680+ .unwrap();
681+ let class = crate::db::class_group::create(
682+ db,
683+ &manager,
684+ ClassName::try_new("9-A").unwrap(),
685+ None,
686+ None,
687+ None,
688+ )
689+ .await
690+ .unwrap();
691+ let course = a_test_course(db).await;
692+ let attached = crate::service::class_course::attach(db, class.get_id(), &course, &manager)
693+ .await
694+ .unwrap();
695+ (attached.get_id().clone(), course)
696+}
697+
692698 /// The race half of "a child of a course must not survive its deletion", run
693699 /// for one child table: [`delete`] is held open by the schema and
694-/// `make` fires its create inside that window, four rounds.
700+/// `make` fires its create inside that window, eight rounds.
695701 ///
696702 /// The harness lives here, beside the cascade being raced, and each child names
697703 /// its own pin in its own module (`exam`, `course_session`, `subject`) — the
@@ -700,12 +706,15 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId {
700706 /// things. The sequential half — a create against a course that is already gone
701707 /// — is `tests/regress_course_child_orphans.rs`, which needs no server.
702708 ///
703-/// The window is opened by the database rather than by a lucky interleaving: a
704-/// `DEFINE EVENT` on `course` fires *inside* the delete's own transaction the
705-/// instant the row goes, so the `SLEEP` lands between the delete and its
706-/// `DELETE <child> WHERE course = $course` sweep every time — and a create
707-/// fired into it reads a course that is still there (removed, uncommitted)
708-/// while the sweep already ran on a snapshot without its row.
709+/// The orphan query is the caller's, because the child's key to the course is
710+/// not: `subject` still names the course directly, while an exam or a session
711+/// hangs off an *instance* ([`crate::db::class_course`]) and reaches the course
712+/// through it. Either way it takes the course uuid as `$1`.
713+///
714+/// The window is opened by the database rather than by a lucky interleaving:
715+/// Postgres puts the racing create and delete on the same rows (the FK claims
716+/// and the cascade), so a barrier start covers every interleaving — and the
717+/// child may never outlive the course in any of them.
709718 ///
710719 /// One child per round, for the reason the menu and `class_course` twins
711720 /// document: a second writer makes the delete lose and re-send, and the re-sent
@@ -718,6 +727,7 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId {
718727 #[cfg(test)]
719728 pub(crate) async fn assert_no_child_outlives_a_course_delete(
720729 table: &str,
730+ orphan_count_sql: &str,
721731 make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>,
722732 ) {
723733 use sqlx::Row as _;
@@ -774,15 +784,13 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete(
774784 // Stored state is the whole verdict; a return value is not evidence.
775785 if read(&db, &course).await.unwrap().is_none() {
776786 swept += 1;
777- orphans += sqlx::query(sqlx::AssertSqlSafe(format!(
778- "SELECT count(*) FROM {table} WHERE course = $1"
779- )))
780- .bind(course.uuid())
781- .fetch_one(&db)
782- .await
783- .unwrap()
784- .try_get::<i64, _>(0)
785- .unwrap() as usize;
787+ orphans += sqlx::query(sqlx::AssertSqlSafe(orphan_count_sql.to_string()))
788+ .bind(course.uuid())
789+ .fetch_one(&db)
790+ .await
791+ .unwrap()
792+ .try_get::<i64, _>(0)
793+ .unwrap() as usize;
786794 } else if matches!(dropped, Ok(true)) {
787795 panic!("{table} round {round}: the delete reported success, the course is still there");
788796 }
@@ -799,9 +807,8 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete(
799807 mod tests {
800808 use super::*;
801809 use sqlx::Row as _;
802- use crate::domain::term::{Term, TermName};
803810
804- /// A real `app_user` row: creators, students and enrollers are foreign
811+ /// A real `app_user` row: creators, attached-bys and managers are foreign
805812 /// keys now. The label names the row's username; the id is minted, so
806813 /// repeated calls are new people, not the same row.
807814 async fn a_person(db: &Database, label: &str, role: &str) -> UserId {
@@ -819,129 +826,43 @@ mod tests {
819826 user
820827 }
821828
822- async fn course_on(term: Option<TermId>, db: &Database) -> Course {
829+ /// A catalog course, minted per call. The catalog is a school-wide
830+ /// template since the remodel: no dönem to link, no capacity to store.
831+ async fn a_course(db: &Database) -> Course {
823832 create(
824833 db,
825834 &a_person(db, "teacher", "teacher").await,
826835 CourseTitle::try_new("algebra").unwrap(),
827836 CourseDescription::try_new("").unwrap(),
828837 CourseKind::course(),
829- term,
830- None,
831838 )
832839 .await
833840 .unwrap()
834841 }
835842
836- /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the
837- /// roster check is now the `WHERE` on the delete itself, so only the guard
838- /// can refuse — and it must refuse having written nothing, cascade
839- /// included. A `>= 0` guard passes the roster branch and fails here.
840- #[tokio::test]
841- async fn a_course_with_a_roster_refuses_to_delete() {
842- let (db, _leases) = crate::database::init_test_db().await;
843- let teacher = a_person(&db, "teacher", "teacher").await;
844- let student = a_person(&db, "student", "student").await;
845- let course = course_on(None, &db).await;
846- crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher)
847- .await
848- .unwrap();
849-
850- assert!(
851- !delete(&db, course.clone()).await.unwrap(),
852- "a non-empty roster must refuse the delete"
853- );
854- assert!(
855- read(&db, course.get_id()).await.unwrap().is_some(),
856- "a refused delete may write nothing"
857- );
858- assert!(
859- crate::db::enrollment::read_for_user(&db, course.get_id(), &student)
860- .await
861- .unwrap()
862- .is_some(),
863- "…the cascade least of all"
864- );
865-
866- crate::db::enrollment::remove(&db, course.get_id(), &student)
867- .await
868- .unwrap();
869- assert!(delete(&db, course.clone()).await.unwrap());
870- assert!(read(&db, course.get_id()).await.unwrap().is_none());
871-
872- // The other half of the same guard: once the course row is gone the
873- // seat claim matches nothing, so a late enroll is a 404 rather than a
874- // roster row that outlived its course.
875- let late = crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher)
876- .await
877- .expect_err("enrolling into a deleted course must fail");
878- assert!(matches!(late, AppError::NotFound), "got {late:?}");
879- }
880-
881- /// The bite test for the refcount that replaced `TERM_LOCK`: a term is
882- /// undeletable exactly while a course links it, and every way a link can
883- /// end — PATCH away, and the course's own delete — gives the reference
884- /// back. Dropping the release in `delete` leaves the term deletable never.
885- #[tokio::test]
886- async fn a_term_is_deletable_only_once_no_course_links_it() {
887- let (db, _leases) = crate::database::init_test_db().await;
888- let at = crate::domain::timestamp::Timestamp::from_millis;
889- let term =
890- crate::db::term::create(&db, TermName::try_new("2026").unwrap(), at(100), at(200))
891- .await
892- .unwrap();
893-
894- let linked = course_on(Some(*term.get_id()), &db).await;
895- let patched = course_on(Some(*term.get_id()), &db).await;
896- assert!(
897- !crate::db::term::delete(&db, term.clone()).await.unwrap(),
898- "two linked courses must refuse the delete"
899- );
900-
901- update(&db, patched, None, None, None, Some(None), None)
902- .await
903- .unwrap();
904- assert!(
905- !crate::db::term::delete(&db, term.clone()).await.unwrap(),
906- "one link is still one link"
907- );
908-
909- assert!(delete(&db, linked).await.unwrap());
910- assert!(
911- crate::db::term::delete(&db, term.clone()).await.unwrap(),
912- "the last link gone, the term may go"
913- );
914- let again = crate::db::term::delete(&db, term).await;
915- assert!(
916- matches!(again, Err(AppError::NotFound)),
917- "a second delete is a 404, not a refusal: {again:?}"
918- );
919- }
920-
921- /// The claim doubles as the existence check the lock used to make safe:
922- /// a term that is already gone cannot be linked, with the same 400 the
923- /// web layer's pre-flight lookup gives.
924- #[tokio::test]
925- async fn a_course_cannot_link_a_term_that_is_gone() {
926- let (db, _leases) = crate::database::init_test_db().await;
927- let error = create(
928- &db,
929- &a_person(&db, "teacher", "teacher").await,
930- CourseTitle::try_new("algebra").unwrap(),
931- CourseDescription::try_new("").unwrap(),
932- CourseKind::course(),
933- Some(TermId::from_key("gone")),
843+ /// A şube, for the tests that need an instance attached to it.
844+ async fn a_class(
845+ on: &UserId,
846+ name: &str,
847+ db: &Database,
848+ ) -> crate::domain::class_group::ClassGroup {
849+ crate::db::class_group::create(
850+ db,
851+ on,
852+ crate::domain::class_group::ClassName::try_new(name).unwrap(),
853+ None,
854+ None,
934855 None,
935856 )
936857 .await
937- .expect_err("a missing term must not be linkable");
938- assert!(error.to_string().contains("term does not exist"));
858+ .unwrap()
939859 }
940860
941- /// The stored `course_count` on one term, absent counting as zero.
942- async fn count_on(term: &TermId, db: &Database) -> i64 {
943- sqlx::query("SELECT COALESCE(course_count, 0) FROM term WHERE id = $1")
944- .bind(term.uuid())
861+ /// The instances a course is attached through, re-read from storage —
862+ /// never off a return value.
863+ async fn instance_rows(course: &CourseId, db: &Database) -> i64 {
864+ sqlx::query("SELECT count(*) FROM class_course WHERE course = $1")
865+ .bind(course.uuid())
945866 .fetch_one(db)
946867 .await
947868 .unwrap()
@@ -959,352 +880,138 @@ mod tests {
959880 .unwrap() as usize
960881 }
961882
962- async fn a_term(name: &str, db: &Database) -> Term {
963- let at = crate::domain::timestamp::Timestamp::from_millis;
964- crate::db::term::create(db, TermName::try_new(name).unwrap(), at(100), at(200))
965- .await
966- .unwrap()
967- }
968-
969- /// The invariant, on the create path: a claim and the row it accounts for
970- /// commit together or not at all. A refused create must therefore leave
971- /// *neither* — no course row, and no count stranded on a term (which is
972- /// worse than it sounds: the term's delete guard reads that count, so a
973- /// stray one makes the term undeletable forever).
974- #[tokio::test]
975- async fn a_refused_create_writes_neither_row_nor_count() {
976- let (db, _leases) = crate::database::init_test_db().await;
977- let term = a_term("2026", &db).await;
978- let id = *term.get_id();
979- assert!(crate::db::term::delete(&db, term).await.unwrap());
980-
981- let error = create(
982- &db,
983- &a_person(&db, "teacher", "teacher").await,
984- CourseTitle::try_new("algebra").unwrap(),
985- CourseDescription::try_new("").unwrap(),
986- CourseKind::course(),
987- Some(id),
988- None,
989- )
990- .await
991- .expect_err("a term that is gone must not be linkable");
992- assert!(error.to_string().contains("term does not exist"));
993- assert_eq!(
994- rows("course", &db).await,
995- 0,
996- "a refused create may write no row"
997- );
998- assert_eq!(
999- rows("term", &db).await,
1000- 0,
1001- "…and least of all a count on a term it just brought back"
1002- );
1003- }
1004-
1005- /// The invariant on the PATCH path, both directions: a move carries the new
1006- /// term's claim and the old term's release with the link itself.
1007- #[tokio::test]
1008- async fn a_term_move_moves_the_count() {
1009- let (db, _leases) = crate::database::init_test_db().await;
1010- let from = a_term("2026", &db).await;
1011- let to = a_term("2027", &db).await;
1012- let course = course_on(Some(*from.get_id()), &db).await;
1013- assert_eq!(count_on(from.get_id(), &db).await, 1);
1014-
1015- let moved = update(
1016- &db,
1017- course,
1018- None,
1019- None,
1020- None,
1021- Some(Some(*to.get_id())),
1022- None,
1023- )
1024- .await
1025- .unwrap();
1026- assert_eq!(moved.get_term(), Some(to.get_id()));
1027- assert_eq!(
1028- count_on(from.get_id(), &db).await,
1029- 0,
1030- "the old term is free"
1031- );
1032- assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
1033- assert!(crate::db::term::delete(&db, from.clone()).await.unwrap());
1034- assert!(!crate::db::term::delete(&db, to.clone()).await.unwrap());
1035- }
1036-
1037- /// The double-claim guard. Both movers compute their claim and release from
1038- /// the row as *they* read it, so two PATCHes moving the same course off the
1039- /// same term both release it and both claim their target — two counts for
1040- /// one link, and the loser's target is undeletable forever. The second call
1041- /// here runs on the struct read before the first one landed, which is that
1042- /// race with the interleaving pinned: it must be refused outright, and the
1043- /// counts must read as if it never ran.
883+ /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the
884+ /// guard is the two counters on the locked course row, so the anchor's
885+ /// refusal is a live instance — and it must refuse having written
886+ /// nothing, the instance least of all. A `>= 0` guard passes the guard
887+ /// branch and fails here by deleting the course out from under its class.
1044888 #[tokio::test]
1045- async fn a_stale_mover_is_refused_and_claims_nothing() {
889+ async fn a_course_an_instance_still_teaches_refuses_to_delete() {
1046890 let (db, _leases) = crate::database::init_test_db().await;
1047- let from = a_term("2026", &db).await;
1048- let to = a_term("2027", &db).await;
1049- let other = a_term("2028", &db).await;
1050- let course = course_on(Some(*from.get_id()), &db).await;
1051- let stale = course.clone();
1052- update(
1053- &db,
1054- course,
1055- None,
1056- None,
1057- None,
1058- Some(Some(*to.get_id())),
1059- None,
1060- )
1061- .await
1062- .unwrap();
891+ let manager = a_person(&db, "manager", "manager").await;
892+ let course = a_course(&db).await;
893+ let class = a_class(&manager, "9-A", &db).await;
894+ let instance =
895+ crate::service::class_course::attach(&db, class.get_id(), course.get_id(), &manager)
896+ .await
897+ .unwrap();
1063898
1064- let error = update(
1065- &db,
1066- stale.clone(),
1067- None,
1068- None,
1069- None,
1070- Some(Some(*other.get_id())),
1071- None,
1072- )
1073- .await
1074- .expect_err("a mover that read a link it no longer holds must be refused");
1075899 assert!(
1076- matches!(error, AppError::Conflict(_)),
1077- "a lost CAS is a conflict, not a 404 or a 500: {error:?}"
1078- );
1079- let stored = read(&db, stale.get_id()).await.unwrap().unwrap();
1080- assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link");
1081- assert_eq!(
1082- count_on(from.get_id(), &db).await,
1083- 0,
1084- "released once, not twice"
1085- );
1086- assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once");
1087- assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed");
1088-
1089- // Same race from the other end: the snapshot says *no* link, so the CAS
1090- // is against an absent column — the shape a bound `NONE` has to match.
1091- let unlinked = course_on(None, &db).await;
1092- let stale = unlinked.clone();
1093- update(
1094- &db,
1095- unlinked,
1096- None,
1097- None,
1098- None,
1099- Some(Some(*to.get_id())),
1100- None,
1101- )
1102- .await
1103- .unwrap();
1104- let error = update(
1105- &db,
1106- stale.clone(),
1107- None,
1108- None,
1109- None,
1110- Some(Some(*other.get_id())),
1111- None,
1112- )
1113- .await
1114- .expect_err("a mover that read an absent link someone else filled must be refused");
1115- assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
1116- assert_eq!(count_on(to.get_id(), &db).await, 2, "one claim per link");
1117- assert_eq!(
1118- count_on(other.get_id(), &db).await,
1119- 0,
1120- "still never claimed"
900+ !delete(&db, course.clone()).await.unwrap(),
901+ "a course a class still teaches must refuse the delete"
1121902 );
1122- // …and the unraced set still lands, so the CAS did not just break moves.
1123- let stored = read(&db, stale.get_id()).await.unwrap().unwrap();
1124- assert_eq!(stored.get_term(), Some(to.get_id()));
1125- }
1126-
1127- /// The same race with the counters taken out of it. A PATCH that re-states
1128- /// the term its snapshot showed shifts *nothing* — [`term::ref_move`] hands
1129- /// back no claim and no release — so if the guard were armed off the counter
1130- /// move it would not be armed here at all, and the write would land: the
1131- /// winner's link silently dragged back, its claim stranded on a term nothing
1132- /// points at (undeletable forever) and the reverted-to term linked at a
1133- /// count of zero (deletable while linked). The guard is armed by the request
1134- /// *carrying* the column instead, which is why this is refused.
1135- #[tokio::test]
1136- async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
1137- let (db, _leases) = crate::database::init_test_db().await;
1138- let from = a_term("2026", &db).await;
1139- let to = a_term("2027", &db).await;
1140- let course = course_on(Some(*from.get_id()), &db).await;
1141- let stale = course.clone();
1142- update(
1143- &db,
1144- course,
1145- None,
1146- None,
1147- None,
1148- Some(Some(*to.get_id())),
1149- None,
1150- )
1151- .await
1152- .unwrap();
1153-
1154- let error = update(
1155- &db,
1156- stale.clone(),
1157- None,
1158- None,
1159- None,
1160- Some(Some(*from.get_id())),
1161- None,
1162- )
1163- .await
1164- .expect_err("re-stating a link someone else moved must be refused");
1165903 assert!(
1166- matches!(error, AppError::Conflict(_)),
1167- "a lost CAS is a conflict, not a silent 200: {error:?}"
1168- );
1169- let stored = read(&db, stale.get_id()).await.unwrap().unwrap();
1170- assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link");
1171- assert_eq!(
1172- count_on(from.get_id(), &db).await,
1173- 0,
1174- "the reverted-to term must not end up linked at zero"
904+ read(&db, course.get_id()).await.unwrap().is_some(),
905+ "a refused delete may write nothing"
1175906 );
1176- assert_eq!(
1177- count_on(to.get_id(), &db).await,
1178- 1,
1179- "…nor the winner's term counted with nothing pointing at it"
907+ assert!(
908+ crate::db::class_course::read(&db, instance.get_id())
909+ .await
910+ .unwrap()
911+ .is_some(),
912+ "…the instance least of all"
1180913 );
1181914
1182- // A *genuine* no-op re-state — nobody moved underneath it — still lands,
1183- // and still moves no counter: the CAS passes trivially.
1184- let fresh = read(&db, stale.get_id()).await.unwrap().unwrap();
1185- let same = update(
1186- &db,
1187- fresh,
1188- None,
1189- None,
1190- None,
1191- Some(Some(*to.get_id())),
1192- None,
1193- )
1194- .await
1195- .expect("re-stating the link the row really holds is not a conflict");
1196- assert_eq!(same.get_term(), Some(to.get_id()));
1197- assert_eq!(count_on(from.get_id(), &db).await, 0, "nothing moved");
1198- assert_eq!(count_on(to.get_id(), &db).await, 1, "…in either direction");
1199- }
1200-
1201- /// The rollback proof. The transaction releases the old term *before* it
1202- /// claims the new one, so a move to a term that is gone has already
1203- /// decremented when the claim throws — the old count still being 1 is the
1204- /// abort undoing a write that really happened, not a branch that never ran.
1205- /// The title moves in the same PATCH, and must not stick either.
1206- #[tokio::test]
1207- async fn a_term_move_to_a_dead_term_leaves_everything_untouched() {
1208- let (db, _leases) = crate::database::init_test_db().await;
1209- let from = a_term("2026", &db).await;
1210- let dead = a_term("2027", &db).await;
1211- let dead_id = *dead.get_id();
1212- assert!(crate::db::term::delete(&db, dead).await.unwrap());
1213- let course = course_on(Some(*from.get_id()), &db).await;
1214-
1215- let error = update(
1216- &db,
1217- course.clone(),
1218- Some(CourseTitle::try_new("moved").unwrap()),
1219- None,
1220- None,
1221- Some(Some(dead_id)),
1222- None,
1223- )
1224- .await
1225- .expect_err("a term that is gone must not be linkable");
1226- assert!(error.to_string().contains("term does not exist"));
915+ // Detaching the last instance frees the row: the catalog is a
916+ // template, and the template whose last class let it go is deletable.
917+ crate::service::class_course::detach(&db, class.get_id(), course.get_id())
918+ .await
919+ .unwrap();
920+ assert!(delete(&db, course.clone()).await.unwrap());
921+ assert!(read(&db, course.get_id()).await.unwrap().is_none());
1227922
1228- let stored = read(&db, course.get_id()).await.unwrap().unwrap();
1229- assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put");
1230- assert_eq!(
1231- stored.get_title().as_str(),
1232- "algebra",
1233- "…and so does the row"
1234- );
923+ // …and the counter the guard read is back to zero with it, not left
924+ // stranded by the cascade.
1235925 assert_eq!(
1236- count_on(from.get_id(), &db).await,
1237- 1,
1238- "the release must roll back with the abort"
926+ instance_rows(course.get_id(), &db).await,
927+ 0,
928+ "the instance rows must go with the course"
1239929 );
1240930 assert_eq!(
1241- rows("term", &db).await,
1242- 1,
1243- "the dead term must not be resurrected by the claim"
931+ rows("course", &db).await,
932+ 0,
933+ "no row may outlive the delete"
1244934 );
1245935 }
1246936
1247- /// MEASUREMENT — the one race test that actually measures the retry, and
1248- /// the only one of the four that does. The other three (subject, term,
1249- /// exam) are status-code guards; each says so on itself.
937+ /// MEASUREMENT — the one race test for `Course::delete`, and the only
938+ /// test that measures `tx_with_retry` on this path at all.
1250939 ///
1251- /// [`delete`] is one `BEGIN…COMMIT` whose guard reads
1252- /// `enrollment_count` off the very record a concurrent enroll increments,
1253- /// so the two contend by design, and its cascade is long enough that a
940+ /// [`delete`] is one `BEGIN…COMMIT` whose guard locks the course row the
941+ /// very counter an attach claims, so the two contend by design: the
942+ /// attach is several statements long (the early verdicts, the counter
943+ /// claim, the roster pump) and the delete's cascade is longer, so a
1254944 /// rival's write lands mid-transaction. Losing that round writes nothing,
1255945 /// which is what makes re-sending it the recovery. Without
1256- /// [`crate::database::transaction_with_retry`] a lost round comes out as a
1257- /// 500: mutation-tested by cutting that retry loop to one attempt, which
946+ /// [`crate::database::transaction_with_retry`] a lost round comes out as
947+ /// a 500: mutation-tested by cutting that retry loop to one attempt, which
1258948 /// turns this test red at 1-2 of 20 rounds (3 runs in 5 — the window is
1259- /// real but narrow, so a single green run under the mutation means nothing).
949+ /// real but narrow, so a single green run under the mutation means
950+ /// nothing).
1260951 ///
1261952 /// A refusal (`Ok(false)`) or an `Err(NotFound)` is *correct* here and
1262- /// must not fail this test: the only defect is `AppError::Db`.
953+ /// must not fail this test: the only defect is `AppError::Db`. The stored
954+ /// half of the verdict is the orphan check — an instance may never name a
955+ /// course that is gone, whichever side of the race it was on.
1263956 ///
1264957 /// The rate is counted over the whole loop instead of asserted per round,
1265958 /// because a per-round `assert!` aborts at the first hit and would report
1266959 /// "1 of 1" for a bug the point of this test is to *quantify*.
1267960 ///
1268- /// Multi-threaded and on a real server for the reasons spelled out on
1269- /// [`crate::domain::fee_plan_assignment`]'s pair of race tests: the
1270- /// current-thread runtime never interleaves the two, and the embedded
1271- /// engine does not conflict-check concurrent writes to one record at all.
961+ /// Each side gets a clear head start on every other round — 2ms is a
962+ /// separation the several-statement rival cannot cross (the same spacing
963+ /// [`crate::db::term`]'s race test settled on). Without it the two sides
964+ /// compete for the same course row and whichever one is marginally faster
965+ /// takes every round, leaving one half of the verdict (`swept > 0`, or
966+ /// `attached > 0`) a coin toss under load.
967+ ///
968+ /// Multi-threaded and on a real server: the current-thread runtime never
969+ /// interleaves the two, and an embedded engine does not conflict-check
970+ /// concurrent writes at all.
1272971 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1273- async fn a_delete_racing_an_enroll_never_answers_500() {
972+ async fn a_delete_racing_an_attach_never_answers_500() {
1274973 let (db, _leases) = crate::database::init_test_db().await;
1275- // The roster rows are foreign keys now: the burst's six racers and
1276- // their enroller are real people, reused every round (each round's
1277- // delete cascade frees the seats back).
1278- let mgr = a_person(&db, "mgr", "manager").await;
1279- let mut students = Vec::new();
974+ let manager = a_person(&db, "mgr", "manager").await;
975+ // One şube per racer; each round attaches them all into one fresh
976+ // catalog course, so the round's delete has six rival claims to meet.
977+ let mut classes = Vec::new();
1280978 for seat in 0..6 {
1281- students.push(a_person(&db, &format!("stu{seat}"), "student").await);
979+ classes.push(a_class(&manager, &format!("9-{seat}"), &db).await);
1282980 }
1283- let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0);
1284- let (mut last_delete, mut last_enroll) = (String::new(), String::new());
981+ let (mut delete_500, mut attach_500, mut attached, mut swept) = (0, 0, 0, 0);
982+ let (mut last_delete, mut last_attach) = (String::new(), String::new());
1285983 for round in 0..20 {
1286- let course = course_on(None, &db).await;
984+ let course = a_course(&db).await;
1287985
1288- // A *burst* of enrolls, and a delete held back by a sweeping beat.
1289- // Released together the delete is one statement while an enroll
1290- // spends two round trips reading before it claims, so it wins every
1291- // round and the guard is never contended at all (measured: 0/20
1292- // seats placed). Six racers over a 0-3ms sweep put the single
1293- // statement somewhere inside the counter writes instead.
986+ // Every other round the attaches are held back so the delete wins
987+ // outright (the course goes, and nothing may survive it); the rest
988+ // release the attaches first, which is the round where the guard
989+ // has to read their claim and refuse the delete.
990+ let clear = std::time::Duration::from_millis(2);
991+ let (delete_beat, attach_beat) = if round % 2 == 0 {
992+ (std::time::Duration::ZERO, clear)
993+ } else {
994+ (clear, std::time::Duration::ZERO)
995+ };
1294996 let drop_it = {
1295997 let (course, db) = (course.clone(), db.clone());
1296- let beat = std::time::Duration::from_millis(round % 4);
1297998 tokio::spawn(async move {
1298- tokio::time::sleep(beat).await;
999+ tokio::time::sleep(delete_beat).await;
12991000 delete(&db, course).await
13001001 })
13011002 };
1302- let joins: Vec<_> = (0..6)
1303- .map(|seat| {
1304- let (id, db, mgr) = (course.get_id().clone(), db.clone(), mgr);
1305- let student = students[seat];
1003+ let joins: Vec<_> = classes
1004+ .iter()
1005+ .map(|class| {
1006+ let (class, course, db, mgr) = (
1007+ class.get_id().clone(),
1008+ course.get_id().clone(),
1009+ db.clone(),
1010+ manager,
1011+ );
13061012 tokio::spawn(async move {
1307- crate::db::enrollment::enroll(&db, &id, &student, &mgr).await
1013+ tokio::time::sleep(attach_beat).await;
1014+ crate::service::class_course::attach(&db, &class, &course, &mgr).await
13081015 })
13091016 })
13101017 .collect();
@@ -1316,36 +1023,41 @@ mod tests {
13161023 for join in joins {
13171024 let join = join.await.unwrap();
13181025 if matches!(join, Err(AppError::Db(_))) {
1319- enroll_500 += 1;
1320- last_enroll = format!("{join:?}");
1026+ attach_500 += 1;
1027+ last_attach = format!("{join:?}");
13211028 }
13221029 }
1323- // Stored state, not the return values: a seat that landed is what
1324- // the guard had to see.
1325- if !crate::db::enrollment::list_for_course(&db, course.get_id(), None, 0)
1326- .await
1327- .unwrap()
1328- .0
1329- .is_empty()
1330- {
1331- enrolled += 1;
1030+ // Stored state, not the return values: an instance that landed is
1031+ // what the guard had to see, and one that outlived a deleted
1032+ // course is the defect this whole shape exists to catch.
1033+ let live = instance_rows(course.get_id(), &db).await;
1034+ if live > 0 {
1035+ attached += 1;
1036+ }
1037+ if read(&db, course.get_id()).await.unwrap().is_none() {
1038+ swept += 1;
1039+ assert_eq!(
1040+ live, 0,
1041+ "round {round}: an instance outlived the course it names"
1042+ );
13321043 }
13331044 }
13341045 eprintln!(
1335- "Course::delete raced: {delete_500}/20 delete 500s, {enroll_500} enroll 500s, \
1336- {enrolled}/20 rounds with a seat placed"
1046+ "Course::delete raced: {delete_500}/20 delete 500s, {attach_500} attach 500s, \
1047+ {attached} rounds with an instance attached / {swept} rounds the course went"
13371048 );
13381049 assert!(
1339- enrolled > 0,
1340- "no round ever placed an enrollment, so the delete guard was never contended"
1050+ attached > 0 && swept > 0,
1051+ "the sweep never crossed the window ({attached} attached / {swept} swept), \
1052+ so at least one verdict was never exercised"
13411053 );
13421054 assert_eq!(
13431055 delete_500, 0,
13441056 "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}"
13451057 );
13461058 assert_eq!(
1347- enroll_500, 0,
1348- "a raced enroll must retry, not 500: {enroll_500}/20 rounds, last {last_enroll}"
1059+ attach_500, 0,
1060+ "a raced attach must be answered, not 500: {attach_500}/20 rounds, last {last_attach}"
13491061 );
13501062 }
13511063 }
src/db/course_membership.rsadded+222 -0
@@ -0,0 +1,222 @@
1+//! The `course_membership` table: a student's individual membership in a
2+//! *school-scoped* course (D9) — a kulüp or an etüt, joined directly rather
3+//! than through a şube's instance.
4+//!
5+//! It is the `enrollment` table's twin minus two things: the instance key (a
6+//! club has no class to belong to) and the roster pump's `source` tag (a
7+//! membership is placed by a human and swept by no class). The membership
8+//! counter on the course moves in the same statement as the row, so the
9+//! catalog's delete guard reads a number its own writes maintain.
10+//!
11+//! Whether a given course *may* be joined this way is
12+//! [`crate::service::enrollment::join_activity`]'s decision: a class-delivered
13+//! ders ([`crate::domain::course::CourseKind::is_class_delivered`]) is joined
14+//! through its instance, never here.
15+
16+use crate::database::{Database, tx_with_retry, unique_violation};
17+use crate::db::page::PagedList;
18+use crate::domain::course::CourseId;
19+use crate::domain::course_membership::CourseMembership;
20+use crate::domain::role::Role;
21+use crate::domain::timestamp::Timestamp;
22+use crate::domain::user::UserId;
23+use crate::error::{AppError, ValidationError};
24+
25+/// What [`add`]'s transaction settled on.
26+enum Verdict {
27+ /// This pair already holds a row — the idempotent hit.
28+ Held,
29+ /// The person being added is no longer a student.
30+ Unfit,
31+ /// The row is written.
32+ Made(CourseMembership),
33+}
34+
35+/// Add (idempotently) `user` to one school-scoped course. The table's primary
36+/// key *is* the (course, user) pair, so concurrent calls converge on one row
37+/// instead of racing into a 500: the loser reads the winner's row back and
38+/// returns it, and the counter moves once.
39+///
40+/// The role check takes the user row `FOR NO KEY UPDATE` — the same lock a
41+/// demotion cascade takes before it sweeps memberships — so an add and a
42+/// demotion serialize in both directions.
43+pub async fn add(
44+ db: &Database,
45+ course: &CourseId,
46+ user: &UserId,
47+ added_by: &UserId,
48+) -> Result<CourseMembership, AppError> {
49+ if let Some(existing) = read_for_user(db, course, user).await? {
50+ return Ok(existing);
51+ }
52+ let course_id = course.clone();
53+ let (user_id, added_by_id) = (*user, *added_by);
54+ let created_at = Timestamp::now();
55+ let verdict = tx_with_retry(db, false, async move |tx| {
56+ // The duplicate gate rides ahead of the role check, so "you are
57+ // already in" still outranks everything.
58+ let held = sqlx::query!(
59+ r#"SELECT 1 AS "one" FROM course_membership WHERE course = $1 AND app_user = $2"#,
60+ course_id.uuid(),
61+ user_id.uuid(),
62+ )
63+ .fetch_optional(&mut *tx)
64+ .await?;
65+ if held.is_some() {
66+ return Ok(Verdict::Held);
67+ }
68+ let role = sqlx::query!(
69+ r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#,
70+ user_id.uuid(),
71+ )
72+ .fetch_optional(&mut *tx)
73+ .await?;
74+ if role.map(|row| row.role).as_deref() != Some(Role::Student.as_str()) {
75+ return Ok(Verdict::Unfit);
76+ }
77+ // The counter and the row in one statement: zero rows means the
78+ // course is gone — the caller's own read answers that 404 one instant
79+ // earlier.
80+ let row = sqlx::query_as!(
81+ CourseMembership,
82+ r#"WITH seat AS (
83+ UPDATE course
84+ SET course_membership_count = course_membership_count + 1
85+ WHERE id = $1
86+ RETURNING 1)
87+ INSERT INTO course_membership (course, app_user, added_by, created_at)
88+ SELECT $1, $2, $3, $4 WHERE EXISTS (SELECT 1 FROM seat)
89+ RETURNING course AS "course: CourseId", app_user AS "user: UserId",
90+ added_by AS "added_by: UserId",
91+ created_at AS "created_at: Timestamp""#,
92+ course_id.uuid(),
93+ user_id.uuid(),
94+ added_by_id.uuid(),
95+ created_at.as_millis(),
96+ )
97+ .fetch_optional(&mut *tx)
98+ .await?;
99+ match row {
100+ Some(row) => Ok(Verdict::Made(row)),
101+ None => {
102+ let now_held = sqlx::query!(
103+ r#"SELECT 1 AS "one" FROM course_membership
104+ WHERE course = $1 AND app_user = $2"#,
105+ course_id.uuid(),
106+ user_id.uuid(),
107+ )
108+ .fetch_optional(&mut *tx)
109+ .await?;
110+ if now_held.is_some() {
111+ return Ok(Verdict::Held);
112+ }
113+ Err(AppError::NotFound)
114+ }
115+ }
116+ })
117+ .await;
118+ // A rival landing between the gate and the insert is answered off the
119+ // table's own primary key — same verdict, no second count.
120+ let verdict = match verdict {
121+ Err(AppError::Db(err))
122+ if unique_violation(&err) == Some("course_membership_course_user") =>
123+ {
124+ Ok(Verdict::Held)
125+ }
126+ other => other,
127+ };
128+ match verdict {
129+ Ok(Verdict::Made(row)) => Ok(row),
130+ Ok(Verdict::Held) => match read_for_user(db, course, user).await? {
131+ Some(existing) => Ok(existing),
132+ None => Err(AppError::Internal("failed to add course membership".into())),
133+ },
134+ Ok(Verdict::Unfit) => Err(AppError::Validation(ValidationError::Invalid {
135+ field: "user_id",
136+ reason: "only students can join a course",
137+ })),
138+ Err(err) => Err(err),
139+ }
140+}
141+
142+/// Some(_) iff `user` holds a membership in `course`.
143+pub async fn read_for_user(
144+ db: &Database,
145+ course: &CourseId,
146+ user: &UserId,
147+) -> Result<Option<CourseMembership>, AppError> {
148+ let row = sqlx::query_as!(
149+ CourseMembership,
150+ r#"SELECT course AS "course: CourseId", app_user AS "user: UserId",
151+ added_by AS "added_by: UserId", created_at AS "created_at: Timestamp"
152+ FROM course_membership WHERE course = $1 AND app_user = $2"#,
153+ course.uuid(),
154+ user.uuid(),
155+ )
156+ .fetch_optional(db)
157+ .await?;
158+ Ok(row)
159+}
160+
161+/// One course's members, newest first.
162+pub async fn list_for_course(
163+ db: &Database,
164+ course: &CourseId,
165+ limit: Option<i64>,
166+ offset: i64,
167+) -> Result<(Vec<CourseMembership>, i64), AppError> {
168+ PagedList::new(
169+ "course_membership WHERE course = $1",
170+ "ORDER BY course DESC, app_user DESC",
171+ )
172+ .bind(course.uuid())
173+ .run::<CourseMembership>(limit, offset, db)
174+ .await
175+}
176+
177+/// Every membership `user` holds, newest first — the "my clubs and etüts"
178+/// read.
179+pub async fn list_for_user(
180+ db: &Database,
181+ user: &UserId,
182+ limit: Option<i64>,
183+ offset: i64,
184+) -> Result<(Vec<CourseMembership>, i64), AppError> {
185+ PagedList::new(
186+ "course_membership WHERE app_user = $1",
187+ "ORDER BY course DESC, app_user DESC",
188+ )
189+ .bind(user.uuid())
190+ .run::<CourseMembership>(limit, offset, db)
191+ .await
192+}
193+
194+/// Take the row and give the course's membership counter back in one
195+/// statement. `None` when the pair held no row.
196+pub async fn remove(
197+ db: &Database,
198+ course: &CourseId,
199+ user: &UserId,
200+) -> Result<Option<CourseMembership>, AppError> {
201+ let gone = sqlx::query_as!(
202+ CourseMembership,
203+ r#"WITH gone AS (
204+ DELETE FROM course_membership
205+ WHERE course = $1 AND app_user = $2
206+ RETURNING course, app_user, added_by, created_at),
207+ counted AS (
208+ UPDATE course
209+ SET course_membership_count = GREATEST(
210+ course_membership_count - (SELECT count(*) FROM gone), 0)
211+ WHERE id = $1
212+ RETURNING 1)
213+ SELECT course AS "course: CourseId", app_user AS "user: UserId",
214+ added_by AS "added_by: UserId", created_at AS "created_at: Timestamp"
215+ FROM gone"#,
216+ course.uuid(),
217+ user.uuid(),
218+ )
219+ .fetch_optional(db)
220+ .await?;
221+ Ok(gone)
222+}
src/db/course_note.rsmodified+1 -4
@@ -167,16 +167,13 @@ mod tests {
167167 #[tokio::test]
168168 async fn delete_returns_the_attachment_rows_it_removed() {
169169 let (db, _leases) = crate::database::init_test_db().await;
170- let creator =
171- crate::db::class_member::tests::fixture_user(&db, "course-note-author").await;
170+ let creator = crate::db::class_member::tests::fixture_user(&db, "course-note-author").await;
172171 let course = crate::db::course::create(
173172 &db,
174173 &creator,
175174 CourseTitle::try_new("Math").unwrap(),
176175 CourseDescription::try_new("").unwrap(),
177176 CourseKind::try_new("course").unwrap(),
178- None,
179- None,
180177 )
181178 .await
182179 .unwrap();
src/db/course_note_file.rsmodified+0 -2
@@ -186,8 +186,6 @@ mod tests {
186186 CourseTitle::try_new("c").unwrap(),
187187 CourseDescription::try_new("").unwrap(),
188188 CourseKind::try_new("course").unwrap(),
189- None,
190- None,
191189 )
192190 .await
193191 .unwrap();
src/db/course_session.rsmodified+58 -26
@@ -1,14 +1,15 @@
1-//! The `course_session` table: reads, a course's timetable listing, the
1+//! The `course_session` table: reads, an instance's timetable listing, the
22 //! request-scoped field update, and the delete that sweeps roll-call rows in
3-//! one transaction. Creation stands on the course foreign key, so a lesson
4-//! can never outlive its course; the web-facing doors and the
5-//! teacher-resolution rule live in [`crate::service::course_session`].
3+//! one transaction. Creation stands on the instance foreign key, so a lesson
4+//! can never outlive the class×course instance it is a lesson of; the
5+//! web-facing doors and the teacher-resolution rule live in
6+//! [`crate::service::course_session`].
67
78 use crate::constant::COURSE_SESSION_TABLE;
89 use crate::database::{Database, foreign_key_violation, tx_with_retry};
910 use crate::db::field_update::FieldUpdate;
1011 use crate::db::page::PagedList;
11-use crate::domain::course::CourseId;
12+use crate::domain::class_course::ClassCourseId;
1213 use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};
1314 use crate::domain::timestamp::{Timestamp, range_error};
1415 use crate::domain::user::UserId;
@@ -16,7 +17,7 @@ use crate::error::AppError;
1617
1718 pub async fn create(
1819 db: &Database,
19- course: &CourseId,
20+ class_course: &ClassCourseId,
2021 teacher: &UserId,
2122 topic: SessionTopic,
2223 starts_at: Timestamp,
@@ -24,28 +25,29 @@ pub async fn create(
2425 ) -> Result<CourseSession, AppError> {
2526 let session = CourseSession {
2627 id: CourseSessionId::generate(),
27- course: course.clone(),
28+ class_course: class_course.clone(),
2829 teacher: *teacher,
2930 topic,
3031 starts_at,
3132 ends_at,
3233 };
33- // The course foreign key is the existence proof the old bump-and-restore
34- // "touch" trick faked: a lesson whose course is already gone — or which
35- // is deleted while this insert is in flight — is refused here, so a
36- // lesson can never outlive its course and 404 through
37- // `session_with_course` forever — unreadable, unpatchable, undeletable.
38- // `23503` is the parent-gone refusal, the same answer the touch
39- // produced.
34+ // The instance foreign key is the existence proof the old
35+ // bump-and-restore "touch" trick faked: a lesson whose instance is
36+ // already gone — or which is detached while this insert is in flight — is
37+ // refused here, so a lesson can never outlive the instance and 404
38+ // through the session reads forever — unreadable, unpatchable,
39+ // undeletable. `23503` is the parent-gone refusal, the same answer the
40+ // touch produced.
4041 let created = sqlx::query_as!(
4142 CourseSession,
42- r#"INSERT INTO course_session (id, course, teacher, topic, starts_at, ends_at)
43+ r#"INSERT INTO course_session (id, class_course, teacher, topic, starts_at, ends_at)
4344 VALUES ($1, $2, $3, $4, $5, $6)
44- RETURNING id AS "id: CourseSessionId", course AS "course: CourseId",
45+ RETURNING id AS "id: CourseSessionId",
46+ class_course AS "class_course: ClassCourseId",
4547 teacher AS "teacher: UserId", topic AS "topic: SessionTopic",
4648 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp""#,
4749 session.id.uuid(),
48- session.course.uuid(),
50+ session.class_course.uuid(),
4951 session.teacher.uuid(),
5052 session.topic.as_str(),
5153 session.starts_at.as_millis(),
@@ -63,7 +65,8 @@ pub async fn create(
6365 pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> {
6466 let session = sqlx::query_as!(
6567 CourseSession,
66- r#"SELECT id AS "id: CourseSessionId", course AS "course: CourseId",
68+ r#"SELECT id AS "id: CourseSessionId",
69+ class_course AS "class_course: ClassCourseId",
6770 teacher AS "teacher: UserId", topic AS "topic: SessionTopic",
6871 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp"
6972 FROM course_session WHERE id = $1"#,
@@ -74,20 +77,20 @@ pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSe
7477 Ok(session)
7578 }
7679
77-/// A course's sessions, most recent lesson first. Ordered by `starts_at`
80+/// An instance's sessions, most recent lesson first. Ordered by `starts_at`
7881 /// (not id): a timetable is read by when the lesson happens, not by when
7982 /// the row was created.
80-pub async fn list_for_course(
83+pub async fn list_for_class_course(
8184 db: &Database,
82- course: &CourseId,
85+ class_course: &ClassCourseId,
8386 limit: Option<i64>,
8487 offset: i64,
8588 ) -> Result<(Vec<CourseSession>, i64), AppError> {
8689 PagedList::new(
87- "course_session WHERE course = $1",
90+ "course_session WHERE class_course = $1",
8891 "ORDER BY starts_at DESC, id DESC",
8992 )
90- .bind(course.uuid())
93+ .bind(class_course.uuid())
9194 .run::<CourseSession>(limit, offset, db)
9295 .await
9396 }
@@ -147,7 +150,8 @@ pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSessi
147150 let deleted = sqlx::query_as!(
148151 CourseSession,
149152 r#"DELETE FROM course_session WHERE id = $1
150- RETURNING id AS "id: CourseSessionId", course AS "course: CourseId",
153+ RETURNING id AS "id: CourseSessionId",
154+ class_course AS "class_course: ClassCourseId",
151155 teacher AS "teacher: UserId", topic AS "topic: SessionTopic",
152156 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp""#,
153157 session.id.uuid(),
@@ -175,6 +179,9 @@ mod tests {
175179 /// rounds orphan.
176180 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
177181 async fn a_session_never_outlives_its_course() {
182+ use crate::domain::course::CourseId;
183+ use crate::domain::user::UserId;
184+
178185 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
179186 tokio::spawn(async move {
180187 // The creator is a foreign key now: a real `app_user` row.
@@ -188,9 +195,27 @@ mod tests {
188195 .execute(&db)
189196 .await
190197 .unwrap();
198+ // The lesson hangs off the instance now, so the round has to
199+ // attach one — that claim is exactly what the racing delete
200+ // contends on, and a course already gone refuses right here.
201+ let class = crate::db::class_group::create(
202+ &db,
203+ &creator,
204+ crate::domain::class_group::ClassName::try_new("9-A").unwrap(),
205+ None,
206+ None,
207+ None,
208+ )
209+ .await?
210+ .get_id()
211+ .clone();
212+ let instance = crate::service::class_course::attach(&db, &class, &course, &creator)
213+ .await?
214+ .get_id()
215+ .clone();
191216 create(
192217 &db,
193- &course,
218+ &instance,
194219 &creator,
195220 SessionTopic::try_new("limits").unwrap(),
196221 Timestamp::from_millis(1),
@@ -200,6 +225,13 @@ mod tests {
200225 .map(|_| ())
201226 })
202227 }
203- crate::db::course::assert_no_child_outlives_a_course_delete("course_session", make).await;
228+ crate::db::course::assert_no_child_outlives_a_course_delete(
229+ "course_session",
230+ "SELECT count(*) FROM course_session s
231+ JOIN class_course cc ON cc.id = s.class_course
232+ WHERE cc.course = $1",
233+ make,
234+ )
235+ .await;
204236 }
205237 }
src/db/enrollment.rsmodified+221 -169
@@ -1,12 +1,18 @@
1-//! The `enrollment` table: the roster read and listing, the seat-returning
2-//! delete, and the enroll claim — one transaction that checks the pair free,
3-//! the member still a student, and the roster under capacity while it
4-//! spends the seat. The target-user gates the HTTP handlers pay live in
5-//! [`crate::service::enrollment`].
1+//! The `enrollment` table: the roster read and listing, the counter-returning
2+//! delete, and the enroll claim — one transaction that checks the pair free
3+//! and the member still a student. The target-user gates the HTTP handlers pay
4+//! live in [`crate::service::enrollment`].
5+//!
6+//! Enrollment keys on the *instance* now (D4): a student is enrolled in the
7+//! Matematik that 5-A teaches, not in a school-wide Matematik row. The seat
8+//! gate is gone with the catalog's `capacity` (D5) — the roster counter is a
9+//! count, not a ceiling — so the only refusals left are "already enrolled"
10+//! (which is an idempotent hit, not an error) and "that user is not a
11+//! student".
612
713 use crate::database::{Database, tx_with_retry, unique_violation};
8-use crate::db::cap;
914 use crate::db::page::PagedList;
15+use crate::domain::class_course::ClassCourseId;
1016 use crate::domain::class_group::ClassGroupId;
1117 use crate::domain::course::CourseId;
1218 use crate::domain::enrollment::Enrollment;
@@ -15,61 +21,59 @@ use crate::domain::timestamp::Timestamp;
1521 use crate::domain::user::UserId;
1622 use crate::error::{AppError, ValidationError};
1723
18-/// What [`enroll`]'s transaction settled on — the three old `THROW` markers
19-/// (`enroll_held`, `enroll_not_student`, `enroll_full`) as Rust verdicts.
24+/// What [`enroll`]'s transaction settled on.
2025 enum Verdict {
2126 /// This pair already holds a row.
2227 Held,
2328 /// The person being enrolled is no longer a student.
2429 Unfit,
25- /// The roster is full — or the course is gone; the caller reads which.
26- Full,
27- /// The seat is spent and the row is written.
30+ /// The row is written.
2831 Made(Enrollment),
2932 }
3033
31-/// The primary key the natural composite PK carries — the constraint name
32-/// that surfaces in SQLSTATE 23505 when a rival lands first.
33-const PAIR_CONSTRAINT: &str = "enrollment_course_user";
34-
35-/// Enroll (idempotently) `user` into `course`. The table's primary key *is*
36-/// the (course, user) pair, so concurrent enrolls of the same pair converge
37-/// on one row instead of racing into a 500: the loser reads the winner's row
38-/// back and returns it. When the course carries a capacity, a full roster
39-/// refuses new members (409) — the seat is taken by a single-record
40-/// conditional write on the course row whose bound is the row's *own*
41-/// `capacity` column, read inside the same statement that spends the seat. A
42-/// snapshot integer taken by a read beforehand would be exactly the number a
43-/// concurrent capacity PATCH invalidates. An already enrolled user is
44-/// returned as-is even when the roster is full, and never charged a seat.
45-/// The same claim is the delete guard's other half: it matches nothing once
46-/// the course row is gone, and while it holds a seat the course cannot be
47-/// deleted — so no roster row can outlive its course.
34+/// Enroll (idempotently) `user` into one instance. The table's primary key
35+/// *is* the (instance, user) pair, so concurrent enrolls of the same pair
36+/// converge on one row instead of racing into a 500: the loser reads the
37+/// winner's row back and returns it. An already enrolled user is returned
38+/// as-is — the counter moves once, and never twice for one row — except that a
39+/// row a class pumped is *disowned* on the way out (see
40+/// [`disown_if_pumped`]): the operator's hand enroll is what the row now
41+/// records.
42+///
43+/// `source` is the class the roster pump wrote this row on behalf of, or
44+/// `None` for a hand-placed (seçmeli) enrollment. The two halves of that
45+/// rule: only a row carrying the key is a class's to take back
46+/// ([`crate::db::class_pump`]), and a hand unenroll wins permanently.
47+///
48+/// The `enrollment_count` counter moves in the same statement as the row (a
49+/// refused insert takes its own bump back), so the instance's roster size
50+/// cannot drift from the rows behind it.
4851 ///
4952 /// Gate order is the old THROW order: an existing pair outranks the role
50-/// check, which outranks a full roster. The role check takes the user row
51-/// `FOR NO KEY UPDATE`, the same row a demotion cascade updates before its
52-/// sweep, so grant and demotion serialize on the row lock in both
53-/// directions — a row landing after the sweep is impossible, and a demotion
54-/// landing before this check refuses it.
53+/// check. The role check takes the user row `FOR NO KEY UPDATE`, the same row
54+/// a demotion cascade updates before its sweep, so grant and demotion
55+/// serialize on the row lock in both directions — a row landing after the
56+/// sweep is impossible, and a demotion landing before this check refuses it.
5557 pub async fn enroll(
5658 db: &Database,
57- course: &CourseId,
59+ class_course: &ClassCourseId,
5860 user: &UserId,
5961 enrolled_by: &UserId,
62+ source: Option<&ClassGroupId>,
6063 ) -> Result<Enrollment, AppError> {
61- if let Some(existing) = read_for_user(db, course, user).await? {
64+ if let Some(existing) = read_for_user(db, class_course, user).await? {
6265 return disown_if_pumped(db, existing).await;
6366 }
64- let course_id = course.clone();
67+ let instance = class_course.clone();
6568 let (user_id, enrolled_by_id) = (*user, *enrolled_by);
69+ let source_id = source.map(ClassGroupId::uuid);
6670 let created_at = Timestamp::now();
6771 let verdict = tx_with_retry(db, false, async move |tx| {
6872 // The duplicate gate rides ahead of the role check, so "you are
6973 // already in" still outranks everything.
7074 let held = sqlx::query!(
71- r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
72- course_id.uuid(),
75+ r#"SELECT 1 AS "one" FROM enrollment WHERE class_course = $1 AND app_user = $2"#,
76+ instance.uuid(),
7377 user_id.uuid(),
7478 )
7579 .fetch_optional(&mut *tx)
@@ -89,27 +93,27 @@ pub async fn enroll(
8993 if role.map(|row| row.role).as_deref() != Some(Role::Student.as_str()) {
9094 return Ok(Verdict::Unfit);
9195 }
92- // The seat and the row in one statement (the cap recipe): a refused
93- // insert takes its own seat bump back; zero rows means the roster is
94- // full or the course is gone — only the caller pays for the read
95- // that tells those apart.
96+ // The counter and the row in one statement: zero rows means the
97+ // instance is gone — the `404` the caller's own read gives an
98+ // instant earlier.
9699 let row = sqlx::query_as!(
97100 Enrollment,
98101 r#"WITH seat AS (
99- UPDATE course
102+ UPDATE class_course
100103 SET enrollment_count = enrollment_count + 1
101104 WHERE id = $1
102- AND enrollment_count < COALESCE(capacity, $2)
103105 RETURNING 1)
104- INSERT INTO enrollment (course, app_user, enrolled_by, source, created_at)
105- SELECT $1, $3, $4, NULL, $5 WHERE EXISTS (SELECT 1 FROM seat)
106- RETURNING course AS "course: CourseId", app_user AS "user: UserId",
107- enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId""#,
108- course_id.uuid(),
109- cap::UNLIMITED,
106+ INSERT INTO enrollment (class_course, app_user, enrolled_by, source, created_at)
107+ SELECT $1, $2, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat)
108+ RETURNING class_course AS "class_course: ClassCourseId",
109+ app_user AS "user: UserId", enrolled_by AS "enrolled_by: UserId",
110+ source AS "source: ClassGroupId",
111+ created_at AS "created_at: Timestamp""#,
112+ instance.uuid(),
110113 user_id.uuid(),
111114 enrolled_by_id.uuid(),
112- created_at as _,
115+ source_id,
116+ created_at.as_millis(),
113117 )
114118 .fetch_optional(&mut *tx)
115119 .await?;
@@ -117,13 +121,14 @@ pub async fn enroll(
117121 Some(row) => Ok(Verdict::Made(row)),
118122 None => {
119123 // A same-student racer whose held-check predated the winner's
120- // commit queues on the role lock, wakes to a full roster, and
121- // its own row is already the winner's: that is the replay,
122- // not a refusal. Fresh snapshot per statement, so this read
123- // sees the committed winner.
124+ // commit queues on the role lock and wakes to its own row
125+ // already there: that is the replay, not a refusal. Fresh
126+ // snapshot per statement, so this read sees the committed
127+ // winner.
124128 let now_held = sqlx::query!(
125- r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
126- course_id.uuid(),
129+ r#"SELECT 1 AS "one" FROM enrollment
130+ WHERE class_course = $1 AND app_user = $2"#,
131+ instance.uuid(),
127132 user_id.uuid(),
128133 )
129134 .fetch_optional(&mut *tx)
@@ -131,24 +136,27 @@ pub async fn enroll(
131136 if now_held.is_some() {
132137 return Ok(Verdict::Held);
133138 }
134- Ok(Verdict::Full)
139+ // No row and no winner: the instance itself is gone.
140+ Err(AppError::NotFound)
135141 }
136142 }
137143 })
138144 .await;
139145 // The 23505 backstop folds into the Held verdict before the mapping:
140146 // someone placed this pair between the gate and the insert, and their
141- // row is the answer — no seat was spent finding that out.
147+ // row is the answer — no counter move was spent finding that out.
142148 let verdict = match verdict {
143- Err(AppError::Db(err)) if unique_violation(&err) == Some(PAIR_CONSTRAINT) => {
149+ Err(AppError::Db(err))
150+ if unique_violation(&err) == Some("enrollment_class_course_user") =>
151+ {
144152 Ok(Verdict::Held)
145153 }
146154 other => other,
147155 };
148156 match verdict {
149157 Ok(Verdict::Made(row)) => Ok(row),
150- Ok(Verdict::Held) => match read_for_user(db, course, user).await? {
151- Some(existing) => disown_if_pumped(db, existing).await,
158+ Ok(Verdict::Held) => match read_for_user(db, class_course, user).await? {
159+ Some(existing) => Ok(existing),
152160 None => Err(AppError::Internal("failed to enroll user".into())),
153161 },
154162 // Demoted while this ran: the same refusal the service's own gate
@@ -157,26 +165,19 @@ pub async fn enroll(
157165 field: "user_id",
158166 reason: "only students can be enrolled in a course",
159167 })),
160- // Full, or the course is gone — the conditional write matches
161- // nothing either way, and only this path pays for the read that
162- // tells them apart.
163- Ok(Verdict::Full) => match crate::db::course::read(db, course).await? {
164- Some(_) => Err(AppError::Conflict("the course is full")),
165- None => Err(AppError::NotFound),
166- },
167168 Err(err) => Err(err),
168169 }
169170 }
170171
171172 /// A hand enroll landing on a row a class pumped takes the row *off* the
172173 /// class: `source` goes, so no later class sweep can unenroll a student an
173-/// operator placed on purpose. The mirror of the rule the sweep already
174-/// holds in the other direction — a manual unenroll wins, permanently — and
175-/// without it "hand-placed" was a state only a first enroll could reach.
174+/// operator placed on purpose. The mirror of the rule the sweep already holds
175+/// in the other direction — a manual unenroll wins, permanently — and without
176+/// it "hand-placed" was a state only a first enroll could reach.
176177 ///
177178 /// `NULL`, not absence: the column is a nullable uuid whose NULL *is* the
178-/// meaning a missing key used to carry (see the struct doc), and it is what
179-/// a hand enroll writes on the create path too.
179+/// meaning a missing key used to carry, and it is what a hand enroll writes on
180+/// the create path too.
180181 async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result<Enrollment, AppError> {
181182 if existing.get_source().is_none() {
182183 return Ok(existing);
@@ -184,35 +185,37 @@ async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result<Enrollm
184185 let disowned = sqlx::query_as!(
185186 Enrollment,
186187 r#"UPDATE enrollment SET source = NULL
187- WHERE course = $1 AND app_user = $2
188- RETURNING course AS "course: CourseId", app_user AS "user: UserId",
189- enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId""#,
190- existing.get_course().uuid(),
188+ WHERE class_course = $1 AND app_user = $2
189+ RETURNING class_course AS "class_course: ClassCourseId",
190+ app_user AS "user: UserId", enrolled_by AS "enrolled_by: UserId",
191+ source AS "source: ClassGroupId",
192+ created_at AS "created_at: Timestamp""#,
193+ existing.get_class_course().uuid(),
191194 existing.get_user().uuid(),
192195 )
193196 .fetch_optional(db)
194197 .await?;
195- // A row that is no longer there is not an internal error: an unenroll
196- // (or the class sweep a role change runs) landing between the read
197- // above and this write matches nothing, and the caller asked to be
198- // enrolled — which they were, by the row this call was handed. The
199- // disown is all that is lost, and it is lost to a delete that took the
200- // whole row with it.
198+ // A row that is no longer there is not an internal error: an unenroll (or
199+ // the class sweep a role change runs) landing between the read above and
200+ // this write matches nothing, and the caller asked to be enrolled — which
201+ // they were, by the row this call was handed. The disown is all that is
202+ // lost, and it is lost to a delete that took the whole row with it.
201203 Ok(disowned.unwrap_or(existing))
202204 }
203205
204-/// Some(_) iff `user` is enrolled in `course` — the grading gate.
206+/// Some(_) iff `user` is enrolled in that instance — the grading gate.
205207 pub async fn read_for_user(
206208 db: &Database,
207- course: &CourseId,
209+ class_course: &ClassCourseId,
208210 user: &UserId,
209211 ) -> Result<Option<Enrollment>, AppError> {
210212 let row = sqlx::query_as!(
211213 Enrollment,
212- r#"SELECT course AS "course: CourseId", app_user AS "user: UserId",
213- enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId"
214- FROM enrollment WHERE course = $1 AND app_user = $2"#,
215- course.uuid(),
214+ r#"SELECT class_course AS "class_course: ClassCourseId", app_user AS "user: UserId",
215+ enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId",
216+ created_at AS "created_at: Timestamp"
217+ FROM enrollment WHERE class_course = $1 AND app_user = $2"#,
218+ class_course.uuid(),
216219 user.uuid(),
217220 )
218221 .fetch_optional(db)
@@ -220,46 +223,105 @@ pub async fn read_for_user(
220223 Ok(row)
221224 }
222225
223-pub async fn list_for_course(
226+/// Whether `user` is one of `course`'s students right now — the point probe
227+/// behind an event addressed at a course.
228+///
229+/// The two membership tiers again: an enrollment in any of the course's
230+/// instances, or an individual club/etüt membership. Both are existence
231+/// probes on their own indexes; one entity's audience must not fold a whole
232+/// roster to answer yes.
233+pub async fn user_is_in_course(
224234 db: &Database,
225235 course: &CourseId,
236+ user: &UserId,
237+) -> Result<bool, AppError> {
238+ let row = sqlx::query!(
239+ r#"SELECT 1 AS "one" FROM (
240+ SELECT e.app_user FROM enrollment e
241+ WHERE e.app_user = $2
242+ AND e.class_course IN (SELECT id FROM class_course WHERE course = $1)
243+ UNION ALL
244+ SELECT m.app_user FROM course_membership m
245+ WHERE m.course = $1 AND m.app_user = $2
246+ ) people LIMIT 1"#,
247+ course.uuid(),
248+ user.uuid(),
249+ )
250+ .fetch_optional(db)
251+ .await?;
252+ Ok(row.is_some())
253+}
254+
255+/// Every student the catalog course reaches right now — the union of its
256+/// instances' rosters and its own individual memberships.
257+///
258+/// One course's "students" is two populations since D9 split the two tiers: a
259+/// ders reaches them through the instance a şube teaches (enrollment), and a
260+/// club/etüt through the school-scoped membership. A reader that wants the
261+/// course's audience — an event addressed at the course, a who-missed report —
262+/// means both, and deduping in SQL keeps a student who is in two of its
263+/// instances on the list once.
264+pub async fn list_users_for_course(
265+ db: &Database,
266+ course: &CourseId,
267+) -> Result<Vec<UserId>, AppError> {
268+ let rows = sqlx::query!(
269+ r#"SELECT DISTINCT app_user AS "user!: UserId" FROM (
270+ SELECT e.app_user FROM enrollment e
271+ JOIN class_course cc ON cc.id = e.class_course
272+ WHERE cc.course = $1
273+ UNION ALL
274+ SELECT m.app_user FROM course_membership m WHERE m.course = $1
275+ ) people ORDER BY app_user"#,
276+ course.uuid(),
277+ )
278+ .fetch_all(db)
279+ .await?;
280+ Ok(rows.into_iter().map(|row| row.user).collect())
281+}
282+
283+/// The instance's roster, newest first — the natural-PK columns sort the way
284+/// the old composite key did, with its instance prefix constant.
285+pub async fn list_for_class_course(
286+ db: &Database,
287+ class_course: &ClassCourseId,
226288 limit: Option<i64>,
227289 offset: i64,
228290 ) -> Result<(Vec<Enrollment>, i64), AppError> {
229- // The old composite key `{course}_{user}` sorted by user within a
230- // course — its course prefix was constant — so the natural-PK columns
231- // sort the same way.
232291 PagedList::new(
233- "enrollment WHERE course = $1",
234- "ORDER BY course DESC, app_user DESC",
292+ "enrollment WHERE class_course = $1",
293+ "ORDER BY class_course DESC, app_user DESC",
235294 )
236- .bind(course.uuid())
295+ .bind(class_course.uuid())
237296 .run::<Enrollment>(limit, offset, db)
238297 .await
239298 }
240299
241-/// Take the row and give its seat back in one statement, so nothing but a
242-/// lost transaction can drift the counter. `None` when the pair held no row.
300+/// Take the row and give the instance's roster counter back in one statement,
301+/// so nothing but a lost transaction can drift the counter. `None` when the
302+/// pair held no row.
243303 pub async fn remove(
244304 db: &Database,
245- course: &CourseId,
305+ class_course: &ClassCourseId,
246306 user: &UserId,
247307 ) -> Result<Option<Enrollment>, AppError> {
248308 let gone = sqlx::query_as!(
249309 Enrollment,
250310 r#"WITH gone AS (
251311 DELETE FROM enrollment
252- WHERE course = $1 AND app_user = $2
253- RETURNING course, app_user, enrolled_by, source),
312+ WHERE class_course = $1 AND app_user = $2
313+ RETURNING class_course, app_user, enrolled_by, source, created_at),
254314 seated AS (
255- UPDATE course
315+ UPDATE class_course
256316 SET enrollment_count = GREATEST(
257317 enrollment_count - (SELECT count(*) FROM gone), 0)
258318 WHERE id = $1
259319 RETURNING 1)
260- SELECT course AS "course: CourseId", app_user AS "user: UserId",
261- enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId" FROM gone"#,
262- course.uuid(),
320+ SELECT class_course AS "class_course: ClassCourseId",
321+ app_user AS "user: UserId", enrolled_by AS "enrolled_by: UserId",
322+ source AS "source: ClassGroupId", created_at AS "created_at: Timestamp"
323+ FROM gone"#,
324+ class_course.uuid(),
263325 user.uuid(),
264326 )
265327 .fetch_optional(db)
@@ -289,82 +351,72 @@ mod tests {
289351 user
290352 }
291353
354+ /// A real instance — class, course and the link between them — because
355+ /// the enrollment's own key is a foreign key now.
356+ async fn an_instance(db: &Database) -> (ClassCourseId, UserId) {
357+ use crate::db::class_member::tests::{a_class, a_course};
358+ use crate::domain::class_course::ClassCourseId;
292359
293- /// A pumped row that vanishes under the disown — a concurrent unenroll, or
294- /// the sweep a role change runs — must answer the row the caller was
295- /// handed, not a 500. The `UPDATE` matches nothing and used to fall through
296- /// to `AppError::Internal`, turning a race the old code answered 200 into a
297- /// server error on an ordinary `POST /courses/{id}/enrollments`.
298- #[tokio::test]
299- async fn a_vanished_row_is_not_an_internal_error() {
300- let (db, _leases) = crate::database::init_test_db().await;
301- let class = crate::domain::class_group::ClassGroupId::generate();
302- sqlx::query("INSERT INTO class_group (id, name, creator) VALUES ($1, '9a', $2)")
360+ let manager = crate::db::class_member::tests::fixture_user(db, "manager").await;
361+ let class = a_class("9-A", db).await;
362+ let course = a_course("algebra", db).await;
363+ crate::service::class_course::attach(db, &class, &course, &manager)
364+ .await
365+ .unwrap();
366+ let id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM class_course WHERE class = $1")
303367 .bind(class.uuid())
304- .bind({
305- let mgr = UserId::generate();
306- sqlx::query(
307- "INSERT INTO app_user (id, username, created_at, role) \
308- VALUES ($1, 'enroll-fixture', 0, 'manager')",
309- )
310- .bind(mgr.uuid())
311- .execute(&db)
312- .await
313- .unwrap();
314- mgr.uuid()
315- })
316- .execute(&db)
368+ .fetch_one(db)
317369 .await
318370 .unwrap();
319- // The course and student are foreign keys now: real rows, like the
320- // class. The enrollment itself is never written — the same store state
321- // a delete in the window leaves.
322- let course = crate::db::course::a_test_course(&db).await;
323- let student = a_person(&db, "student", "student").await;
324- let ghost = Enrollment {
325- course: course.clone(),
326- user: student,
327- enrolled_by: a_person(&db, "mgr", "manager").await,
328- source: Some(class),
329- };
330-
331- let answered = disown_if_pumped(&db, ghost).await.unwrap();
332- assert_eq!(answered.get_user(), &student);
333- assert_eq!(answered.get_course(), &course);
371+ (
372+ ClassCourseId::from_key(&id.to_string()),
373+ a_person(db, "student", "student").await,
374+ )
334375 }
335376
336- /// And the other half of "absence is the meaning": a hand-placed enrollment
337- /// must store *no* source key, or a class sweep would take back a row it
338- /// never wrote. Asserted on the stored row, not the returned one.
377+ /// Enrollment is idempotent and the roster counter moves once: a repeat
378+ /// enroll answers the row already there and leaves the counter as it
379+ /// stands.
339380 #[tokio::test]
340- async fn a_hand_placed_enrollment_stores_no_source_key() {
341- use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
342-
381+ async fn a_repeat_enroll_moves_the_counter_once() {
343382 let (db, _leases) = crate::database::init_test_db().await;
344- let teacher = a_person(&db, "teacher", "teacher").await;
345- let course = crate::db::course::create(
346- &db,
347- &teacher,
348- CourseTitle::try_new("algebra").unwrap(),
349- CourseDescription::try_new("").unwrap(),
350- CourseKind::course(),
351- None,
352- None,
353- )
354- .await
355- .unwrap();
356- enroll(&db, course.get_id(), &a_person(&db, "student", "student").await, &teacher)
357- .await
358- .unwrap();
383+ let (instance, student) = an_instance(&db).await;
384+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
359385
360- let source_rows: i64 =
361- sqlx::query_scalar("SELECT count(*) FROM enrollment WHERE source IS NOT NULL")
362- .fetch_one(&db)
386+ for _ in 0..2 {
387+ enroll(&db, &instance, &student, &manager, None)
363388 .await
364389 .unwrap();
390+ }
365391 assert_eq!(
366- source_rows, 0,
392+ crate::db::class_member::tests::counter("enrollment_count", instance.uuid(), &db).await,
393+ 1,
394+ "one row, one count"
395+ );
396+ }
397+
398+ /// A hand-placed enrollment carries no source key, and removing it gives
399+ /// the counter back in the same statement.
400+ #[tokio::test]
401+ async fn a_hand_placed_row_carries_no_source_and_gives_its_count_back() {
402+ let (db, _leases) = crate::database::init_test_db().await;
403+ let (instance, student) = an_instance(&db).await;
404+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
405+
406+ let row = enroll(&db, &instance, &student, &manager, None)
407+ .await
408+ .unwrap();
409+ assert!(
410+ row.get_source().is_none(),
367411 "a hand-placed row may carry no source key"
368412 );
413+
414+ let removed = remove(&db, &instance, &student).await.unwrap();
415+ assert!(removed.is_some(), "the row was there to take back");
416+ assert_eq!(
417+ crate::db::class_member::tests::counter("enrollment_count", instance.uuid(), &db).await,
418+ 0,
419+ "the counter goes back with the row"
420+ );
369421 }
370422 }
src/db/event.rsmodified+38 -35
@@ -26,20 +26,24 @@ pub async fn includes(db: &Database, event: &Event, user: &User) -> Result<bool,
2626 crate::domain::event::EventAudienceKind::Role => {
2727 Ok(Some(user.get_role()) == event.get_audience_role())
2828 }
29- crate::domain::event::EventAudienceKind::Course => {
30- match event.get_audience_course() {
31- Some(course) => Ok(crate::db::enrollment::read_for_user(db, course, user.get_id())
32- .await?
33- .is_some()),
34- None => Ok(false),
29+ crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() {
30+ Some(course) => {
31+ Ok(crate::db::enrollment::user_is_in_course(db, course, user.get_id()).await?)
3532 }
36- }
37- // The (class, user) pair is the membership row's own primary key, so
38- // the point check is one existence probe — no scan, no index needed.
33+ None => Ok(false),
34+ },
35+ // The (class, user) pair is the membership row's own key, so the point
36+ // check is one existence probe — and `left_at IS NULL` makes it the
37+ // *live* stint's, the row the partial unique index
38+ // `class_member_live_pair` carries: a student who left the şube is
39+ // history, not audience, and a stale probe would let them be marked
40+ // present at (and counted by) an event their section no longer
41+ // attends.
3942 crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() {
4043 Some(class) => {
4144 let row = sqlx::query!(
42- "SELECT EXISTS(SELECT 1 FROM class_member WHERE class = $1 AND app_user = $2)
45+ "SELECT EXISTS(SELECT 1 FROM class_member
46+ WHERE class = $1 AND app_user = $2 AND left_at IS NULL)
4347 AS \"present!\"",
4448 class.uuid(),
4549 user.get_id().uuid()
@@ -50,11 +54,11 @@ pub async fn includes(db: &Database, event: &Event, user: &User) -> Result<bool,
5054 }
5155 None => Ok(false),
5256 },
53- crate::domain::event::EventAudienceKind::Registration => {
54- Ok(crate::db::registration::read_for_user(db, event.get_id(), user.get_id())
57+ crate::domain::event::EventAudienceKind::Registration => Ok(
58+ crate::db::registration::read_for_user(db, event.get_id(), user.get_id())
5559 .await?
56- .is_some())
57- }
60+ .is_some(),
61+ ),
5862 }
5963 }
6064
@@ -63,31 +67,26 @@ pub async fn includes(db: &Database, event: &Event, user: &User) -> Result<bool,
6367 /// are kept; the caller degrades their display like any stale reference.
6468 pub async fn members(db: &Database, event: &Event) -> Result<Vec<UserId>, AppError> {
6569 match event.get_audience_kind() {
66- crate::domain::event::EventAudienceKind::School => Ok(crate::db::user::list_all(db, None, 0)
67- .await?
68- .0
69- .iter()
70- .map(|user| *user.get_id())
71- .collect()),
72- crate::domain::event::EventAudienceKind::Role => {
73- match event.get_audience_role() {
74- Some(role) => Ok(crate::db::user::list_by_role(db, role)
75- .await?
76- .iter()
77- .map(|user| *user.get_id())
78- .collect()),
79- None => Ok(Vec::new()),
80- }
81- }
82- crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() {
83- Some(course) => Ok(crate::db::enrollment::list_for_course(db, course, None, 0)
70+ crate::domain::event::EventAudienceKind::School => {
71+ Ok(crate::db::user::list_all(db, None, 0)
8472 .await?
8573 .0
8674 .iter()
87- .map(|enrollment| *enrollment.get_user())
75+ .map(|user| *user.get_id())
76+ .collect())
77+ }
78+ crate::domain::event::EventAudienceKind::Role => match event.get_audience_role() {
79+ Some(role) => Ok(crate::db::user::list_by_role(db, role)
80+ .await?
81+ .iter()
82+ .map(|user| *user.get_id())
8883 .collect()),
8984 None => Ok(Vec::new()),
9085 },
86+ crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() {
87+ Some(course) => Ok(crate::db::enrollment::list_users_for_course(db, course).await?),
88+ None => Ok(Vec::new()),
89+ },
9190 crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() {
9291 Some(class) => Ok(crate::db::class_member::list_for_class(db, class, None, 0)
9392 .await?
@@ -225,11 +224,15 @@ pub async fn update(
225224 )
226225 .set(
227226 "audience_course",
228- audience.as_ref().map(|a| Param::OptUuid(a.course.as_ref().map(|c| c.uuid()))),
227+ audience
228+ .as_ref()
229+ .map(|a| Param::OptUuid(a.course.as_ref().map(|c| c.uuid()))),
229230 )
230231 .set(
231232 "audience_class",
232- audience.as_ref().map(|a| Param::OptUuid(a.class.as_ref().map(|c| c.uuid()))),
233+ audience
234+ .as_ref()
235+ .map(|a| Param::OptUuid(a.class.as_ref().map(|c| c.uuid()))),
233236 )
234237 .set(
235238 "audience_capacity",
src/db/exam.rsmodified+325 -75
@@ -2,12 +2,16 @@
22 //! course that is gone, the compare-and-set every PATCH writes through, and
33 //! the cascading delete. The PATCH re-derive lives in [`crate::service::exam`].
44
5+use sqlx::PgConnection;
6+
57 use crate::database::{Database, foreign_key_violation, tx_with_retry};
8+use crate::domain::class_course::ClassCourseId;
69 use crate::domain::course::CourseId;
710 use crate::domain::exam::{
811 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
912 ExamSchedule, ExamTitle, redraft_error,
1013 };
14+use crate::domain::term::TermId;
1115 use crate::domain::timestamp::Timestamp;
1216 use crate::domain::user::UserId;
1317 use crate::error::AppError;
@@ -19,7 +23,8 @@ use crate::error::AppError;
1923 pub async fn create(
2024 db: &Database,
2125 creator: &UserId,
22- course: &CourseId,
26+ class_course: &ClassCourseId,
27+ term: &TermId,
2328 title: ExamTitle,
2429 description: ExamDescription,
2530 kind: ExamKind,
@@ -29,55 +34,163 @@ pub async fn create(
2934 allow_review: bool,
3035 draft: bool,
3136 ) -> Result<Exam, AppError> {
32- // A missing parent is refused by the real foreign keys: a course or a
33- // creator that is gone is `SQLSTATE 23503`, and this call site's
34- // parent-gone answer is the same `NotFound` the old existence-proof
35- // touch (`cap::touch_and_create`, deleted) answered with. The bump that
36- // touch made and unmade is gone with it — an exam was never counted
37- // anywhere.
38- let created = sqlx::query_as!(
37+ // A missing parent is refused by the real foreign keys: an instance, a
38+ // dönem or a creator that is gone is `SQLSTATE 23503`, and this call
39+ // site's parent-gone answer is the same `NotFound` the old
40+ // existence-proof touch answered with.
41+ //
42+ // The dönem is *claimed* in the same statement as the row (`exam_count`
43+ // +1, a conditional write on the term row), the shape the old course
44+ // create used against `term.course_count`: the count is what the term's
45+ // own delete guard reads, and claim-and-insert in one CTE means no crash
46+ // can leave one half without the other.
47+ //
48+ // The owner's `exam_audience` row is written in the same transaction,
49+ // *always*: the audience is what every listing reads through, so an exam
50+ // with no audience row would be invisible to its own instance. An ortak
51+ // sınav is extra audience rows on this one exam (D2), never a second
52+ // shape.
53+ let id = ExamId::generate();
54+ let creator = *creator;
55+ let class_course = class_course.clone();
56+ // `TermId` is `Copy`: one copy here, and the per-attempt closure below
57+ // re-yields values rather than clones.
58+ let term = *term;
59+ // The binds are hoisted to owned values so the closure below only has to
60+ // clone them per attempt: the write itself is a named future, for the
61+ // reason [`insert_in`] gives.
62+ let title_text = title.as_str().to_string();
63+ let description_text = description.as_str().to_string();
64+ let kind_text = kind.as_str().to_string();
65+ let mode_text = schedule.mode.as_ref().map(|mode| mode.as_str().to_string());
66+ let starts_at = schedule.starts_at.map(|at| at.as_millis());
67+ let ends_at = schedule.ends_at.map(|at| at.as_millis());
68+ let duration_ms = schedule.duration_ms.map(|duration| duration.as_millis());
69+ let max_attempts = max_attempts.as_i64();
70+ let created = tx_with_retry(db, false, async move |tx| {
71+ insert_in(
72+ tx,
73+ id.clone(),
74+ creator,
75+ class_course.clone(),
76+ term,
77+ title_text.clone(),
78+ description_text.clone(),
79+ kind_text.clone(),
80+ mode_text.clone(),
81+ starts_at,
82+ ends_at,
83+ duration_ms,
84+ max_attempts,
85+ allow_rejoin,
86+ allow_review,
87+ draft,
88+ )
89+ .await
90+ })
91+ .await?;
92+ Ok(created)
93+}
94+
95+/// The claim, the row and its audience row, on one connection — [`create`]'s
96+/// body as a *named* future.
97+///
98+/// Named, and taking owned values, because the anonymous `async move |tx|`
99+/// closure does not work here: with this many binds, rustc cannot prove the
100+/// closure's future is `Send` under [`tx_with_retry`]'s
101+/// `AsyncFnMut(&mut PgConnection)` higher-ranked bound, so every axum handler
102+/// that awaits [`create`] fails with "implementation of `Send` is not general
103+/// enough" pointing at its `routes!` entry. A named `async fn` has a concrete
104+/// future type rustc can check, exactly as
105+/// [`crate::db::answer_image::upsert_in`] does for the same reason.
106+///
107+/// Everything it decides is the closure's own: a claim that matched no dönem
108+/// row is [`crate::domain::term::gone_error`], any other foreign key is the
109+/// parent-gone `NotFound`, and the audience row is written in the same
110+/// transaction as the row it names.
111+#[expect(
112+ clippy::too_many_arguments,
113+ reason = "the create's own field list, spelled once for the named future"
114+)]
115+pub(crate) async fn insert_in(
116+ tx: &mut PgConnection,
117+ id: ExamId,
118+ creator: UserId,
119+ class_course: ClassCourseId,
120+ term: TermId,
121+ title: String,
122+ description: String,
123+ kind: String,
124+ mode: Option<String>,
125+ starts_at: Option<i64>,
126+ ends_at: Option<i64>,
127+ duration_ms: Option<i64>,
128+ max_attempts: i64,
129+ allow_rejoin: bool,
130+ allow_review: bool,
131+ draft: bool,
132+) -> Result<Exam, AppError> {
133+ let written = sqlx::query_as!(
39134 Exam,
40- r#"INSERT INTO exam (id, creator, course, title, description, kind, mode,
41- starts_at, ends_at, duration_ms, max_attempts,
42- allow_rejoin, allow_review, draft)
43- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
44- RETURNING id AS "id: ExamId", creator AS "creator: UserId",
45- course AS "course: CourseId", title AS "title: ExamTitle",
46- description AS "description: ExamDescription",
47- kind AS "kind: ExamKind", mode AS "mode: ExamMode",
48- starts_at AS "starts_at: Timestamp",
49- ends_at AS "ends_at: Timestamp",
50- duration_ms AS "duration_ms: ExamDuration",
51- max_attempts AS "max_attempts: ExamAttemptLimit",
52- allow_rejoin, allow_review, draft"#,
53- ExamId::generate().uuid(),
135+ r#"WITH room AS (
136+ UPDATE term SET exam_count = exam_count + 1
137+ WHERE id = $3
138+ RETURNING 1)
139+ INSERT INTO exam (id, creator, class_course, term, title, description, kind, mode,
140+ starts_at, ends_at, duration_ms, max_attempts,
141+ allow_rejoin, allow_review, draft)
142+ SELECT $1, $2, $4, $3, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15
143+ WHERE EXISTS (SELECT 1 FROM room)
144+ RETURNING id AS "id: ExamId", creator AS "creator: UserId",
145+ class_course AS "class_course: ClassCourseId",
146+ term AS "term: TermId", title AS "title: ExamTitle",
147+ description AS "description: ExamDescription",
148+ kind AS "kind: ExamKind", mode AS "mode: ExamMode",
149+ starts_at AS "starts_at: Timestamp",
150+ ends_at AS "ends_at: Timestamp",
151+ duration_ms AS "duration_ms: ExamDuration",
152+ max_attempts AS "max_attempts: ExamAttemptLimit",
153+ allow_rejoin, allow_review, draft"#,
154+ id.uuid(),
54155 creator.uuid(),
55- course.uuid(),
156+ term.uuid(),
157+ class_course.uuid(),
56158 title.as_str(),
57159 description.as_str(),
58160 kind.as_str(),
59- schedule.mode.as_ref().map(ExamMode::as_str),
60- schedule.starts_at.map(|at| at.as_millis()),
61- schedule.ends_at.map(|at| at.as_millis()),
62- schedule.duration_ms.map(|duration| duration.as_millis()),
63- max_attempts.as_i64(),
161+ mode.as_deref(),
162+ starts_at,
163+ ends_at,
164+ duration_ms,
165+ max_attempts,
64166 allow_rejoin,
65167 allow_review,
66168 draft,
67169 )
68- .fetch_one(db)
170+ .fetch_optional(&mut *tx)
69171 .await;
70- match created {
71- Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),
72- Err(err) => Err(err.into()),
73- Ok(exam) => Ok(exam),
74- }
172+ let exam = match written {
173+ Ok(Some(exam)) => exam,
174+ // The conditional claim matched no dönem row: the term is gone.
175+ Ok(None) => return Err(crate::domain::term::gone_error()),
176+ Err(err) if foreign_key_violation(&err) => return Err(AppError::NotFound),
177+ Err(err) => return Err(err.into()),
178+ };
179+ sqlx::query!(
180+ r#"INSERT INTO exam_audience (exam, class_course) VALUES ($1, $2)"#,
181+ exam.id.uuid(),
182+ exam.class_course.uuid(),
183+ )
184+ .execute(&mut *tx)
185+ .await?;
186+ Ok(exam)
75187 }
76188
77189 pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError> {
78190 Ok(sqlx::query_as!(
79191 Exam,
80- r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId",
192+ r#"SELECT id AS "id: ExamId", creator AS "creator: UserId",
193+ class_course AS "class_course: ClassCourseId", term AS "term: TermId",
81194 title AS "title: ExamTitle", description AS "description: ExamDescription",
82195 kind AS "kind: ExamKind", mode AS "mode: ExamMode",
83196 starts_at AS "starts_at: Timestamp",
@@ -97,7 +210,8 @@ pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError>
97210 pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
98211 Ok(sqlx::query_as!(
99212 Exam,
100- r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId",
213+ r#"SELECT id AS "id: ExamId", creator AS "creator: UserId",
214+ class_course AS "class_course: ClassCourseId", term AS "term: TermId",
101215 title AS "title: ExamTitle", description AS "description: ExamDescription",
102216 kind AS "kind: ExamKind", mode AS "mode: ExamMode",
103217 starts_at AS "starts_at: Timestamp",
@@ -111,26 +225,84 @@ pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
111225 .await?)
112226 }
113227
114-pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Exam>, AppError> {
228+/// The exams of one instance, newest first.
229+///
230+/// It reads through `exam_audience` rather than off `exam.class_course`: the
231+/// owner's row is always there (the create writes it), so the two agree for
232+/// every exam this instance owns, and the join is what lets an ortak sınav be
233+/// one exam addressed to several instances (D2) without a second read path.
234+pub async fn list_for_class_course(
235+ db: &Database,
236+ class_course: &ClassCourseId,
237+) -> Result<Vec<Exam>, AppError> {
115238 Ok(sqlx::query_as!(
116239 Exam,
117- r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId",
118- title AS "title: ExamTitle", description AS "description: ExamDescription",
119- kind AS "kind: ExamKind", mode AS "mode: ExamMode",
120- starts_at AS "starts_at: Timestamp",
121- ends_at AS "ends_at: Timestamp",
122- duration_ms AS "duration_ms: ExamDuration",
123- max_attempts AS "max_attempts: ExamAttemptLimit",
124- allow_rejoin, allow_review, draft
125- FROM exam WHERE course = $1 ORDER BY id DESC"#,
126- course.uuid(),
240+ r#"SELECT DISTINCT ON (e.id)
241+ e.id AS "id: ExamId", e.creator AS "creator: UserId",
242+ e.class_course AS "class_course: ClassCourseId",
243+ e.term AS "term: TermId", e.title AS "title: ExamTitle",
244+ e.description AS "description: ExamDescription",
245+ e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode",
246+ e.starts_at AS "starts_at: Timestamp",
247+ e.ends_at AS "ends_at: Timestamp",
248+ e.duration_ms AS "duration_ms: ExamDuration",
249+ e.max_attempts AS "max_attempts: ExamAttemptLimit",
250+ e.allow_rejoin, e.allow_review, e.draft
251+ FROM exam e
252+ JOIN exam_audience a ON a.exam = e.id
253+ WHERE a.class_course = $1
254+ ORDER BY e.id DESC"#,
255+ class_course.uuid(),
127256 )
128257 .fetch_all(db)
129258 .await?)
130259 }
131260
132-/// Every exam of every course in `courses` (one query) — the catalog as one
133-/// user sees it.
261+/// Every exam of every instance in `instances` (one query) — the karne and
262+/// marks reports' cross-instance read, and the list behind a caller's visible
263+/// courses.
264+///
265+/// `DISTINCT ON (e.id)` because an exam may be addressed to several instances
266+/// at once (an ortak sınav): the filters ask "is this exam visible here", not
267+/// "how many audiences does it have", so each exam is returned once with its
268+/// own owner instance.
269+pub async fn list_for_class_course_courses(
270+ db: &Database,
271+ instances: &[ClassCourseId],
272+) -> Result<Vec<Exam>, AppError> {
273+ if instances.is_empty() {
274+ return Ok(Vec::new());
275+ }
276+ let instances = instances
277+ .iter()
278+ .map(ClassCourseId::uuid)
279+ .collect::<Vec<_>>();
280+ Ok(sqlx::query_as!(
281+ Exam,
282+ r#"SELECT DISTINCT ON (e.id)
283+ e.id AS "id: ExamId", e.creator AS "creator: UserId",
284+ e.class_course AS "class_course: ClassCourseId",
285+ e.term AS "term: TermId", e.title AS "title: ExamTitle",
286+ e.description AS "description: ExamDescription",
287+ e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode",
288+ e.starts_at AS "starts_at: Timestamp",
289+ e.ends_at AS "ends_at: Timestamp",
290+ e.duration_ms AS "duration_ms: ExamDuration",
291+ e.max_attempts AS "max_attempts: ExamAttemptLimit",
292+ e.allow_rejoin, e.allow_review, e.draft
293+ FROM exam e
294+ JOIN exam_audience a ON a.exam = e.id
295+ WHERE a.class_course = ANY($1)
296+ ORDER BY e.id DESC"#,
297+ &instances,
298+ )
299+ .fetch_all(db)
300+ .await?)
301+}
302+
303+/// Every exam of every *catalog* course in `courses` (one query) — the
304+/// catalog as one user sees it, across the instances those courses are taught
305+/// in.
134306 pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec<Exam>, AppError> {
135307 if courses.is_empty() {
136308 return Ok(Vec::new());
@@ -138,15 +310,22 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec
138310 let courses = courses.iter().map(CourseId::uuid).collect::<Vec<_>>();
139311 Ok(sqlx::query_as!(
140312 Exam,
141- r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId",
142- title AS "title: ExamTitle", description AS "description: ExamDescription",
143- kind AS "kind: ExamKind", mode AS "mode: ExamMode",
144- starts_at AS "starts_at: Timestamp",
145- ends_at AS "ends_at: Timestamp",
146- duration_ms AS "duration_ms: ExamDuration",
147- max_attempts AS "max_attempts: ExamAttemptLimit",
148- allow_rejoin, allow_review, draft
149- FROM exam WHERE course = ANY($1) ORDER BY id DESC"#,
313+ r#"SELECT DISTINCT ON (e.id)
314+ e.id AS "id: ExamId", e.creator AS "creator: UserId",
315+ e.class_course AS "class_course: ClassCourseId",
316+ e.term AS "term: TermId", e.title AS "title: ExamTitle",
317+ e.description AS "description: ExamDescription",
318+ e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode",
319+ e.starts_at AS "starts_at: Timestamp",
320+ e.ends_at AS "ends_at: Timestamp",
321+ e.duration_ms AS "duration_ms: ExamDuration",
322+ e.max_attempts AS "max_attempts: ExamAttemptLimit",
323+ e.allow_rejoin, e.allow_review, e.draft
324+ FROM exam e
325+ JOIN exam_audience a ON a.exam = e.id
326+ JOIN class_course cc ON cc.id = a.class_course
327+ WHERE cc.course = ANY($1)
328+ ORDER BY e.id DESC"#,
150329 &courses,
151330 )
152331 .fetch_all(db)
@@ -272,7 +451,8 @@ pub async fn update_if_unchanged(
272451 AND draft = $23
273452 AND result_count = $24
274453 RETURNING id AS "id: ExamId", creator AS "creator: UserId",
275- course AS "course: CourseId", title AS "title: ExamTitle",
454+ class_course AS "class_course: ClassCourseId",
455+ term AS "term: TermId", title AS "title: ExamTitle",
276456 description AS "description: ExamDescription",
277457 kind AS "kind: ExamKind", mode AS "mode: ExamMode",
278458 starts_at AS "starts_at: Timestamp",
@@ -355,16 +535,19 @@ pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> {
355535 db,
356536 true,
357537 async move |conn| {
358- // The row lock every other exam-child writer contends on.
538+ // The row lock every other exam-child writer contends on. The
539+ // dönem rides out of the same read: the term's `exam_count` is
540+ // given back in this transaction, and the row that names it is
541+ // the one being deleted.
359542 let locked = sqlx::query!(
360- r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#,
543+ r#"SELECT term AS "term: TermId" FROM exam WHERE id = $1 FOR UPDATE"#,
361544 target.id.uuid(),
362545 )
363546 .fetch_optional(&mut *conn)
364547 .await?;
365- if locked.is_none() {
548+ let Some(locked) = locked else {
366549 return Err(AppError::NotFound);
367- }
550+ };
368551 // The blob names, collected *before* the rows go — inside the
369552 // lock, so an image row written after this snapshot cannot
370553 // strand its bytes on disk even though the row itself would be
@@ -441,11 +624,21 @@ pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> {
441624 )
442625 .execute(&mut *conn)
443626 .await?;
627+ // The sitting instances go with the exam: every read goes through
628+ // the audience join, so a row pointing at a deleted exam would be
629+ // both invisible and undeletable.
630+ sqlx::query!(
631+ r#"DELETE FROM exam_audience WHERE exam = $1"#,
632+ target.id.uuid(),
633+ )
634+ .execute(&mut *conn)
635+ .await?;
444636 let deleted = sqlx::query_as!(
445637 Exam,
446638 r#"DELETE FROM exam WHERE id = $1
447639 RETURNING id AS "id: ExamId", creator AS "creator: UserId",
448- course AS "course: CourseId", title AS "title: ExamTitle",
640+ class_course AS "class_course: ClassCourseId",
641+ term AS "term: TermId", title AS "title: ExamTitle",
449642 description AS "description: ExamDescription",
450643 kind AS "kind: ExamKind", mode AS "mode: ExamMode",
451644 starts_at AS "starts_at: Timestamp",
@@ -460,6 +653,15 @@ pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> {
460653 let Some(exam) = deleted else {
461654 return Err(AppError::NotFound);
462655 };
656+ // The dönem gets its exam reference back inside the same
657+ // transaction — the other half of the claim `create` makes.
658+ sqlx::query!(
659+ r#"UPDATE term SET exam_count = GREATEST(exam_count - 1, 0)
660+ WHERE id = $1"#,
661+ locked.term.uuid(),
662+ )
663+ .execute(&mut *conn)
664+ .await?;
463665 Ok(Deleted {
464666 exam,
465667 question_image_files: image_files,
@@ -494,13 +696,20 @@ pub(crate) async fn published_exam(db: &Database) -> Exam {
494696 .execute(db)
495697 .await
496698 .unwrap();
699+ // The exam hangs off the *instance* and carries the dönem it is graded in
700+ // (both foreign keys): both are real rows, minted per call —
701+ // [`crate::db::course::a_test_instance`] mints the class, the course and
702+ // the link, [`crate::db::term::a_test_term`] the year under the term.
703+ let (instance, _course) = crate::db::course::a_test_instance(db).await;
704+ let term = crate::db::term::a_test_term(db).await;
497705 create(
498706 db,
499707 &creator,
500- &crate::db::course::a_test_course(db).await,
708+ &instance,
709+ &term,
501710 ExamTitle::try_new("midterm").unwrap(),
502711 ExamDescription::try_new("").unwrap(),
503- ExamKind::try_new("midterm", &allowed).unwrap(),
712+ ExamKind::try_new("yazili", &allowed).unwrap(),
504713 ExamSchedule::try_new(None, None, None, None).unwrap(),
505714 ExamAttemptLimit::try_new(1).unwrap(),
506715 true,
@@ -524,7 +733,7 @@ mod tests {
524733
525734 /// An exam must not outlive the course it belongs to. It is the worst of
526735 /// the three children `Course::delete` used to leave behind: every exam
527- /// route funnels through `course_of`, which answers
736+ /// route funnels through `class_course_of`, which answers
528737 /// `Internal("exam references a missing course")`, so an orphan **500s
529738 /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while
530739 /// [`crate::db::exam::list_all`] still hands it to every manager+ on `GET /exams`.
@@ -552,13 +761,34 @@ mod tests {
552761 .execute(&db)
553762 .await
554763 .unwrap();
764+ // The exam's parents: a dönem, and an instance of *this*
765+ // course. Attaching it is the claim the racing delete
766+ // contends on, so the round where the course is gone refuses
767+ // here — which is the refusal this test wants to see answered.
768+ let term = crate::db::term::a_test_term(&db).await;
769+ let class = crate::db::class_group::create(
770+ &db,
771+ &creator,
772+ crate::domain::class_group::ClassName::try_new("9-A").unwrap(),
773+ None,
774+ None,
775+ None,
776+ )
777+ .await?
778+ .get_id()
779+ .clone();
780+ let instance = crate::service::class_course::attach(&db, &class, &course, &creator)
781+ .await?
782+ .get_id()
783+ .clone();
555784 create(
556785 &db,
557786 &creator,
558- &course,
787+ &instance,
788+ &term,
559789 ExamTitle::try_new("quiz").unwrap(),
560790 ExamDescription::try_new("").unwrap(),
561- ExamKind::try_new("quiz", &kinds).unwrap(),
791+ ExamKind::try_new("yazili", &kinds).unwrap(),
562792 ExamSchedule::try_new(None, None, None, None).unwrap(),
563793 ExamAttemptLimit::try_new(1).unwrap(),
564794 true,
@@ -569,7 +799,13 @@ mod tests {
569799 .map(|_| ())
570800 })
571801 }
572- crate::db::course::assert_no_child_outlives_a_course_delete("exam", make).await;
802+ crate::db::course::assert_no_child_outlives_a_course_delete(
803+ "exam",
804+ "SELECT count(*) FROM exam e JOIN class_course cc ON cc.id = e.class_course
805+ WHERE cc.course = $1",
806+ make,
807+ )
808+ .await;
573809 }
574810
575811 /// A real `app_user` row: students and graders are foreign keys now. The
@@ -705,10 +941,18 @@ mod tests {
705941 let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
706942 .get_exam_kinds()
707943 .to_vec();
708- for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] {
944+ // The K12 defaults, pinned by name: the acceptance set of a fresh
945+ // school is exactly these three, and the pre-remodel vocabulary
946+ // ("quiz", "midterm", …) is not in it.
947+ for kind in ["yazili", "sozlu", "uygulama"] {
709948 assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind);
710949 }
711- assert!(ExamKind::try_new("essay", &allowed).is_err());
950+ for stale in ["quiz", "midterm", "exam"] {
951+ assert!(
952+ ExamKind::try_new(stale, &allowed).is_err(),
953+ "{stale} is not in the school's list"
954+ );
955+ }
712956 assert!(ExamKind::try_new("", &allowed).is_err());
713957 // A school-defined list swaps the acceptance set wholesale.
714958 let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()];
@@ -1196,8 +1440,13 @@ mod tests {
11961440 })
11971441 };
11981442 let child = {
1199- let (db, exam_id, on, student, gate) =
1200- (db.clone(), id.clone(), question.get_id().clone(), student, gate);
1443+ let (db, exam_id, on, student, gate) = (
1444+ db.clone(),
1445+ id.clone(),
1446+ question.get_id().clone(),
1447+ student,
1448+ gate,
1449+ );
12011450 tokio::spawn(async move {
12021451 gate.wait().await;
12031452 let image = AnswerImage::new(
@@ -1264,7 +1513,8 @@ mod tests {
12641513 })
12651514 };
12661515 let child = {
1267- let (db, exam_id, on, gate) = (db.clone(), id.clone(), question.get_id().clone(), gate);
1516+ let (db, exam_id, on, gate) =
1517+ (db.clone(), id.clone(), question.get_id().clone(), gate);
12681518 tokio::spawn(async move {
12691519 gate.wait().await;
12701520 let image = QuestionImage::new(
src/db/exam_answer.rsmodified+12 -3
@@ -312,13 +312,18 @@ mod tests {
312312 let kinds = crate::domain::settings::Settings::defaults()
313313 .get_exam_kinds()
314314 .to_vec();
315+ // The instance and the dönem are foreign keys now: real rows the
316+ // fixture mints.
317+ let (instance, _course) = crate::db::course::a_test_instance(&db).await;
318+ let term = crate::db::term::a_test_term(&db).await;
315319 let exam = crate::db::exam::create(
316320 &db,
317321 &student(),
318- &crate::db::course::a_test_course(&db).await,
322+ &instance,
323+ &term,
319324 ExamTitle::try_new("quiz").unwrap(),
320325 ExamDescription::try_new("").unwrap(),
321- ExamKind::try_new("quiz", &kinds).unwrap(),
326+ ExamKind::try_new("yazili", &kinds).unwrap(),
322327 ExamSchedule::try_new(None, None, None, None).unwrap(),
323328 ExamAttemptLimit::try_new(1).unwrap(),
324329 true,
@@ -396,7 +401,11 @@ mod tests {
396401 assert_eq!(stored(&db).await, Some(7), "the touch moved a real count");
397402
398403 // The gate that makes the touch worth having: no exam, no answer.
399- let orphan = choice_question(&ExamId::from_key("019732e3-7b00-7000-8000-00000000e0a0"), 10, 0);
404+ let orphan = choice_question(
405+ &ExamId::from_key("019732e3-7b00-7000-8000-00000000e0a0"),
406+ 10,
407+ 0,
408+ );
400409 let pick = choice_id(&orphan, 0).as_str().to_string();
401410 let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await;
402411 assert!(
src/db/exam_attempt.rsmodified+7 -3
@@ -400,15 +400,19 @@ mod tests {
400400 .execute(db)
401401 .await
402402 .unwrap();
403- let course = crate::db::course::a_test_course(db).await;
403+ // The instance and the dönem are foreign keys now: real rows the
404+ // fixture mints.
405+ let (instance, _course) = crate::db::course::a_test_instance(db).await;
406+ let term = crate::db::term::a_test_term(db).await;
404407 let kinds = Settings::defaults().get_exam_kinds().to_vec();
405408 let exam = crate::db::exam::create(
406409 db,
407410 &creator,
408- &course,
411+ &instance,
412+ &term,
409413 ExamTitle::try_new("practice").unwrap(),
410414 ExamDescription::try_new("").unwrap(),
411- ExamKind::try_new("quiz", &kinds).unwrap(),
415+ ExamKind::try_new("yazili", &kinds).unwrap(),
412416 ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
413417 .unwrap(),
414418 ExamAttemptLimit::try_new(max_attempts).unwrap(),
src/db/exam_question.rsmodified+12 -9
@@ -458,13 +458,18 @@ mod tests {
458458 .await
459459 .unwrap();
460460 let kinds = Settings::defaults().get_exam_kinds().to_vec();
461+ // The instance and the dönem are foreign keys now: real rows the
462+ // fixture mints, per call.
463+ let (instance, _course) = crate::db::course::a_test_instance(db).await;
464+ let term = crate::db::term::a_test_term(db).await;
461465 crate::db::exam::create(
462466 db,
463467 &creator,
464- &crate::db::course::a_test_course(db).await,
468+ &instance,
469+ &term,
465470 ExamTitle::try_new("practice").unwrap(),
466471 ExamDescription::try_new("").unwrap(),
467- ExamKind::try_new("quiz", &kinds).unwrap(),
472+ ExamKind::try_new("yazili", &kinds).unwrap(),
468473 ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
469474 .unwrap(),
470475 ExamAttemptLimit::try_new(1).unwrap(),
@@ -514,13 +519,11 @@ mod tests {
514519
515520 /// The stored `exam_question_count` on one subject, absent = zero.
516521 async fn count_on(subject: &SubjectId, db: &Database) -> i64 {
517- sqlx::query_scalar::<_, i64>(
518- "SELECT exam_question_count FROM subject WHERE id = $1",
519- )
520- .bind(subject.uuid())
521- .fetch_one(db)
522- .await
523- .unwrap()
522+ sqlx::query_scalar::<_, i64>("SELECT exam_question_count FROM subject WHERE id = $1")
523+ .bind(subject.uuid())
524+ .fetch_one(db)
525+ .await
526+ .unwrap()
524527 }
525528
526529 async fn rows(sql: &str, db: &Database) -> usize {
src/db/exam_result.rsmodified+41 -23
@@ -6,11 +6,12 @@
66
77 use crate::constant::HIGH_MARK_MIN;
88 use crate::database::{Database, tx_with_retry};
9-use crate::domain::course::CourseId;
9+use crate::domain::class_course::ClassCourseId;
1010 use crate::domain::exam::ExamId;
1111 use crate::domain::exam_result::{
1212 ExamResult, Mark, draft_error, latest_per_pair, retired_kind_error,
1313 };
14+use crate::domain::term::TermId;
1415 use crate::domain::timestamp::Timestamp;
1516 use crate::domain::user::UserId;
1617 use crate::error::AppError;
@@ -202,11 +203,11 @@ pub async fn grade(
202203 .await
203204 }
204205
205-/// The user's graded results restricted to one course's exams — the raw
206-/// rows behind the per-course block of the marks report.
206+/// The user's graded results restricted to one instance's exams — the raw
207+/// rows behind the per-instance block of the marks report.
207208 pub async fn list_for_user_in_course(
208209 db: &Database,
209- course: &CourseId,
210+ class_course: &ClassCourseId,
210211 user: &UserId,
211212 ) -> Result<Vec<ExamResult>, AppError> {
212213 let rows = sqlx::query_as!(
@@ -214,10 +215,33 @@ pub async fn list_for_user_in_course(
214215 r#"SELECT r.exam AS "exam: ExamId", r.app_user AS "user: UserId", r.seq,
215216 r.mark AS "mark: Mark", r.graded_by AS "graded_by: UserId"
216217 FROM exam_result r JOIN exam e ON e.id = r.exam
217- WHERE r.app_user = $1 AND e.course = $2
218+ WHERE r.app_user = $1 AND e.class_course = $2
218219 ORDER BY r.exam DESC, r.seq DESC"#,
219220 user.uuid(),
220- course.uuid(),
221+ class_course.uuid(),
222+ )
223+ .fetch_all(db)
224+ .await?;
225+ Ok(latest_per_pair(rows))
226+}
227+
228+/// The user's graded results inside one dönem — every instance's exams whose
229+/// `term` is `term`, which is exactly the karne's input slice (D8: a karne is
230+/// per dönem, and an exam belongs to the dönem it was sat in).
231+pub async fn list_for_user_in_term(
232+ db: &Database,
233+ user: &UserId,
234+ term: &TermId,
235+) -> Result<Vec<ExamResult>, AppError> {
236+ let rows = sqlx::query_as!(
237+ ExamResult,
238+ r#"SELECT r.exam AS "exam: ExamId", r.app_user AS "user: UserId", r.seq,
239+ r.mark AS "mark: Mark", r.graded_by AS "graded_by: UserId"
240+ FROM exam_result r JOIN exam e ON e.id = r.exam
241+ WHERE r.app_user = $1 AND e.term = $2
242+ ORDER BY r.exam DESC, r.seq DESC"#,
243+ user.uuid(),
244+ term.uuid(),
221245 )
222246 .fetch_all(db)
223247 .await?;
@@ -505,8 +529,7 @@ mod tests {
505529 .unwrap()
506530 .map(|row| row.try_get::<i64, _>(0).unwrap())
507531 .unwrap_or(0);
508- let exam_count =
509- sqlx::query("SELECT COALESCE(sum(result_count), 0)::bigint FROM exam")
532+ let exam_count = sqlx::query("SELECT COALESCE(sum(result_count), 0)::bigint FROM exam")
510533 .fetch_one(db)
511534 .await
512535 .unwrap()
@@ -517,8 +540,9 @@ mod tests {
517540
518541 async fn an_exam(db: &Database, exam: &ExamId, kind: &str) {
519542 // The exam has to be real: a mark is refused on one that isn't. Its
520- // creator and course are real parents now, so the fixture grows them
521- // too (the teacher idempotently — [`the_two_people`] re-runs it).
543+ // creator is a real row (idempotently — [`the_two_people`] re-runs it)
544+ // and so are its parents: the instance it is taught in and the dönem it
545+ // is graded in, both through the shared fixtures.
522546 let teacher = UserId::from_key(TEACHER);
523547 sqlx::query(
524548 "INSERT INTO app_user (id, username, created_at, role) \
@@ -528,23 +552,17 @@ mod tests {
528552 .execute(db)
529553 .await
530554 .unwrap();
531- let course = CourseId::generate();
532- sqlx::query(
533- "INSERT INTO course (id, creator, title, description) \
534- VALUES ($1, $2, 'c', '')",
535- )
536- .bind(course.uuid())
537- .bind(teacher.uuid())
538- .execute(db)
539- .await
540- .unwrap();
555+ let (instance, _course) = crate::db::course::a_test_instance(db).await;
556+ let term = crate::db::term::a_test_term(db).await;
541557 sqlx::query(
542- "INSERT INTO exam (id, creator, course, title, description, kind) \
543- VALUES ($1, $2, $3, 't', '', $4)",
558+ "INSERT INTO exam (id, creator, class_course, term, title, description, kind, \
559+ max_attempts, allow_rejoin, allow_review, draft) \
560+ VALUES ($1, $2, $3, $4, 't', '', $5, 1, true, false, false)",
544561 )
545562 .bind(exam.uuid())
546563 .bind(teacher.uuid())
547- .bind(course.uuid())
564+ .bind(instance.uuid())
565+ .bind(term.uuid())
548566 .bind(kind)
549567 .execute(db)
550568 .await
src/db/fee_plan.rsmodified+1 -2
@@ -177,8 +177,7 @@ mod tests {
177177 #[tokio::test]
178178 async fn installments_survive_a_round_trip_through_the_schema() {
179179 let (db, _leases) = crate::database::init_test_db().await;
180- let manager =
181- crate::db::class_member::tests::fixture_user(&db, "fee-manager").await;
180+ let manager = crate::db::class_member::tests::fixture_user(&db, "fee-manager").await;
182181 let installments = vec![
183182 Installment::new(
184183 LedgerAmount::try_new(150_000).unwrap(),
src/db/field_update.rsmodified+8 -1
@@ -336,7 +336,14 @@ async fn run_with_refcount(
336336 // lifted from an async fn's *pattern parameter* poisons the higher-ranked
337337 // `AsyncFnMut`/`Send` evaluation of any closure that captures it
338338 // ("`Send` would have to be implemented for `&'0 str`, for any lifetime").
339- let Refcount { counter_table, counter_field, claim, release, refused, .. } = refcount;
339+ let Refcount {
340+ counter_table,
341+ counter_field,
342+ claim,
343+ release,
344+ refused,
345+ ..
346+ } = refcount;
340347 // Owned into the closure: a captured `&str` — even `'static` — drags the
341348 // async closure's arg lifetime off the higher-ranked one `tx_with_retry`
342349 // needs ("AsyncFnMut is not general enough" at the route registration).
src/db/homework.rsmodified+71 -101
@@ -5,7 +5,7 @@
55 //! delete.
66
77 use crate::database::{Database, tx_with_retry};
8-use crate::domain::course::CourseId;
8+use crate::domain::class_course::ClassCourseId;
99 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
1010 use crate::domain::subject::SubjectId;
1111 use crate::domain::timestamp::Timestamp;
@@ -36,7 +36,7 @@ const STALE_MOVE: &str = "the link this update moves changed since it was read;
3636 )]
3737 pub async fn create(
3838 db: &Database,
39- course: &CourseId,
39+ class_course: &ClassCourseId,
4040 subject: &SubjectId,
4141 title: HomeworkTitle,
4242 description: Option<HomeworkDescription>,
@@ -56,7 +56,7 @@ pub async fn create(
5656 // whole-course, not even for the instant of its create.
5757 let homework = Homework {
5858 id: HomeworkId::generate(),
59- course: course.clone(),
59+ class_course: class_course.clone(),
6060 subject: *subject,
6161 title,
6262 description,
@@ -82,13 +82,13 @@ pub async fn create(
8282 // comes back "not general enough" over the higher-ranked connection
8383 // lease — every tx_with_retry site captures only owned values.
8484 let subject = *subject;
85- let course = course.clone();
85+ let class_course = class_course.clone();
8686 tx_with_retry(db, false, async move |tx| {
8787 // And every bind is a precomputed value of this coroutine's own: a
8888 // bind expression reading a capture inside the macro keeps that
8989 // borrow alive across the await to the same `Send` end.
9090 let subject_uuid = subject.uuid();
91- let course_uuid = course.uuid();
91+ let class_course_uuid = class_course.uuid();
9292 let homework_uuid = homework.id.uuid();
9393 let title = homework.title.clone();
9494 let description = homework.description.clone();
@@ -103,10 +103,10 @@ pub async fn create(
103103 WHERE id = $1
104104 RETURNING 1
105105 )
106- INSERT INTO homework (id, course, subject, title, description, due_at, created_by, created_at)
106+ INSERT INTO homework (id, class_course, subject, title, description, due_at, created_by, created_at)
107107 SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)
108108 RETURNING id AS "id: HomeworkId",
109- course AS "course: CourseId",
109+ class_course AS "class_course: ClassCourseId",
110110 subject AS "subject: SubjectId",
111111 title AS "title: HomeworkTitle",
112112 description AS "description: HomeworkDescription",
@@ -116,7 +116,7 @@ pub async fn create(
116116 created_at AS "created_at: Timestamp""#,
117117 subject_uuid,
118118 homework_uuid,
119- course_uuid,
119+ class_course_uuid,
120120 title.as_str(),
121121 description.as_ref().map(HomeworkDescription::as_str),
122122 due_at_millis,
@@ -158,7 +158,7 @@ pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, Ap
158158 Ok(sqlx::query_as!(
159159 Homework,
160160 r#"SELECT id AS "id: HomeworkId",
161- course AS "course: CourseId",
161+ class_course AS "class_course: ClassCourseId",
162162 subject AS "subject: SubjectId",
163163 title AS "title: HomeworkTitle",
164164 description AS "description: HomeworkDescription",
@@ -174,13 +174,16 @@ pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, Ap
174174 .await?)
175175 }
176176
177-/// The course's homework, newest first (v7 ids sort by creation). The web
177+/// The instance's homework, newest first (v7 ids sort by creation). The web
178178 /// layer retains only the rows a given student `student_sees`.
179-pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Homework>, AppError> {
179+pub async fn list_for_class_course(
180+ db: &Database,
181+ class_course: &ClassCourseId,
182+) -> Result<Vec<Homework>, AppError> {
180183 Ok(sqlx::query_as!(
181184 Homework,
182185 r#"SELECT id AS "id: HomeworkId",
183- course AS "course: CourseId",
186+ class_course AS "class_course: ClassCourseId",
184187 subject AS "subject: SubjectId",
185188 title AS "title: HomeworkTitle",
186189 description AS "description: HomeworkDescription",
@@ -189,8 +192,8 @@ pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Hom
189192 WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
190193 created_by AS "created_by: UserId",
191194 created_at AS "created_at: Timestamp"
192- FROM homework WHERE course = $1 ORDER BY id DESC"#,
193- course.uuid()
195+ FROM homework WHERE class_course = $1 ORDER BY id DESC"#,
196+ class_course.uuid()
194197 )
195198 .fetch_all(db)
196199 .await?)
@@ -202,7 +205,7 @@ pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> {
202205 Ok(sqlx::query_as!(
203206 Homework,
204207 r#"SELECT id AS "id: HomeworkId",
205- course AS "course: CourseId",
208+ class_course AS "class_course: ClassCourseId",
206209 subject AS "subject: SubjectId",
207210 title AS "title: HomeworkTitle",
208211 description AS "description: HomeworkDescription",
@@ -217,22 +220,22 @@ pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> {
217220 .await?)
218221 }
219222
220-/// Every homework of every course in `courses`, newest first (one query) —
221-/// the cross-course list over a caller's visible courses. The web layer
222-/// still trims each course's rows to what the caller may see (a student to
223-/// the ones they `student_sees`).
224-pub async fn list_for_courses(
223+/// Every homework of every instance in `instances`, newest first (one
224+/// query) — the cross-instance list over a caller's visible courses. The web
225+/// layer still trims each instance's rows to what the caller may see (a
226+/// student to the ones they `student_sees`).
227+pub async fn list_for_class_courses(
225228 db: &Database,
226- courses: &[CourseId],
229+ instances: &[ClassCourseId],
227230 ) -> Result<Vec<Homework>, AppError> {
228- if courses.is_empty() {
231+ if instances.is_empty() {
229232 return Ok(Vec::new());
230233 }
231- let ids: Vec<uuid::Uuid> = courses.iter().map(CourseId::uuid).collect();
234+ let ids: Vec<uuid::Uuid> = instances.iter().map(ClassCourseId::uuid).collect();
232235 Ok(sqlx::query_as!(
233236 Homework,
234237 r#"SELECT id AS "id: HomeworkId",
235- course AS "course: CourseId",
238+ class_course AS "class_course: ClassCourseId",
236239 subject AS "subject: SubjectId",
237240 title AS "title: HomeworkTitle",
238241 description AS "description: HomeworkDescription",
@@ -241,27 +244,27 @@ pub async fn list_for_courses(
241244 WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
242245 created_by AS "created_by: UserId",
243246 created_at AS "created_at: Timestamp"
244- FROM homework WHERE course = ANY($1) ORDER BY id DESC"#,
247+ FROM homework WHERE class_course = ANY($1) ORDER BY id DESC"#,
245248 &ids
246249 )
247250 .fetch_all(db)
248251 .await?)
249252 }
250253
251-/// The homework of `course` that `user` is meant to see — whole-course ones
252-/// plus any subset that names them — newest first. Backs a student's (or an
253-/// observer's) per-course homework report; mirrors
254+/// The homework of one instance that `user` is meant to see — whole-class
255+/// ones plus any subset that names them — newest first. Backs a student's (or
256+/// an observer's) per-instance homework report; mirrors
254257 /// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees)
255258 /// in SQL so the filter runs in the database.
256259 pub async fn list_for_user_in_course(
257260 db: &Database,
258- course: &CourseId,
261+ class_course: &ClassCourseId,
259262 user: &UserId,
260263 ) -> Result<Vec<Homework>, AppError> {
261264 Ok(sqlx::query_as!(
262265 Homework,
263266 r#"SELECT id AS "id: HomeworkId",
264- course AS "course: CourseId",
267+ class_course AS "class_course: ClassCourseId",
265268 subject AS "subject: SubjectId",
266269 title AS "title: HomeworkTitle",
267270 description AS "description: HomeworkDescription",
@@ -271,13 +274,13 @@ pub async fn list_for_user_in_course(
271274 created_by AS "created_by: UserId",
272275 created_at AS "created_at: Timestamp"
273276 FROM homework
274- WHERE course = $1
277+ WHERE class_course = $1
275278 AND (NOT EXISTS (SELECT 1 FROM homework_assignment a
276279 WHERE a.homework = homework.id)
277280 OR EXISTS (SELECT 1 FROM homework_assignment a
278281 WHERE a.homework = homework.id AND a.student = $2))
279282 ORDER BY id DESC"#,
280- course.uuid(),
283+ class_course.uuid(),
281284 user.uuid()
282285 )
283286 .fetch_all(db)
@@ -318,7 +321,7 @@ pub async fn update(
318321 let current = sqlx::query_as!(
319322 Homework,
320323 r#"SELECT id AS "id: HomeworkId",
321- course AS "course: CourseId",
324+ class_course AS "class_course: ClassCourseId",
322325 subject AS "subject: SubjectId",
323326 title AS "title: HomeworkTitle",
324327 description AS "description: HomeworkDescription",
@@ -420,7 +423,7 @@ pub async fn update(
420423 due_at = $5
421424 WHERE id = $1
422425 RETURNING id AS "id: HomeworkId",
423- course AS "course: CourseId",
426+ class_course AS "class_course: ClassCourseId",
424427 subject AS "subject: SubjectId",
425428 title AS "title: HomeworkTitle",
426429 description AS "description: HomeworkDescription",
@@ -552,7 +555,7 @@ pub async fn delete(
552555 Homework,
553556 r#"DELETE FROM homework WHERE id = $1
554557 RETURNING id AS "id: HomeworkId",
555- course AS "course: CourseId",
558+ class_course AS "class_course: ClassCourseId",
556559 subject AS "subject: SubjectId",
557560 title AS "title: HomeworkTitle",
558561 description AS "description: HomeworkDescription",
@@ -596,8 +599,9 @@ mod tests {
596599 }
597600
598601 async fn homework_on(subject: &SubjectId, db: &Database) -> Homework {
599- // The course and the teacher are foreign keys now: a real course row
600- // (the subject's own fixture path mints one) and a real teacher.
602+ // The instance and the teacher are foreign keys now: a real instance
603+ // row (the class, the course and their link, minted by the fixture)
604+ // and a real teacher.
601605 let teacher = UserId::generate();
602606 sqlx::query(
603607 "INSERT INTO app_user (id, username, created_at, role) \
@@ -610,7 +614,7 @@ mod tests {
610614 .unwrap();
611615 create(
612616 db,
613- &crate::db::course::a_test_course(db).await,
617+ &crate::db::course::a_test_instance(db).await.0,
614618 subject,
615619 HomeworkTitle::try_new("essay").unwrap(),
616620 None,
@@ -655,7 +659,7 @@ mod tests {
655659
656660 let error = create(
657661 &db,
658- &CourseId::from_key("course"),
662+ &crate::domain::class_course::ClassCourseId::from_key("course"),
659663 &id,
660664 HomeworkTitle::try_new("essay").unwrap(),
661665 None,
@@ -688,17 +692,9 @@ mod tests {
688692 let homework = homework_on(from.get_id(), &db).await;
689693 assert_eq!(count_on(from.get_id(), &db).await, 1);
690694
691- let moved = update(
692- &db,
693- homework,
694- Some(*to.get_id()),
695- None,
696- None,
697- None,
698- None,
699- )
700- .await
701- .unwrap();
695+ let moved = update(&db, homework, Some(*to.get_id()), None, None, None, None)
696+ .await
697+ .unwrap();
702698 assert_eq!(moved.get_subject(), to.get_id());
703699 assert_eq!(
704700 count_on(from.get_id(), &db).await,
@@ -728,17 +724,9 @@ mod tests {
728724 crate::db::subject::delete(&db, dead).await.unwrap();
729725 let homework = homework_on(from.get_id(), &db).await;
730726
731- let error = update(
732- &db,
733- homework.clone(),
734- Some(gone),
735- None,
736- None,
737- None,
738- None,
739- )
740- .await
741- .expect_err("a subject that is gone must not be taggable");
727+ let error = update(&db, homework.clone(), Some(gone), None, None, None, None)
728+ .await
729+ .expect_err("a subject that is gone must not be taggable");
742730 assert!(error.to_string().contains("subject does not exist"));
743731 let stored = read(&db, homework.get_id()).await.unwrap().unwrap();
744732 assert_eq!(stored.get_subject(), from.get_id(), "the tag never moved");
@@ -770,17 +758,9 @@ mod tests {
770758 let other = a_subject("calculus", &db).await;
771759 let homework = homework_on(from.get_id(), &db).await;
772760 let stale = homework.clone();
773- update(
774- &db,
775- homework,
776- Some(*to.get_id()),
777- None,
778- None,
779- None,
780- None,
781- )
782- .await
783- .unwrap();
761+ update(&db, homework, Some(*to.get_id()), None, None, None, None)
762+ .await
763+ .unwrap();
784764
785765 let error = update(
786766 &db,
@@ -823,17 +803,9 @@ mod tests {
823803 let to = a_subject("geometry", &db).await;
824804 let homework = homework_on(from.get_id(), &db).await;
825805 let stale = homework.clone();
826- update(
827- &db,
828- homework,
829- Some(*to.get_id()),
830- None,
831- None,
832- None,
833- None,
834- )
835- .await
836- .unwrap();
806+ update(&db, homework, Some(*to.get_id()), None, None, None, None)
807+ .await
808+ .unwrap();
837809
838810 let error = update(
839811 &db,
@@ -866,17 +838,9 @@ mod tests {
866838 // A *genuine* no-op re-state — nobody moved underneath it — still lands,
867839 // and still moves no counter: the CAS passes trivially.
868840 let fresh = read(&db, stale.get_id()).await.unwrap().unwrap();
869- let same = update(
870- &db,
871- fresh,
872- Some(*to.get_id()),
873- None,
874- None,
875- None,
876- None,
877- )
878- .await
879- .expect("re-stating the tag actually held is not a race");
841+ let same = update(&db, fresh, Some(*to.get_id()), None, None, None, None)
842+ .await
843+ .expect("re-stating the tag actually held is not a race");
880844 assert_eq!(same.get_subject(), to.get_id());
881845 assert_eq!(
882846 count_on(from.get_id(), &db).await,
@@ -924,10 +888,10 @@ mod tests {
924888 .execute(&db)
925889 .await
926890 .unwrap();
927- let course = crate::db::course::a_test_course(&db).await;
891+ let instance = crate::db::course::a_test_instance(&db).await.0;
928892 let homework = create(
929893 &db,
930- &course,
894+ &instance,
931895 subject.get_id(),
932896 HomeworkTitle::try_new("essay").unwrap(),
933897 None,
@@ -939,27 +903,33 @@ mod tests {
939903 .unwrap();
940904 assert_eq!(homework.get_assigned(), Some(&[ali][..]));
941905 assert_eq!(
942- list_for_user_in_course(&db, &course, &ali).await.unwrap().len(),
906+ list_for_user_in_course(&db, &instance, &ali)
907+ .await
908+ .unwrap()
909+ .len(),
943910 1,
944911 "the named student sees the subset"
945912 );
946913 assert!(
947- list_for_user_in_course(&db, &course, &veli)
914+ list_for_user_in_course(&db, &instance, &veli)
948915 .await
949916 .unwrap()
950917 .is_empty(),
951918 "an unnamed student sees nothing"
952919 );
953- // Widening back to the whole course (`Some(None)`) empties the
920+ // Widening back to the whole instance (`Some(None)`) empties the
954921 // junction: everyone — including the never-named student — is covered.
955922 let widened = update(&db, homework, None, None, None, None, Some(None))
956923 .await
957924 .unwrap();
958925 assert_eq!(widened.get_assigned(), None);
959926 assert_eq!(
960- list_for_user_in_course(&db, &course, &veli).await.unwrap().len(),
927+ list_for_user_in_course(&db, &instance, &veli)
928+ .await
929+ .unwrap()
930+ .len(),
961931 1,
962- "whole-course reaches the never-named student"
932+ "whole-instance reaches the never-named student"
963933 );
964934 }
965935 }
src/db/homework_file.rsmodified+22 -15
@@ -199,7 +199,10 @@ pub async fn file_keys_for_course(
199199 r#"SELECT file FROM homework_file
200200 WHERE submission IN (
201201 SELECT id FROM homework_submission
202- WHERE homework IN (SELECT id FROM homework WHERE course = $1)
202+ WHERE homework IN (
203+ SELECT h.id FROM homework h
204+ JOIN class_course cc ON cc.id = h.class_course
205+ WHERE cc.course = $1)
203206 )"#,
204207 course.uuid()
205208 )
@@ -284,7 +287,7 @@ mod tests {
284287 use crate::domain::homework::HomeworkTitle;
285288 use crate::domain::subject::{SubjectDescription, SubjectName};
286289
287- let course = crate::db::course::a_test_course(db).await;
290+ let (instance, course) = crate::db::course::a_test_instance(db).await;
288291 let subject = crate::db::subject::create(
289292 db,
290293 &course,
@@ -295,7 +298,7 @@ mod tests {
295298 .unwrap();
296299 hw::create(
297300 db,
298- &course,
301+ &instance,
299302 subject.get_id(),
300303 HomeworkTitle::try_new("essay").unwrap(),
301304 None,
@@ -310,24 +313,28 @@ mod tests {
310313 /// A real `app_user` row: submitters are foreign keys too.
311314 async fn a_student(db: &Database) -> UserId {
312315 let user = UserId::generate();
313- sqlx::query("INSERT INTO app_user (id, username, created_at, role) VALUES ($1, $2, 0, 'student')")
314- .bind(user.uuid())
315- .bind(format!("s-{}", &user.key()[30..]))
316- .execute(db)
317- .await
318- .unwrap();
316+ sqlx::query(
317+ "INSERT INTO app_user (id, username, created_at, role) VALUES ($1, $2, 0, 'student')",
318+ )
319+ .bind(user.uuid())
320+ .bind(format!("s-{}", &user.key()[30..]))
321+ .execute(db)
322+ .await
323+ .unwrap();
319324 user
320325 }
321326
322327 /// A real `app_user` row: creators and submitters are foreign keys now.
323328 async fn a_teacher(db: &Database) -> UserId {
324329 let user = UserId::generate();
325- sqlx::query("INSERT INTO app_user (id, username, created_at, role) VALUES ($1, $2, 0, 'teacher')")
326- .bind(user.uuid())
327- .bind(format!("t-{}", &user.key()[30..]))
328- .execute(db)
329- .await
330- .unwrap();
330+ sqlx::query(
331+ "INSERT INTO app_user (id, username, created_at, role) VALUES ($1, $2, 0, 'teacher')",
332+ )
333+ .bind(user.uuid())
334+ .bind(format!("t-{}", &user.key()[30..]))
335+ .execute(db)
336+ .await
337+ .unwrap();
331338 user
332339 }
333340
src/db/homework_result.rsmodified+6 -6
@@ -6,7 +6,7 @@
66 //! [`crate::domain::homework_result`].
77
88 use crate::database::{Database, tx_with_retry};
9-use crate::domain::course::CourseId;
9+use crate::domain::class_course::ClassCourseId;
1010 use crate::domain::exam_result::Mark;
1111 use crate::domain::homework::HomeworkId;
1212 use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus};
@@ -180,7 +180,7 @@ pub async fn list_for_homework(
180180 /// `ExamResult::list_for_user_in_course`.
181181 pub async fn list_for_user_in_course(
182182 db: &Database,
183- course: &CourseId,
183+ class_course: &ClassCourseId,
184184 user: &UserId,
185185 ) -> Result<Vec<HomeworkResult>, AppError> {
186186 Ok(sqlx::query_as!(
@@ -194,10 +194,10 @@ pub async fn list_for_user_in_course(
194194 created_at AS "created_at: Timestamp"
195195 FROM homework_result
196196 WHERE app_user = $1
197- AND homework IN (SELECT id FROM homework WHERE course = $2)
197+ AND homework IN (SELECT id FROM homework WHERE class_course = $2)
198198 ORDER BY id DESC"#,
199199 user.uuid(),
200- course.uuid()
200+ class_course.uuid()
201201 )
202202 .fetch_all(db)
203203 .await?)
@@ -304,7 +304,7 @@ mod tests {
304304 use crate::domain::homework::HomeworkTitle;
305305 use crate::domain::subject::{SubjectDescription, SubjectName};
306306
307- let course = crate::db::course::a_test_course(db).await;
307+ let (instance, course) = crate::db::course::a_test_instance(db).await;
308308 let subject = crate::db::subject::create(
309309 db,
310310 &course,
@@ -315,7 +315,7 @@ mod tests {
315315 .unwrap();
316316 homework::create(
317317 db,
318- &course,
318+ &instance,
319319 subject.get_id(),
320320 HomeworkTitle::try_new("essay").unwrap(),
321321 None,
src/db/homework_submission.rsmodified+2 -2
@@ -403,7 +403,7 @@ mod tests {
403403 /// A real homework row (and the subject it must reference) due at `due_at` —
404404 /// `upsert` now reads the deadline off the entity, so the tests need one.
405405 async fn a_homework(due_at: Timestamp, db: &Database) -> Homework {
406- let course = crate::db::course::a_test_course(db).await;
406+ let (instance, course) = crate::db::course::a_test_instance(db).await;
407407 let subject = crate::db::subject::create(
408408 db,
409409 &course,
@@ -414,7 +414,7 @@ mod tests {
414414 .unwrap();
415415 homework_db::create(
416416 db,
417- &course,
417+ &instance,
418418 subject.get_id(),
419419 HomeworkTitle::try_new("essay").unwrap(),
420420 None,
src/db/karne.rsadded+66 -0
@@ -0,0 +1,66 @@
1+//! The `karne_snapshot` table: the frozen per-student, per-dönem report
2+//! written when a term is archived.
3+//!
4+//! Karne is a *computed* read (D8) — per-instance weighted average, graded
5+//! against the school's bands, then a `ders_saati`-weighted year average. The
6+//! snapshot exists for the moment that computation must stop moving: once a
7+//! dönem is archived, the report is a record of what the school issued, and a
8+//! later correction to a mark must not silently rewrite a karne a family
9+//! already holds. [`crate::service::karne::freeze`] writes the rows;
10+//! [`crate::service::karne::build`] serves the snapshot back for an archived
11+//! term and computes live for an open one.
12+
13+use sqlx::types::Json;
14+
15+use crate::database::Database;
16+use crate::domain::term::TermId;
17+use crate::domain::timestamp::Timestamp;
18+use crate::domain::user::UserId;
19+use crate::error::AppError;
20+
21+/// Write (or refresh) `user`'s frozen report for `term`.
22+///
23+/// An upsert rather than an insert: freezing is idempotent and converges —
24+/// archiving an already-archived term writes nothing
25+/// ([`crate::db::term::archive`]), and a re-run recomputes the same payload
26+/// from the same rows, so overwriting it is a no-op in substance and one
27+/// statement instead of an existence dance.
28+pub async fn snapshot(
29+ db: &Database,
30+ term: &TermId,
31+ user: &UserId,
32+ payload: &serde_json::Value,
33+) -> Result<(), AppError> {
34+ let payload = Json(payload.clone());
35+ sqlx::query!(
36+ r#"INSERT INTO karne_snapshot (term, app_user, payload, created_at)
37+ VALUES ($1, $2, $3, $4)
38+ ON CONFLICT (term, app_user) DO UPDATE
39+ SET payload = EXCLUDED.payload, created_at = EXCLUDED.created_at"#,
40+ term.uuid(),
41+ user.uuid(),
42+ payload as _,
43+ Timestamp::now().as_millis(),
44+ )
45+ .execute(db)
46+ .await?;
47+ Ok(())
48+}
49+
50+/// `user`'s frozen report for `term`, or `None` when that dönem was never
51+/// frozen (or they had no roster row to freeze).
52+pub async fn read_snapshot(
53+ db: &Database,
54+ term: &TermId,
55+ user: &UserId,
56+) -> Result<Option<serde_json::Value>, AppError> {
57+ let row = sqlx::query!(
58+ r#"SELECT payload AS "payload: Json<serde_json::Value>"
59+ FROM karne_snapshot WHERE term = $1 AND app_user = $2"#,
60+ term.uuid(),
61+ user.uuid(),
62+ )
63+ .fetch_optional(db)
64+ .await?;
65+ Ok(row.map(|row| row.payload.0))
66+}
src/db/meal_booking.rsmodified+4 -5
@@ -588,11 +588,10 @@ mod tests {
588588 "the attempt this call read is gone, so it releases nothing"
589589 );
590590 // Stored state, not the returned value: the mem engine forges wins.
591- let stored =
592- read(&db, &MealBookingId::composite(&menu, live.get_student()))
593- .await
594- .unwrap()
595- .unwrap();
591+ let stored = read(&db, &MealBookingId::composite(&menu, live.get_student()))
592+ .await
593+ .unwrap()
594+ .unwrap();
596595 assert_eq!(stored.get_status(), MealBookingStatus::Booked);
597596 assert_eq!(stored.get_attempt(), live.get_attempt());
598597 assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back");
src/db/meal_ledger.rsmodified+1 -1
@@ -8,8 +8,8 @@ use crate::db::page::PagedList;
88 use crate::domain::meal_ledger::{
99 LedgerAmount, LedgerMethod, LedgerNote, MealLedger, MealLedgerId, MealLedgerKind,
1010 };
11-use crate::domain::timestamp::Timestamp;
1211 use crate::domain::menu::MenuId;
12+use crate::domain::timestamp::Timestamp;
1313 use crate::domain::user::UserId;
1414 use crate::error::AppError;
1515
src/db/message.rsmodified+4 -8
@@ -66,16 +66,12 @@ pub async fn list_folder(
6666 let home_arm = folder == Folder::Inbox;
6767 let mut from = match folder {
6868 Folder::Sent => "message WHERE sender = $1 AND sender_folder = 'sent'".to_string(),
69- Folder::Archive => {
70- "message WHERE (recipient = $1 AND recipient_folder = 'archive') \
69+ Folder::Archive => "message WHERE (recipient = $1 AND recipient_folder = 'archive') \
7170 OR (sender = $1 AND sender_folder = 'archive')"
72- .to_string()
73- }
74- Folder::Trash => {
75- "message WHERE (recipient = $1 AND recipient_folder = 'trash') \
71+ .to_string(),
72+ Folder::Trash => "message WHERE (recipient = $1 AND recipient_folder = 'trash') \
7673 OR (sender = $1 AND sender_folder = 'trash')"
77- .to_string()
78- }
74+ .to_string(),
7975 _ => "message WHERE recipient = $1 AND recipient_folder = $2".to_string(),
8076 };
8177 // The `read` filter binds after whichever placeholders the folder shape
src/db/mod.rsmodified+5 -1
@@ -1,4 +1,5 @@
11 //! The only layer that executes queries.
2+pub mod academic_year;
23 pub mod answer_image;
34 pub mod appointment;
45 pub mod appointment_slot;
@@ -14,10 +15,12 @@ pub mod chatbot_message;
1415 pub mod chatbot_thread;
1516 pub mod class_blueprint;
1617 pub mod class_course;
18+pub mod class_course_teacher;
1719 pub mod class_group;
1820 pub mod class_member;
1921 pub mod class_pump;
2022 pub mod course;
23+pub mod course_membership;
2124 pub mod course_note;
2225 pub mod course_note_file;
2326 pub mod course_session;
@@ -36,6 +39,7 @@ pub mod homework;
3639 pub mod homework_file;
3740 pub mod homework_result;
3841 pub mod homework_submission;
42+pub mod karne;
3943 pub mod meal_attendance;
4044 pub mod meal_booking;
4145 pub mod meal_ledger;
@@ -46,8 +50,8 @@ pub mod note;
4650 pub mod note_file;
4751 pub mod page;
4852 pub mod parent_link;
49-pub mod person;
5053 pub mod payment_ledger;
54+pub mod person;
5155 pub mod pomodoro;
5256 pub mod pool_question;
5357 pub mod pool_question_image;
src/db/payment_ledger.rsmodified+0 -1
@@ -302,4 +302,3 @@ pub(crate) async fn applied_to(
302302 let total = PaymentLedger::fold_balance(folds.into_iter().map(|fold| (fold.kind, fold.total)));
303303 Ok(total * -target_kind.sign())
304304 }
305-
src/db/question_image.rsmodified+5 -2
@@ -167,14 +167,17 @@ pub async fn delete_choices_not_in(
167167 }
168168
169169 /// The blob names behind every image of every exam of `course` — collected
170-/// *before* the course-delete cascade wipes the rows.
170+/// *before* the course-delete cascade wipes the rows. The exams belong to the
171+/// course's instances since D1, so the join goes through `class_course`.
171172 pub async fn file_keys_for_course(
172173 db: &Database,
173174 course: &CourseId,
174175 ) -> Result<Vec<String>, AppError> {
175176 let rows = sqlx::query!(
176177 r#"SELECT qi.file FROM question_image qi
177- JOIN exam e ON e.id = qi.exam WHERE e.course = $1"#,
178+ JOIN exam e ON e.id = qi.exam
179+ JOIN class_course cc ON cc.id = e.class_course
180+ WHERE cc.course = $1"#,
178181 course.uuid(),
179182 )
180183 .fetch_all(db)
src/db/rag_output.rsmodified+0 -2
@@ -312,8 +312,6 @@ mod tests {
312312 CourseTitle::try_new("c").unwrap(),
313313 CourseDescription::try_new("").unwrap(),
314314 CourseKind::try_new("course").unwrap(),
315- None,
316- None,
317315 )
318316 .await
319317 .unwrap();
src/db/session_attendance.rsmodified+14 -10
@@ -7,7 +7,7 @@
77 use crate::database::{Database, tx_with_retry};
88 use crate::db::page::PagedList;
99 use crate::domain::attendance::AttendanceStatus;
10-use crate::domain::course::CourseId;
10+use crate::domain::class_course::ClassCourseId;
1111 use crate::domain::course_session::{CourseSession, CourseSessionId};
1212 use crate::domain::session_attendance::SessionAttendance;
1313 use crate::domain::timestamp::Timestamp;
@@ -20,7 +20,7 @@ use crate::error::AppError;
2020 ///
2121 /// The "session still exists" gate is a row lock: the transaction takes the
2222 /// session row `FOR NO KEY UPDATE` before anything else, so a session (or
23-/// course) delete cascading beneath this mark simply waits, and a delete
23+/// instance) delete cascading beneath this mark simply waits, and a delete
2424 /// that got there first leaves this gate matching nothing — `404`, the
2525 /// mirror of [`crate::db::course_session::delete`]. The caller's
2626 /// pre-flight read sits several round trips in front of this write, which
@@ -130,17 +130,18 @@ pub async fn mark(
130130 .unwrap_or(false);
131131 let row = sqlx::query_as!(
132132 SessionAttendance,
133- r#"INSERT INTO session_attendance (session, app_user, course, status, marked_by, marked_at)
133+ r#"INSERT INTO session_attendance (session, app_user, class_course, status, marked_by, marked_at)
134134 VALUES ($1, $2, $3, $4, $5, $6)
135135 ON CONFLICT (session, app_user) DO UPDATE
136136 SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by,
137137 marked_at = EXCLUDED.marked_at
138138 RETURNING session AS "session: CourseSessionId", app_user AS "user: UserId",
139- course AS "course: CourseId", status AS "status: AttendanceStatus",
139+ class_course AS "class_course: ClassCourseId",
140+ status AS "status: AttendanceStatus",
140141 marked_by AS "marked_by: UserId""#,
141142 session.id.uuid(),
142143 user.uuid(),
143- session.course.uuid(),
144+ session.class_course.uuid(),
144145 status.as_str(),
145146 marked_by.uuid(),
146147 now.as_millis(),
@@ -213,7 +214,8 @@ pub async fn list_for_user(
213214 let rows = sqlx::query_as!(
214215 SessionAttendance,
215216 r#"SELECT session AS "session: CourseSessionId", app_user AS "user: UserId",
216- course AS "course: CourseId", status AS "status: AttendanceStatus",
217+ class_course AS "class_course: ClassCourseId",
218+ status AS "status: AttendanceStatus",
217219 marked_by AS "marked_by: UserId"
218220 FROM session_attendance WHERE app_user = $1
219221 ORDER BY session DESC, app_user DESC"#,
@@ -251,7 +253,8 @@ pub async fn remove(
251253 let Some(gone) = sqlx::query_as!(
252254 SessionAttendance,
253255 r#"SELECT session AS "session: CourseSessionId", app_user AS "user: UserId",
254- course AS "course: CourseId", status AS "status: AttendanceStatus",
256+ class_course AS "class_course: ClassCourseId",
257+ status AS "status: AttendanceStatus",
255258 marked_by AS "marked_by: UserId"
256259 FROM session_attendance
257260 WHERE session = $1 AND app_user = $2
@@ -336,7 +339,7 @@ mod tests {
336339 async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession {
337340 crate::db::course_session::create(
338341 db,
339- &crate::db::course::a_test_course(db).await,
342+ &crate::db::course::a_test_instance(db).await.0,
340343 teacher,
341344 SessionTopic::try_new("limits").unwrap(),
342345 Timestamp::from_millis(starts_at),
@@ -656,8 +659,9 @@ mod tests {
656659
657660 let teacher = a_teacher("t", &db).await;
658661 let (mut swept, mut orphans) = (0, 0);
659- for (round, already_counted) in
660- [false, true, false, true, false, true, false, true].into_iter().enumerate()
662+ for (round, already_counted) in [false, true, false, true, false, true, false, true]
663+ .into_iter()
664+ .enumerate()
661665 {
662666 let session = if already_counted {
663667 // Counted by somebody else's mark, so this one credits nothing.
src/db/settings.rsmodified+77 -9
@@ -22,6 +22,18 @@ fn sorted(values: &[String]) -> Vec<String> {
2222 sorted
2323 }
2424
25+/// One optional JSONB list as the value a statement binds: the list when the
26+/// setting carries one, SQL `NULL` when it does not.
27+fn encode_optional(
28+ values: &Option<Json<Vec<String>>>,
29+) -> Result<Option<serde_json::Value>, AppError> {
30+ values
31+ .as_ref()
32+ .map(|list| serde_json::to_value(&list.0))
33+ .transpose()
34+ .map_err(|e| AppError::Internal(format!("settings encode: {e}")))
35+}
36+
2537 /// The one read: row columns plus both vocabularies re-assembled from their
2638 /// child tables. An absent dietary set reads as `None` — the same shape an
2739 /// unset column used to carry.
@@ -44,7 +56,12 @@ where
4456 (SELECT array_agg(t.tag ORDER BY t.tag)
4557 FROM settings_dietary_tag t
4658 WHERE t.settings = s.id) AS dietary_tags,
47- s.meal_cancel_cutoff_minutes
59+ s.meal_cancel_cutoff_minutes,
60+ s.branches AS "branches: Json<Vec<String>>",
61+ s.excuse_kinds AS "excuse_kinds: Json<Vec<String>>",
62+ s.max_excused_absent_days,
63+ s.max_unexcused_absent_days,
64+ s.timezone
4865 FROM settings s WHERE s.id = 'school'"#
4966 )
5067 .fetch_optional(db)
@@ -113,6 +130,12 @@ pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppErro
113130 .map(|slots| serde_json::to_value(&slots.0))
114131 .transpose()
115132 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
133+ // The two JSONB vocabularies ride the row like `meal_slots`: an unset
134+ // list stays NULL rather than being coerced to `[]`, because a whole-row
135+ // save that wrote `[]` for a field it never carried would erase the
136+ // distinction an unset column carries.
137+ let branches = encode_optional(&settings.branches)?;
138+ let excuse_kinds = encode_optional(&settings.excuse_kinds)?;
116139 let attendance = sorted(&settings.attendance_statuses);
117140 let dietary = settings.dietary_tags.clone();
118141 tx_with_retry(db, true, async move |tx| {
@@ -120,8 +143,10 @@ pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppErro
120143 r#"INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,
121144 chatbot_history_turns, max_chatbot_message_len,
122145 max_chatbot_threads, meal_slots,
123- meal_cancel_cutoff_minutes)
124- VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8)
146+ meal_cancel_cutoff_minutes, branches, excuse_kinds,
147+ max_excused_absent_days, max_unexcused_absent_days,
148+ timezone)
149+ VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
125150 ON CONFLICT (id) DO UPDATE SET
126151 exam_kinds = EXCLUDED.exam_kinds,
127152 grade_bands = EXCLUDED.grade_bands,
@@ -130,7 +155,12 @@ pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppErro
130155 max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,
131156 max_chatbot_threads = EXCLUDED.max_chatbot_threads,
132157 meal_slots = EXCLUDED.meal_slots,
133- meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes"#,
158+ meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes,
159+ branches = EXCLUDED.branches,
160+ excuse_kinds = EXCLUDED.excuse_kinds,
161+ max_excused_absent_days = EXCLUDED.max_excused_absent_days,
162+ max_unexcused_absent_days = EXCLUDED.max_unexcused_absent_days,
163+ timezone = EXCLUDED.timezone"#,
134164 exam_kinds,
135165 grade_bands,
136166 settings.max_file_bytes,
@@ -139,6 +169,11 @@ pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppErro
139169 settings.max_chatbot_threads,
140170 meal_slots,
141171 settings.meal_cancel_cutoff_minutes,
172+ branches,
173+ excuse_kinds,
174+ settings.max_excused_absent_days,
175+ settings.max_unexcused_absent_days,
176+ settings.timezone,
142177 )
143178 .execute(&mut *tx)
144179 .await?;
@@ -205,6 +240,10 @@ where
205240 .map(|slots| serde_json::to_value(&slots.0))
206241 .transpose()
207242 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
243+ let branches = encode_optional(&settings.branches)?;
244+ let excuse_kinds = encode_optional(&settings.excuse_kinds)?;
245+ let expected_branches = encode_optional(&expected.branches)?;
246+ let expected_excuse_kinds = encode_optional(&expected.excuse_kinds)?;
208247 let attendance = sorted(&settings.attendance_statuses);
209248 let expected_attendance = sorted(&expected.attendance_statuses);
210249 // An empty `Some` must compare equal to the stored NULL an empty set
@@ -220,8 +259,10 @@ where
220259 INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,
221260 chatbot_history_turns, max_chatbot_message_len,
222261 max_chatbot_threads, meal_slots,
223- meal_cancel_cutoff_minutes)
224- VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10)
262+ meal_cancel_cutoff_minutes, branches, excuse_kinds,
263+ max_excused_absent_days, max_unexcused_absent_days,
264+ timezone)
265+ VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10, $21, $22, $23, $24, $25)
225266 ON CONFLICT (id) DO UPDATE SET
226267 exam_kinds = $1,
227268 grade_bands = $3,
@@ -230,7 +271,12 @@ where
230271 max_chatbot_message_len = $6,
231272 max_chatbot_threads = $7,
232273 meal_slots = $8,
233- meal_cancel_cutoff_minutes = $10
274+ meal_cancel_cutoff_minutes = $10,
275+ branches = $21,
276+ excuse_kinds = $22,
277+ max_excused_absent_days = $23,
278+ max_unexcused_absent_days = $24,
279+ timezone = $25
234280 WHERE settings.exam_kinds IS NOT DISTINCT FROM $13
235281 AND settings.grade_bands IS NOT DISTINCT FROM $14
236282 AND settings.max_file_bytes IS NOT DISTINCT FROM $15
@@ -239,6 +285,11 @@ where
239285 AND settings.max_chatbot_threads IS NOT DISTINCT FROM $18
240286 AND settings.meal_slots IS NOT DISTINCT FROM $19
241287 AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20
288+ AND settings.branches IS NOT DISTINCT FROM $26
289+ AND settings.excuse_kinds IS NOT DISTINCT FROM $27
290+ AND settings.max_excused_absent_days IS NOT DISTINCT FROM $28
291+ AND settings.max_unexcused_absent_days IS NOT DISTINCT FROM $29
292+ AND settings.timezone IS NOT DISTINCT FROM $30
242293 AND COALESCE((SELECT array_agg(s.status ORDER BY s.status)
243294 FROM settings_attendance_status s
244295 WHERE s.settings = settings.id), '{}')
@@ -249,7 +300,9 @@ where
249300 IS NOT DISTINCT FROM $12::text[]
250301 RETURNING exam_kinds, grade_bands, max_file_bytes,
251302 chatbot_history_turns, max_chatbot_message_len,
252- max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes),
303+ max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes,
304+ branches, excuse_kinds, max_excused_absent_days,
305+ max_unexcused_absent_days, timezone),
253306 status_del AS (
254307 DELETE FROM settings_attendance_status
255308 WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)
@@ -280,7 +333,12 @@ where
280333 r.max_chatbot_threads,
281334 r.meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",
282335 (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags,
283- r.meal_cancel_cutoff_minutes
336+ r.meal_cancel_cutoff_minutes,
337+ r.branches AS "branches: Json<Vec<String>>",
338+ r.excuse_kinds AS "excuse_kinds: Json<Vec<String>>",
339+ r.max_excused_absent_days,
340+ r.max_unexcused_absent_days,
341+ r.timezone
284342 FROM new_row r"#,
285343 exam_kinds,
286344 &attendance,
@@ -302,6 +360,16 @@ where
302360 expected.max_chatbot_threads,
303361 expected_meal_slots,
304362 expected.meal_cancel_cutoff_minutes,
363+ branches,
364+ excuse_kinds,
365+ settings.max_excused_absent_days,
366+ settings.max_unexcused_absent_days,
367+ settings.timezone,
368+ expected_branches,
369+ expected_excuse_kinds,
370+ expected.max_excused_absent_days,
371+ expected.max_unexcused_absent_days,
372+ expected.timezone,
305373 )
306374 .fetch_optional(db)
307375 .await?;
src/db/subject.rsmodified+6 -1
@@ -218,7 +218,12 @@ mod tests {
218218 .map(|_| ())
219219 })
220220 }
221- crate::db::course::assert_no_child_outlives_a_course_delete("subject", make).await;
221+ crate::db::course::assert_no_child_outlives_a_course_delete(
222+ "subject",
223+ "SELECT count(*) FROM subject WHERE course = $1",
224+ make,
225+ )
226+ .await;
222227 }
223228
224229 /// GUARD, not a retry measurement — read the last paragraph before
src/db/term.rsmodified+133 -48
@@ -8,44 +8,64 @@ use crate::constant::TERM_TABLE;
88 use crate::database::Database;
99 use crate::db::field_update::FieldUpdate;
1010 use crate::db::page::PagedList;
11+use crate::domain::academic_year::AcademicYearId;
1112 use crate::domain::term::{Term, TermId, TermName};
1213 use crate::domain::timestamp::{Timestamp, range_error};
13-use crate::error::AppError;
14+use crate::error::{AppError, ValidationError};
1415
1516 pub async fn create(
1617 db: &Database,
1718 name: TermName,
19+ year: AcademicYearId,
1820 starts_at: Timestamp,
1921 ends_at: Timestamp,
2022 ) -> Result<Term, AppError> {
2123 let term = Term {
2224 id: TermId::generate(),
25+ year,
2326 name,
2427 starts_at,
2528 ends_at,
2629 archived_at: None,
2730 };
31+ // The year is claimed in the same statement as the row: `academic_year.
32+ // term_count` + 1 is what the year's own delete guard reads, and
33+ // claim-and-insert in one CTE means no crash can strand one half without
34+ // the other. A year that is gone matches nothing — the `gone_error` the
35+ // web layer's own read answers one instant earlier.
2836 let created = sqlx::query_as!(
2937 Term,
30- r#"INSERT INTO term (id, name, starts_at, ends_at, archived_at)
31- VALUES ($1, $2, $3, $4, NULL)
32- RETURNING id AS "id: TermId", name AS "name: TermName",
38+ r#"WITH room AS (
39+ UPDATE academic_year SET term_count = term_count + 1
40+ WHERE id = $5
41+ RETURNING 1)
42+ INSERT INTO term (id, name, year, starts_at, ends_at, archived_at)
43+ SELECT $1, $2, $5, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM room)
44+ RETURNING id AS "id: TermId", year AS "year: AcademicYearId",
45+ name AS "name: TermName",
3346 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
3447 archived_at AS "archived_at: Timestamp""#,
3548 term.id.uuid(),
3649 term.name.as_str(),
3750 term.starts_at.as_millis(),
3851 term.ends_at.as_millis(),
52+ term.year.uuid(),
3953 )
40- .fetch_one(db)
54+ .fetch_optional(db)
4155 .await?;
42- Ok(created)
56+ created.ok_or_else(|| {
57+ AppError::Validation(ValidationError::Invalid {
58+ field: "year",
59+ reason: "academic year does not exist",
60+ })
61+ })
4362 }
4463
4564 pub async fn read(db: &Database, id: &TermId) -> Result<Option<Term>, AppError> {
4665 let term = sqlx::query_as!(
4766 Term,
48- r#"SELECT id AS "id: TermId", name AS "name: TermName",
67+ r#"SELECT id AS "id: TermId", year AS "year: AcademicYearId",
68+ name AS "name: TermName",
4969 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
5070 archived_at AS "archived_at: Timestamp" FROM term WHERE id = $1"#,
5171 id.uuid(),
@@ -86,25 +106,42 @@ pub async fn update(
86106 .await
87107 }
88108
89-/// Delete the term, but only while no course *and no class* links it —
90-/// nothing here unlinks or cascades. `false` = refused, nothing was written.
109+/// Delete the term, but only while nothing links it — nothing here unlinks or
110+/// cascades. `false` = refused, nothing was written.
111+///
112+/// Two children refuse it. Exams are counted by the term's own `exam_count`
113+/// refcount, claimed by [`crate::db::exam::create`] *before* it writes the
114+/// link, so the check and the delete are one conditional write on one record:
115+/// an exam write racing this either claims first (and the delete is refused)
116+/// or finds the row gone (and is refused itself). A frozen karne
117+/// ([`crate::db::karne`]) has no counter — it is written once per archived
118+/// dönem — so its existence is the `NOT EXISTS` half of the same guard: a
119+/// dönem a family holds a karne for is history, not a calendar entry.
91120 ///
92-/// The roster of linking courses is the term's own `course_count`
93-/// refcount, claimed by [`crate::db::course::create`] and
94-/// `update` *before* they write a link, so the check and the delete are one
95-/// conditional write on one record: a course write racing this either
96-/// claims first (and the delete is refused) or finds the row gone (and is
97-/// refused itself, with the same 400 the lookup gives). `Err(NotFound)`
121+/// The referencing foreign keys (`exam.term`, `karne_snapshot.term`, both
122+/// `NO ACTION`) are the backstop behind the guard, not a second one: while
123+/// the count is honest the `WHERE` decides every race on its own, because the
124+/// claim path locks this very row before it writes a link. `Err(NotFound)`
98125 /// keeps the answer a concurrent *delete* used to get.
99126 ///
100-/// The referencing foreign keys (`course.term`, `class_group.term`, both
101-/// `NO ACTION`) are the backstop behind the counters, not a second guard:
102-/// while the counts are honest the `WHERE` decides every race on its own,
103-/// because both claim paths lock this very row before they write a link.
127+/// The year is handed its reference back in the *same statement* — a
128+/// `DELETE … RETURNING year` feeding the decrement, the shape
129+/// [`crate::db::course::delete`] uses for its classes — so a year whose last
130+/// dönem was just deleted is deletable the moment this lands. The counter
131+/// lives on the year row and only this statement may release it: without the
132+/// release the year's own `term_count = 0` delete guard could never pass
133+/// again, and a year nobody links would be undeletable forever.
104134 pub async fn delete(db: &Database, term: Term) -> Result<bool, AppError> {
105135 let gone = sqlx::query!(
106- r#"DELETE FROM term
107- WHERE id = $1 AND course_count = 0 AND class_count = 0"#,
136+ r#"WITH gone AS (
137+ DELETE FROM term
138+ WHERE id = $1 AND exam_count = 0
139+ AND NOT EXISTS (SELECT 1 FROM karne_snapshot WHERE term = $1)
140+ RETURNING year)
141+ UPDATE academic_year
142+ SET term_count = GREATEST(term_count - 1, 0)
143+ FROM gone
144+ WHERE academic_year.id = gone.year"#,
108145 term.id.uuid(),
109146 )
110147 .execute(db)
@@ -128,7 +165,8 @@ pub async fn archive(db: &Database, term: Term) -> Result<Term, AppError> {
128165 Term,
129166 r#"UPDATE term SET archived_at = $2
130167 WHERE id = $1 AND archived_at IS NULL
131- RETURNING id AS "id: TermId", name AS "name: TermName",
168+ RETURNING id AS "id: TermId", year AS "year: AcademicYearId",
169+ name AS "name: TermName",
132170 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
133171 archived_at AS "archived_at: Timestamp""#,
134172 term.id.uuid(),
@@ -150,7 +188,8 @@ pub async fn unarchive(db: &Database, term: Term) -> Result<Term, AppError> {
150188 Term,
151189 r#"UPDATE term SET archived_at = NULL
152190 WHERE id = $1 AND archived_at IS NOT NULL
153- RETURNING id AS "id: TermId", name AS "name: TermName",
191+ RETURNING id AS "id: TermId", year AS "year: AcademicYearId",
192+ name AS "name: TermName",
154193 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
155194 archived_at AS "archived_at: Timestamp""#,
156195 term.id.uuid(),
@@ -163,6 +202,23 @@ pub async fn unarchive(db: &Database, term: Term) -> Result<Term, AppError> {
163202 }
164203 }
165204
205+/// A real dönem behind a real academic year — the parent every exam names and
206+/// the grading slice every term-keyed read scopes to. Minted per call.
207+#[cfg(test)]
208+pub(crate) async fn a_test_term(db: &Database) -> TermId {
209+ let year = crate::db::academic_year::a_test_year(db).await;
210+ let term = create(
211+ db,
212+ TermName::try_new("1. Dönem").unwrap(),
213+ year,
214+ Timestamp::from_millis(0),
215+ Timestamp::from_millis(1),
216+ )
217+ .await
218+ .unwrap();
219+ *term.get_id()
220+}
221+
166222 #[cfg(test)]
167223 mod tests {
168224 use super::*;
@@ -175,9 +231,15 @@ mod tests {
175231 async fn a_moved_end_is_refused_against_the_stored_other_end() {
176232 let (db, _leases) = crate::database::init_test_db().await;
177233 let at = Timestamp::from_millis;
178- let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200))
179- .await
180- .unwrap();
234+ let term = create(
235+ &db,
236+ TermName::try_new("2026").unwrap(),
237+ crate::db::academic_year::a_test_year(&db).await,
238+ at(100),
239+ at(200),
240+ )
241+ .await
242+ .unwrap();
181243
182244 let refused = update(&db, term.clone(), None, None, Some(at(50)))
183245 .await
@@ -204,11 +266,13 @@ mod tests {
204266 async fn identical_starts_at_still_pages_each_term_exactly_once() {
205267 let (db, _leases) = crate::database::init_test_db().await;
206268 let at = Timestamp::from_millis;
269+ let year = crate::db::academic_year::a_test_year(&db).await;
207270 let mut minted = Vec::new();
208271 for i in 0..12 {
209272 let term = create(
210273 &db,
211274 TermName::try_new(&format!("t{i}")).unwrap(),
275+ year,
212276 at(100),
213277 at(200),
214278 )
@@ -248,8 +312,8 @@ mod tests {
248312 /// through. A store answering "conflict, retry" therefore comes out as a
249313 /// 500 instead of the 404 or 409 the request owes.
250314 ///
251- /// The racer is [`crate::db::course::create`] against this
252- /// term: it claims `course_count` on the term row before it writes the
315+ /// The racer is [`crate::db::exam::create`] against this
316+ /// dönem: it claims `exam_count` on the term row before it writes the
253317 /// link, which is the same record and the same column the guard reads. Both
254318 /// sides are swept across each other sub-millisecond, exactly as in
255319 /// [`crate::db::subject::delete`]'s race test — a whole
@@ -263,15 +327,19 @@ mod tests {
263327 /// [`write_with_retry`] is a single round trip wide — measured at 0
264328 /// conflicts in 100 raced rounds, green with the retry loop cut to a single
265329 /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and
266- /// never 500, and a course that got linked survives it. The retry is
330+ /// never 500, and an exam that got linked survives it. The retry is
267331 /// measured on [`crate::db::course::delete`].
268332 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
269- async fn a_delete_racing_a_course_create_never_answers_500() {
270- use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
333+ async fn a_delete_racing_an_exam_create_never_answers_500() {
334+ use crate::domain::exam::{
335+ ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
336+ };
271337 use crate::domain::user::UserId;
272338 let (db, _leases) = crate::database::init_test_db().await;
273- // The course's teacher is a foreign key now: one real row, reused by
274- // every create in every round.
339+ // The exam's parents are foreign keys now: one real instance — with
340+ // its class and course — reused by every create in every round, and
341+ // one real creator.
342+ let (instance, _course) = crate::db::course::a_test_instance(&db).await;
275343 let teacher = UserId::generate();
276344 sqlx::query(
277345 "INSERT INTO app_user (id, username, created_at, role) \
@@ -282,14 +350,24 @@ mod tests {
282350 .execute(&db)
283351 .await
284352 .unwrap();
353+ let kinds = crate::domain::settings::Settings::defaults()
354+ .get_exam_kinds()
355+ .to_vec();
356+ let year = crate::db::academic_year::a_test_year(&db).await;
285357 let (mut delete_500, mut create_500) = (0, 0);
286358 let (mut linked, mut wiped) = (0, 0);
287359 let (mut last_delete, mut last_create) = (String::new(), String::new());
288360 let at = Timestamp::from_millis;
289361 for round in 0..20 {
290- let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200))
291- .await
292- .unwrap();
362+ let term = create(
363+ &db,
364+ TermName::try_new("2026").unwrap(),
365+ year,
366+ at(100),
367+ at(200),
368+ )
369+ .await
370+ .unwrap();
293371
294372 let separated = round % 4 == 0;
295373 let drop_it = {
@@ -312,7 +390,9 @@ mod tests {
312390 };
313391 let makes: Vec<_> = (0..6)
314392 .map(|_| {
315- let (id, db, teacher) = (*term.get_id(), db.clone(), teacher);
393+ let (instance, db, teacher, kinds) =
394+ (instance.clone(), db.clone(), teacher, kinds.clone());
395+ let term = *term.get_id();
316396 let head_start = if separated {
317397 std::time::Duration::from_millis(2)
318398 } else {
@@ -320,14 +400,19 @@ mod tests {
320400 };
321401 tokio::spawn(async move {
322402 tokio::time::sleep(head_start).await;
323- crate::db::course::create(
403+ crate::db::exam::create(
324404 &db,
325405 &teacher,
326- CourseTitle::try_new("algebra").unwrap(),
327- CourseDescription::try_new("").unwrap(),
328- CourseKind::course(),
329- Some(id),
330- None,
406+ &instance,
407+ &term,
408+ ExamTitle::try_new("algebra").unwrap(),
409+ ExamDescription::try_new("").unwrap(),
410+ ExamKind::try_new("yazili", &kinds).unwrap(),
411+ ExamSchedule::try_new(None, None, None, None).unwrap(),
412+ ExamAttemptLimit::try_new(1).unwrap(),
413+ true,
414+ false,
415+ false,
331416 )
332417 .await
333418 })
@@ -338,7 +423,7 @@ mod tests {
338423 delete_500 += 1;
339424 last_delete = format!("{drop_it:?}");
340425 }
341- // Stored state, both sides: a linked course means the claim beat the
426+ // Stored state, both sides: a linked exam means the claim beat the
342427 // guard, a gone term means the delete did.
343428 let mut landed = false;
344429 for make in makes {
@@ -347,8 +432,8 @@ mod tests {
347432 create_500 += 1;
348433 last_create = format!("{make:?}");
349434 }
350- if let Ok(course) = &make
351- && crate::db::course::read(&db, course.get_id())
435+ if let Ok(exam) = &make
436+ && crate::db::exam::read(&db, exam.get_id())
352437 .await
353438 .unwrap()
354439 .is_some()
@@ -363,7 +448,7 @@ mod tests {
363448 }
364449 eprintln!(
365450 "Term::delete raced: {delete_500}/20 delete 500s, {create_500} create 500s, \
366- {linked} rounds with a course linked / {wiped} wiped"
451+ {linked} rounds with an exam linked / {wiped} wiped"
367452 );
368453 assert!(
369454 linked > 0 && wiped > 0,
@@ -375,7 +460,7 @@ mod tests {
375460 );
376461 assert_eq!(
377462 create_500, 0,
378- "a raced course create must retry, not 500: {create_500}/20 rounds, last {last_create}"
463+ "a raced exam create must retry, not 500: {create_500}/20 rounds, last {last_create}"
379464 );
380465 }
381466 }
src/db/user.rsmodified+51 -10
@@ -78,6 +78,7 @@ pub async fn create_with_role(
7878 bio AS "bio: Bio",
7979 avatar_file,
8080 avatar_content_type AS "avatar_content_type: FileContentType",
81+ branch,
8182 avatar_size"#,
8283 id.uuid(),
8384 username.as_str(),
@@ -121,6 +122,7 @@ pub async fn read(db: &Database, id: &UserId) -> Result<Option<User>, AppError>
121122 bio AS "bio: Bio",
122123 avatar_file,
123124 avatar_content_type AS "avatar_content_type: FileContentType",
125+ branch,
124126 avatar_size
125127 FROM app_user WHERE id = $1"#,
126128 id.uuid()
@@ -165,6 +167,7 @@ pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result<Vec<User>, App
165167 bio AS "bio: Bio",
166168 avatar_file,
167169 avatar_content_type AS "avatar_content_type: FileContentType",
170+ branch,
168171 avatar_size
169172 FROM app_user WHERE id = ANY($1)"#,
170173 &ids
@@ -196,6 +199,7 @@ pub async fn list_by_role(db: &Database, role: Role) -> Result<Vec<User>, AppErr
196199 bio AS "bio: Bio",
197200 avatar_file,
198201 avatar_content_type AS "avatar_content_type: FileContentType",
202+ branch,
199203 avatar_size
200204 FROM app_user WHERE role = $1 ORDER BY id DESC"#,
201205 role.as_str()
@@ -417,6 +421,7 @@ pub async fn set_role_cascade(
417421 bio AS "bio: Bio",
418422 avatar_file,
419423 avatar_content_type AS "avatar_content_type: FileContentType",
424+ branch,
420425 avatar_size"#,
421426 target.uuid(),
422427 role.as_str(),
@@ -430,27 +435,49 @@ pub async fn set_role_cascade(
430435 };
431436
432437 if role != Role::Student {
433- // Class memberships go, and each class they were on gets its
434- // seat back. One row per (class, user), so one decrement each.
438+ // Class memberships go *soft*: the live stint is stamped, not
439+ // deleted — membership history survives a demotion, and the
440+ // partial unique index leaves the pair free to rejoin if the
441+ // account is promoted back — while each class they were live in
442+ // gets its seat back (the counter counts live rows). One live row
443+ // per (class, user), so one decrement each.
435444 sqlx::query!(
436445 r#"WITH gone AS (
437- DELETE FROM class_member WHERE app_user = $1 RETURNING class
446+ UPDATE class_member SET left_at = $2
447+ WHERE app_user = $1 AND left_at IS NULL
448+ RETURNING class
438449 )
439450 UPDATE class_group
440451 SET class_member_count = GREATEST(class_member_count - 1, 0)
441452 WHERE id IN (SELECT gone.class FROM gone)"#,
442453 target.uuid(),
454+ now,
443455 )
444456 .execute(&mut *tx)
445457 .await?;
446458 // Every enrollment row — hand-placed included — and each
447- // course's seat with it.
459+ // *instance's* roster count with it (the roster counter lives on
460+ // the class×course instance now).
448461 sqlx::query!(
449462 r#"WITH gone AS (
450- DELETE FROM enrollment WHERE app_user = $1 RETURNING course
463+ DELETE FROM enrollment WHERE app_user = $1 RETURNING class_course
451464 )
452- UPDATE course
465+ UPDATE class_course
453466 SET enrollment_count = GREATEST(enrollment_count - 1, 0)
467+ WHERE id IN (SELECT gone.class_course FROM gone)"#,
468+ target.uuid(),
469+ )
470+ .execute(&mut *tx)
471+ .await?;
472+ // The individual club/etüt memberships go with them: a demoted
473+ // account may hold no seat in a school-scoped course either, and
474+ // each course gets its membership count back.
475+ sqlx::query!(
476+ r#"WITH gone AS (
477+ DELETE FROM course_membership WHERE app_user = $1 RETURNING course
478+ )
479+ UPDATE course
480+ SET course_membership_count = GREATEST(course_membership_count - 1, 0)
454481 WHERE id IN (SELECT gone.course FROM gone)"#,
455482 target.uuid(),
456483 )
@@ -562,11 +589,12 @@ pub async fn set_role_cascade(
562589 }
563590
564591 if !role.at_least(Role::Teacher) {
565- // Course staffing goes — only teacher+ may hold a seat, and the
566- // seat is a `course_teacher` row now: one `DELETE` by its
567- // `teacher` index takes every assignment.
592+ // Instance staffing goes — only teacher+ may hold a seat, and the
593+ // seat is a `class_course_teacher` row now (D6 moved assignment
594+ // onto the instance): one `DELETE` by its `teacher` index takes
595+ // every assignment.
568596 sqlx::query!(
569- "DELETE FROM course_teacher WHERE teacher = $1",
597+ "DELETE FROM class_course_teacher WHERE teacher = $1",
570598 target.uuid(),
571599 )
572600 .execute(&mut *tx)
@@ -643,6 +671,7 @@ pub async fn set_profile(
643671 birth_date: Option<Option<BirthDate>>,
644672 display_name: Option<Option<DisplayName>>,
645673 bio: Option<Option<Bio>>,
674+ branch: Option<Option<String>>,
646675 ) -> Result<User, AppError> {
647676 // `Some(None)` must bind an explicit NULL and `Some(Some(v))` a value:
648677 // `Param::OptText` carries both shapes of one nullable TEXT column.
@@ -682,6 +711,13 @@ pub async fn set_profile(
682711 "bio",
683712 text(bio.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))),
684713 )
714+ // The branş is plain text, not a newtype: the school's own list is
715+ // settings data, so its membership check belongs to the write path
716+ // that holds that list (the web layer), not to a row type.
717+ .set(
718+ "branch",
719+ text(branch.as_ref().map(|n| n.as_ref().map(String::as_str))),
720+ )
685721 .run(db)
686722 .await
687723 }
@@ -729,6 +765,7 @@ pub async fn set_avatar(
729765 bio AS "bio: Bio",
730766 avatar_file,
731767 avatar_content_type AS "avatar_content_type: FileContentType",
768+ branch,
732769 avatar_size
733770 FROM app_user WHERE id = $1 FOR UPDATE"#,
734771 id.uuid()
@@ -777,6 +814,7 @@ pub async fn clear_avatar(db: &Database, id: &UserId) -> Result<Option<User>, Ap
777814 bio AS "bio: Bio",
778815 avatar_file,
779816 avatar_content_type AS "avatar_content_type: FileContentType",
817+ branch,
780818 avatar_size
781819 FROM app_user WHERE id = $1 FOR UPDATE"#,
782820 id.uuid()
@@ -839,6 +877,7 @@ pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Us
839877 bio AS "bio: Bio",
840878 avatar_file,
841879 avatar_content_type AS "avatar_content_type: FileContentType",
880+ branch,
842881 avatar_size
843882 FROM app_user WHERE username = $1"#,
844883 username
@@ -890,6 +929,7 @@ mod tests {
890929 None,
891930 None,
892931 None,
932+ None,
893933 )
894934 .await
895935 .unwrap();
@@ -931,6 +971,7 @@ mod tests {
931971 None,
932972 Some(Some(display_name.clone())),
933973 None,
974+ None,
934975 )
935976 .await
936977 .unwrap();
src/db/work_entry.rsmodified+7 -4
@@ -147,10 +147,13 @@ pub async fn list_for_user(
147147 // A window that can hide rows needs the count over the same WHERE;
148148 // an unpaged read from row zero already holds every row.
149149 let total = if limit.is_some() || offset > 0 {
150- sqlx::query_scalar!("SELECT count(*) FROM work_entry WHERE app_user = $1", user.uuid())
151- .fetch_one(db)
152- .await?
153- .unwrap_or(0)
150+ sqlx::query_scalar!(
151+ "SELECT count(*) FROM work_entry WHERE app_user = $1",
152+ user.uuid()
153+ )
154+ .fetch_one(db)
155+ .await?
156+ .unwrap_or(0)
154157 } else {
155158 rows.len() as i64
156159 };
src/domain/academic_year.rsadded+257 -0
@@ -0,0 +1,257 @@
1+//! An academic year (eğitim yılı): the container a şube and its dönemler
2+//! belong to. Above [`crate::domain::term::Term`], which is a grading slice
3+//! inside it.
4+//!
5+//! The year carries the sınıf geçme policy (`grade_promotions`): a mapping
6+//! from one grade label to the next, applied by the explicit, idempotent
7+//! rollover command ([`crate::service::academic_year::rollover`]). A grade
8+//! absent from the list is not rolled over — that is how graduation is
9+//! expressed.
10+//!
11+//! The queries live in [`crate::db::academic_year`]; this file is the row
12+//! shape, its newtypes and the archive guard.
13+
14+use serde::{Deserialize, Serialize};
15+use sqlx::types::Json;
16+
17+use crate::constant::{MAX_ACADEMIC_YEAR_NAME_LEN, MAX_CLASS_GRADE_LEN};
18+use crate::domain::monotonic_id::next_uuid;
19+use crate::domain::timestamp::Timestamp;
20+use crate::domain::user::UserId;
21+use crate::error::{AppError, ValidationError};
22+use crate::validate::validate_required;
23+
24+/// Typed academic-year row id. A UUIDv7 minted by the process-wide monotonic
25+/// generator, so `id` order is mint order.
26+#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
27+#[sqlx(transparent)]
28+pub struct AcademicYearId(uuid::Uuid);
29+
30+impl AcademicYearId {
31+ pub fn generate() -> Self {
32+ Self(next_uuid())
33+ }
34+
35+ /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
36+ /// cannot take the newtype. Static `query!` binds take `self` directly.
37+ pub fn uuid(&self) -> uuid::Uuid {
38+ self.0
39+ }
40+
41+ /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
42+ /// which matches no row.
43+ pub fn from_key(key: &str) -> Self {
44+ Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
45+ }
46+
47+ pub fn key(&self) -> String {
48+ self.0.to_string()
49+ }
50+}
51+
52+/// The refusal every write against an archived year gets, coded so a client
53+/// can tell it from the other 409s on the same route.
54+pub fn archived_error() -> AppError {
55+ AppError::ConflictCoded {
56+ code: "academic_year_archived",
57+ message: "this academic year is archived — past years are read-only".into(),
58+ }
59+}
60+
61+/// The refusal a rollover into an already-populated target year gets.
62+pub fn rollover_target_not_empty() -> AppError {
63+ AppError::ConflictCoded {
64+ code: "rollover_target_not_empty",
65+ message: "the target year already has classes — roll into an empty year".into(),
66+ }
67+}
68+
69+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
70+#[sqlx(transparent)]
71+pub struct AcademicYearName(String);
72+
73+impl AcademicYearName {
74+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
75+ validate_required("name", value, MAX_ACADEMIC_YEAR_NAME_LEN)?;
76+ Ok(Self(value.to_string()))
77+ }
78+
79+ pub fn as_str(&self) -> &str {
80+ &self.0
81+ }
82+}
83+
84+/// One sınıf-geçme mapping: a student who finished `from_grade` moves to
85+/// `to_grade` at rollover.
86+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87+pub struct GradePromotion {
88+ from_grade: String,
89+ to_grade: String,
90+}
91+
92+impl GradePromotion {
93+ pub fn try_new(from_grade: &str, to_grade: &str) -> Result<Self, ValidationError> {
94+ let bound = |field: &'static str, value: &str| {
95+ if value.is_empty() || value.chars().count() > MAX_CLASS_GRADE_LEN {
96+ Err(ValidationError::Invalid {
97+ field,
98+ reason: "grade labels must be 1 to 20 characters",
99+ })
100+ } else {
101+ Ok(())
102+ }
103+ };
104+ bound("from_grade", from_grade)?;
105+ bound("to_grade", to_grade)?;
106+ Ok(Self {
107+ from_grade: from_grade.to_string(),
108+ to_grade: to_grade.to_string(),
109+ })
110+ }
111+
112+ pub fn get_from_grade(&self) -> &str {
113+ &self.from_grade
114+ }
115+
116+ pub fn get_to_grade(&self) -> &str {
117+ &self.to_grade
118+ }
119+}
120+
121+/// One academic year. Both ends are required; `archived_at` NULL = open.
122+#[derive(Debug, Clone, sqlx::FromRow)]
123+pub struct AcademicYear {
124+ pub(crate) id: AcademicYearId,
125+ pub(crate) name: AcademicYearName,
126+ pub(crate) starts_at: Timestamp,
127+ pub(crate) ends_at: Timestamp,
128+ pub(crate) archived_at: Option<Timestamp>,
129+ pub(crate) creator: UserId,
130+ pub(crate) grade_promotions: Json<Vec<GradePromotion>>,
131+ pub(crate) class_count: i64,
132+ pub(crate) term_count: i64,
133+}
134+
135+impl AcademicYear {
136+ pub fn try_new(
137+ name: &str,
138+ starts_at: Timestamp,
139+ ends_at: Timestamp,
140+ creator: UserId,
141+ grade_promotions: Vec<GradePromotion>,
142+ ) -> Result<Self, ValidationError> {
143+ if ends_at <= starts_at {
144+ return Err(ValidationError::Invalid {
145+ field: "ends_at",
146+ reason: "must be after starts_at",
147+ });
148+ }
149+ Ok(Self {
150+ id: AcademicYearId::generate(),
151+ name: AcademicYearName::try_new(name)?,
152+ starts_at,
153+ ends_at,
154+ archived_at: None,
155+ creator,
156+ grade_promotions: Json(grade_promotions),
157+ class_count: 0,
158+ term_count: 0,
159+ })
160+ }
161+
162+ pub fn get_id(&self) -> &AcademicYearId {
163+ &self.id
164+ }
165+
166+ pub fn get_name(&self) -> &AcademicYearName {
167+ &self.name
168+ }
169+
170+ pub fn get_starts_at(&self) -> Timestamp {
171+ self.starts_at
172+ }
173+
174+ pub fn get_ends_at(&self) -> Timestamp {
175+ self.ends_at
176+ }
177+
178+ pub fn get_archived_at(&self) -> Option<Timestamp> {
179+ self.archived_at
180+ }
181+
182+ pub fn get_creator(&self) -> &UserId {
183+ &self.creator
184+ }
185+
186+ pub fn get_grade_promotions(&self) -> &[GradePromotion] {
187+ &self.grade_promotions.0
188+ }
189+
190+ /// The grade a şube of `grade` rolls into, or `None` when the grade has no
191+ /// promotion entry (graduation).
192+ pub fn promotion_for(&self, grade: &str) -> Option<&str> {
193+ self.grade_promotions
194+ .0
195+ .iter()
196+ .find(|promo| promo.from_grade == grade)
197+ .map(|promo| promo.to_grade.as_str())
198+ }
199+
200+ pub fn get_class_count(&self) -> i64 {
201+ self.class_count
202+ }
203+
204+ pub fn get_term_count(&self) -> i64 {
205+ self.term_count
206+ }
207+
208+ pub fn is_archived(&self) -> bool {
209+ self.archived_at.is_some()
210+ }
211+}
212+
213+#[cfg(test)]
214+mod tests {
215+ use super::*;
216+
217+ fn ts(ms: i64) -> Timestamp {
218+ Timestamp::from_millis(ms)
219+ }
220+
221+ #[tokio::test]
222+ async fn name_is_required_and_bounded() {
223+ assert!(AcademicYearName::try_new("2026-2027").is_ok());
224+ assert!(AcademicYearName::try_new("").is_err());
225+ assert!(AcademicYearName::try_new(" ").is_err());
226+ assert!(AcademicYearName::try_new(&"x".repeat(MAX_ACADEMIC_YEAR_NAME_LEN + 1)).is_err());
227+ }
228+
229+ #[tokio::test]
230+ async fn promotions_validate_both_labels() {
231+ assert!(GradePromotion::try_new("5", "6").is_ok());
232+ assert!(GradePromotion::try_new("", "6").is_err());
233+ assert!(GradePromotion::try_new("5", &"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err());
234+ }
235+
236+ #[tokio::test]
237+ async fn a_year_needs_a_forward_range() {
238+ let creator = UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e");
239+ assert!(AcademicYear::try_new("2026-2027", ts(0), ts(1000), creator, vec![]).is_ok());
240+ assert!(AcademicYear::try_new("2026-2027", ts(1000), ts(1000), creator, vec![]).is_err());
241+ }
242+
243+ #[tokio::test]
244+ async fn promotion_for_maps_known_grades_only() {
245+ let creator = UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e");
246+ let year = AcademicYear::try_new(
247+ "2026-2027",
248+ ts(0),
249+ ts(1000),
250+ creator,
251+ vec![GradePromotion::try_new("5", "6").unwrap()],
252+ )
253+ .unwrap();
254+ assert_eq!(year.promotion_for("5"), Some("6"));
255+ assert_eq!(year.promotion_for("12"), None);
256+ }
257+}
src/domain/appointment.rsmodified+1 -1
@@ -25,7 +25,7 @@
2525 //! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional
2626 //! `UPDATE`.
2727
28-use crate::constant::{MAX_APPOINTMENT_REASON_LEN};
28+use crate::constant::MAX_APPOINTMENT_REASON_LEN;
2929 use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};
3030 use crate::domain::monotonic_id::next_uuid;
3131 use crate::domain::timestamp::Timestamp;
src/domain/appointment_slot.rsmodified+1 -3
@@ -19,9 +19,7 @@
1919 //! live in [`crate::db::appointment_slot`]; the publish and delete workflows
2020 //! in [`crate::service::appointment_slot`].
2121
22-use crate::constant::{
23- MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK,
24-};
22+use crate::constant::{MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK};
2523 use crate::domain::monotonic_id::next_uuid;
2624 use crate::domain::timestamp::Timestamp;
2725 use crate::domain::user::UserId;
src/domain/chatbot_message.rsmodified+1 -3
@@ -9,9 +9,7 @@
99 //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process
1010 //! happens once, at mint, in `database.rs`'s school migration sweep.
1111
12-use crate::constant::{
13- CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE,
14-};
12+use crate::constant::{CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE};
1513 use crate::domain::chatbot_thread::ChatbotThreadId;
1614 use crate::domain::monotonic_id::next_uuid;
1715 use crate::domain::timestamp::Timestamp;
src/domain/chatbot_thread.rsmodified+1 -1
@@ -4,7 +4,7 @@
44 //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the
55 //! threads' own persistence lives in [`crate::db::chatbot_thread`].
66
7-use crate::constant::{MAX_CHATBOT_THREAD_TITLE_LEN};
7+use crate::constant::MAX_CHATBOT_THREAD_TITLE_LEN;
88 use crate::domain::monotonic_id::next_uuid;
99 use crate::domain::timestamp::Timestamp;
1010 use crate::domain::user::UserId;
src/domain/class_blueprint.rsmodified+0 -2
@@ -250,7 +250,6 @@ mod tests {
250250 (Attached::PivotGone, "course_deleted"),
251251 (Attached::ClassFull, "class_at_course_ceiling"),
252252 (Attached::ClassOverloaded, "class_roster_too_large"),
253- (Attached::Full("course:algebra".into()), "course_full"),
254253 (
255254 Attached::CourseGone("course:algebra".into()),
256255 "linked_course_missing",
@@ -298,7 +297,6 @@ mod tests {
298297 Attached::<ClassCourse>::Duplicate,
299298 Attached::Gone,
300299 Attached::PivotGone,
301- Attached::Full("course:algebra".into()),
302300 Attached::CourseGone("course:algebra".into()),
303301 Attached::SourceGone,
304302 ] {
src/domain/class_course.rsmodified+90 -31
@@ -1,59 +1,102 @@
1-//! A course attached to a class, and the enrollments that attachment implies.
1+//! A course as taught in one class: the academic *instance*.
22 //!
3-//! The mirror of [`crate::domain::class_member`] along the pump's other axis:
4-//! attaching a course enrolls the class's whole roster into it, detaching it
5-//! sweeps the rows that attach wrote. The attach/detach workflows live in
6-//! [`crate::service::class_course`]; the row's reads in
7-//! [`crate::db::class_course`] — this file is the row shape and its
8-//! composite id.
3+//! The anchor of the K12 model. A course in the school catalog is a template;
4+//! attaching it to a şube mints one of these rows, and exams, sessions,
5+//! roll-call, homework and enrollments all key on the instance — so two
6+//! şubeler teaching the same course have separate rosters, exams, timetables
7+//! and teachers. The row carries the weekly hours (`ders_saati`, the karne
8+//! weight) and whether it counts toward the karne.
9+//!
10+//! The attach/detach workflows live in [`crate::service::class_course`]; the
11+//! row's reads in [`crate::db::class_course`] — this file is the row shape and
12+//! its id.
913
14+use crate::constant::{MAX_DERS_SAATI, MIN_DERS_SAATI};
1015 use crate::domain::class_blueprint::ClassBlueprintId;
1116 use crate::domain::class_group::ClassGroupId;
1217 use crate::domain::course::CourseId;
18+use crate::domain::monotonic_id::next_uuid;
19+use crate::domain::timestamp::Timestamp;
1320 use crate::domain::user::UserId;
21+use crate::error::ValidationError;
1422
15-/// The identity of one (class, course) pair. Not a row column: the table's
16-/// primary key *is* the pair, and this struct's job is the underscore-joined
17-/// wire form at the HTTP edge.
18-#[derive(Debug, Clone, PartialEq, Eq)]
19-pub struct ClassCourseId {
20- pub(crate) class: ClassGroupId,
21- pub(crate) course: CourseId,
22-}
23+/// The identity of one class×course instance. A UUIDv7 minted by the
24+/// process-wide monotonic generator, so a class's instances list in creation
25+/// order.
26+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
27+#[sqlx(transparent)]
28+pub struct ClassCourseId(uuid::Uuid);
2329
2430 impl ClassCourseId {
25- /// The one id a (class, course) pair can have.
26- pub fn composite(class: &ClassGroupId, course: &CourseId) -> Self {
27- Self {
28- class: class.clone(),
29- course: course.clone(),
30- }
31+ pub fn generate() -> Self {
32+ Self(next_uuid())
33+ }
34+
35+ /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
36+ /// cannot take the newtype. Static `query!` binds take `self` directly.
37+ pub fn uuid(&self) -> uuid::Uuid {
38+ self.0
39+ }
40+
41+ /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
42+ /// which matches no row.
43+ pub fn from_key(key: &str) -> Self {
44+ Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
3145 }
3246
33- /// The underscore-joined wire form (`{class}_{course}`).
47+ /// The bare uuid wire form.
3448 pub fn key(&self) -> String {
35- format!("{}_{}", self.class.key(), self.course.key())
49+ self.0.to_string()
50+ }
51+}
52+
53+/// Weekly lesson hours of an instance: the weight the instance carries in the
54+/// year's karne average, and the count a timetable grid would lay out.
55+#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
56+#[sqlx(transparent)]
57+pub struct DersSaati(i64);
58+
59+impl DersSaati {
60+ pub fn try_new(value: i64) -> Result<Self, ValidationError> {
61+ if !(MIN_DERS_SAATI..=MAX_DERS_SAATI).contains(&value) {
62+ return Err(ValidationError::Invalid {
63+ field: "ders_saati",
64+ reason: "must be between 1 and 40 weekly hours",
65+ });
66+ }
67+ Ok(Self(value))
68+ }
69+
70+ pub fn as_i64(&self) -> i64 {
71+ self.0
3672 }
3773 }
3874
39-/// One course a class is attached to. `attached_by` is who attached it.
75+/// One course taught in one class. `attached_by` is who attached it, `source`
76+/// the blueprint that placed it (absent for a hand attach). `ders_saati` and
77+/// `counts_toward_karne` are the instance's own policy — what two şubeler
78+/// teaching the same catalog course may legitimately differ on.
4079 #[derive(Debug, Clone, sqlx::FromRow)]
4180 pub struct ClassCourse {
81+ pub(crate) id: ClassCourseId,
4282 pub(crate) class: ClassGroupId,
4383 pub(crate) course: CourseId,
4484 pub(crate) attached_by: UserId,
4585 /// The grade blueprint that placed this attachment, absent when a human
46- /// attached the course to this class directly — the mirror of
47- /// [`crate::domain::enrollment`]'s `source`, and read the same way: only a
48- /// row carrying the key is a blueprint's to take back, so a hand-attached
49- /// course survives every blueprint sweep.
86+ /// attached the course to this class directly — read the same way as
87+ /// [`crate::domain::enrollment`]'s `source`: only a row carrying the key
88+ /// is a blueprint's to take back, so a hand-attached course survives every
89+ /// blueprint sweep.
5090 pub(crate) source: Option<ClassBlueprintId>,
91+ pub(crate) ders_saati: DersSaati,
92+ pub(crate) counts_toward_karne: bool,
93+ pub(crate) enrollment_count: i64,
94+ pub(crate) attached_at: Timestamp,
5195 }
5296
5397 impl ClassCourse {
54- /// The row's identity, built back from its primary-key columns.
55- pub fn get_id(&self) -> ClassCourseId {
56- ClassCourseId::composite(&self.class, &self.course)
98+ pub fn get_id(&self) -> &ClassCourseId {
99+ &self.id
57100 }
58101
59102 pub fn get_class(&self) -> &ClassGroupId {
@@ -72,4 +115,20 @@ impl ClassCourse {
72115 pub fn get_source(&self) -> Option<&ClassBlueprintId> {
73116 self.source.as_ref()
74117 }
118+
119+ pub fn get_ders_saati(&self) -> DersSaati {
120+ self.ders_saati
121+ }
122+
123+ pub fn counts_toward_karne(&self) -> bool {
124+ self.counts_toward_karne
125+ }
126+
127+ pub fn get_enrollment_count(&self) -> i64 {
128+ self.enrollment_count
129+ }
130+
131+ pub fn get_attached_at(&self) -> Timestamp {
132+ self.attached_at
133+ }
75134 }
src/domain/class_group.rsmodified+12 -10
@@ -4,19 +4,21 @@
44 //! counted on this row — a class may only be deleted at zero on both, the same
55 //! stored guard shape courses and terms use.
66 //!
7-//! A class links a term exactly like a course does, and claims a reference on it
8-//! before the link is written. The reference is its *own* column
9-//! ([`crate::constant::TERM_CLASS_COUNT_FIELD`]) rather than the courses' `course_count`, because
10-//! boot seeds that one from the course rows alone and would wipe a class's share
11-//! of it on the next migration.
7+//! A class belongs to an academic year ([`crate::domain::academic_year`]), not
8+//! to a term: the şube keeps the same roster all year and the dönem is a
9+//! grading slice inside it. It claims a reference on its year before the link
10+//! is written; the reference is its *own* column
11+//! ([`crate::constant::ACADEMIC_YEAR_CLASS_COUNT_FIELD`]) rather than the
12+//! courses' own count, so a class's share is never confused with another
13+//! roster's.
1214 //!
13-//! The queries live in [`crate::db::class_group`]; the archived-term guard and
15+//! The queries live in [`crate::db::class_group`]; the archived-year guard and
1416 //! the route-facing wrappers in [`crate::service::class_group`] — this file is
1517 //! the row shape, its newtypes and getters.
1618
1719 use crate::constant::{MAX_CLASS_GRADE_LEN, MAX_CLASS_NAME_LEN};
20+use crate::domain::academic_year::AcademicYearId;
1821 use crate::domain::monotonic_id::next_uuid;
19-use crate::domain::term::TermId;
2022 use crate::domain::user::UserId;
2123 use crate::error::ValidationError;
2224 use crate::validate::{validate_optional, validate_required};
@@ -94,7 +96,7 @@ pub struct ClassGroup {
9496 pub(crate) creator: UserId,
9597 pub(crate) name: ClassName,
9698 pub(crate) grade: Option<ClassGrade>,
97- pub(crate) term: Option<TermId>,
99+ pub(crate) year: Option<AcademicYearId>,
98100 pub(crate) teacher: Option<UserId>,
99101 }
100102
@@ -115,8 +117,8 @@ impl ClassGroup {
115117 self.grade.as_ref()
116118 }
117119
118- pub fn get_term(&self) -> Option<&TermId> {
119- self.term.as_ref()
120+ pub fn get_year(&self) -> Option<&AcademicYearId> {
121+ self.year.as_ref()
120122 }
121123
122124 /// The homeroom teacher (sınıf öğretmeni), if one is assigned.
src/domain/class_member.rsmodified+58 -26
@@ -1,54 +1,69 @@
1-//! A student's place in a class, and the enrollments that place implies.
1+//! A student's stint in a class, and the enrollments that place implies.
22 //!
3-//! Both writes are one call into [`crate::db::class_pump`]: adding a member
4-//! and attaching a course to the class are the same pump seen from its two
5-//! ends. The refusals-to-errors policy and the detach live in
3+//! A history table: `left_at` NULL is the live stint, and the partial unique
4+//! index `(class, app_user) WHERE left_at IS NULL` keeps one live stint per
5+//! pair while preserving rejoin history (a student who leaves and comes back
6+//! has two rows). Both writes are one call into [`crate::db::class_pump`]:
7+//! adding a member and attaching a course to the class are the same pump seen
8+//! from its two ends. The refusals-to-errors policy and the detach live in
69 //! [`crate::service::class_member`]; the roster reads in
7-//! [`crate::db::class_member`] — this file is the row shape and its
8-//! composite id.
10+//! [`crate::db::class_member`] — this file is the row shape and its id.
911
1012 use crate::domain::class_group::ClassGroupId;
13+use crate::domain::monotonic_id::next_uuid;
14+use crate::domain::timestamp::Timestamp;
1115 use crate::domain::user::UserId;
1216
13-/// The identity of one (class, user) pair. Not a row column: the table's
14-/// primary key *is* the pair, and this struct's job is the underscore-joined
15-/// wire form at the HTTP edge.
16-#[derive(Debug, Clone, PartialEq, Eq)]
17-pub struct ClassMemberId {
18- pub(crate) class: ClassGroupId,
19- pub(crate) user: UserId,
20-}
17+/// The identity of one class-member stunt. A UUIDv7 minted by the
18+/// process-wide monotonic generator, so a class's roster lists in join order.
19+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
20+#[sqlx(transparent)]
21+pub struct ClassMemberId(uuid::Uuid);
2122
2223 impl ClassMemberId {
23- /// The one id a (class, user) pair can have.
24- pub fn composite(class: &ClassGroupId, user: &UserId) -> Self {
25- Self {
26- class: class.clone(),
27- user: *user,
28- }
24+ pub fn generate() -> Self {
25+ Self(next_uuid())
26+ }
27+
28+ /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
29+ /// cannot take the newtype. Static `query!` binds take `self` directly.
30+ pub fn uuid(&self) -> uuid::Uuid {
31+ self.0
32+ }
33+
34+ /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
35+ /// which matches no row.
36+ pub fn from_key(key: &str) -> Self {
37+ Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
2938 }
3039
31- /// The underscore-joined wire form (`{class}_{user}`).
40+ /// The bare uuid wire form.
3241 pub fn key(&self) -> String {
33- format!("{}_{}", self.class.key(), self.user.key())
42+ self.0.to_string()
3443 }
3544 }
3645
37-/// One student in one class. `added_by` is who put them there.
46+/// One student's stint in one class. `added_by` is who put them there;
47+/// `source_class_group` names the şube a rollover copied them from (absent for
48+/// a hand-added member).
3849 #[derive(Debug, Clone, sqlx::FromRow)]
3950 pub struct ClassMember {
51+ pub(crate) id: ClassMemberId,
4052 pub(crate) class: ClassGroupId,
4153 /// The column is `app_user` (the reserved-word rename); the Rust name is
4254 /// the domain's.
4355 #[sqlx(rename = "app_user")]
4456 pub(crate) user: UserId,
4557 pub(crate) added_by: UserId,
58+ pub(crate) joined_at: Timestamp,
59+ /// When the student left; `None` while the stint is live.
60+ pub(crate) left_at: Option<Timestamp>,
61+ pub(crate) source_class_group: Option<ClassGroupId>,
4662 }
4763
4864 impl ClassMember {
49- /// The row's identity, built back from its primary-key columns.
50- pub fn get_id(&self) -> ClassMemberId {
51- ClassMemberId::composite(&self.class, &self.user)
65+ pub fn get_id(&self) -> &ClassMemberId {
66+ &self.id
5267 }
5368
5469 pub fn get_class(&self) -> &ClassGroupId {
@@ -62,4 +77,21 @@ impl ClassMember {
6277 pub fn get_added_by(&self) -> &UserId {
6378 &self.added_by
6479 }
80+
81+ pub fn get_joined_at(&self) -> Timestamp {
82+ self.joined_at
83+ }
84+
85+ pub fn get_left_at(&self) -> Option<Timestamp> {
86+ self.left_at
87+ }
88+
89+ /// Whether this stint is live (the student is currently in the class).
90+ pub fn is_live(&self) -> bool {
91+ self.left_at.is_none()
92+ }
93+
94+ pub fn get_source_class_group(&self) -> Option<&ClassGroupId> {
95+ self.source_class_group.as_ref()
96+ }
6597 }
src/domain/course.rsmodified+29 -33
@@ -1,6 +1,5 @@
11 use crate::constant::{MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN};
22 use crate::domain::monotonic_id::next_uuid;
3-use crate::domain::term::TermId;
43 use crate::domain::user::UserId;
54 use crate::error::ValidationError;
65 use crate::validate::{validate_course_kind, validate_optional, validate_required};
@@ -66,7 +65,8 @@ impl CourseDescription {
6665
6766 /// A validated course kind: `course` (a regular class — ders), `study` (a
6867 /// supervised study session — etüt), or `club` (a student club — kulüp).
69-/// Purely a label; all kinds behave identically.
68+/// Only `course` is class-delivered (a şube attaches it as an instance);
69+/// `study`/`club` are school-scoped and joined individually.
7070 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
7171 #[sqlx(transparent)]
7272 pub struct CourseKind(String);
@@ -85,32 +85,36 @@ impl CourseKind {
8585 pub fn as_str(&self) -> &str {
8686 &self.0
8787 }
88+
89+ /// Whether a şube attaches this kind as an instance. Only a regular ders
90+ /// (`course`) is class-delivered; clubs and etüt are school-scoped and
91+ /// joined individually ([`crate::domain::course_membership`]).
92+ pub fn is_class_delivered(&self) -> bool {
93+ self.0 == "course"
94+ }
8895 }
8996
90-/// A course: the unit exams and enrollments hang off. Marks are computed per
91-/// course, each exam weighted by its kind's settings weight. May belong to an
92-/// academic term. Comes in three behaviorally identical kinds: `course`,
93-/// `study` (etüt), and `club` (kulüp). An optional `capacity` caps the roster
94-/// at enroll time (`NULL` = unlimited).
97+/// A course: a school-level catalog entry. It is a *template* — the academic
98+/// work (roster, exams, timetable) lives on the instances a class attaches
99+/// ([`crate::domain::class_course::ClassCourse`]), so this row carries only
100+/// what every instance shares: title, description, kind.
95101 ///
96-/// `creator` owns the course for good — only they (or a manager+) may delete
97-/// it. `teachers` are the staff a manager assigned to run it: full management
98-/// rights inside the course, no power to delete it or change the assignment
99-/// list. The assignment itself is `course_teacher` rows; the struct carries
100-/// the resolved list, joined on by the db layer.
102+/// `creator` is who minted it; the catalog is Manager+-owned, so there is no
103+/// per-teacher ownership. The two counters are the delete guard: a course may
104+/// only be dropped when no class attaches it and no one holds an individual
105+/// membership.
101106 ///
102107 /// Fields are crate-visible: [`crate::db::course`] mints the rows on create
103108 /// and reads the id when updating and cascading a delete.
104-#[derive(Debug, Clone)]
109+#[derive(Debug, Clone, sqlx::FromRow)]
105110 pub struct Course {
106111 pub(crate) id: CourseId,
107112 pub(crate) creator: UserId,
108- pub(crate) teachers: Vec<UserId>,
109113 pub(crate) title: CourseTitle,
110114 pub(crate) description: CourseDescription,
111115 pub(crate) kind: CourseKind,
112- pub(crate) term: Option<TermId>,
113- pub(crate) capacity: Option<i64>,
116+ pub(crate) class_course_count: i64,
117+ pub(crate) course_membership_count: i64,
114118 }
115119
116120 impl Course {
@@ -134,30 +138,19 @@ impl Course {
134138 &self.kind
135139 }
136140
137- pub fn get_term(&self) -> Option<&TermId> {
138- self.term.as_ref()
141+ /// How many class instances attach this catalog course.
142+ pub fn get_class_course_count(&self) -> i64 {
143+ self.class_course_count
139144 }
140145
141- /// The seat cap enforced at enroll time; `None` = unlimited.
142- pub fn get_capacity(&self) -> Option<i64> {
143- self.capacity
146+ /// How many users hold an individual (club/etüt) membership.
147+ pub fn get_course_membership_count(&self) -> i64 {
148+ self.course_membership_count
144149 }
145150
146151 pub fn is_creator(&self, user: &UserId) -> bool {
147152 &self.creator == user
148153 }
149-
150- /// The staff assigned to run this course. Assignment order is not kept:
151- /// the links are `course_teacher` rows now, and a set has no order.
152- pub fn get_teachers(&self) -> &[UserId] {
153- &self.teachers
154- }
155-
156- /// Whether `user` was assigned to teach this course. Says nothing about
157- /// the creator — they own it whether or not they also appear here.
158- pub fn is_assigned(&self, user: &UserId) -> bool {
159- self.teachers.contains(user)
160- }
161154 }
162155
163156 #[cfg(test)]
@@ -183,5 +176,8 @@ mod tests {
183176 assert!(CourseKind::try_new("club").is_ok());
184177 assert!(CourseKind::try_new("etut").is_err());
185178 assert_eq!(CourseKind::course().as_str(), "course");
179+ assert!(CourseKind::course().is_class_delivered());
180+ assert!(!CourseKind::try_new("club").unwrap().is_class_delivered());
181+ assert!(!CourseKind::try_new("study").unwrap().is_class_delivered());
186182 }
187183 }
src/domain/course_membership.rsadded+62 -0
@@ -0,0 +1,62 @@
1+use crate::domain::course::CourseId;
2+use crate::domain::timestamp::Timestamp;
3+use crate::domain::user::UserId;
4+
5+/// The identity of one (course, user) pair. Not a row column: the table's
6+/// primary key *is* the pair, which makes joining a single atomic UPSERT
7+/// (`ON CONFLICT (course, app_user)`) with no find-then-insert race. This
8+/// struct's job is the underscore-joined wire form at the HTTP edge.
9+#[derive(Debug, Clone, PartialEq, Eq)]
10+pub struct CourseMembershipId {
11+ pub(crate) course: CourseId,
12+ pub(crate) user: UserId,
13+}
14+
15+impl CourseMembershipId {
16+ pub fn composite(course: &CourseId, user: &UserId) -> Self {
17+ Self {
18+ course: course.clone(),
19+ user: *user,
20+ }
21+ }
22+
23+ /// The underscore-joined wire form (`{course}_{user}`).
24+ pub fn key(&self) -> String {
25+ format!("{}_{}", self.course.key(), self.user.key())
26+ }
27+}
28+
29+/// A user's individual membership in a *school-scoped* course (D9): a club or
30+/// an etüt a student joins directly. A class-delivered course
31+/// ([`crate::domain::course::CourseKind::is_class_delivered`]) is joined
32+/// through its instance instead, never here — that gate lives in the service.
33+#[derive(Debug, Clone, sqlx::FromRow)]
34+pub struct CourseMembership {
35+ pub(crate) course: CourseId,
36+ #[sqlx(rename = "app_user")]
37+ pub(crate) user: UserId,
38+ pub(crate) added_by: UserId,
39+ pub(crate) created_at: Timestamp,
40+}
41+
42+impl CourseMembership {
43+ pub fn get_id(&self) -> CourseMembershipId {
44+ CourseMembershipId::composite(&self.course, &self.user)
45+ }
46+
47+ pub fn get_course(&self) -> &CourseId {
48+ &self.course
49+ }
50+
51+ pub fn get_user(&self) -> &UserId {
52+ &self.user
53+ }
54+
55+ pub fn get_added_by(&self) -> &UserId {
56+ &self.added_by
57+ }
58+
59+ pub fn get_created_at(&self) -> Timestamp {
60+ self.created_at
61+ }
62+}
src/domain/course_note_file.rsmodified+0 -1
@@ -43,7 +43,6 @@ impl CourseNoteFileId {
4343 }
4444 }
4545
46-
4746 #[derive(Debug, Clone, sqlx::FromRow)]
4847 pub struct CourseNoteFile {
4948 pub(crate) id: CourseNoteFileId,
src/domain/course_session.rsmodified+4 -4
@@ -1,5 +1,5 @@
11 use crate::constant::MAX_SESSION_TOPIC_LEN;
2-use crate::domain::course::CourseId;
2+use crate::domain::class_course::ClassCourseId;
33 use crate::domain::monotonic_id::next_uuid;
44 use crate::domain::timestamp::Timestamp;
55 use crate::domain::user::UserId;
@@ -56,7 +56,7 @@ impl SessionTopic {
5656 #[derive(Debug, Clone, sqlx::FromRow)]
5757 pub struct CourseSession {
5858 pub(crate) id: CourseSessionId,
59- pub(crate) course: CourseId,
59+ pub(crate) class_course: ClassCourseId,
6060 /// Who teaches this session. Must hold the `teacher` role or higher —
6161 /// enforced by [`crate::service::course_session::resolve_session_teacher`],
6262 /// where the target user row is at hand.
@@ -71,8 +71,8 @@ impl CourseSession {
7171 &self.id
7272 }
7373
74- pub fn get_course(&self) -> &CourseId {
75- &self.course
74+ pub fn get_class_course(&self) -> &ClassCourseId {
75+ &self.class_course
7676 }
7777
7878 pub fn get_teacher(&self) -> &UserId {
src/domain/dietary_profile.rsmodified+1 -4
@@ -13,7 +13,6 @@
1313 //!
1414 //! [`Settings::get_dietary_tags`]: crate::domain::settings::Settings::get_dietary_tags
1515
16-
1716 use crate::constant::{MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS};
1817 use crate::domain::timestamp::Timestamp;
1918 use crate::domain::user::UserId;
@@ -30,9 +29,7 @@ pub struct DietaryProfileId {
3029
3130 impl DietaryProfileId {
3231 pub fn of(student: &UserId) -> Self {
33- Self {
34- student: *student,
35- }
32+ Self { student: *student }
3633 }
3734
3835 /// The student's wire key, which is the profile's.
src/domain/enrollment.rsmodified+22 -15
@@ -1,34 +1,36 @@
1+use crate::domain::class_course::ClassCourseId;
12 use crate::domain::class_group::ClassGroupId;
2-use crate::domain::course::CourseId;
3+use crate::domain::timestamp::Timestamp;
34 use crate::domain::user::UserId;
45
5-/// The identity of one (course, user) pair. Not a row column: the table's
6+/// The identity of one (instance, user) pair. Not a row column: the table's
67 /// primary key *is* the pair, which is what makes enrolling a single atomic
7-/// UPSERT (`ON CONFLICT (course, app_user)`) with no find-then-insert race
8-/// and one-row-per-pair by construction. This struct's job is the
8+/// UPSERT (`ON CONFLICT (class_course, app_user)`) with no find-then-insert
9+/// race and one-row-per-pair by construction. This struct's job is the
910 /// underscore-joined wire form at the HTTP edge.
1011 #[derive(Debug, Clone, PartialEq, Eq)]
1112 pub struct EnrollmentId {
12- pub(crate) course: CourseId,
13+ pub(crate) class_course: ClassCourseId,
1314 pub(crate) user: UserId,
1415 }
1516
1617 impl EnrollmentId {
17- pub fn composite(course: &CourseId, user: &UserId) -> Self {
18+ pub fn composite(class_course: &ClassCourseId, user: &UserId) -> Self {
1819 Self {
19- course: course.clone(),
20+ class_course: class_course.clone(),
2021 user: *user,
2122 }
2223 }
2324
24- /// The underscore-joined wire form (`{course}_{user}`).
25+ /// The underscore-joined wire form (`{class_course}_{user}`).
2526 pub fn key(&self) -> String {
26- format!("{}_{}", self.course.key(), self.user.key())
27+ format!("{}_{}", self.class_course.key(), self.user.key())
2728 }
2829 }
2930
30-/// A user's membership in a course. Grading requires it; removing it hides the
31-/// user's marks from the report but never deletes result rows.
31+/// A user's membership in one class's instance of a course. Grading requires
32+/// it; removing it hides the user's marks from the report but never deletes
33+/// result rows.
3234 ///
3335 /// `source` names the class ([`crate::domain::class_group::ClassGroup`]) that
3436 /// pumped this row, and is NULL when a human placed the student directly —
@@ -36,21 +38,22 @@ impl EnrollmentId {
3638 /// it: a class sweep may only take back the rows it wrote.
3739 #[derive(Debug, Clone, sqlx::FromRow)]
3840 pub struct Enrollment {
39- pub(crate) course: CourseId,
41+ pub(crate) class_course: ClassCourseId,
4042 #[sqlx(rename = "app_user")]
4143 pub(crate) user: UserId,
4244 pub(crate) enrolled_by: UserId,
4345 pub(crate) source: Option<ClassGroupId>,
46+ pub(crate) created_at: Timestamp,
4447 }
4548
4649 impl Enrollment {
4750 /// The row's identity, built back from its primary-key columns.
4851 pub fn get_id(&self) -> EnrollmentId {
49- EnrollmentId::composite(&self.course, &self.user)
52+ EnrollmentId::composite(&self.class_course, &self.user)
5053 }
5154
52- pub fn get_course(&self) -> &CourseId {
53- &self.course
55+ pub fn get_class_course(&self) -> &ClassCourseId {
56+ &self.class_course
5457 }
5558
5659 pub fn get_user(&self) -> &UserId {
@@ -65,4 +68,8 @@ impl Enrollment {
6568 pub fn get_source(&self) -> Option<&ClassGroupId> {
6669 self.source.as_ref()
6770 }
71+
72+ pub fn get_created_at(&self) -> Timestamp {
73+ self.created_at
74+ }
6875 }
src/domain/exam.rsmodified+10 -4
@@ -1,7 +1,8 @@
11 use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS};
2-use crate::domain::course::CourseId;
2+use crate::domain::class_course::ClassCourseId;
33 use crate::domain::monotonic_id::next_uuid;
44 use crate::domain::settings::ExamKindDef;
5+use crate::domain::term::TermId;
56 use crate::domain::timestamp::Timestamp;
67 use crate::domain::user::UserId;
78 use crate::error::{AppError, ValidationError};
@@ -286,7 +287,8 @@ impl ExamSchedule {
286287 pub struct Exam {
287288 pub(crate) id: ExamId,
288289 pub(crate) creator: UserId,
289- pub(crate) course: CourseId,
290+ pub(crate) class_course: ClassCourseId,
291+ pub(crate) term: TermId,
290292 pub(crate) title: ExamTitle,
291293 pub(crate) description: ExamDescription,
292294 pub(crate) kind: ExamKind,
@@ -311,8 +313,12 @@ impl Exam {
311313 &self.creator
312314 }
313315
314- pub fn get_course(&self) -> &CourseId {
315- &self.course
316+ pub fn get_class_course(&self) -> &ClassCourseId {
317+ &self.class_course
318+ }
319+
320+ pub fn get_term(&self) -> &TermId {
321+ &self.term
316322 }
317323
318324 pub fn get_title(&self) -> &ExamTitle {
src/domain/exam_result.rsmodified+2 -2
@@ -165,8 +165,8 @@ mod tests {
165165 let got = latest_per_pair(vec![
166166 row(user, 1, 60),
167167 row(other, 1, 70),
168- row(user, 2, 85), // retake outranks the seq-1 mark
169- row(other, 3, 40), // third sitting of the second pair
168+ row(user, 2, 85), // retake outranks the seq-1 mark
169+ row(other, 3, 40), // third sitting of the second pair
170170 ]);
171171 assert_eq!(got.len(), 2);
172172 assert_eq!(got[0].get_user(), &user);
src/domain/homework.rsmodified+5 -5
@@ -13,7 +13,7 @@
1313 //! same-course by the web layer, exactly like an exam question's subject.
1414
1515 use crate::constant::{MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN};
16-use crate::domain::course::CourseId;
16+use crate::domain::class_course::ClassCourseId;
1717 use crate::domain::monotonic_id::next_uuid;
1818 use crate::domain::subject::SubjectId;
1919 use crate::domain::timestamp::Timestamp;
@@ -90,7 +90,7 @@ impl HomeworkDescription {
9090 #[derive(Debug, Clone, sqlx::FromRow)]
9191 pub struct Homework {
9292 pub(crate) id: HomeworkId,
93- pub(crate) course: CourseId,
93+ pub(crate) class_course: ClassCourseId,
9494 pub(crate) subject: SubjectId,
9595 pub(crate) title: HomeworkTitle,
9696 pub(crate) description: Option<HomeworkDescription>,
@@ -105,8 +105,8 @@ impl Homework {
105105 &self.id
106106 }
107107
108- pub fn get_course(&self) -> &CourseId {
109- &self.course
108+ pub fn get_class_course(&self) -> &ClassCourseId {
109+ &self.class_course
110110 }
111111
112112 pub fn get_subject(&self) -> &SubjectId {
@@ -177,7 +177,7 @@ mod tests {
177177 let b = UserId::from_key(B);
178178 let with = |assigned| Homework {
179179 id: HomeworkId::generate(),
180- course: CourseId::from_key("0198f1a2-3b4c-7d5e-8f90-cccc3c4d5e6f"),
180+ class_course: ClassCourseId::from_key("0198f1a2-3b4c-7d5e-8f90-cccc3c4d5e6f"),
181181 subject: SubjectId::from_key("0198f1a2-3b4c-7d5e-8f90-dddd4c4d5e6f"),
182182 title: HomeworkTitle::try_new("hw").unwrap(),
183183 description: None,
src/domain/key.rsmodified+8 -2
@@ -40,7 +40,10 @@ mod tests {
4040 #[test]
4141 fn a_slot_key_never_collides_with_the_illustration() {
4242 assert_eq!(slot(QUESTION, None), format!("{QUESTION}_q"));
43- assert_eq!(slot(QUESTION, Some(STUDENT)), format!("{QUESTION}_{STUDENT}"));
43+ assert_eq!(
44+ slot(QUESTION, Some(STUDENT)),
45+ format!("{QUESTION}_{STUDENT}")
46+ );
4447 // A choice id is a UUID, so it can never be the literal "q".
4548 assert_ne!(slot(QUESTION, Some(STUDENT)), slot(QUESTION, None));
4649 }
@@ -49,7 +52,10 @@ mod tests {
4952 fn the_first_sitting_stays_bare_and_later_ones_are_numbered() {
5053 // Byte-for-byte the shape the four sitting-keyed tables wrote before
5154 // this helper existed; a pre-history row is keyed by the bare pair.
52- assert_eq!(sitting(QUESTION, STUDENT, 1), format!("{QUESTION}_{STUDENT}"));
55+ assert_eq!(
56+ sitting(QUESTION, STUDENT, 1),
57+ format!("{QUESTION}_{STUDENT}")
58+ );
5359 assert_eq!(
5460 sitting(QUESTION, STUDENT, 2),
5561 format!("{QUESTION}_{STUDENT}_2")
src/domain/meal_ledger.rsmodified+2 -5
@@ -319,11 +319,8 @@ impl MealLedger {
319319 recorded_by: &UserId,
320320 ) -> Option<(MealLedgerId, MealLedger)> {
321321 let amount = booking.get_price_minor()?;
322- let charge = MealLedgerId::for_attempt(
323- &booking.id(),
324- booking.get_attempt(),
325- MealLedgerKind::Charge,
326- );
322+ let charge =
323+ MealLedgerId::for_attempt(&booking.id(), booking.get_attempt(), MealLedgerKind::Charge);
327324 let line = MealLedger {
328325 id: MealLedgerId::for_attempt(
329326 &booking.id(),
src/domain/message.rsmodified+2 -2
@@ -2,8 +2,8 @@ use sqlx::Type;
22 use uuid::Uuid;
33
44 use crate::constant::{
5- MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN,
6- RECIPIENT_FOLDERS, SENDER_FOLDERS,
5+ MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, RECIPIENT_FOLDERS,
6+ SENDER_FOLDERS,
77 };
88 use crate::domain::monotonic_id::next_uuid;
99 use crate::domain::timestamp::Timestamp;
src/domain/mod.rsmodified+3 -1
@@ -4,6 +4,7 @@
44 //! newtypes derive `sqlx::Type` so a column reads straight into the validated
55 //! wrapper.
66
7+pub mod academic_year;
78 pub mod answer_image;
89 pub mod appointment;
910 pub mod appointment_slot;
@@ -21,6 +22,7 @@ pub mod class_course;
2122 pub mod class_group;
2223 pub mod class_member;
2324 pub mod course;
25+pub mod course_membership;
2426 pub mod course_note;
2527 pub mod course_note_file;
2628 pub mod course_session;
@@ -50,6 +52,7 @@ pub mod note;
5052 pub mod note_file;
5153 pub mod parent_link;
5254 pub mod payment_ledger;
55+pub mod person;
5356 pub mod pomodoro;
5457 pub mod pool_question;
5558 pub mod pool_question_image;
@@ -58,7 +61,6 @@ pub mod profile;
5861 pub mod question_image;
5962 pub mod rag_output;
6063 pub mod registration;
61-pub mod person;
6264 pub mod role;
6365 pub mod session;
6466 pub mod session_attendance;
src/domain/payment_ledger.rsmodified+2 -1
@@ -332,7 +332,8 @@ mod tests {
332332 fn a_charge_key_is_the_plan_the_student_and_the_installment() {
333333 const PLAN: &str = "018f1a00-0000-7000-8000-000000000001";
334334 const STU: &str = "018f1a00-0000-7000-8000-000000000002";
335- let assignment = FeePlanAssignmentId::composite(&FeePlanId::from_key(PLAN), &UserId::from_key(STU));
335+ let assignment =
336+ FeePlanAssignmentId::composite(&FeePlanId::from_key(PLAN), &UserId::from_key(STU));
336337 let first = PaymentLedgerId::for_installment(&assignment, 1);
337338 assert_eq!(first.key(), format!("{PLAN}_{STU}_c1"));
338339 assert_eq!(
src/domain/pool_question.rsmodified+0 -1
@@ -145,4 +145,3 @@ impl PoolQuestion {
145145 self.approved_by.as_ref()
146146 }
147147 }
148-
src/domain/question_image.rsmodified+4 -1
@@ -40,7 +40,10 @@ impl QuestionImageId {
4040 /// The wire form, `None` spelled with the `"q"` sentinel — the same
4141 /// spelling the stored key uses.
4242 pub fn key(&self) -> String {
43- crate::domain::key::slot(&self.question.key(), self.slot.as_ref().map(|id| id.as_str()))
43+ crate::domain::key::slot(
44+ &self.question.key(),
45+ self.slot.as_ref().map(|id| id.as_str()),
46+ )
4447 }
4548
4649 pub fn question(&self) -> &ExamQuestionId {
src/domain/role.rsmodified+8 -1
@@ -174,7 +174,14 @@ mod tests {
174174 // never drifts from `as_str` — the CHECK constraint and the filters
175175 // spell these same words.
176176 let mut buf = sqlx::postgres::PgArgumentBuffer::default();
177- for role in [Role::Ai, Role::Parent, Role::Student, Role::Teacher, Role::Manager, Role::Admin] {
177+ for role in [
178+ Role::Ai,
179+ Role::Parent,
180+ Role::Student,
181+ Role::Teacher,
182+ Role::Manager,
183+ Role::Admin,
184+ ] {
178185 buf.clear();
179186 let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&role, &mut buf).unwrap();
180187 assert_eq!(std::str::from_utf8(&buf).unwrap(), role.as_str());
src/domain/session_attendance.rsmodified+7 -7
@@ -1,5 +1,5 @@
11 use crate::domain::attendance::AttendanceStatus;
2-use crate::domain::course::CourseId;
2+use crate::domain::class_course::ClassCourseId;
33 use crate::domain::course_session::CourseSessionId;
44 use crate::domain::user::UserId;
55
@@ -63,13 +63,13 @@ pub(crate) fn counts_as_attended(status: &AttendanceStatus) -> bool {
6363 matches!(status.as_str(), "present" | "late")
6464 }
6565
66-/// One person's roll-call state for one lesson. `course` is denormalized from
67-/// the session so the per-course attendance report is a single indexed query
68-/// (`WHERE app_user = $u`) with no join.
66+/// One person's roll-call state for one lesson. `class_course` is
67+/// denormalized from the session so the per-instance attendance report is a
68+/// single indexed query (`WHERE app_user = $u`) with no join.
6969 #[derive(Debug, Clone, sqlx::FromRow)]
7070 pub struct SessionAttendance {
7171 pub(crate) session: CourseSessionId,
72- pub(crate) course: CourseId,
72+ pub(crate) class_course: ClassCourseId,
7373 #[sqlx(rename = "app_user")]
7474 pub(crate) user: UserId,
7575 pub(crate) status: AttendanceStatus,
@@ -81,8 +81,8 @@ impl SessionAttendance {
8181 &self.session
8282 }
8383
84- pub fn get_course(&self) -> &CourseId {
85- &self.course
84+ pub fn get_class_course(&self) -> &ClassCourseId {
85+ &self.class_course
8686 }
8787
8888 pub fn get_user(&self) -> &UserId {
src/domain/settings.rsmodified+136 -11
@@ -16,13 +16,13 @@ use sqlx::types::Json;
1616
1717 use crate::constant::{
1818 DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS,
19- DEFAULT_EXAM_KINDS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_CHATBOT_THREADS,
20- DEFAULT_MAX_FILE_BYTES, DEFAULT_MEAL_SLOTS, MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT,
21- MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN,
22- MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES,
23- MAX_MEAL_SERVING_MINUTE, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN,
24- MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN,
25- MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES,
19+ DEFAULT_EXAM_KINDS, DEFAULT_GRADE_BANDS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN,
20+ DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_FILE_BYTES, DEFAULT_MEAL_SLOTS, DEFAULT_TIMEZONE,
21+ MAX_ABSENCE_DAYS, MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS,
22+ MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN, MAX_MAX_CHATBOT_THREADS,
23+ MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES, MAX_MEAL_SERVING_MINUTE,
24+ MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT,
25+ MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, TIMEZONES,
2626 };
2727 use crate::domain::text_fold;
2828 use crate::error::ValidationError;
@@ -215,6 +215,21 @@ pub struct Settings {
215215 /// for both deadlines; `None` = no cutoff at all, which is also what an
216216 /// unset column reads as.
217217 pub(crate) meal_cancel_cutoff_minutes: Option<i64>,
218+ /// Öğretmen branş lists (D6): the school's subject specialisations a
219+ /// teacher profile may name. `None`-while-unset; an empty list is legal
220+ /// (a school that never configured branş).
221+ pub(crate) branches: Option<Json<Vec<String>>>,
222+ /// What an absence may be excused as (raporlu/izinli/…): the vocabulary
223+ /// pointed at by an excused roll-call row. `None`-while-unset, like
224+ /// `branches`.
225+ pub(crate) excuse_kinds: Option<Json<Vec<String>>>,
226+ /// Devamsızlık policy (D7): the per-dönem excused/unexcused day limits a
227+ /// student may exceed. `None` = no limit configured.
228+ pub(crate) max_excused_absent_days: Option<i64>,
229+ pub(crate) max_unexcused_absent_days: Option<i64>,
230+ /// The school's IANA timezone, used to bucket attendance days. `None`
231+ /// reads as [`crate::constant::DEFAULT_TIMEZONE`].
232+ pub(crate) timezone: Option<String>,
218233 }
219234
220235 /// Everything [`Settings::try_new`] validates, in one struct — the knobs
@@ -233,6 +248,13 @@ pub struct SettingsParams {
233248 pub dietary_tags: Vec<String>,
234249 /// `None` = no booking/cancel cutoff.
235250 pub meal_cancel_cutoff_minutes: Option<i64>,
251+ pub branches: Vec<String>,
252+ pub excuse_kinds: Vec<String>,
253+ /// `None` = no limit configured.
254+ pub max_excused_absent_days: Option<i64>,
255+ pub max_unexcused_absent_days: Option<i64>,
256+ /// `None` = the deployment default timezone.
257+ pub timezone: Option<String>,
236258 }
237259
238260 impl Settings {
@@ -253,7 +275,14 @@ impl Settings {
253275 statuses.sort();
254276 statuses
255277 },
256- grade_bands: Json(Vec::new()),
278+ grade_bands: Json(
279+ DEFAULT_GRADE_BANDS
280+ .map(|(min, label)| GradeBand {
281+ min,
282+ label: label.to_string(),
283+ })
284+ .to_vec(),
285+ ),
257286 max_file_bytes: None,
258287 chatbot_history_turns: None,
259288 max_chatbot_threads: None,
@@ -261,6 +290,11 @@ impl Settings {
261290 meal_slots: None,
262291 dietary_tags: None,
263292 meal_cancel_cutoff_minutes: None,
293+ branches: None,
294+ excuse_kinds: None,
295+ max_excused_absent_days: None,
296+ max_unexcused_absent_days: None,
297+ timezone: None,
264298 }
265299 }
266300
@@ -278,6 +312,11 @@ impl Settings {
278312 meal_slots: self.get_meal_slots(),
279313 dietary_tags: self.get_dietary_tags(),
280314 meal_cancel_cutoff_minutes: self.meal_cancel_cutoff_minutes,
315+ branches: self.get_branches(),
316+ excuse_kinds: self.get_excuse_kinds(),
317+ max_excused_absent_days: self.max_excused_absent_days,
318+ max_unexcused_absent_days: self.max_unexcused_absent_days,
319+ timezone: self.timezone.clone(),
281320 }
282321 }
283322
@@ -301,6 +340,11 @@ impl Settings {
301340 meal_slots,
302341 dietary_tags,
303342 meal_cancel_cutoff_minutes,
343+ branches,
344+ excuse_kinds,
345+ max_excused_absent_days,
346+ max_unexcused_absent_days,
347+ timezone,
304348 } = params;
305349 in_range(
306350 "max_file_bytes",
@@ -395,6 +439,41 @@ impl Settings {
395439 )?;
396440 }
397441
442+ // Branş and excuse-kind lists follow the same rules as the kinds and
443+ // statuses above, but empty is legal on both — a school that never
444+ // configured either is not forced to invent one.
445+ let branches = if branches.is_empty() {
446+ branches
447+ } else {
448+ validate_list("branches", branches)?
449+ };
450+ let excuse_kinds = if excuse_kinds.is_empty() {
451+ excuse_kinds
452+ } else {
453+ validate_list("excuse_kinds", excuse_kinds)?
454+ };
455+ for (field, value) in [
456+ ("max_excused_absent_days", max_excused_absent_days),
457+ ("max_unexcused_absent_days", max_unexcused_absent_days),
458+ ] {
459+ if let Some(days) = value {
460+ in_range(
461+ field,
462+ days,
463+ 0..=MAX_ABSENCE_DAYS,
464+ "must be between 0 and 365 days",
465+ )?;
466+ }
467+ }
468+ if let Some(tz) = timezone.as_deref()
469+ && !TIMEZONES.contains(&tz)
470+ {
471+ return Err(ValidationError::Invalid {
472+ field: "timezone",
473+ reason: "is not a supported timezone (see GET /limits)",
474+ });
475+ }
476+
398477 Ok(Self {
399478 exam_kinds: Json(exam_kinds),
400479 attendance_statuses,
@@ -406,6 +485,11 @@ impl Settings {
406485 meal_slots: Some(Json(meal_slots)),
407486 dietary_tags: Some(dietary_tags),
408487 meal_cancel_cutoff_minutes,
488+ branches: Some(Json(branches)),
489+ excuse_kinds: Some(Json(excuse_kinds)),
490+ max_excused_absent_days,
491+ max_unexcused_absent_days,
492+ timezone,
409493 })
410494 }
411495
@@ -496,6 +580,39 @@ impl Settings {
496580 self.meal_cancel_cutoff_minutes
497581 }
498582
583+ /// The branş (subject specialisation) vocabulary a teacher profile may
584+ /// name; empty while the school never configured one.
585+ pub fn get_branches(&self) -> Vec<String> {
586+ self.branches
587+ .as_ref()
588+ .map(|list| list.0.clone())
589+ .unwrap_or_default()
590+ }
591+
592+ /// The excuse-kind vocabulary an excused absence may name; empty while the
593+ /// school never configured one.
594+ pub fn get_excuse_kinds(&self) -> Vec<String> {
595+ self.excuse_kinds
596+ .as_ref()
597+ .map(|list| list.0.clone())
598+ .unwrap_or_default()
599+ }
600+
601+ /// The per-dönem excused-absence day limit; `None` = no limit configured.
602+ pub fn get_max_excused_absent_days(&self) -> Option<i64> {
603+ self.max_excused_absent_days
604+ }
605+
606+ /// The per-dönem unexcused-absence day limit; `None` = no limit configured.
607+ pub fn get_max_unexcused_absent_days(&self) -> Option<i64> {
608+ self.max_unexcused_absent_days
609+ }
610+
611+ /// The school's IANA timezone; the deployment default while unset.
612+ pub fn get_timezone(&self) -> &str {
613+ self.timezone.as_deref().unwrap_or(DEFAULT_TIMEZONE)
614+ }
615+
499616 /// The label of the band `mark` falls into: the band with the greatest
500617 /// `min` at or below it. `None` when no bands are configured. Takes an
501618 /// `f64` so course averages label the same way plain marks do.
@@ -600,7 +717,10 @@ mod tests {
600717 let defaults = Settings::defaults();
601718 let rebuilt = Settings::try_new(defaults.params()).unwrap();
602719 assert_eq!(rebuilt.get_exam_kinds(), defaults.get_exam_kinds());
603- assert!(defaults.get_grade_bands().is_empty());
720+ // The Türkiye 5-point scale ships by default, so a mark always labels.
721+ assert_eq!(defaults.get_grade_bands().len(), DEFAULT_GRADE_BANDS.len());
722+ assert_eq!(defaults.grade_label(90.0), Some("5"));
723+ assert_eq!(defaults.grade_label(0.0), Some("1"));
604724 }
605725
606726 #[tokio::test]
@@ -846,7 +966,12 @@ mod tests {
846966 assert_eq!(s.grade_label(84.9), Some("CC"));
847967 assert_eq!(s.grade_label(85.0), Some("AA"));
848968 assert_eq!(s.grade_label(100.0), Some("AA"));
849- // No bands configured → no label, never a panic.
850- assert_eq!(Settings::defaults().grade_label(90.0), None);
969+ // With no bands configured there is no label, never a panic.
970+ let bare = Settings::try_new(SettingsParams {
971+ grade_bands: vec![],
972+ ..params()
973+ })
974+ .unwrap();
975+ assert_eq!(bare.grade_label(90.0), None);
851976 }
852977 }
src/domain/solution.rsmodified+0 -1
@@ -97,7 +97,6 @@ impl Solution {
9797 pub fn get_offered_at(&self) -> Timestamp {
9898 self.offered_at
9999 }
100-
101100 }
102101
103102 #[cfg(test)]
src/domain/term.rsmodified+7 -0
@@ -2,6 +2,7 @@ use sqlx::Type;
22 use uuid::Uuid;
33
44 use crate::constant::MAX_TERM_NAME_LEN;
5+use crate::domain::academic_year::AcademicYearId;
56 use crate::domain::monotonic_id::next_uuid;
67 use crate::domain::timestamp::Timestamp;
78 use crate::error::{AppError, ValidationError};
@@ -92,6 +93,8 @@ impl TermName {
9293 #[derive(Debug, Clone, sqlx::FromRow)]
9394 pub struct Term {
9495 pub(crate) id: TermId,
96+ /// The academic year this dönem is a grading slice of.
97+ pub(crate) year: AcademicYearId,
9598 pub(crate) name: TermName,
9699 pub(crate) starts_at: Timestamp,
97100 pub(crate) ends_at: Timestamp,
@@ -106,6 +109,10 @@ impl Term {
106109 &self.id
107110 }
108111
112+ pub fn get_year(&self) -> &AcademicYearId {
113+ &self.year
114+ }
115+
109116 pub fn get_name(&self) -> &TermName {
110117 &self.name
111118 }
src/domain/text_fold.rsmodified+1 -2
@@ -118,8 +118,7 @@ mod tests {
118118 let sql = search_fold_sql("name");
119119 for (from, to) in TEXT_FOLD_REPLACEMENTS {
120120 assert!(
121- sql.contains(&"replace(".to_string())
122- && sql.contains(&format!("'{from}', '{to}'")),
121+ sql.contains(&"replace(".to_string()) && sql.contains(&format!("'{from}', '{to}'")),
123122 "rule {from} -> {to} missing from the emitted expression"
124123 );
125124 assert_eq!(search_fold(from), *to);
src/domain/timestamp.rsmodified+14 -2
@@ -29,7 +29,18 @@ pub(crate) fn range_error() -> AppError {
2929 /// A unix-millisecond instant (UTC by construction). Stored as a `BIGINT`.
3030 /// Also serializes as its bare number: the fee plan's installments ride the
3131 /// row as JSON, and a due date must stay a plain millisecond count there too.
32-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, sqlx::Type, serde::Serialize, serde::Deserialize)]
32+#[derive(
33+ Debug,
34+ Clone,
35+ Copy,
36+ PartialEq,
37+ Eq,
38+ PartialOrd,
39+ Ord,
40+ sqlx::Type,
41+ serde::Serialize,
42+ serde::Deserialize,
43+)]
3344 #[sqlx(transparent)]
3445 pub struct Timestamp(i64);
3546
@@ -172,7 +183,8 @@ mod tests {
172183 serde_json::to_value(Timestamp::from_millis(1_700_000_000_000)).unwrap(),
173184 serde_json::json!(1_700_000_000_000i64)
174185 );
175- let back: Timestamp = serde_json::from_value(serde_json::json!(1_700_000_000_000i64)).unwrap();
186+ let back: Timestamp =
187+ serde_json::from_value(serde_json::json!(1_700_000_000_000i64)).unwrap();
176188 assert_eq!(back.as_millis(), 1_700_000_000_000);
177189 }
178190 }
src/domain/user.rsmodified+11 -0
@@ -233,6 +233,10 @@ pub struct User {
233233 // type and size live on the row.
234234 pub(crate) display_name: Option<DisplayName>,
235235 pub(crate) bio: Option<Bio>,
236+ /// The staff member's branş (subject area), free text validated against
237+ /// the school's own `Settings::get_branches()` list at the web layer —
238+ /// optional like every other profile field, and clearable.
239+ pub(crate) branch: Option<String>,
236240 pub(crate) avatar_file: Option<String>,
237241 pub(crate) avatar_content_type: Option<FileContentType>,
238242 pub(crate) avatar_size: Option<i64>,
@@ -262,6 +266,7 @@ impl User {
262266 palette_color: None,
263267 display_name: None,
264268 bio: None,
269+ branch: None,
265270 avatar_file: None,
266271 avatar_content_type: None,
267272 avatar_size: None,
@@ -323,6 +328,12 @@ impl User {
323328 self.bio.as_ref()
324329 }
325330
331+ /// The staff member's branş, as stored (free text; membership in the
332+ /// school's list is the write path's check, not this read's).
333+ pub fn get_branch(&self) -> Option<&str> {
334+ self.branch.as_deref()
335+ }
336+
326337 pub fn get_avatar_file(&self) -> Option<&str> {
327338 self.avatar_file.as_deref()
328339 }
src/error.rsmodified+4 -4
@@ -115,7 +115,6 @@ pub enum AppError {
115115 Internal(String),
116116 }
117117
118-
119118 impl From<sqlx::Error> for AppError {
120119 fn from(e: sqlx::Error) -> Self {
121120 match e {
@@ -289,7 +288,6 @@ impl AppError {
289288 mod tests {
290289 use super::*;
291290
292-
293291 /// The refusal a gated nest answers with. Both keys, and the `403` — a
294292 /// client switches on `module`, so neither may drift.
295293 #[tokio::test]
@@ -327,7 +325,9 @@ mod tests {
327325 let io = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "gone");
328326 assert!(matches!(AppError::from(Error::Io(io)), AppError::DbTimeout));
329327 // A query that found no row is the caller's 404, never a 500.
330- assert!(matches!(AppError::from(Error::RowNotFound), AppError::NotFound));
328+ assert!(matches!(
329+ AppError::from(Error::RowNotFound),
330+ AppError::NotFound
331+ ));
331332 }
332-
333333 }
src/lib.rsmodified+38 -20
@@ -61,24 +61,26 @@ use crate::web::module_gate::gate;
6161 (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),
6262 (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused. The bookable list carries each slot's teacher identity (id, username, display name) to every caller, parents included — deliberate, since a conference cannot be booked from an anonymous calendar; it is the staff directory for booking, narrowed to whoever published bookable time, and the direct people routes stay closed to a parent"),
6363 (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"),
64- (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"),
65- (name = "course-notes", description = "Notes a teacher attaches to a course — announcements, recaps, anything worth pinning to the class rather than to one student — with file attachments, mirroring the personal `notes` stack. Writing (create, edit, delete, upload, delete a file) requires teacher+ and management rights over the course (its creator, an assigned teacher, or a manager/admin); reading (`GET /course-notes/{id}`, listing, downloading) is open to anyone who can view the course — its enrolled users plus whoever can manage it. `GET /course-notes` requires `?course=` and lists that course's notes only, newest first. At most 10 files per note, each at most the school's `max_file_bytes`. `GET /course-notes/{id}/rag` serves what the backend's `rag.index` AI service produced for a note — an index or summary, stored verbatim and unread by this side — to anyone who can view the course; `DELETE /course-notes/{id}/rag/{output_id}` drops one, and needs the same management rights as any other write. Outputs are derived data: deleting one does not suppress anything, and the next edit to the note or its files may regenerate it."),
66- (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry — unpaged, since the set is the şube one school runs at one grade — because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and `missing` only ever names courses that still exist: deleting a course takes its id out of every blueprint holding it, in the same cascade that detaches it from the sections, so no template is left naming a course that is gone (which used to be permanent at a grade with no sections, and made the re-`PATCH` below a `400`). Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached — they still carry that blueprint's tag, so dropping one from that template still detaches them — and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `blueprint_deleted`), like every other enum here. The **manual** attaches answer that same vocabulary, each route with its own set: a `409` from `POST /classes/{id}/courses` carries `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` or `course_full`, and one from `POST /classes/{id}/members` carries `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full` or `linked_course_missing`. The three *deleted* codes are a pump's alone — on a manual attach a deleted class or course is a `404`, never a `409` — and the ceiling pair differs by route because the ceilings do: a member add is refused by a full roster (`class_at_roster_ceiling`) or by a course list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both. `duplicate` (already attached / already a member) is a refusal on either route, and no skip for a pump, which asked for a row that is already in place; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet, since it is the one attach that walks the section's existing course links while a pump attaches a course it has just proved alive. No other route publishes a `code`, and the field is simply absent where it does not. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list — the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"),
64+ (name = "courses", description = "The course **catalog**: the school's reusable rows — kind `course` (a regular ders), `study` (etüt, a supervised study session) or `club` (kulüp) — with their curriculum subjects (`/courses/{id}/subjects`). A catalog row teaches nobody by itself: a ders is taught by attaching it to a şube, which mints an instance (`POST /classes/{id}/instances`), and everything a class actually runs — roster, teachers, exams, lessons, homework — belongs to that instance (`GET /instances/{id}`). An etüt or kulüp has no şube at all: it is joined school-wide (`POST /courses/{id}/members`, students only), and a `course`-kind ders refuses that door with a `400` — its students come through its instances. Catalog rights are the office's and the row's creator: edit, delete, its subjects and its member list all need the creator or manager+, and a row still taught anywhere (any instance, any member) cannot be deleted (`409`). `GET /courses/me` is what a caller is reached by, both tiers together; the instances themselves are `GET /instances/me`."),
65+ (name = "instances", description = "One catalog course **as one şube teaches it** — the instance, and the anchor everything academic hangs off. Attaching a course to a class (`POST /classes/{id}/instances`) mints one; two şubeler teaching the same course are two instances with their own roster, teachers, exams, lessons and homework. The row carries the instance's own policy: `ders_saati` (weekly lesson hours — the weight the instance takes in the year's karne average) and `counts_toward_karne`. Acting on an instance (`PATCH`, its rosters, its exams/sessions/homework, its roll-call) is open to manager+, to a teacher assigned to that instance (`POST /instances/{id}/teachers`, manager+) and to the şube's homeroom teacher — one rule, applied by every route here. `GET /instances/me` is a student's own list: the instances of the şubeler they are a live member of."),
66+ (name = "course-notes", description = "Notes a teacher attaches to a **catalog course** — announcements, recaps, anything worth pinning to the course rather than to one student — with file attachments, mirroring the personal `notes` stack. Writing (create, edit, delete, upload, delete a file) requires teacher+ and catalog rights over the course (its creator, or a manager/admin); reading (`GET /course-notes/{id}`, listing, downloading) is open to anyone the course reaches — a student enrolled in one of its instances, a member of it, its creator, or a manager/admin. `GET /course-notes` requires `?course=` and lists that course's notes only, newest first. At most 10 files per note, each at most the school's `max_file_bytes`. `GET /course-notes/{id}/rag` serves what the backend indexed for the AI features, and is derived data: deleting it suppresses nothing, and the next edit to the note or its files may regenerate it."),
67+ (name = "classes", description = "Class sections (şube): a named set of students the school moves as one, sitting in an academic year (`year`; a şube with no year takes no exam and is never rolled over). A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every instance the class carries, and attaching a course (`POST /classes/{id}/instances`) mints the class×course **instance** and enrolls the whole roster into it, the rows written being ordinary enrollments tagged with the şube that pumped them (a row with no such tag was placed by hand, and no sweep takes it back). A student already enrolled by hand keeps their own row. Removing a member is a **soft** leave: the stint is stamped `left_at` and the live-member counter comes down, but the row stays as the section's history — re-adding the same student is a fresh stint, so a pair may hold two rows, one live. `DELETE /classes/{id}/instances/{instance}` takes the whole instance with it — exams, homework, sessions, the roster it pumped, its teacher links — and unlinks the uploaded files those rows named. A homeroom teacher (`teacher_id`, sınıf öğretmeni) may act on every instance of their section; the class itself is the office's (manager+). Refusals carry a machine `code` beside the prose where two routes share one vocabulary: a member add is refused by a full roster (`class_at_roster_ceiling`) or by an instance list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both (`class_at_course_ceiling`, `class_roster_too_large`); `duplicate` is a refusal on either manual route; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet. Grade blueprints (`/classes/blueprints`) are the template side: a manager+ writes the courses every section of a grade takes, and the pump that stocks a section from it is idempotent and best-effort — the courses that did not fit come back in `skipped` with those codes, and `blueprint_deleted`/`class_deleted`/`course_deleted` report a row that vanished mid-pump."),
6768 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher). Roll call is also what feeds two badge counters (see `users`): the first mark taken for a lesson **at or after its own `starts_at`** credits its teacher's `lessons_held_total` once — a sheet opened early is never refused, it simply holds nothing until the bell — and a student marked `present` or `late` gains a `lessons_attended_total` a later correction gives back"),
6869 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
6970 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints. A finished stint answers `counted`: whether it moved the lifetime counters the badges and the study streak read, which it does when it ran at least `pomodoro.min_counted_ms` and is within that UTC day's `pomodoro.max_counted_per_day` (both on `GET /limits`, both compiled in). A stint that counts for nothing is still recorded, still listed and still sums into `total_focus_ms` — the rule bounds what counts, never what is kept, and it exists because finishing is self-service: two requests, no second person and no elapsed time, so a counter moved once per round-trip is farmable and a badge is never revoked"),
7071 (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)"),
7172 (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 = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
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"),
7374 (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"),
7475 (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"),
7576 (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 = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
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"),
7778 (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and a slot with no serving minute carries **no cutoff at all** rather than one counted from midnight) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"),
78- (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),
79- (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks), and the ones it does name get its `assigned` list narrowed to their own id — who else was assigned is roster information, and the roster is teacher+-only; a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"),
79+ (name = "subjects", description = "A **catalog** course's curriculum topics (Matematik's \"Üslü sayılar\", not one şube's lesson plan). Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question of every instance teaching that course links to one of them, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (anyone it reaches, its creator, manager+); edit follows catalog rights (its creator or a manager/admin)."),
80+ (name = "homework", description = "Instance homework: a teacher assigns it per class×course instance (`POST /instances/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks), and the ones it does name get its `assigned` list narrowed to their own id — who else was assigned is roster information, and the roster is teacher+-only; a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"),
8081 (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. `GET /boards` takes `?open=true|false` to narrow the list by the closing stamp (`total` counts the filtered list) — a closed board is never deleted, so this is how a creator holding many boards trims the retired ones out of sight. It filters `closed_at` and nothing else: a **locked** board, and one that has spent its lifetime stroke budget but was never drawn on again, are both still open, because the stamp is written only by `/close` or by the append the lifetime cap refuses. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) — so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there — taken off the roster, or demoted below `student` — is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion below `student` also sweeps that account off every roster it was on, and the rosters an older binary left behind were repaired at boot: a board written before that sweep can name a parent, or a user since deleted, and every such id is stripped the first time this binary starts. A board whose *creator* was demoted is **closed** by that same write: barred to them, still fully readable to everyone else, and refusing every write with the terminal `board_closed` — because clearing, locking, closing and deleting are the creator's alone and nothing lists a board the caller is not on, so a room whose creator was demoted could be ended by nobody at all while its participants kept drawing on it. Nothing is deleted (the marks are the participants' work too) and the seat it holds on `max_boards_per_creator` stays taken, exactly as a manually closed board's does. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch — drawn marks only, never a `clear` marker, exactly as the room's socket replays it, so the REST catch-up and the live canvas can never disagree, `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board and the **locked** one — the pause the creator set holds against their own clear too, so a locked board sitting at `max_epoch_strokes` is recovered by unlock, clear, relock — since the marker is a stored row charged to the lifetime cap), each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. Closing and locking are independent, and a board holding both flags answers **closed** everywhere — a stroke, a socket `clear` and `POST /boards/{id}/clear` all report the terminal state, never the pause, because the pause can never lift. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). `POST /boards/{id}/invite` fills that roster from a group that already exists rather than one id at a time — `{kind:\"class\", class}` for a class section (şube), `{kind:\"course\", course}` for a course's enrolled students (clubs and study groups *are* courses, so this is how a whole club is invited), `{kind:\"event\", event}` for an event's expected-attendee roster exactly as `GET /events/{id}/roster` resolves it. It is the creator's alone and strictly **additive** — nothing is ever removed by it, removal stays `PATCH` — and it resolves **once**, at the call: a board holds a flat list of ids and no memory of where they came from, so a student who joins that class tomorrow is not on today's board, and re-inviting the same source is how a roster is topped up (idempotent when nothing changed). Ineligible members are dropped silently rather than failing the call for everyone else — ids that no longer resolve to a user, and anyone below `student`, which is the same cut that keeps `parent` off a whiteboard — but the participant cap is **all-or-nothing**: an invite that would carry the board past `max_participants` is refused with a `409` naming both numbers, and nobody is added. Since a board's roster is visible to every participant, inviting a group *discloses* that group's membership, so each source carries the gate its own listing route already carries: teacher+ for a class, the course's creator/assigned teacher/manager+ for a course, teacher+ for an event. A student may still build a board one id at a time; they cannot pour a class roster into one. Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"),
81- (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses and classes may link to one. A term still linked by any course or class cannot be deleted (409) — unlink them first. A finished year is closed with `POST /terms/{id}/archive` (manager+), reopened with `POST /terms/{id}/unarchive`; both are idempotent — archiving an already-archived term answers 200 with the original `archived_at` stamp, and unarchiving an open one answers 200 too. An archived term is read-only: `PATCH`/`DELETE /terms/{id}` and linking a new course or class to it are refused, as is every write to a course or class already on it and to everything hanging off them — enrollment, teacher assignment, class membership and homeroom, class↔course attach/detach and blueprint apply, sessions and roll call, subjects, exams with their questions, images, attempts and answers, marks and grading, homework and submissions, course notes and files — each with `409` and `code: \"term_archived\"` (\"this term is archived — past years are read-only\"). Reads stay open throughout, and unarchiving restores writes. Read: any authenticated user; edit: manager+"),
82+ (name = "academic-years", description = "The calendar above the dönemler. A year (`POST /academic-years`, manager+) holds the şubeler and the sınıf-geçme policy (`grade_promotions`) that `POST /academic-years/{id}/rollover` applies: each şube of the source year whose grade the target promotes is planted afresh there — same name, mapped grade, copies of its instances (same courses, `ders_saati`, karne policy), their assigned teachers and every live member, who are also enrolled into the new instances. A grade the policy does not name is not carried over: that is how graduation is expressed, and `graduated` reports it. The target year must still be empty (a second rollover into it is `409`, which is what makes the command idempotent), open, and different from the source. An archived year is read-only — no new şube, no new dönem, no new exam inside it — and a year still linked by any şube or dönem cannot be deleted (`409`). `GET` is teacher+, every write manager+."),
83+ (name = "terms", description = "Academic terms (dönem: semester/trimester/quarter — whatever the school runs), each a grading slice **inside an academic year** (`year`, required; `GET /academic-years`). Exams name one — that is the dönem whose karne their marks count into — and `?term=` on `/marks/karne` picks one. A dönem still holding an exam or a frozen karne cannot be deleted (`409`). `POST /terms/{id}/archive` (manager+) **freezes the karnes**: every student with a roster row under the dönem's year gets a snapshot of their report, and from then on the karne route serves that record instead of recomputing, so a mark corrected later never rewrites what a family holds; `POST /terms/{id}/unarchive` re-opens it. Both are idempotent — a second archive answers 200 with the original stamp and never re-freezes. An archived dönem is read-only (`PATCH`/`DELETE` refused, no new exam); creating an exam inside it stays allowed while its *year* is open, because the archive is a record and not a wall. An archived **year** is what refuses new structure: şubeler, dönemler, and every write to either."),
8284 ),
8385 )]
8486 struct ApiDoc;
@@ -98,28 +100,42 @@ impl Modify for SecurityAddon {
98100 }
99101 }
100102
101-/// `/courses` and the four foreign-module route pairs mounted inside it. The
102-/// children carry their own module's gate *and*, through the outer one applied
103-/// here, the course gate — so either module being off refuses them.
103+/// `/courses` and the foreign-module route pair mounted inside it. The child
104+/// carries its own module's gate *and*, through the outer one applied here, the
105+/// course gate — so either module being off refuses it.
106+///
107+/// The other three pairs that used to live here (exams, sessions, homework)
108+/// moved to `/instances/{id}/...`, because they hang off the class×course
109+/// instance rather than off the catalog row; see [`instances_router`].
104110 fn courses_router(state: &AppState) -> OpenApiRouter<AppState> {
105- let children = gate(web::courses::exam_routes(), state, Module::Exams)
111+ let children = gate(web::courses::subject_routes(), state, Module::Subjects);
112+ gate(
113+ web::courses::routes().merge(children),
114+ state,
115+ Module::Courses,
116+ )
117+}
118+
119+/// `/instances` and the three foreign-module route pairs mounted inside it —
120+/// the same split as `/courses`, one anchor down: the instance is what a şube
121+/// teaches, and what exams, sessions and homework hang off. Each child carries
122+/// its own module's gate *and*, through the outer one applied here, the course
123+/// gate (an instance is a course taught somewhere), so either module being off
124+/// refuses it.
125+fn instances_router(state: &AppState) -> OpenApiRouter<AppState> {
126+ let children = gate(web::instances::exam_routes(), state, Module::Exams)
106127 .merge(gate(
107- web::courses::session_routes(),
128+ web::instances::session_routes(),
108129 state,
109130 Module::Sessions,
110131 ))
111132 .merge(gate(
112- web::courses::subject_routes(),
113- state,
114- Module::Subjects,
115- ))
116- .merge(gate(
117- web::courses::homework_routes(),
133+ web::instances::homework_routes(),
118134 state,
119135 Module::Homework,
120136 ));
121137 gate(
122- web::courses::routes().merge(children),
138+ web::instances::routes().merge(children),
123139 state,
124140 Module::Courses,
125141 )
@@ -158,6 +174,8 @@ pub fn build_router(state: AppState) -> Router {
158174 gate(web::appointments::routes(), &state, Module::Appointments),
159175 )
160176 .nest("/courses", courses_router(&state))
177+ .nest("/instances", instances_router(&state))
178+ .nest("/academic-years", web::academic_years::routes())
161179 .nest(
162180 "/course-notes",
163181 gate(web::course_notes::routes(), &state, Module::CourseNotes),
src/service/academic_year.rsadded+285 -0
@@ -0,0 +1,285 @@
1+//! Academic-year workflows: the archived-year refusal every write against past
2+//! structure pays, the link resolver class/term create pass through, and the
3+//! rollover — the one command that carries a year's şubeler into the next. The
4+//! queries live in [`crate::db::academic_year`].
5+
6+use crate::database::Database;
7+use crate::db::academic_year;
8+use crate::db::class_course;
9+use crate::db::class_course_teacher;
10+use crate::db::class_group;
11+use crate::db::class_member;
12+use crate::db::class_pump::{self, Attached};
13+use crate::domain::academic_year::{
14+ AcademicYear, AcademicYearId, AcademicYearName, GradePromotion, archived_error,
15+ rollover_target_not_empty,
16+};
17+use crate::domain::class_group::ClassGrade;
18+use crate::domain::timestamp::Timestamp;
19+use crate::domain::user::UserId;
20+use crate::error::{AppError, ValidationError};
21+
22+/// The year row, for callers that only inspect it — the web layer's gates
23+/// read through here.
24+pub async fn read(db: &Database, id: &AcademicYearId) -> Result<Option<AcademicYear>, AppError> {
25+ academic_year::read(db, id).await
26+}
27+
28+/// Every year, newest first, paged — the calendar is small by nature.
29+pub async fn list_all(
30+ db: &Database,
31+ limit: Option<i64>,
32+ offset: i64,
33+) -> Result<(Vec<AcademicYear>, i64), AppError> {
34+ academic_year::list_all(db, limit, offset).await
35+}
36+
37+/// Mint one year. Both ends are required and the range is checked here, where
38+/// the store's own insert has no `WHERE` to re-check it — the same rule
39+/// [`AcademicYear::try_new`] states, in the same words.
40+pub async fn create(
41+ db: &Database,
42+ creator: &UserId,
43+ name: AcademicYearName,
44+ starts_at: Timestamp,
45+ ends_at: Timestamp,
46+ grade_promotions: Vec<GradePromotion>,
47+) -> Result<AcademicYear, AppError> {
48+ if ends_at <= starts_at {
49+ return Err(AppError::Validation(ValidationError::Invalid {
50+ field: "ends_at",
51+ reason: "must be after starts_at",
52+ }));
53+ }
54+ academic_year::create(db, creator, name, starts_at, ends_at, grade_promotions).await
55+}
56+
57+/// Turn an optional request-supplied year id into a validated reference —
58+/// `None` stays `None`, an unknown id is a `400` naming the field, and an
59+/// *archived* one is the year's `409`. This is the single spot every new link
60+/// to a year passes through: a şube create/update and a dönem create alike,
61+/// so past years take no new structure. The mirror of
62+/// [`crate::service::term::resolve`], one layer up the calendar.
63+pub async fn resolve(db: &Database, id: Option<&str>) -> Result<Option<AcademicYearId>, AppError> {
64+ let Some(id) = id else {
65+ return Ok(None);
66+ };
67+ let resolved = academic_year::read(db, &AcademicYearId::from_key(id))
68+ .await?
69+ .ok_or(AppError::Validation(ValidationError::Invalid {
70+ field: "year_id",
71+ reason: "academic year does not exist",
72+ }))?;
73+ if resolved.is_archived() {
74+ return Err(archived_error());
75+ }
76+ Ok(Some(*resolved.get_id()))
77+}
78+
79+/// Refuse when the named year is archived. A missing row is `Ok(())`: a
80+/// dangling link is not this guard's error, and the caller that cares already
81+/// answers it (the store's own year-gone refusal).
82+pub async fn require_open(db: &Database, id: &AcademicYearId) -> Result<(), AppError> {
83+ match academic_year::read(db, id).await? {
84+ Some(year) if year.is_archived() => Err(archived_error()),
85+ _ => Ok(()),
86+ }
87+}
88+
89+/// Refuse when this year row is archived — the read-only rule for past
90+/// structure, judged against a row the caller already read through [`read`];
91+/// a missing row is the caller's 404, not this guard's answer.
92+pub fn require_writable(year: &AcademicYear) -> Result<(), AppError> {
93+ if year.is_archived() {
94+ return Err(archived_error());
95+ }
96+ Ok(())
97+}
98+
99+/// Update an open year; an archived one is refused — past years are read-only.
100+pub async fn update(
101+ db: &Database,
102+ target: AcademicYear,
103+ name: Option<AcademicYearName>,
104+ starts_at: Option<Timestamp>,
105+ ends_at: Option<Timestamp>,
106+ grade_promotions: Option<Vec<GradePromotion>>,
107+) -> Result<AcademicYear, AppError> {
108+ require_writable(&target)?;
109+ academic_year::update(
110+ db,
111+ target.get_id(),
112+ name,
113+ starts_at,
114+ ends_at,
115+ grade_promotions,
116+ )
117+ .await
118+}
119+
120+/// Delete the year while nothing links it — the linked-refusal is the rule's
121+/// own answer, so the message the web layer used to pick is coded here; a row
122+/// that is already gone is the store's `404` ([`academic_year::delete`]).
123+pub async fn delete(db: &Database, target: AcademicYear) -> Result<(), AppError> {
124+ if academic_year::delete(db, target).await? {
125+ Ok(())
126+ } else {
127+ Err(AppError::Conflict(
128+ "classes and terms are still linked to this academic year — unlink them first",
129+ ))
130+ }
131+}
132+
133+/// What one [`rollover`] carried: how many şubeler were planted in the target
134+/// year, how many live students came with them, and the grades that stayed
135+/// behind because the year lists no promotion for them (graduation).
136+#[derive(Debug, Clone)]
137+pub struct RolloverReport {
138+ pub classes: usize,
139+ pub students: usize,
140+ pub graduated: Vec<String>,
141+}
142+
143+/// Carry `from`'s şubeler into `target`, the explicit year-boundary command.
144+///
145+/// A grade with **no** promotion entry is not rolled over — that is how
146+/// graduation is expressed — and a şube carrying no grade at all is not
147+/// either: there is nothing to promote it on. Each rolled şube is created
148+/// afresh in the target year with the same name and the mapped grade, then
149+/// gets copies of everything that belongs to the *structure* of the year: its
150+/// instances (same courses, same `ders_saati`, same karne policy, `source`
151+/// left NULL so no blueprint sweep can take a copied link back), each
152+/// instance's assigned teachers, and every **live** member — copied through
153+/// the pump, which is also what enrolls them into the new instances, and
154+/// tagged `source_class_group` with the şube they were copied out of (the
155+/// provenance §4.9 asks for: the new roster still names the old stint's şube).
156+/// The old year is untouched: it stays the record of what was taught.
157+///
158+/// Refusals: the target year must be empty (a second rollover into it is a
159+/// `409`, which is also what makes the command idempotent — a re-run is
160+/// refused, never duplicated), archived (read-only), and distinct from the
161+/// source. The emptiness check is a pre-flight read, an accepted race in the
162+/// README's sense: two rollovers racing the same empty target can each plant
163+/// şubeler; the class writes themselves serialize on the year row, so the
164+/// counters stay honest either way.
165+///
166+/// Each şube is carried over on its own: a failure mid-run leaves the
167+/// şubeler already planted in place, and a re-run is refused by the emptiness
168+/// guard — the report says what landed, and the operator resolves the rest by
169+/// hand. One transaction per write, never one across the run: the store owns
170+/// concurrency, and a run-wide transaction would hold the year row for the
171+/// length of the whole school.
172+pub async fn rollover(
173+ db: &Database,
174+ target: &AcademicYearId,
175+ from: &AcademicYearId,
176+ by: &UserId,
177+) -> Result<RolloverReport, AppError> {
178+ let target_year = read(db, target).await?.ok_or(AppError::NotFound)?;
179+ require_writable(&target_year)?;
180+ if target == from {
181+ return Err(AppError::Conflict(
182+ "a year cannot roll over into itself — name the year that follows",
183+ ));
184+ }
185+ if target_year.get_class_count() != 0 {
186+ return Err(rollover_target_not_empty());
187+ }
188+ let from_year = read(db, from).await?.ok_or(AppError::NotFound)?;
189+
190+ let mut report = RolloverReport {
191+ classes: 0,
192+ students: 0,
193+ graduated: Vec::new(),
194+ };
195+ for class in class_group::list_for_year(db, from).await? {
196+ let Some(grade) = class.get_grade() else {
197+ continue;
198+ };
199+ let Some(mapped) = from_year.promotion_for(grade.as_str()) else {
200+ // No promotion entry: this grade graduated. Reported once per
201+ // label, however many şubeler carry it.
202+ let label = grade.as_str().to_string();
203+ if !report.graduated.contains(&label) {
204+ report.graduated.push(label);
205+ }
206+ continue;
207+ };
208+ let next = ClassGrade::try_new(mapped)?;
209+ let planted = class_group::create(
210+ db,
211+ by,
212+ class.get_name().clone(),
213+ Some(next),
214+ Some(*target),
215+ class.get_teacher().copied(),
216+ )
217+ .await?;
218+ let planted_id = planted.get_id().clone();
219+
220+ // The structure first, so the member copy below enrolls the students
221+ // into every instance the new şube carries; the pump's member axis is
222+ // what pays those enrollments.
223+ for instance in
224+ class_course::list_for_class_ids(db, std::slice::from_ref(class.get_id())).await?
225+ {
226+ let landed =
227+ class_course::attach_sourced(db, &planted_id, instance.get_course(), by, None)
228+ .await?;
229+ let Attached::Made(copied) = landed else {
230+ // A fresh şube cannot hold the course already, and its caps
231+ // cannot be full: anything else here is the store disagreeing
232+ // with the read one statement earlier, which is a 500 and not
233+ // a partial rollover.
234+ return Err(AppError::Internal(format!(
235+ "rollover: attaching {} to the new class was refused",
236+ instance.get_course().key()
237+ )));
238+ };
239+ class_course::update(
240+ db,
241+ copied.get_id(),
242+ Some(instance.get_ders_saati()),
243+ Some(instance.counts_toward_karne()),
244+ )
245+ .await?;
246+ for teacher in class_course_teacher::list_for_instance(db, instance.get_id()).await? {
247+ class_course_teacher::assign(db, copied.get_id(), &teacher).await?;
248+ }
249+ }
250+
251+ for member in class_member::list_for_class(db, class.get_id(), None, 0)
252+ .await?
253+ .0
254+ {
255+ // The stint carries where the student came from: the copy names the
256+ // şube it was copied out of, so last year's roster is still legible
257+ // from the new one (and the tag is written in the same statement as
258+ // the stint — see `add_member_sourced`).
259+ match class_pump::add_member_sourced(
260+ db,
261+ &planted_id,
262+ member.get_user(),
263+ by,
264+ Some(class.get_id()),
265+ )
266+ .await?
267+ {
268+ Attached::Made(_) => report.students += 1,
269+ // A student the pump refuses (demoted out of `student` since
270+ // the stint was read, or gone) is not carried over: the new
271+ // year's roster is written under the same role rule the route
272+ // is.
273+ Attached::PivotGone | Attached::Gone => continue,
274+ _ => {
275+ return Err(AppError::Internal(format!(
276+ "rollover: adding {} to the new class was refused",
277+ member.get_user().key()
278+ )));
279+ }
280+ }
281+ }
282+ report.classes += 1;
283+ }
284+ Ok(report)
285+}
src/service/appointment.rsmodified+54 -19
@@ -207,10 +207,7 @@ async fn approve_inner(
207207 }
208208 _ => {}
209209 }
210- let slot_id = expected
211- .get_slot()
212- .ok_or(AppError::NotFound)?
213- .clone();
210+ let slot_id = expected.get_slot().ok_or(AppError::NotFound)?.clone();
214211 let slot = appointment_slot::read_on(&mut *tx, &slot_id)
215212 .await?
216213 .ok_or(AppError::NotFound)?;
@@ -456,7 +453,13 @@ mod tests {
456453 .await
457454 .unwrap();
458455 assert!(matches!(
459- book(&db, started.get_id(), &a_person(&db, "s1", "student").await, reason()).await,
456+ book(
457+ &db,
458+ started.get_id(),
459+ &a_person(&db, "s1", "student").await,
460+ reason()
461+ )
462+ .await,
460463 Err(AppError::Conflict("the slot has already started"))
461464 ));
462465
@@ -464,9 +467,14 @@ mod tests {
464467 .await
465468 .unwrap();
466469 assert!(
467- book(&db, upcoming.get_id(), &a_person(&db, "s1", "student").await, reason())
468- .await
469- .is_ok()
470+ book(
471+ &db,
472+ upcoming.get_id(),
473+ &a_person(&db, "s1", "student").await,
474+ reason()
475+ )
476+ .await
477+ .is_ok()
470478 );
471479 }
472480
@@ -710,12 +718,23 @@ mod tests {
710718 .unwrap();
711719 let reason = || AppointmentReason::try_new("görüşme").unwrap();
712720
713- book(&db, slot.get_id(), &a_person(&db, "s1", "student").await, reason())
714- .await
715- .unwrap();
721+ book(
722+ &db,
723+ slot.get_id(),
724+ &a_person(&db, "s1", "student").await,
725+ reason(),
726+ )
727+ .await
728+ .unwrap();
716729 assert_eq!(occupied(slot.get_id(), &db).await, 1);
717730
718- let refused = book(&db, slot.get_id(), &a_person(&db, "s2", "student").await, reason()).await;
731+ let refused = book(
732+ &db,
733+ slot.get_id(),
734+ &a_person(&db, "s2", "student").await,
735+ reason(),
736+ )
737+ .await;
719738 assert!(
720739 matches!(refused, Err(AppError::Conflict(_))),
721740 "the slot is taken"
@@ -785,11 +804,22 @@ mod tests {
785804 .unwrap();
786805 let reason = || AppointmentReason::try_new("görüşme").unwrap();
787806
788- let first = book(&db, slot.get_id(), &a_person(&db, "s1", "student").await, reason())
789- .await
790- .unwrap();
807+ let first = book(
808+ &db,
809+ slot.get_id(),
810+ &a_person(&db, "s1", "student").await,
811+ reason(),
812+ )
813+ .await
814+ .unwrap();
791815 assert!(matches!(
792- book(&db, slot.get_id(), &a_person(&db, "s2", "student").await, reason()).await,
816+ book(
817+ &db,
818+ slot.get_id(),
819+ &a_person(&db, "s2", "student").await,
820+ reason()
821+ )
822+ .await,
793823 Err(AppError::Conflict(_))
794824 ));
795825 // The live booking also blocks the slot delete.
@@ -800,9 +830,14 @@ mod tests {
800830
801831 reject(&db, first.get_id(), &teacher, None).await.unwrap();
802832 assert_eq!(occupied(slot.get_id(), &db).await, 0);
803- let second = book(&db, slot.get_id(), &a_person(&db, "s2", "student").await, reason())
804- .await
805- .unwrap();
833+ let second = book(
834+ &db,
835+ slot.get_id(),
836+ &a_person(&db, "s2", "student").await,
837+ reason(),
838+ )
839+ .await
840+ .unwrap();
806841 assert_eq!(second.get_status(), AppointmentStatus::Pending);
807842 assert_eq!(occupied(slot.get_id(), &db).await, 1);
808843 }
src/service/appointment_slot.rsmodified+2 -6
@@ -75,9 +75,7 @@ pub async fn create(
7575 series: None,
7676 created_at: Timestamp::now(),
7777 }],
78- AppError::ConflictOwned(
79- "this time overlaps a slot you have already published".into(),
80- ),
78+ AppError::ConflictOwned("this time overlaps a slot you have already published".into()),
8179 )
8280 .await?
8381 .into_iter()
@@ -151,9 +149,7 @@ pub async fn publish_weekly(
151149 db,
152150 teacher,
153151 rows,
154- AppError::ConflictOwned(
155- "a repeated slot overlaps one you have already published".into(),
156- ),
152+ AppError::ConflictOwned("a repeated slot overlaps one you have already published".into()),
157153 )
158154 .await?;
159155 if created.len() != windows.len() {
src/service/board.rsmodified+0 -1
@@ -220,7 +220,6 @@ pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> {
220220
221221 #[cfg(test)]
222222 mod tests {
223-
224223
225224 /// The security boundary of the gates this module owns, in one test: an
226225 /// outsider is told the board does not exist, an insider without rights is
src/service/class_blueprint.rsmodified+48 -36
@@ -105,12 +105,19 @@ pub async fn list_all(
105105 /// it holds, so an edit racing a pump is only ever the retro-pump this
106106 /// feature is built on. Rows a racing edit leaves behind stay reachable,
107107 /// because [`delete`] sweeps the whole tag rather than a list.
108+///
109+/// Answers `(the stored template, what the pump did, the blob keys the
110+/// removals swept)`: detaching an instance takes its exams'/homework's images
111+/// and files with it ([`class_blueprint::drop_links`]), and those rows are
112+/// gone by the time this returns, so the keys have to reach the caller's route
113+/// to be unlinked. They ride out as a third element rather than inside
114+/// [`Pumped`] — the pump never touched a blob, and said so.
108115 pub async fn set_courses(
109116 db: &Database,
110117 blueprint: ClassBlueprint,
111118 courses: Vec<CourseId>,
112119 by: &UserId,
113-) -> Result<(ClassBlueprint, Pumped), AppError> {
120+) -> Result<(ClassBlueprint, Pumped, Vec<String>), AppError> {
114121 let wanted = ClassBlueprint::course_list(courses)?;
115122 let Some(mut saved) = class_blueprint::set_courses_if_unchanged(
116123 db,
@@ -131,9 +138,9 @@ pub async fn set_courses(
131138 };
132139 };
133140 let doomed = class_blueprint::sourced_links(db, saved.get_id(), &saved.courses).await?;
134- class_blueprint::drop_links(db, saved.get_id(), doomed).await?;
141+ let blob_keys = class_blueprint::drop_links(db, saved.get_id(), doomed).await?;
135142 let pumped = pump(db, &mut saved, by).await?;
136- Ok((saved, pumped))
143+ Ok((saved, pumped, blob_keys))
137144 }
138145
139146 /// Delete the blueprint, taking every attachment it made with it. Courses a
@@ -177,7 +184,16 @@ pub async fn set_courses(
177184 /// Content-equal is intent-equal — the end state is the one the caller
178185 /// asked for — and telling the two apart needs a revision column on the
179186 /// row, which nothing else here would use.
180-pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppError> {
187+///
188+/// Answers the blob keys the tag sweep's detaches removed
189+/// ([`class_blueprint::drop_links`]): each detached instance took its exams'
190+/// and homework's images and files with it, and the rows are gone by the time
191+/// this returns, so those names have to reach the route to be unlinked. The
192+/// keys are the sweep's, not the caller's — a hand-attached course carries no
193+/// tag and is not swept, so nothing of its is in the list. A failure between
194+/// the sweep and the commit drops them, the same accepted window the rest of
195+/// this doc covers.
196+pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<Vec<String>, AppError> {
181197 // The claim, the sweep and the delete are one transaction — the shape
182198 // Postgres demands and the doc above argues for. The old order (delete
183199 // the row on the pool, then sweep) cannot work against an enforcing
@@ -204,10 +220,8 @@ pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppE
204220 // holds the claim: it touches no `class_blueprint` rows, so it cannot
205221 // deadlock against the lock it runs under.
206222 let doomed = class_blueprint::sourced_links(db, &blueprint.id, &[]).await?;
207- class_blueprint::drop_links(db, &blueprint.id, doomed).await?;
208- if !class_blueprint::delete_if_unchanged_in(&mut tx, &blueprint.id, &blueprint.courses)
209- .await?
210- {
223+ let blob_keys = class_blueprint::drop_links(db, &blueprint.id, doomed).await?;
224+ if !class_blueprint::delete_if_unchanged_in(&mut tx, &blueprint.id, &blueprint.courses).await? {
211225 // The row was locked, matched at the claim, and vanished anyway:
212226 // nothing does that but a bug.
213227 return Err(AppError::Internal(
@@ -215,7 +229,7 @@ pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppE
215229 ));
216230 }
217231 tx.commit().await?;
218- Ok(())
232+ Ok(blob_keys)
219233 }
220234
221235 /// Attach every course in this blueprint to `class`, skipping — never
@@ -443,7 +457,7 @@ mod tests {
443457
444458 // The course is deleted out from under the pump: the pivot claim
445459 // matches nothing.
446- let course = a_course("algebra", None, &db).await;
460+ let course = a_course("algebra", &db).await;
447461 let class = class_group::read(&db, &a_class("9-A", &db).await)
448462 .await
449463 .unwrap()
@@ -484,7 +498,7 @@ mod tests {
484498 // The class is deleted out from under the pump: the counter claim
485499 // matches nothing and the read that follows finds no row.
486500 let (db, _leases) = crate::database::init_test_db().await;
487- let course = a_course("algebra", None, &db).await;
501+ let course = a_course("algebra", &db).await;
488502 let class = class_group::read(&db, &a_class("9-A", &db).await)
489503 .await
490504 .unwrap()
@@ -514,18 +528,16 @@ mod tests {
514528 // The class stands at its own ceiling: the same claim matches nothing,
515529 // but the row is there — and that is the one a manager can act on.
516530 let (db, _leases) = crate::database::init_test_db().await;
517- let course = a_course("algebra", None, &db).await;
531+ let course = a_course("algebra", &db).await;
518532 let class = class_group::read(&db, &a_class("9-A", &db).await)
519533 .await
520534 .unwrap()
521535 .unwrap();
522536 let blueprint = a_blueprint(vec![course], &db).await;
523- sqlx::query(
524- sqlx::AssertSqlSafe(format!(
525- "UPDATE class_group SET class_course_count = {} WHERE id = $1",
526- MAX_CLASS_COURSES
527- )),
528- )
537+ sqlx::query(sqlx::AssertSqlSafe(format!(
538+ "UPDATE class_group SET class_course_count = {} WHERE id = $1",
539+ MAX_CLASS_COURSES
540+ )))
529541 .bind(class.get_id().uuid())
530542 .execute(&db)
531543 .await
@@ -549,8 +561,8 @@ mod tests {
549561 async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() {
550562 let (db, _leases) = crate::database::init_test_db().await;
551563 let manager = fixture_user(&db, "manager").await;
552- let algebra = a_course("algebra", None, &db).await;
553- let physics = a_course("physics", None, &db).await;
564+ let algebra = a_course("algebra", &db).await;
565+ let physics = a_course("physics", &db).await;
554566 let class = class_group::read(&db, &a_class("9-A", &db).await)
555567 .await
556568 .unwrap()
@@ -561,7 +573,7 @@ mod tests {
561573 // The edit this caller did not see: it adds a course and pumps it into
562574 // the section. (The pump is applied by hand because the helper class
563575 // carries no grade for `set_courses`'s own loop to find.)
564- let (edited, _) = set_courses(
576+ let (edited, _, _) = set_courses(
565577 &db,
566578 read(&db, stale.get_id()).await.unwrap().unwrap(),
567579 vec![algebra, physics],
@@ -603,7 +615,7 @@ mod tests {
603615 async fn a_delete_waits_for_an_attach_in_flight() {
604616 let (db, _leases) = crate::database::init_test_db().await;
605617 let manager = fixture_user(&db, "manager").await;
606- let algebra = a_course("algebra", None, &db).await;
618+ let algebra = a_course("algebra", &db).await;
607619 let class = class_group::read(&db, &a_class("9-A", &db).await)
608620 .await
609621 .unwrap()
@@ -692,8 +704,8 @@ mod tests {
692704 let (db, _leases) = crate::database::init_test_db().await;
693705 let manager = fixture_user(&db, "manager").await;
694706 let courses = vec![
695- a_course("algebra", None, &db).await,
696- a_course("physics", None, &db).await,
707+ a_course("algebra", &db).await,
708+ a_course("physics", &db).await,
697709 ];
698710 let blueprint = a_blueprint(courses, &db).await;
699711 let mut classes = Vec::new();
@@ -737,16 +749,16 @@ mod tests {
737749 // The pump is answered in bounded time even though the delete is
738750 // sweeping two sections' link rows — and answered with one of the two
739751 // honest outcomes, never a 500.
740- let pumped =
741- tokio::time::timeout(std::time::Duration::from_secs(10), pumping)
742- .await
743- .expect("a pump must not wait behind a delete's unbounded sweep")
744- .unwrap();
752+ let pumped = tokio::time::timeout(std::time::Duration::from_secs(10), pumping)
753+ .await
754+ .expect("a pump must not wait behind a delete's unbounded sweep")
755+ .unwrap();
745756 let skipped = pumped.unwrap();
746757 assert!(
747- skipped.iter().all(|s| {
748- s.reason == "blueprint_deleted" || s.reason == "course_deleted"
749- }) || skipped.is_empty(),
758+ skipped
759+ .iter()
760+ .all(|s| { s.reason == "blueprint_deleted" || s.reason == "course_deleted" })
761+ || skipped.is_empty(),
750762 "neither a clean attach nor a clean skip: {skipped:?}"
751763 );
752764
@@ -776,7 +788,7 @@ mod tests {
776788 async fn a_pump_whose_blueprint_died_attaches_nothing() {
777789 let (db, _leases) = crate::database::init_test_db().await;
778790 let manager = fixture_user(&db, "manager").await;
779- let algebra = a_course("algebra", None, &db).await;
791+ let algebra = a_course("algebra", &db).await;
780792 let class = class_group::read(&db, &a_class("9-A", &db).await)
781793 .await
782794 .unwrap()
@@ -815,8 +827,8 @@ mod tests {
815827 async fn a_dead_course_is_pruned_and_skipped_once_for_the_whole_grade() {
816828 let (db, _leases) = crate::database::init_test_db().await;
817829 let manager = fixture_user(&db, "manager").await;
818- let astronomy = a_course("astronomy", None, &db).await;
819- let algebra = a_course("algebra", None, &db).await;
830+ let astronomy = a_course("astronomy", &db).await;
831+ let algebra = a_course("algebra", &db).await;
820832 let a = a_section("9-A", &db).await;
821833 let b = a_section("9-B", &db).await;
822834 let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await;
@@ -876,7 +888,7 @@ mod tests {
876888 async fn a_deleted_blueprint_stops_the_grade_loop_after_one_skip() {
877889 let (db, _leases) = crate::database::init_test_db().await;
878890 let manager = fixture_user(&db, "manager").await;
879- let algebra = a_course("algebra", None, &db).await;
891+ let algebra = a_course("algebra", &db).await;
880892 a_section("9-A", &db).await;
881893 a_section("9-B", &db).await;
882894 let mut stale = a_blueprint(vec![algebra], &db).await;
src/service/class_course.rsmodified+397 -189
@@ -1,24 +1,28 @@
11 //! Class-course workflows: the attach that maps the pump's refusals to this
2-//! route's answers, and the detach that turns a zero-row sweep into a 404.
3-//! The transactions live in [`crate::db::class_pump`] and
4-//! [`crate::db::class_course`].
2+//! route's answers, the detach that turns a zero-row sweep into a 404, and the
3+//! instance-scoped gates every route under `/instances` pays — the archived
4+//! year and the D10 "who may act on this instance" rule. The transactions live
5+//! in [`crate::db::class_pump`] and [`crate::db::class_course`].
56
67 use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
78 use crate::database::Database;
89 use crate::db::class_course;
910 use crate::db::class_pump::{self, Axis};
10-use crate::domain::class_course::ClassCourse;
11+use crate::domain::academic_year::AcademicYearId;
12+use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati};
1113 use crate::domain::class_group::ClassGroupId;
1214 use crate::domain::course::CourseId;
13-use crate::domain::user::UserId;
14-use crate::error::AppError;
15+use crate::domain::role::Role;
16+use crate::domain::user::{User, UserId};
17+use crate::error::{AppError, ValidationError};
1518
1619 /// Attach `course` to `class` and enroll the class's whole roster into it,
1720 /// in one transaction.
1821 ///
19-/// Students already in the course keep the rows they have — no seat
20-/// charged, `source` untouched — and a roster that does not fit refuses the
21-/// whole attach rather than filling the course to its cap and stopping.
22+/// Students already in the course keep the rows they have — no second
23+/// enrollment written, `source` untouched — and the attach is one
24+/// `class_course` row per (class, course): the instance every exam, session,
25+/// homework and enrollment under this class's course now keys on.
2226 pub async fn attach(
2327 db: &Database,
2428 class: &ClassGroupId,
@@ -54,10 +58,6 @@ pub async fn attach(
5458 remove some before attaching a course"
5559 ),
5660 }),
57- class_pump::Attached::Full(full) => Err(AppError::ConflictCoded {
58- code,
59- message: format!("{full} cannot hold the whole class"),
60- }),
6161 // Unreachable on this axis, and kept because the match is
6262 // exhaustive: the pair loop enrolls the roster into `$pivot` and
6363 // nothing else, and the pivot claim already proved *that* course
@@ -82,18 +82,29 @@ pub async fn attach(
8282 /// into it. A course that was not attached is a [`AppError::NotFound`],
8383 /// raised here rather than left to each caller to re-derive from a boolean.
8484 ///
85-/// to that class (see [`class_pump::detach_course`]).
85+/// The instance is the anchor, so this takes everything the class taught under
86+/// it — exams, sessions, homework, the roster and the teacher links (see
87+/// [`class_pump::detach_course`]) — and answers the blob keys of the image and
88+/// homework-file rows that cascade removed, so the route can unlink those files
89+/// after the commit (the shape [`crate::service::course::delete`] already has).
90+/// The rows are gone by the time this returns: a caller that drops the list
91+/// leaves the bytes on disk with nothing pointing at them.
92+///
93+/// An empty list is *not* the refusal — an instance that carried no uploads
94+/// detaches fine and simply has no files to unlink. Only a pair holding no
95+/// instance at all is the 404.
8696 pub async fn detach(
8797 db: &Database,
8898 class: &ClassGroupId,
8999 course: &CourseId,
90-) -> Result<(), AppError> {
91- let gone = class_pump::detach_course(db, class, course, None).await?;
92- (gone > 0).then_some(()).ok_or(AppError::NotFound)
100+) -> Result<Vec<String>, AppError> {
101+ class_pump::detach_course(db, class, course, None)
102+ .await?
103+ .ok_or(AppError::NotFound)
93104 }
94105
95106 /// The courses a class is attached to, newest first, paged — the read behind
96-/// `GET /classes/{id}/courses`.
107+/// `GET /classes/{id}/instances`.
97108 pub async fn list_for_class(
98109 db: &Database,
99110 class: &ClassGroupId,
@@ -103,21 +114,183 @@ pub async fn list_for_class(
103114 class_course::list_for_class(db, class, limit, offset).await
104115 }
105116
117+/// One instance, or `None` when the id names no row — the read behind
118+/// `GET /instances/{id}`.
119+pub async fn read(db: &Database, id: &ClassCourseId) -> Result<Option<ClassCourse>, AppError> {
120+ class_course::read(db, id).await
121+}
122+
123+/// PATCH one instance's own policy: the weekly hours and whether it counts
124+/// toward the karne. Both are non-clearable, so an omitted field keeps the
125+/// stored value.
126+pub async fn update(
127+ db: &Database,
128+ id: &ClassCourseId,
129+ staff: Option<DersSaati>,
130+ counts: Option<bool>,
131+) -> Result<ClassCourse, AppError> {
132+ class_course::update(db, id, staff, counts).await
133+}
134+
135+/// The academic year this instance sits under, if any — the seam every
136+/// instance-scoped write reads the archive gate off (instance → şube → year).
137+pub async fn year_of(
138+ db: &Database,
139+ instance: &ClassCourseId,
140+) -> Result<Option<AcademicYearId>, AppError> {
141+ let Some(class) = class_course::class_of(db, instance).await? else {
142+ return Ok(None);
143+ };
144+ Ok(crate::db::class_group::read(db, &class)
145+ .await?
146+ .and_then(|class| class.get_year().copied()))
147+}
148+
149+/// Refuse the write when the instance's year is archived — past years are
150+/// read-only. A pre-flight guard, accepted race (see README concurrency
151+/// model): a year archived after this read still lets the write through.
152+///
153+/// A şube with no year, or one whose year row is gone, passes: a dangling
154+/// link is not this guard's error, and the caller that cares answers it.
155+pub async fn require_open(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> {
156+ if let Some(year) = year_of(db, instance).await? {
157+ crate::service::academic_year::require_open(db, &year).await?;
158+ }
159+ Ok(())
160+}
161+
162+/// Assign `target` to teach this instance, on `by`'s orders.
163+///
164+/// The target must already hold the `teacher` role or higher — assignment
165+/// hands out the rights every instance-scoped gate re-checks against that bar,
166+/// so assigning anyone below it would write a row that can never be used —
167+/// and the caller `by` must hold `manager`+: staffing is the office's call,
168+/// stated here so it holds for every caller of this workflow and not only for
169+/// the route that remembers to extract it. Assignment is idempotent, and a
170+/// past year is read-only: staffing an archived year's instance is refused
171+/// like every other write against it.
172+pub async fn assign_teacher(
173+ db: &Database,
174+ instance: &ClassCourseId,
175+ target: &UserId,
176+ by: &UserId,
177+) -> Result<(), AppError> {
178+ let Some(actor) = crate::db::user::read(db, by).await? else {
179+ return Err(AppError::Unauthorized);
180+ };
181+ if !actor.get_role().at_least(Role::Manager) {
182+ return Err(AppError::Forbidden(
183+ "assigning a teacher is the office's call — manager role or higher",
184+ ));
185+ }
186+ let Some(target_user) = crate::db::user::read(db, target).await? else {
187+ return Err(AppError::Validation(ValidationError::Invalid {
188+ field: "user_id",
189+ reason: "target user does not exist",
190+ }));
191+ };
192+ if !target_user.get_role().at_least(Role::Teacher) {
193+ return Err(AppError::Validation(ValidationError::Invalid {
194+ field: "user_id",
195+ reason: "target user must hold the teacher role or higher",
196+ }));
197+ }
198+ require_open(db, instance).await?;
199+ crate::db::class_course_teacher::assign(db, instance, target).await?;
200+ Ok(())
201+}
202+
203+/// Drop `target` from this instance's teachers: read-only in a past year, like
204+/// every other write against archived structure. `false` when they were not
205+/// assigned to it, so the web layer can answer 404 instead of pretending it
206+/// removed someone.
207+pub async fn unassign_teacher(
208+ db: &Database,
209+ instance: &ClassCourseId,
210+ target: &UserId,
211+) -> Result<bool, AppError> {
212+ require_open(db, instance).await?;
213+ crate::db::class_course_teacher::unassign(db, instance, target).await
214+}
215+
216+/// A 403 unless `user` may act on this instance — D10, the one gate every
217+/// instance-scoped route shares in place of a `class_course_teacher` lookup of
218+/// its own. It passes when the user is `manager`+ (the office), when they are
219+/// one of the instance's assigned teachers, or when they are the şube's
220+/// homeroom teacher (sınıf öğretmeni) — the three ways a person legitimately
221+/// runs a section's course.
222+///
223+/// A gone instance is a `404`, never a 403: the route the user asked about
224+/// does not exist.
225+pub async fn ensure_instance_teacher(
226+ db: &Database,
227+ user: &User,
228+ instance: &ClassCourseId,
229+) -> Result<(), AppError> {
230+ if user.get_role().at_least(Role::Manager) {
231+ return Ok(());
232+ }
233+ let Some(class) = class_course::class_of(db, instance).await? else {
234+ return Err(AppError::NotFound);
235+ };
236+ // Both ways in below are an *assignment*, and an assignment is history:
237+ // the caller's live role decides, exactly as it does on the catalog path
238+ // ([`crate::web::courses::can_manage_course`]). The demotion cascade
239+ // sweeps the assignment table and the homeroom column only when it runs
240+ // with the role write, so a flip that skipped it would otherwise leave a
241+ // student running the section they were stripped of.
242+ if user.get_role().at_least(Role::Teacher)
243+ && (crate::db::class_course_teacher::list_for_instance(db, instance)
244+ .await?
245+ .contains(user.get_id())
246+ || crate::db::class_group::read(db, &class)
247+ .await?
248+ .and_then(|class| class.get_teacher().copied())
249+ .as_ref()
250+ == Some(user.get_id()))
251+ {
252+ return Ok(());
253+ }
254+ Err(AppError::Forbidden(
255+ "only this instance's teachers, its class's homeroom teacher, or a manager may act here",
256+ ))
257+}
258+
106259 #[cfg(test)]
107260 mod tests {
108261 use super::*;
262+ use crate::db::class_group;
109263 use crate::db::class_member::tests::{
110264 a_class, a_course, counter, course_exists, link_exists, rows, source_of,
111265 };
266+ use crate::domain::user::Username;
112267 use crate::service::class_member;
113268
114- /// Attaching seeds the course from the roster the class already holds.
269+ /// The stored user row, for the gates that judge a live role.
270+ async fn user_of(db: &Database, id: &UserId) -> User {
271+ crate::db::user::read(db, id).await.unwrap().unwrap()
272+ }
273+
274+ /// A real account at a role — the D10 gates judge the live row, so a
275+ /// fixture id would not do.
276+ async fn staff(db: &Database, username: &str, role: Role) -> UserId {
277+ let account = crate::db::user::create(db, Username::try_new(username).unwrap(), None)
278+ .await
279+ .unwrap();
280+ crate::service::user::set_role(db, account.get_id(), role)
281+ .await
282+ .unwrap();
283+ *account.get_id()
284+ }
285+
286+ /// Attaching mints the instance, seeds it from the roster the class already
287+ /// holds, and refuses a second attach of the same pair.
115288 #[tokio::test]
116- async fn an_attach_enrolls_the_whole_roster() {
289+ async fn an_attach_enrolls_the_whole_roster_into_the_new_instance() {
117290 let (db, _leases) = crate::database::init_test_db().await;
118291 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
119292 let class = a_class("9-A", &db).await;
120- let algebra = a_course("algebra", None, &db).await;
293+ let algebra = a_course("algebra", &db).await;
121294 let students = [
122295 crate::db::class_member::tests::fixture_user(&db, "a").await,
123296 crate::db::class_member::tests::fixture_user(&db, "b").await,
@@ -128,14 +301,17 @@ mod tests {
128301 .unwrap();
129302 }
130303
131- attach(&db, &class, &algebra, &manager).await.unwrap();
304+ let instance = attach(&db, &class, &algebra, &manager).await.unwrap();
132305 for student in &students {
133306 assert_eq!(
134- source_of(&algebra, student, &db).await,
307+ source_of(instance.get_id(), student, &db).await,
135308 Some(Some(class.clone()))
136309 );
137310 }
138- assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 2);
311+ assert_eq!(
312+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
313+ 2
314+ );
139315 assert_eq!(counter("class_course_count", class.uuid(), &db).await, 1);
140316
141317 let again = attach(&db, &class, &algebra, &manager).await;
@@ -145,71 +321,107 @@ mod tests {
145321 );
146322 }
147323
148- /// A course with room for only part of the roster takes none of it: zero
149- /// enrollments, the counter unmoved, and no attachment row.
324+ /// Two şubeler teaching one catalog course are two instances — that is the
325+ /// whole remodel — and each keeps its own roster.
150326 #[tokio::test]
151- async fn a_roster_that_does_not_fit_attaches_nothing() {
327+ async fn two_classes_teaching_one_course_keep_their_own_rosters() {
152328 let (db, _leases) = crate::database::init_test_db().await;
153329 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
154- let class = a_class("9-A", &db).await;
155- let tight = a_course("algebra", Some(2), &db).await;
156- for name in ["a", "b", "c"] {
157- let student = crate::db::class_member::tests::fixture_user(&db, name).await;
158- class_member::add(&db, &class, &student, &manager).await.unwrap();
159- }
330+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
331+ let algebra = a_course("algebra", &db).await;
332+ let fifth_a = a_class("5-A", &db).await;
333+ let fifth_b = a_class("5-B", &db).await;
160334
161- let refused = attach(&db, &class, &tight, &manager).await;
162- assert!(
163- matches!(refused, Err(AppError::ConflictCoded { code, ref message })
164- if code == "course_full" && message.contains(tight.key().as_str())),
165- "the refusal must be coded `course_full` and name the course: {refused:?}"
335+ let first = attach(&db, &fifth_a, &algebra, &manager).await.unwrap();
336+ let second = attach(&db, &fifth_b, &algebra, &manager).await.unwrap();
337+ assert_ne!(
338+ first.get_id(),
339+ second.get_id(),
340+ "one catalog course, one instance per şube"
166341 );
342+
343+ class_member::add(&db, &fifth_a, &student, &manager)
344+ .await
345+ .unwrap();
167346 assert_eq!(
168- rows("enrollment", &db).await,
169- 0,
170- "the two seats that did fit must be given back with the third"
347+ source_of(first.get_id(), &student, &db).await,
348+ Some(Some(fifth_a.clone())),
349+ "5-A's student lands in 5-A's instance"
171350 );
172351 assert_eq!(
173- rows("class_course", &db).await,
174- 0,
175- "…and no attachment row may survive"
352+ source_of(second.get_id(), &student, &db).await,
353+ None,
354+ "…and nowhere near 5-B's"
355+ );
356+
357+ // Detaching one şube takes its instance and its roster; the other
358+ // şube's instance and roster stand.
359+ detach(&db, &fifth_a, &algebra).await.unwrap();
360+ assert_eq!(source_of(first.get_id(), &student, &db).await, None);
361+ assert_eq!(
362+ source_of(second.get_id(), &student, &db).await,
363+ None,
364+ "5-B's instance was never enrolled either"
365+ );
366+ assert_eq!(
367+ counter("class_course_count", fifth_b.uuid(), &db).await,
368+ 1,
369+ "the other şube keeps its instance"
370+ );
371+ assert_eq!(
372+ counter("class_member_count", fifth_a.uuid(), &db).await,
373+ 1,
374+ "the two axes are independent: dropping the course keeps the roster"
176375 );
177- assert_eq!(counter("enrollment_count", tight.uuid(), &db).await, 0);
178- assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0);
179376 }
180377
181- /// A hand-placed row is skipped on the way in and left standing on the way
182- /// out — the class never owned it.
378+ /// A hand-placed row is never adopted: the pump skips it, and a member
379+ /// exit leaves it standing because it carries no class `source`. The
380+ /// detach is the other story: it takes the whole instance subtree, and a
381+ /// hand row lives on that instance like any other.
183382 #[tokio::test]
184- async fn a_hand_placed_row_survives_the_detach() {
383+ async fn a_hand_placed_row_is_never_adopted_by_the_class() {
185384 let (db, _leases) = crate::database::init_test_db().await;
186385 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
187- let student =
188- crate::db::class_member::tests::fixture_user(&db, "student").await;
386+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
189387 let class = a_class("9-A", &db).await;
190- let algebra = a_course("algebra", None, &db).await;
191- crate::db::enrollment::enroll(&db, &algebra, &student, &manager)
388+ let algebra = a_course("algebra", &db).await;
389+ let instance = attach(&db, &class, &algebra, &manager).await.unwrap();
390+ crate::db::enrollment::enroll(&db, instance.get_id(), &student, &manager, None)
192391 .await
193392 .unwrap();
194393 class_member::add(&db, &class, &student, &manager)
195394 .await
196395 .unwrap();
197396
198- attach(&db, &class, &algebra, &manager).await.unwrap();
199397 assert_eq!(
200- source_of(&algebra, &student, &db).await,
398+ source_of(instance.get_id(), &student, &db).await,
201399 Some(None),
202- "an attach may not adopt a hand-placed row"
400+ "the pump may not adopt a hand-placed row"
203401 );
204402 assert_eq!(
205- counter("enrollment_count", algebra.uuid(), &db).await,
403+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
206404 1,
207- "…nor charge a seat for it"
405+ "…nor count it twice"
406+ );
407+
408+ class_member::leave(&db, &class, &student).await.unwrap();
409+ assert_eq!(
410+ source_of(instance.get_id(), &student, &db).await,
411+ Some(None),
412+ "the member sweep may only take back the rows the class wrote"
413+ );
414+ assert_eq!(
415+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
416+ 1
208417 );
209418
210419 detach(&db, &class, &algebra).await.unwrap();
211- assert_eq!(source_of(&algebra, &student, &db).await, Some(None));
212- assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
420+ assert_eq!(
421+ source_of(instance.get_id(), &student, &db).await,
422+ None,
423+ "the detach takes the instance and every row on it"
424+ );
213425 let again = detach(&db, &class, &algebra).await;
214426 assert!(
215427 matches!(again, Err(AppError::NotFound)),
@@ -217,24 +429,23 @@ mod tests {
217429 );
218430 }
219431
220- /// Detaching with nobody else claiming the rows deletes them and gives the
221- /// seats back.
432+ /// Detaching sweeps the rows the class pumped, and only those: the
433+ /// membership row is a separate axis and stays.
222434 #[tokio::test]
223435 async fn a_detach_sweeps_the_rows_it_pumped() {
224436 let (db, _leases) = crate::database::init_test_db().await;
225437 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
226- let student =
227- crate::db::class_member::tests::fixture_user(&db, "student").await;
438+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
228439 let class = a_class("9-A", &db).await;
229- let algebra = a_course("algebra", None, &db).await;
440+ let algebra = a_course("algebra", &db).await;
230441 class_member::add(&db, &class, &student, &manager)
231442 .await
232443 .unwrap();
233- attach(&db, &class, &algebra, &manager).await.unwrap();
444+ let instance = attach(&db, &class, &algebra, &manager).await.unwrap();
234445
235446 detach(&db, &class, &algebra).await.unwrap();
236- assert_eq!(source_of(&algebra, &student, &db).await, None);
237- assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0);
447+ assert_eq!(source_of(instance.get_id(), &student, &db).await, None);
448+ assert_eq!(rows("enrollment", &db).await, 0);
238449 assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0);
239450 assert_eq!(
240451 rows("class_member", &db).await,
@@ -244,146 +455,137 @@ mod tests {
244455 );
245456 }
246457
247- /// Two classes, one course, one student in both: the second attach skipped
248- /// the row the first wrote, so the row names only the first class — and
249- /// detaching *that* class must hand the row to the second rather than
250- /// unenroll a student the second is still responsible for. Detaching the
251- /// second then finds nobody left and takes the seat back.
458+ /// The attach of an empty class leaves the new instance's counter at zero —
459+ /// nothing to enroll, nothing charged.
252460 #[tokio::test]
253- async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() {
461+ async fn the_attach_of_an_empty_roster_charges_no_seat() {
254462 let (db, _leases) = crate::database::init_test_db().await;
255463 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
256- let student =
257- crate::db::class_member::tests::fixture_user(&db, "student").await;
258- let algebra = a_course("algebra", None, &db).await;
259- let first = a_class("9-A", &db).await;
260- let second = a_class("club", &db).await;
261- for class in [&first, &second] {
262- class_member::add(&db, class, &student, &manager)
263- .await
264- .unwrap();
265- attach(&db, class, &algebra, &manager).await.unwrap();
266- }
267- assert_eq!(
268- source_of(&algebra, &student, &db).await,
269- Some(Some(first.clone())),
270- "the second attach must skip the row the first wrote"
271- );
272- assert_eq!(
273- counter("enrollment_count", algebra.uuid(), &db).await,
274- 1,
275- "…and pay no second seat for it"
276- );
277-
278- detach(&db, &first, &algebra).await.unwrap();
279- assert_eq!(
280- source_of(&algebra, &student, &db).await,
281- Some(Some(second.clone())),
282- "the row must be handed to the class that still claims it"
283- );
284- assert_eq!(
285- counter("enrollment_count", algebra.uuid(), &db).await,
286- 1,
287- "a repair is not a release"
288- );
289-
290- detach(&db, &second, &algebra).await.unwrap();
464+ let class = a_class("9-A", &db).await;
465+ let algebra = a_course("algebra", &db).await;
466+ let instance = attach(&db, &class, &algebra, &manager).await.unwrap();
291467 assert_eq!(
292- source_of(&algebra, &student, &db).await,
293- None,
294- "the last claimant leaving takes the row with it"
468+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
469+ 0,
470+ "a fresh instance's roster counter is zero"
295471 );
296- assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0);
297472 }
298473
299- /// The same repair along the member axis: removing the student from the
300- /// class that owns the row hands it to the other class they are in.
474+ /// PATCHing the instance writes only what the request carried.
301475 #[tokio::test]
302- async fn a_member_removal_hands_a_shared_row_over_too() {
476+ async fn an_update_writes_only_the_fields_it_carried() {
303477 let (db, _leases) = crate::database::init_test_db().await;
304478 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
305- let student =
306- crate::db::class_member::tests::fixture_user(&db, "student").await;
307- let algebra = a_course("algebra", None, &db).await;
308- let first = a_class("9-A", &db).await;
309- let second = a_class("club", &db).await;
310- for class in [&first, &second] {
311- attach(&db, class, &algebra, &manager).await.unwrap();
312- class_member::add(&db, class, &student, &manager)
313- .await
314- .unwrap();
315- }
479+ let class = a_class("9-A", &db).await;
480+ let algebra = a_course("algebra", &db).await;
481+ let instance = attach(&db, &class, &algebra, &manager).await.unwrap();
316482
317- class_member::remove(&db, &first, &student).await.unwrap();
318- assert_eq!(
319- source_of(&algebra, &student, &db).await,
320- Some(Some(second.clone())),
321- "the student is still in the second class, so the row stays"
483+ let updated = update(
484+ &db,
485+ instance.get_id(),
486+ Some(DersSaati::try_new(5).unwrap()),
487+ None,
488+ )
489+ .await
490+ .unwrap();
491+ assert_eq!(updated.get_ders_saati().as_i64(), 5);
492+ assert!(
493+ updated.counts_toward_karne(),
494+ "the omitted field keeps its stored value"
322495 );
323- assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
324496
325- class_member::remove(&db, &second, &student).await.unwrap();
326- assert_eq!(source_of(&algebra, &student, &db).await, None);
327- assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0);
497+ let again = update(&db, instance.get_id(), None, Some(false))
498+ .await
499+ .unwrap();
500+ assert!(!again.counts_toward_karne());
501+ assert_eq!(
502+ again.get_ders_saati().as_i64(),
503+ 5,
504+ "…and the other direction holds too"
505+ );
328506 }
329507
330- /// The restore half of the pivot claim: it bumps the course's counter to
331- /// prove the row is there and must put it back *exactly* as it found it —
332- /// absent, which the boot backfill keys on (`WHERE enrollment_count =
333- /// NONE`). An empty roster is the case that has no seat write to hide a
334- /// leftover bump behind.
508+ /// D10: the instance's own teacher, the şube's homeroom teacher and a
509+ /// manager may act on it; another instance's teacher and a plain student
510+ /// may not. Assignment itself is the office's call and the assignee must
511+ /// hold the teacher bar.
335512 #[tokio::test]
336- async fn the_pivot_claim_gives_the_courses_counter_back_untouched() {
513+ async fn the_instance_gate_admits_its_teachers_homeroom_and_managers() {
337514 let (db, _leases) = crate::database::init_test_db().await;
338- let class = a_class("9-A", &db).await;
339- let algebra = a_course("algebra", None, &db).await;
340- // The course's own counter: fresh means 0 (the Postgres column is
341- // NOT NULL DEFAULT 0), and the claim's bump must be restored, not
342- // left dangling at 1 with an empty roster behind it.
343- let count = || {
344- sqlx::query_scalar::<_, i64>("SELECT enrollment_count FROM course WHERE id = $1")
345- .bind(algebra.uuid())
346- };
347- assert_eq!(
348- count().fetch_one(&db).await.unwrap(),
349- 0,
350- "a fresh course carries no count"
515+ let manager = staff(&db, "mudur", Role::Manager).await;
516+ let assigned = staff(&db, "ayse", Role::Teacher).await;
517+ let outsider = staff(&db, "mehmet", Role::Teacher).await;
518+ let homeroom = staff(&db, "zeynep", Role::Teacher).await;
519+ let student = crate::db::class_member::tests::fixture_user(&db, "ogrenci").await;
520+ let algebra = a_course("algebra", &db).await;
521+ let class = class_group::create(
522+ &db,
523+ &manager,
524+ crate::domain::class_group::ClassName::try_new("9-A").unwrap(),
525+ None,
526+ None,
527+ Some(homeroom),
528+ )
529+ .await
530+ .unwrap();
531+ let instance = attach(&db, &class.get_id().clone(), &algebra, &manager)
532+ .await
533+ .unwrap();
534+
535+ assign_teacher(&db, instance.get_id(), &assigned, &manager)
536+ .await
537+ .unwrap();
538+ // Idempotent, like every other assignment.
539+ assign_teacher(&db, instance.get_id(), &assigned, &manager)
540+ .await
541+ .unwrap();
542+
543+ assert!(
544+ ensure_instance_teacher(&db, &user_of(&db, &manager).await, instance.get_id())
545+ .await
546+ .is_ok()
547+ );
548+ assert!(
549+ ensure_instance_teacher(&db, &user_of(&db, &assigned).await, instance.get_id())
550+ .await
551+ .is_ok()
552+ );
553+ assert!(
554+ ensure_instance_teacher(&db, &user_of(&db, &homeroom).await, instance.get_id())
555+ .await
556+ .is_ok()
557+ );
558+ assert!(
559+ ensure_instance_teacher(&db, &user_of(&db, &outsider).await, instance.get_id())
560+ .await
561+ .is_err(),
562+ "a teacher of another instance is not this one's"
563+ );
564+ assert!(
565+ ensure_instance_teacher(&db, &user_of(&db, &student).await, instance.get_id())
566+ .await
567+ .is_err()
351568 );
352569
353- let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
354- attach(&db, &class, &algebra, &manager).await.unwrap();
355- assert_eq!(
356- count().fetch_one(&db).await.unwrap(),
357- 0,
358- "the claim's bump must be restored, not left dangling"
570+ // A student cannot be made an instance's teacher, and a non-manager
571+ // cannot assign one.
572+ let refused = assign_teacher(&db, instance.get_id(), &student, &manager).await;
573+ assert!(
574+ matches!(refused, Err(AppError::Validation(_))),
575+ "a student is not a teacher: {refused:?}"
576+ );
577+ let refused = assign_teacher(&db, instance.get_id(), &assigned, &outsider).await;
578+ assert!(
579+ matches!(refused, Err(AppError::Forbidden(_))),
580+ "staffing is the office's call: {refused:?}"
359581 );
360582 }
361583
362584 /// The `Menu::delete` defect on the class layer: a `class_course` row must
363585 /// not outlive the course it names. The attach's proof that the course is
364- /// still there is a *write* on the course row
365- /// ([`crate::db::class_pump::Axis::pivot_claim`]), landing it on the
366- /// very key `Course::delete`'s guard writes — but only because that write
367- /// now *moves* the counter. The `count = count` this shipped with left the
368- /// document unchanged, which SurrealDB 3.2.3 elides: it entered no write
369- /// set, collided with nothing, and both callers were told OK while the link
370- /// stayed pointing at a deleted course.
371- ///
372- /// The roster is empty deliberately — that is the only shape where nothing
373- /// else in the transaction touches the course row, so the claim is the
374- /// whole guard. One child per round, for the reason the menu twin
375- /// documents: a second writer makes the delete lose and re-send, and the
376- /// re-sent sweep clears the evidence.
377- ///
378- /// The window is opened by the schema, not by a lucky interleaving: a
379- /// `DEFINE EVENT` on `course` fires inside the delete's own transaction the
380- /// instant the row goes, so the `SLEEP` lands between the delete and its
381- /// `DELETE class_course WHERE course = $course` sweep every time.
382- ///
383- /// Real server, and `#[ignore]`d for it: the subject *is* the store's
384- /// conflict detection, which `init_mem`'s embedded engine does not have —
385- /// it commits both and answers `Ok` to each, so this passes there on broken
386- /// code.
586+ /// still there lands on the very row `Course::delete`'s guard locks, so
587+ /// whatever the interleaving, a link row and a deleted course can never
588+ /// both stand.
387589 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
388590 async fn a_class_course_link_never_outlives_the_course() {
389591 let (db, _leases) = crate::database::init_test_db().await;
@@ -391,16 +593,14 @@ mod tests {
391593 let (mut orphans, mut swept, mut miscounted) = (0, 0, 0);
392594 for round in 0..4 {
393595 let class = a_class(&format!("9-{round}"), &db).await;
394- let algebra = a_course(&format!("algebra{round}"), None, &db).await;
596+ let algebra = a_course(&format!("algebra{round}"), &db).await;
395597 let course = crate::db::course::read(&db, &algebra)
396598 .await
397599 .unwrap()
398600 .unwrap();
399601
400- // The old engine needed a schema event to hold the delete's
401- // window open; Postgres puts the racing delete and attach on the
402- // same rows, so a barrier start covers every interleaving — the
403- // link row may never outlive the course in any of them.
602+ // A barrier start covers every interleaving — the link row may
603+ // never outlive the course in any of them.
404604 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
405605 let drop_it = {
406606 let (db, gate, course) = (db.clone(), gate.clone(), course.clone());
@@ -414,6 +614,14 @@ mod tests {
414614 (db.clone(), class.clone(), algebra.clone(), manager, gate);
415615 tokio::spawn(async move {
416616 gate.wait().await;
617+ // Every other round the attach is held back a clear 2ms so
618+ // the delete wins outright (`swept > 0` below is a coin
619+ // toss without it): with the course counter claim live both
620+ // sides write the very row the guard reads, so whichever is
621+ // marginally faster otherwise takes every round under load.
622+ if round % 2 == 0 {
623+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;
624+ }
417625 attach(&db, &class, &algebra, &manager).await
418626 })
419627 };
src/service/class_group.rsmodified+20 -13
@@ -1,35 +1,35 @@
1-//! Class workflows: the archived-term guard every class write re-checks, and
1+//! Class workflows: the archived-year guard every class write re-checks, and
22 //! the thin route-facing wrappers the handlers call. The queries live in
33 //! [`crate::db::class_group`].
44
55 use crate::database::Database;
66 use crate::db::class_group;
7+use crate::domain::academic_year::AcademicYearId;
78 use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName};
8-use crate::domain::term::TermId;
99 use crate::domain::user::UserId;
1010 use crate::error::AppError;
1111
12-/// Refuse the write when this class's term is archived — a pre-flight guard,
13-/// accepted race (see README concurrency model): a term archived after this
12+/// Refuse the write when this class's year is archived — a pre-flight guard,
13+/// accepted race (see README concurrency model): a year archived after this
1414 /// read still lets the write through.
1515 pub async fn require_open(db: &Database, class: &ClassGroup) -> Result<(), AppError> {
16- match class.get_term() {
16+ match class.get_year() {
1717 None => Ok(()),
18- Some(term) => crate::service::term::require_open(db, term).await,
18+ Some(year) => crate::service::academic_year::require_open(db, year).await,
1919 }
2020 }
2121
22-/// Create a class, claiming the term reference in the same transaction —
22+/// Create a class, claiming the year reference in the same transaction —
2323 /// see [`class_group::create`].
2424 pub async fn create(
2525 db: &Database,
2626 creator: &UserId,
2727 name: ClassName,
2828 grade: Option<ClassGrade>,
29- term: Option<TermId>,
29+ year: Option<AcademicYearId>,
3030 teacher: Option<UserId>,
3131 ) -> Result<ClassGroup, AppError> {
32- class_group::create(db, creator, name, grade, term, teacher).await
32+ class_group::create(db, creator, name, grade, year, teacher).await
3333 }
3434
3535 /// The row, for callers that only inspect it — the web layer's
@@ -55,20 +55,27 @@ pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result<Vec<Clas
5555 class_group::list_by_ids(db, ids).await
5656 }
5757
58-/// Write only the fields the PATCH carried; a term move claims the new term
58+/// Every class `user` is the homeroom teacher of, newest first — the visible
59+/// set a sınıf öğretmeni reads their own instances through (D10), the read
60+/// behind `visible_instances` in the web layer.
61+pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<ClassGroup>, AppError> {
62+ class_group::list_for_teacher(db, user).await
63+}
64+
65+/// Write only the fields the PATCH carried; a year move claims the new year
5966 /// and releases the old one inside the very transaction that moves the link.
6067 pub async fn update(
6168 db: &Database,
6269 class: ClassGroup,
6370 name: Option<ClassName>,
6471 grade: Option<Option<ClassGrade>>,
65- term: Option<Option<TermId>>,
72+ year: Option<Option<AcademicYearId>>,
6673 teacher: Option<Option<UserId>>,
6774 ) -> Result<ClassGroup, AppError> {
68- class_group::update(db, class, name, grade, term, teacher).await
75+ class_group::update(db, class, name, grade, year, teacher).await
6976 }
7077
71-/// Delete the class and give its term reference back; `false` = refused,
78+/// Delete the class and give its year reference back; `false` = refused,
7279 /// nothing was written (the class still holds students or courses).
7380 pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> {
7481 class_group::delete(db, class).await
src/service/class_member.rsmodified+211 -139
@@ -1,8 +1,9 @@
1-//! Class-membership workflows: the member-axis add and remove — the pump's
2-//! refusals mapped to this route's answers, and a zero-row sweep turned into
3-//! a 404 — plus the roster reads the web layer pages through. The transaction
4-//! itself lives in [`crate::db::class_pump`]; the table reads in
5-//! [`crate::db::class_member`].
1+//! Class-membership workflows: the member-axis add and the two exits — the
2+//! soft `leave` a route takes and the hard `remove` a transfer rollback needs —
3+//! with the pump's refusals mapped to this route's answers and a zero-row
4+//! sweep turned into a 404, plus the roster reads the web layer pages through.
5+//! The transaction itself lives in [`crate::db::class_pump`]; the table reads
6+//! in [`crate::db::class_member`].
67
78 use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
89 use crate::database::Database;
@@ -16,10 +17,9 @@ use crate::error::{AppError, ValidationError};
1617 /// Put `user` in `class` and enroll them into every course the class is
1718 /// already attached to, in one transaction.
1819 ///
19-/// A student already enrolled in one of those courses keeps the row they
20-/// have — no seat is charged and their `source` is untouched, so a
21-/// hand-placed enrollment is never adopted by the class — and a course with
22-/// no free seat refuses the *whole* join rather than half of it.
20+/// A student already enrolled in one of those instances keeps the row they
21+/// have — no second enrollment and their `source` untouched, so a hand-placed
22+/// enrollment is never adopted by the class.
2323 pub async fn add(
2424 db: &Database,
2525 class: &ClassGroupId,
@@ -59,12 +59,8 @@ pub async fn add(
5959 detach some before adding a student"
6060 ),
6161 }),
62- class_pump::Attached::Full(course) => Err(AppError::ConflictCoded {
63- code,
64- message: format!("{course} is full, so the class cannot take this student"),
65- }),
66- // Not a capacity problem, and told apart from one on purpose: no
67- // number anyone can raise unblocks this class, only detaching the
62+ // Not a ceiling someone can raise, and told apart from one on
63+ // purpose: no number changes this class's answer, only detaching the
6864 // link the deleted course left behind.
6965 class_pump::Attached::CourseGone(course) => Err(AppError::ConflictCoded {
7066 code,
@@ -78,13 +74,30 @@ pub async fn add(
7874 }
7975 }
8076
81-/// Take `user` out of `class` and sweep the enrollments the class pumped
82-/// for them. A student who was not in the class is a
83-/// [`AppError::NotFound`], raised here rather than left to each caller to
84-/// re-derive from a boolean.
77+/// Take `user` out of `class` — the *soft* exit the route takes: the stint's
78+/// `left_at` is stamped and the row stays as history, while the class's member
79+/// count comes back so the student no longer counts as a live member. A
80+/// student who rejoins later gets a fresh live row beside the old one, which
81+/// is how "left in October, came back in January" is represented.
82+///
83+/// A student who was not in the class is a [`AppError::NotFound`], raised here
84+/// rather than left to each caller to re-derive from a boolean. The
85+/// enrollments the class pumped for them are released — one row per instance,
86+/// so a seat they also hold in another section teaching the same course is
87+/// that section's own row and is not touched (see
88+/// [`class_pump::leave_member`]).
89+pub async fn leave(db: &Database, class: &ClassGroupId, user: &UserId) -> Result<(), AppError> {
90+ let gone = class_pump::leave_member(db, class, user).await?;
91+ (gone > 0).then_some(()).ok_or(AppError::NotFound)
92+}
93+
94+/// Take `user` out of `class` for good — the hard exit, which deletes the
95+/// stint rather than stamping it. Kept for the şube-transfer rollback path
96+/// alone, where the stint being undone must leave no trace a later read could
97+/// mistake for history; every route uses [`leave`].
8598 ///
86-/// An enrollment another attached class still claims is re-tagged to that
87-/// class instead of deleted (see [`class_pump::remove_member`]).
99+/// The enrollment release is [`leave`]'s: every row the stint owned goes, and
100+/// no other section's seat is affected (see [`class_pump::remove_member`]).
88101 pub async fn remove(db: &Database, class: &ClassGroupId, user: &UserId) -> Result<(), AppError> {
89102 let gone = class_pump::remove_member(db, class, user).await?;
90103 (gone > 0).then_some(()).ok_or(AppError::NotFound)
@@ -115,73 +128,76 @@ pub async fn list_for_user(
115128 #[cfg(test)]
116129 mod tests {
117130 use super::*;
131+ use crate::db::class_member::is_live_member;
118132 use crate::db::class_member::tests::{
119133 a_class, a_course, counter, enrollment_exists, rows, source_of,
120134 };
121135 use crate::service::class_course;
122136
123- /// Adding a member enrolls them into every course the class already
137+ /// Adding a member enrolls them into every instance the class already
124138 /// carries, each row tagged with the class, and the class's own member
125139 /// counter ticks once.
126140 #[tokio::test]
127- async fn a_member_is_enrolled_into_every_attached_course() {
141+ async fn a_member_is_enrolled_into_every_attached_instance() {
128142 let (db, _leases) = crate::database::init_test_db().await;
129143 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
130144 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
131145 let class = a_class("9-A", &db).await;
132- let algebra = a_course("algebra", None, &db).await;
133- let physics = a_course("physics", None, &db).await;
134- class_course::attach(&db, &class, &algebra, &manager)
146+ let algebra = a_course("algebra", &db).await;
147+ let physics = a_course("physics", &db).await;
148+ let algebra_instance = class_course::attach(&db, &class, &algebra, &manager)
135149 .await
136150 .unwrap();
137- class_course::attach(&db, &class, &physics, &manager)
151+ let physics_instance = class_course::attach(&db, &class, &physics, &manager)
138152 .await
139153 .unwrap();
140154
141155 add(&db, &class, &student, &manager).await.unwrap();
142156
143- for course in [&algebra, &physics] {
157+ for instance in [&algebra_instance, &physics_instance] {
144158 assert_eq!(
145- source_of(course, &student, &db).await,
159+ source_of(instance.get_id(), &student, &db).await,
146160 Some(Some(class.clone())),
147- "every attached course must hold a row tagged with the class"
161+ "every attached instance must hold a row tagged with the class"
162+ );
163+ assert_eq!(
164+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
165+ 1
148166 );
149- assert_eq!(counter("enrollment_count", course.uuid(), &db).await, 1);
150167 }
151168 assert_eq!(counter("class_member_count", class.uuid(), &db).await, 1);
152169 }
153170
154- /// The pumped row must carry the *same* composite id a hand enroll would
155- /// mint, or the two paths would key one pair two ways and only the unique
156- /// index (a 500) would notice.
171+ /// The pumped row keys the same `(instance, user)` pair a hand enroll
172+ /// writes, or the two paths would key one pair two ways and only the
173+ /// primary key (a 500) would notice.
157174 #[tokio::test]
158- async fn a_pumped_row_uses_the_hand_enrolls_composite_id() {
175+ async fn a_pumped_row_uses_the_hand_enrolls_pair() {
159176 let (db, _leases) = crate::database::init_test_db().await;
160177 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
161178 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
162179 let class = a_class("9-A", &db).await;
163- let algebra = a_course("algebra", None, &db).await;
164- class_course::attach(&db, &class, &algebra, &manager)
180+ let algebra = a_course("algebra", &db).await;
181+ let instance = class_course::attach(&db, &class, &algebra, &manager)
165182 .await
166183 .unwrap();
167184 add(&db, &class, &student, &manager).await.unwrap();
168185
169186 assert!(
170- enrollment_exists(&algebra, &student, &db).await,
171- "the pump must key the pair the way Enrollment::composite does"
187+ enrollment_exists(instance.get_id(), &student, &db).await,
188+ "the pump must key the pair the way enrollment does"
172189 );
173190 }
174191
175- /// Re-adding is a 409, and it must cost nothing: no second counter tick and
176- /// no second sweep of anybody's enrollment.
192+ /// Re-adding is a 409, and it must cost nothing: no second counter tick.
177193 #[tokio::test]
178194 async fn a_second_add_is_refused_and_writes_nothing() {
179195 let (db, _leases) = crate::database::init_test_db().await;
180196 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
181197 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
182198 let class = a_class("9-A", &db).await;
183- let algebra = a_course("algebra", None, &db).await;
184- class_course::attach(&db, &class, &algebra, &manager)
199+ let algebra = a_course("algebra", &db).await;
200+ let instance = class_course::attach(&db, &class, &algebra, &manager)
185201 .await
186202 .unwrap();
187203 add(&db, &class, &student, &manager).await.unwrap();
@@ -196,113 +212,113 @@ mod tests {
196212 1,
197213 "a refused add may not tick the counter"
198214 );
199- assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
215+ assert_eq!(
216+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
217+ 1
218+ );
200219 }
201220
202- /// Adding into a class whose courses have no room refuses the *whole* join:
203- /// the roomy course must not keep a seat the full one denied.
221+ /// A student already enrolled by hand keeps their own row: the pump skips
222+ /// it, and leaving the class leaves it standing.
204223 #[tokio::test]
205- async fn a_full_course_refuses_the_whole_join() {
224+ async fn a_hand_placed_enrollment_is_skipped_and_survives_the_exit() {
206225 let (db, _leases) = crate::database::init_test_db().await;
207226 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
208227 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
209228 let class = a_class("9-A", &db).await;
210- let roomy = a_course("algebra", None, &db).await;
211- let full = a_course("physics", Some(0), &db).await;
212- class_course::attach(&db, &class, &roomy, &manager)
229+ let algebra = a_course("algebra", &db).await;
230+ let instance = class_course::attach(&db, &class, &algebra, &manager)
213231 .await
214232 .unwrap();
215- class_course::attach(&db, &class, &full, &manager)
233+ crate::db::enrollment::enroll(&db, instance.get_id(), &student, &manager, None)
216234 .await
217235 .unwrap();
218236
219- // The refusal names the course that had no seat. Postgres ids are
220- // bare uuids (no record-id prefix to inherit), so the message is
221- // matched on the course's own key.
222- let named = full.key().to_string();
223- let refused = add(&db, &class, &student, &manager).await;
224- assert!(
225- matches!(refused, Err(AppError::ConflictCoded { code, ref message })
226- if code == "course_full" && message.contains(&named)),
227- "the refusal must be coded `course_full` and name the course that had no seat \
228- as {named}: {refused:?}"
237+ add(&db, &class, &student, &manager).await.unwrap();
238+ assert_eq!(
239+ source_of(instance.get_id(), &student, &db).await,
240+ Some(None),
241+ "the class must not adopt a hand-placed row"
229242 );
230243 assert_eq!(
231- rows("enrollment", &db).await,
232- 0,
233- "not one seat may survive the refusal"
244+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
245+ 1,
246+ "the skipped pair may not be counted twice"
234247 );
248+
249+ leave(&db, &class, &student).await.unwrap();
235250 assert_eq!(
236- rows("class_member", &db).await,
237- 0,
238- "…nor the membership row itself"
251+ source_of(instance.get_id(), &student, &db).await,
252+ Some(None),
253+ "the sweep may only take back the rows the class wrote"
239254 );
240255 assert_eq!(
241- counter("enrollment_count", roomy.uuid(), &db).await,
242- 0,
243- "…nor the roomy course's counter"
256+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
257+ 1
244258 );
245- assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
246259 }
247260
248- /// A student already enrolled by hand keeps their own row: no seat is
249- /// charged for them, the row's `source` stays empty, and removing them from
250- /// the class leaves it standing.
261+ /// The soft exit: the stint is stamped, not deleted, and a rejoin writes a
262+ /// fresh live row beside it — the shape "left in October, came back in
263+ /// January" needs.
251264 #[tokio::test]
252- async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() {
265+ async fn a_leave_stamps_the_stint_and_a_rejoin_writes_a_second_row() {
253266 let (db, _leases) = crate::database::init_test_db().await;
254267 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
255268 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
256269 let class = a_class("9-A", &db).await;
257- let algebra = a_course("algebra", None, &db).await;
258- crate::db::enrollment::enroll(&db, &algebra, &student, &manager)
270+ let algebra = a_course("algebra", &db).await;
271+ let instance = class_course::attach(&db, &class, &algebra, &manager)
259272 .await
260273 .unwrap();
261- class_course::attach(&db, &class, &algebra, &manager)
262- .await
263- .unwrap();
264-
265274 add(&db, &class, &student, &manager).await.unwrap();
275+
276+ leave(&db, &class, &student).await.unwrap();
266277 assert_eq!(
267- source_of(&algebra, &student, &db).await,
268- Some(None),
269- "the class must not adopt a hand-placed row"
270- );
271- assert_eq!(
272- counter("enrollment_count", algebra.uuid(), &db).await,
278+ rows("class_member", &db).await,
273279 1,
274- "the skipped pair may not be charged a second seat"
280+ "the stint is history, not a deletion"
281+ );
282+ assert!(
283+ !is_live_member(&db, &class, &student).await.unwrap(),
284+ "…and it no longer counts as a live member"
275285 );
286+ assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
276287
277- remove(&db, &class, &student).await.unwrap();
288+ // The rejoin is a fresh row: the partial unique index only guards the
289+ // live stint, so the pair may hold one live row again.
290+ add(&db, &class, &student, &manager).await.unwrap();
291+ assert_eq!(rows("class_member", &db).await, 2);
292+ assert!(is_live_member(&db, &class, &student).await.unwrap());
293+ assert_eq!(counter("class_member_count", class.uuid(), &db).await, 1);
278294 assert_eq!(
279- source_of(&algebra, &student, &db).await,
280- Some(None),
281- "the sweep may only take back the rows the class wrote"
295+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
296+ 1,
297+ "the rejoin enrols the pair once, not twice"
282298 );
283- assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
284299 }
285300
286- /// Removal with nobody else claiming the row: the enrollment goes and its
287- /// seat comes back.
301+ /// The hard exit deletes the stint and sweeps the rows the class pumped —
302+ /// the transfer-rollback path.
288303 #[tokio::test]
289- async fn removal_deletes_the_rows_the_class_pumped() {
304+ async fn a_remove_deletes_the_stint_and_the_rows_the_class_pumped() {
290305 let (db, _leases) = crate::database::init_test_db().await;
291306 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
292307 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
293308 let class = a_class("9-A", &db).await;
294- let algebra = a_course("algebra", None, &db).await;
295- class_course::attach(&db, &class, &algebra, &manager)
309+ let algebra = a_course("algebra", &db).await;
310+ let instance = class_course::attach(&db, &class, &algebra, &manager)
296311 .await
297312 .unwrap();
298313 add(&db, &class, &student, &manager).await.unwrap();
299314
300315 remove(&db, &class, &student).await.unwrap();
301- assert_eq!(source_of(&algebra, &student, &db).await, None);
316+ assert_eq!(rows("class_member", &db).await, 0);
317+ assert_eq!(source_of(instance.get_id(), &student, &db).await, None);
302318 assert_eq!(
303- counter("enrollment_count", algebra.uuid(), &db).await,
319+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
304320 0,
305- "the seat must come back with the row that held it"
321+ "the count must come back with the row that held it"
306322 );
307323 assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
308324 let again = remove(&db, &class, &student).await;
@@ -312,33 +328,24 @@ mod tests {
312328 );
313329 }
314330
315- /// A member who is not in any attached course still removes cleanly, and a
316- /// course deleted out from under the class leaves nothing to sweep — the
317- /// membership row and the pumped enrollment are independent facts.
331+ /// A member whose class no longer carries the course still leaves cleanly:
332+ /// the membership row and the pumped enrollment are independent facts.
318333 #[tokio::test]
319- async fn a_sweep_tolerates_rows_a_course_delete_already_took() {
334+ async fn a_sweep_tolerates_an_instance_the_class_already_dropped() {
320335 let (db, _leases) = crate::database::init_test_db().await;
321336 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
322337 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
323338 let class = a_class("9-A", &db).await;
324- let algebra = a_course("algebra", None, &db).await;
339+ let algebra = a_course("algebra", &db).await;
325340 class_course::attach(&db, &class, &algebra, &manager)
326341 .await
327342 .unwrap();
328343 add(&db, &class, &student, &manager).await.unwrap();
329344
330- // `Course::delete` refuses while the roster is occupied, so the wipe is
331- // spelled the way the cascade does it, minus the guard — children
332- // first, the FK ordering the cascade itself runs.
333- for sql in [
334- "DELETE FROM enrollment WHERE course = $1",
335- "DELETE FROM class_course WHERE course = $1",
336- "DELETE FROM course WHERE id = $1",
337- ] {
338- sqlx::query(sql).bind(algebra.uuid()).execute(&db).await.unwrap();
339- }
340-
341- remove(&db, &class, &student)
345+ // The detach takes the instance and the rows it pumped; the stint
346+ // survives it, so the exit has nothing left to sweep.
347+ class_course::detach(&db, &class, &algebra).await.unwrap();
348+ leave(&db, &class, &student)
342349 .await
343350 .expect("the membership must still be removable with its enrollment gone");
344351 assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
@@ -346,8 +353,8 @@ mod tests {
346353
347354 /// The role-change sweep, which is one transaction with the role write
348355 /// itself: the memberships go with their counters, the enrollment rows go
349- /// with their seats, and each seat comes back exactly once — the double
350- /// decrement the old two-call split existed to avoid.
356+ /// with their instance counts, and each count comes back exactly once —
357+ /// the double decrement the old two-call split existed to avoid.
351358 #[tokio::test]
352359 async fn the_role_sweep_takes_memberships_and_enrollments_together() {
353360 let (db, _leases) = crate::database::init_test_db().await;
@@ -363,8 +370,8 @@ mod tests {
363370 let student = *account.get_id();
364371 let first = a_class("9-A", &db).await;
365372 let second = a_class("club", &db).await;
366- let algebra = a_course("algebra", None, &db).await;
367- class_course::attach(&db, &first, &algebra, &manager)
373+ let algebra = a_course("algebra", &db).await;
374+ let instance = class_course::attach(&db, &first, &algebra, &manager)
368375 .await
369376 .unwrap();
370377 add(&db, &first, &student, &manager).await.unwrap();
@@ -373,8 +380,16 @@ mod tests {
373380 crate::service::user::set_role(&db, account.get_id(), crate::domain::role::Role::Teacher)
374381 .await
375382 .unwrap();
376- assert_eq!(rows("class_member", &db).await, 0);
383+ assert_eq!(
384+ rows("class_member", &db).await,
385+ 2,
386+ "the stints stay as history — a soft leave, not a deletion"
387+ );
377388 for class in [&first, &second] {
389+ assert!(
390+ !is_live_member(&db, class, &student).await.unwrap(),
391+ "no live stint may survive the sweep"
392+ );
378393 assert_eq!(
379394 counter("class_member_count", class.uuid(), &db).await,
380395 0,
@@ -382,29 +397,86 @@ mod tests {
382397 );
383398 }
384399 assert_eq!(
385- source_of(&algebra, &student, &db).await,
400+ source_of(instance.get_id(), &student, &db).await,
386401 None,
387402 "the enrollment goes in the same transaction as the membership"
388403 );
389404 assert_eq!(
390- counter("enrollment_count", algebra.uuid(), &db).await,
405+ counter("enrollment_count", instance.get_id().uuid(), &db).await,
391406 0,
392- "…and its seat comes back once, not twice"
407+ "…and its count comes back once, not twice"
393408 );
394- // Which is the point of folding them: the class the student was in is
395- // free of them entirely — no membership, no count, and no enrollment
396- // row left tagged with a class that is about to be deletable.
397- assert!(
398- crate::db::class_group::delete(
399- &db,
400- crate::db::class_group::read(&db, &second)
401- .await
402- .unwrap()
403- .unwrap(),
404- )
409+ // Which is the point of folding them: the sweep is one transaction, so
410+ // no enrollment row is left tagged with a class whose live roster is
411+ // already empty — the shape that stranded rows nothing could reach.
412+ assert_eq!(
413+ counter("class_course_count", first.uuid(), &db).await,
414+ 1,
415+ "the attachment itself is untouched by a role sweep"
416+ );
417+ }
418+
419+ /// D4: a member exit **releases** the rows the leaving section wrote —
420+ /// there is no heir to hand one over to. Two şubeler teaching the same
421+ /// catalog course hold the student in their *own* instance, each with its
422+ /// own row tagged with its own class, so a release may only take the
423+ /// leaving section's row and count back; the rival's row stands exactly as
424+ /// written. The old rule re-tagged the row with a rival section instead
425+ /// (keeping it on the juncture of a class that no longer held the student),
426+ /// which is what this pins gone.
427+ #[tokio::test]
428+ async fn a_member_exit_releases_its_own_row_and_leaves_the_rivals_standing() {
429+ let (db, _leases) = crate::database::init_test_db().await;
430+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
431+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
432+ let first = a_class("5-A", &db).await;
433+ let second = a_class("5-B", &db).await;
434+ let algebra = a_course("algebra", &db).await;
435+ let first_instance = class_course::attach(&db, &first, &algebra, &manager)
405436 .await
406- .unwrap(),
407- "a class holding neither members nor courses must delete"
437+ .unwrap();
438+ let second_instance = class_course::attach(&db, &second, &algebra, &manager)
439+ .await
440+ .unwrap();
441+
442+ // Both sections hold the student, so both instances carry a row — each
443+ // tagged with the section that pumped it.
444+ for class in [&first, &second] {
445+ add(&db, class, &student, &manager).await.unwrap();
446+ }
447+ assert_eq!(
448+ source_of(first_instance.get_id(), &student, &db).await,
449+ Some(Some(first.clone()))
450+ );
451+ assert_eq!(
452+ source_of(second_instance.get_id(), &student, &db).await,
453+ Some(Some(second.clone()))
454+ );
455+
456+ // 5-A lets the student go: its own row goes and its own count comes
457+ // back. 5-B's row is a row *it* wrote, on *its* instance, and stands.
458+ leave(&db, &first, &student).await.unwrap();
459+ assert_eq!(
460+ source_of(first_instance.get_id(), &student, &db).await,
461+ None,
462+ "the leaving section's row must be released"
463+ );
464+ assert_eq!(
465+ counter("enrollment_count", first_instance.get_id().uuid(), &db).await,
466+ 0,
467+ "…and its roster count comes back with it"
468+ );
469+ assert_eq!(
470+ source_of(second_instance.get_id(), &student, &db).await,
471+ Some(Some(second.clone())),
472+ "the rival section's own row and its tag must stand"
473+ );
474+ assert_eq!(
475+ counter("enrollment_count", second_instance.get_id().uuid(), &db).await,
476+ 1,
477+ "…and so must the rival's roster count"
408478 );
479+ assert_eq!(counter("class_member_count", first.uuid(), &db).await, 0);
480+ assert_eq!(counter("class_member_count", second.uuid(), &db).await, 1);
409481 }
410482 }
src/service/course.rsmodified+16 -74
@@ -1,39 +1,27 @@
1-//! Course workflows: the archived-term gate every course-scoped write pays,
2-//! the staffing changes a manager makes, and the delete that collects the
3-//! image/homework/note-file blob keys before the guarded cascade sweeps
4-//! those rows. The queries live in
1+//! Course workflows: the catalog's CRUD — the template a şube attaches, with
2+//! no term, capacity or teacher list of its own any more (D1/D5/D6: staffing
3+//! and roster live on the instances, [`crate::service::class_course`]) — and
4+//! the delete that collects the image/homework/note-file blob keys before the
5+//! guarded cascade sweeps those rows. The queries live in
56 //! [`crate::db::course`].
67
78 use crate::database::Database;
89 use crate::db::course;
910 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
10-use crate::domain::role::Role;
11-use crate::domain::term::TermId;
1211 use crate::domain::user::UserId;
13-use crate::error::{AppError, ValidationError};
14-use crate::service::term;
15-
16-/// Refuse the write when this course's term is archived — a pre-flight guard,
17-/// accepted race (see README concurrency model): a term archived after this
18-/// read still lets the write through.
19-pub async fn require_open(db: &Database, course: &Course) -> Result<(), AppError> {
20- let Some(term) = course.get_term().cloned() else {
21- return Ok(());
22- };
23- let db = db.clone();
24- term::require_open(&db, &term).await
25-}
12+use crate::error::AppError;
2613
14+/// Mint a catalog course. The catalog is not bound to a dönem (D1): exams are,
15+/// through their instance, and no capacity is stored — the roster counter
16+/// lives on the instance and gates nothing.
2717 pub async fn create(
2818 db: &Database,
2919 creator: &UserId,
3020 title: CourseTitle,
3121 description: CourseDescription,
3222 kind: CourseKind,
33- term: Option<TermId>,
34- capacity: Option<i64>,
3523 ) -> Result<Course, AppError> {
36- course::create(db, creator, title, description, kind, term, capacity).await
24+ course::create(db, creator, title, description, kind).await
3725 }
3826
3927 pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> {
@@ -69,63 +57,16 @@ pub async fn update(
6957 title: Option<CourseTitle>,
7058 description: Option<CourseDescription>,
7159 kind: Option<CourseKind>,
72- term: Option<Option<TermId>>,
73- capacity: Option<Option<i64>>,
74-) -> Result<Course, AppError> {
75- course::update(db, course, title, description, kind, term, capacity).await
76-}
77-
78-/// Assign `target` to run `course`, or return the course untouched if they
79-/// already run it — assignment is idempotent, like enrollment.
80-///
81-/// The assignee must already hold the `teacher` role or higher: assignment
82-/// hands out course-management rights, which every gate behind it re-checks
83-/// against the `teacher` bar — assigning anyone below it would write a row
84-/// that can never be used.
85-pub async fn assign_teacher(
86- db: &Database,
87- course: &Course,
88- target: &UserId,
8960 ) -> Result<Course, AppError> {
90- require_open(db, course).await?;
91- let Some(target_user) = crate::db::user::read(db, target).await? else {
92- return Err(AppError::Validation(ValidationError::Invalid {
93- field: "user_id",
94- reason: "target user does not exist",
95- }));
96- };
97- if !target_user.get_role().at_least(Role::Teacher) {
98- return Err(AppError::Validation(ValidationError::Invalid {
99- field: "user_id",
100- reason: "assigned teacher must hold the teacher role or higher",
101- }));
102- }
103- course::assign_teacher(db, course.clone(), target).await
104-}
105-
106-/// Drop `target` from this course's assigned teachers. `None` when they
107-/// weren't assigned, so the web layer can answer 404 instead of pretending
108-/// it removed someone.
109-pub async fn unassign_teacher(
110- db: &Database,
111- course: &Course,
112- target: &UserId,
113-) -> Result<Option<Course>, AppError> {
114- require_open(db, course).await?;
115- course::unassign_teacher(db, course.clone(), target).await
116-}
117-
118-/// Strip `user` from every course they were assigned to — the sweep for a
119-/// user demoted below `teacher`, who may no longer run anything.
120-pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
121- course::unassign_everywhere(db, user).await
61+ course::update(db, course, title, description, kind).await
12262 }
12363
12464 /// What [`delete`] did: whether the course went, and the blob keys of the
12565 /// rows its cascade removed — exactly whose files the web layer may unlink.
12666 #[derive(Debug)]
12767 pub struct DeleteOutcome {
128- /// `false` = refused, nothing was written: someone is still enrolled.
68+ /// `false` = refused, nothing was written: a şube still teaches this
69+ /// course, or a student still holds an individual membership in it.
12970 pub deleted: bool,
13071 pub image_files: Vec<String>,
13172 pub answer_image_files: Vec<String>,
@@ -134,7 +75,9 @@ pub struct DeleteOutcome {
13475 }
13576
13677 /// Delete the course: collect the image/homework/note-file blob keys, then
137-/// run the cascading delete.
78+/// run the cascading delete — which takes every instance the catalog is taught
79+/// in (with everything under them), every individual membership and every
80+/// teacher link, all in one guarded transaction.
13881 ///
13982 /// The old writer leases on the exam-attempt and homework state are gone
14083 /// with the store that needed them: this cascade is one guarded
@@ -149,7 +92,6 @@ pub struct DeleteOutcome {
14992 /// web layer's job — a crash in between strands at worst an unreachable
15093 /// blob.
15194 pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> {
152- require_open(db, course).await?;
15395 let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?;
15496 let answer_image_files =
15597 crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?;
src/service/course_session.rsmodified+9 -10
@@ -6,7 +6,7 @@
66
77 use crate::database::Database;
88 use crate::db::course_session;
9-use crate::domain::course::CourseId;
9+use crate::domain::class_course::ClassCourseId;
1010 use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};
1111 use crate::domain::role::Role;
1212 use crate::domain::timestamp::Timestamp;
@@ -47,32 +47,31 @@ pub async fn resolve_session_teacher(
4747 Ok(user)
4848 }
4949
50-/// Schedule a lesson on `course`. The write bumps the course row in the same
51-/// transaction (`cap::touch_and_create`), so a lesson can never outlive its
52-/// course — a create racing the course delete refuses instead of orphaning.
50+/// Schedule a lesson on `class_course` — one dated occurrence of the instance,
51+/// which is what a roll call hangs off.
5352 pub async fn create(
5453 db: &Database,
55- course: &CourseId,
54+ class_course: &ClassCourseId,
5655 teacher: &UserId,
5756 topic: SessionTopic,
5857 starts_at: Timestamp,
5958 ends_at: Option<Timestamp>,
6059 ) -> Result<CourseSession, AppError> {
61- course_session::create(db, course, teacher, topic, starts_at, ends_at).await
60+ course_session::create(db, class_course, teacher, topic, starts_at, ends_at).await
6261 }
6362
6463 pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> {
6564 course_session::read(db, id).await
6665 }
6766
68-/// A course's sessions, most recent lesson first — the timetable read.
69-pub async fn list_for_course(
67+/// An instance's sessions, most recent lesson first — the timetable read.
68+pub async fn list_for_class_course(
7069 db: &Database,
71- course: &CourseId,
70+ class_course: &ClassCourseId,
7271 limit: Option<i64>,
7372 offset: i64,
7473 ) -> Result<(Vec<CourseSession>, i64), AppError> {
75- course_session::list_for_course(db, course, limit, offset).await
74+ course_session::list_for_class_course(db, class_course, limit, offset).await
7675 }
7776
7877 /// Only what the request carried is written: an omitted field (`None`) is
src/service/enrollment.rsmodified+95 -35
@@ -1,52 +1,47 @@
11 //! Enrollment workflows: the target-user gates the enroll/unenroll HTTP
22 //! handlers pay (the target must exist and still be a student; unenrolling a
3-//! pair with no row is a 404) wrapped around the atomic seat claim in
4-//! [`crate::db::enrollment`].
3+//! pair with no row is a 404) wrapped around the instance-keyed write in
4+//! [`crate::db::enrollment`], plus the school-scoped club/etüt membership
5+//! ([`crate::db::course_membership`]) with the one rule that keeps the two
6+//! tiers apart: a class-delivered ders is joined through its instance, never
7+//! directly.
58
69 use crate::database::Database;
10+use crate::db::course_membership;
711 use crate::db::enrollment;
12+use crate::domain::class_course::ClassCourseId;
813 use crate::domain::course::CourseId;
14+use crate::domain::course_membership::CourseMembership;
915 use crate::domain::enrollment::Enrollment;
1016 use crate::domain::role::Role;
1117 use crate::domain::user::UserId;
1218 use crate::error::{AppError, ValidationError};
1319
14-/// Enroll `target` into `course` on `enrolled_by`'s orders. The target-user
15-/// gates first — they are validation of the request, so a 400, and they run
16-/// in the order the handler used to: an unknown user outranks a non-student
17-/// one — then the claim (idempotent for an already-enrolled pair; 409 on a
18-/// full roster; 404 when the course is gone).
20+/// Enroll `target` into one class×course instance on `enrolled_by`'s orders —
21+/// the hand placement, so the row carries no class `source` and no class sweep
22+/// can ever take it back. The target-user gates first — they are validation of
23+/// the request, so a 400, and they run in the order the handler used to: an
24+/// unknown user outranks a non-student one — then the idempotent write (an
25+/// already-enrolled pair is returned as-is; 404 when the instance is gone).
1926 pub async fn enroll(
2027 db: &Database,
21- course: &CourseId,
28+ class_course: &ClassCourseId,
2229 target: &UserId,
2330 enrolled_by: &UserId,
2431 ) -> Result<Enrollment, AppError> {
25- let Some(target_user) = crate::db::user::read(db, target).await? else {
26- return Err(AppError::Validation(ValidationError::Invalid {
27- field: "user_id",
28- reason: "target user does not exist",
29- }));
30- };
31-
32- // Enrollment is student membership: it gates sitting exams, being graded,
33- // and appearing on a lesson roster — all student-only. Staff run courses,
34- // they don't enroll in them.
35- if target_user.get_role() != Role::Student {
36- return Err(AppError::Validation(ValidationError::Invalid {
37- field: "user_id",
38- reason: "only students can be enrolled in a course",
39- }));
40- }
41-
42- enrollment::enroll(db, course, target, enrolled_by).await
32+ ensure_student(db, target, "only students can be enrolled in a course").await?;
33+ enrollment::enroll(db, class_course, target, enrolled_by, None).await
4334 }
4435
45-/// Unenroll `target` from `course`. `NotFound` when the pair holds no row —
46-/// unenrolling someone who was never enrolled removed nothing, so the web
36+/// Unenroll `target` from one instance. `NotFound` when the pair holds no row
37+/// — unenrolling someone who was never enrolled removed nothing, so the web
4738 /// layer must not pretend they did.
48-pub async fn unenroll(db: &Database, course: &CourseId, target: &UserId) -> Result<(), AppError> {
49- enrollment::remove(db, course, target)
39+pub async fn unenroll(
40+ db: &Database,
41+ class_course: &ClassCourseId,
42+ target: &UserId,
43+) -> Result<(), AppError> {
44+ enrollment::remove(db, class_course, target)
5045 .await?
5146 .ok_or(AppError::NotFound)?;
5247 Ok(())
@@ -54,17 +49,82 @@ pub async fn unenroll(db: &Database, course: &CourseId, target: &UserId) -> Resu
5449
5550 pub async fn read_for_user(
5651 db: &Database,
57- course: &CourseId,
52+ class_course: &ClassCourseId,
5853 user: &UserId,
5954 ) -> Result<Option<Enrollment>, AppError> {
60- enrollment::read_for_user(db, course, user).await
55+ enrollment::read_for_user(db, class_course, user).await
6156 }
6257
63-pub async fn list_for_course(
58+/// One instance's roster, newest first, paged.
59+pub async fn list_for_class_course(
6460 db: &Database,
65- course: &CourseId,
61+ class_course: &ClassCourseId,
6662 limit: Option<i64>,
6763 offset: i64,
6864 ) -> Result<(Vec<Enrollment>, i64), AppError> {
69- enrollment::list_for_course(db, course, limit, offset).await
65+ enrollment::list_for_class_course(db, class_course, limit, offset).await
66+}
67+
68+/// Join `target` to a school-scoped course — a kulüp or an etüt — on `added_by`
69+/// 's orders.
70+///
71+/// The one refusal this tier owns: a class-delivered ders
72+/// ([`CourseKind::is_class_delivered`](crate::domain::course::CourseKind::is_class_delivered))
73+/// has no school-wide roster to join — its students come from the şubeler that
74+/// teach it — so a direct join is a `400` naming the course, and the instance's
75+/// enrollment route is where that request belongs.
76+pub async fn join_activity(
77+ db: &Database,
78+ course: &CourseId,
79+ target: &UserId,
80+ added_by: &UserId,
81+) -> Result<CourseMembership, AppError> {
82+ let Some(course_row) = crate::service::course::read(db, course).await? else {
83+ return Err(AppError::NotFound);
84+ };
85+ if course_row.get_kind().is_class_delivered() {
86+ return Err(AppError::Validation(ValidationError::Invalid {
87+ field: "course_id",
88+ reason: "a ders is joined through the class instance that teaches it, not directly",
89+ }));
90+ }
91+ ensure_student(db, target, "only students can join a course").await?;
92+ course_membership::add(db, course, target, added_by).await
93+}
94+
95+/// Leave a school-scoped course. `NotFound` when the pair holds no membership
96+/// — leaving something one never joined removed nothing.
97+pub async fn leave_activity(
98+ db: &Database,
99+ course: &CourseId,
100+ target: &UserId,
101+) -> Result<(), AppError> {
102+ course_membership::remove(db, course, target)
103+ .await?
104+ .ok_or(AppError::NotFound)?;
105+ Ok(())
106+}
107+
108+/// The target-user gates both tiers share: the row must exist and be a
109+/// student. Membership is student membership — it gates sitting exams, being
110+/// graded, and appearing on a roster — all student-only. Staff run courses,
111+/// they don't enroll in them.
112+async fn ensure_student(
113+ db: &Database,
114+ target: &UserId,
115+ reason: &'static str,
116+) -> Result<(), AppError> {
117+ let Some(target_user) = crate::db::user::read(db, target).await? else {
118+ return Err(AppError::Validation(ValidationError::Invalid {
119+ field: "user_id",
120+ reason: "target user does not exist",
121+ }));
122+ };
123+ if target_user.get_role() != Role::Student {
124+ return Err(AppError::Validation(ValidationError::Invalid {
125+ field: "user_id",
126+ reason,
127+ }));
128+ }
129+ Ok(())
70130 }
src/service/exam.rsmodified+82 -17
@@ -1,8 +1,9 @@
1-//! Exam workflows: the PATCH re-derive — the merge (set / clear / keep per
2-//! field) re-judged against a fresh read every retry round, and the
3-//! mode-freeze, re-draft, and kind gates that guard it — and the delete that
4-//! collects the image blob keys inside the cascade's own transaction. The
5-//! queries live in [`crate::db::exam`]; the sitting workflows next door in
1+//! Exam workflows: the create that resolves the exam's instance and dönem,
2+//! the PATCH re-derive — the merge (set / clear / keep per field) re-judged
3+//! against a fresh read every retry round, and the mode-freeze, re-draft, and
4+//! kind gates that guard it — and the delete that collects the image blob keys
5+//! inside the cascade's own transaction. The queries live in
6+//! [`crate::db::exam`]; the sitting workflows next door in
67 //! [`crate::service::exam_attempt`].
78
89 use crate::constant::CAS_UPDATE_RETRIES;
@@ -10,17 +11,34 @@ use crate::database::Database;
1011 use crate::db::exam;
1112 use crate::db::exam_attempt::any_for_exam;
1213 use crate::db::exam_result;
14+use crate::domain::class_course::ClassCourseId;
1315 use crate::domain::course::CourseId;
1416 use crate::domain::exam::{
1517 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
1618 ExamSchedule, ExamTitle, redraft_error,
1719 };
20+use crate::domain::term::TermId;
1821 use crate::domain::timestamp::Timestamp;
1922 use crate::domain::user::UserId;
20-use crate::error::AppError;
21-use crate::service::course::require_open;
22-use crate::service::exam_attempt::course_of;
23+use crate::error::{AppError, ValidationError};
24+use crate::service::exam_attempt::require_open;
2325
26+/// Publish (or draft) an exam on one class×course instance, inside one dönem.
27+///
28+/// Two refusals stand in front of the write. The instance's catalog course
29+/// must be class-delivered (`kind = course`): a kulüp or etüt has no exams —
30+/// D9 keeps the two membership tiers apart, and an exam on a club would be a
31+/// roster nothing enrolls into. And the instance's *year* must still be open
32+/// (D8: the dönem is a grading slice inside the year, so the year is what the
33+/// exam's structure belongs to; a dönem archived inside an open year does not
34+/// close exam creation — the archive is a record, not a wall).
35+///
36+/// The `term` is the dönem the exam is sat in, and it is required; the store's
37+/// create claims it in the same transaction as the row. It must be one of the
38+/// *instance's own year's* dönems: a dönem is a grading slice inside a year, so
39+/// a term from another year is refused here with a `400` on the field rather
40+/// than filed — the write would succeed in the store and misfile the exam in
41+/// the karne of a year it is not taught in.
2442 #[expect(
2543 clippy::too_many_arguments,
2644 reason = "mirrors the sibling entities' create(field, field, ..) shape"
@@ -28,7 +46,8 @@ use crate::service::exam_attempt::course_of;
2846 pub async fn create(
2947 db: &Database,
3048 creator: &UserId,
31- course: &CourseId,
49+ class_course: &ClassCourseId,
50+ term: &TermId,
3251 title: ExamTitle,
3352 description: ExamDescription,
3453 kind: ExamKind,
@@ -38,10 +57,42 @@ pub async fn create(
3857 allow_review: bool,
3958 draft: bool,
4059 ) -> Result<Exam, AppError> {
60+ let Some(instance) = crate::db::class_course::read(db, class_course).await? else {
61+ return Err(AppError::NotFound);
62+ };
63+ let Some(course) = crate::db::course::read(db, instance.get_course()).await? else {
64+ return Err(AppError::Internal(
65+ "the instance references a missing course".into(),
66+ ));
67+ };
68+ if !course.get_kind().is_class_delivered() {
69+ return Err(AppError::Validation(ValidationError::Invalid {
70+ field: "course",
71+ reason: "only a ders can carry exams — a club or etüt is joined, not sat",
72+ }));
73+ }
74+ // The dönem must be one of the instance's own year's: the year is the
75+ // scope a karne is computed over (and a dönem is a grading slice *inside*
76+ // it), so an exam filed under another year's dönem would be counted into a
77+ // report whose terms it does not belong to — invisible to the year it is
78+ // actually taught in and foreign to the one it names. The instance's year
79+ // is its şube's, read through the one seam that resolves it.
80+ let Some(term_row) = crate::db::term::read(db, term).await? else {
81+ return Err(crate::domain::term::gone_error());
82+ };
83+ let instance_year = crate::service::class_course::year_of(db, class_course).await?;
84+ if instance_year != Some(*term_row.get_year()) {
85+ return Err(AppError::Validation(ValidationError::Invalid {
86+ field: "term",
87+ reason: "the term belongs to another academic year than this class",
88+ }));
89+ }
90+ crate::service::class_course::require_open(db, class_course).await?;
4191 exam::create(
4292 db,
4393 creator,
44- course,
94+ class_course,
95+ term,
4596 title,
4697 description,
4798 kind,
@@ -64,12 +115,27 @@ pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
64115 exam::list_all(db).await
65116 }
66117
67-pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Exam>, AppError> {
68- exam::list_for_course(db, course).await
118+/// One instance's exams, newest first — the read behind
119+/// `GET /instances/{id}/exams`.
120+pub async fn list_for_class_course(
121+ db: &Database,
122+ class_course: &ClassCourseId,
123+) -> Result<Vec<Exam>, AppError> {
124+ exam::list_for_class_course(db, class_course).await
125+}
126+
127+/// Every exam of every instance in `instances` (one query) — the karne and
128+/// marks reports' cross-instance read, and the list behind a caller's visible
129+/// instances.
130+pub async fn list_for_class_course_courses(
131+ db: &Database,
132+ instances: &[ClassCourseId],
133+) -> Result<Vec<Exam>, AppError> {
134+ exam::list_for_class_course_courses(db, instances).await
69135 }
70136
71-/// Every exam of every course in `courses` (one query) — the catalog as one
72-/// user sees it.
137+/// Every exam of every catalog course in `courses` (one query) — the catalog
138+/// as one user sees it, across the instances those courses are taught in.
73139 pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec<Exam>, AppError> {
74140 exam::list_for_courses(db, courses).await
75141 }
@@ -118,8 +184,7 @@ pub async fn update(db: &Database, id: &ExamId, patch: &ExamPatch) -> Result<Exa
118184 let mut left = CAS_UPDATE_RETRIES;
119185 loop {
120186 let current = exam::read(db, id).await?.ok_or(AppError::NotFound)?;
121- let course = course_of(&current, db).await?;
122- require_open(db, &course).await?;
187+ require_open(db, &current).await?;
123188
124189 let title = patch
125190 .title
@@ -264,7 +329,7 @@ pub struct DeleteOutcome {
264329 /// out-of-transaction snapshot cannot strand its bytes on disk even though
265330 /// the row itself is now refused.
266331 pub async fn delete(db: &Database, target: &Exam) -> Result<DeleteOutcome, AppError> {
267- require_open(db, &course_of(target, db).await?).await?;
332+ require_open(db, target).await?;
268333 // Rows go first (the delete cascades them), blobs after — a crash in
269334 // between strands at worst an unreachable blob.
270335 let deleted = exam::delete(db, target.clone()).await?;
src/service/exam_attempt.rsmodified+54 -18
@@ -18,7 +18,7 @@
1818 /// ([`crate::db::subject::delete`]) needs no partner lock at all.
1919 use crate::database::Database;
2020 use crate::db::cap;
21-use crate::domain::course::Course;
21+use crate::domain::class_course::ClassCourse;
2222
2323 use crate::domain::exam::{Exam, ExamId};
2424 use crate::domain::exam_answer::ExamAnswer;
@@ -28,7 +28,6 @@ use crate::domain::timestamp::Timestamp;
2828 use crate::domain::user::{User, UserId};
2929 use crate::error::AppError;
3030
31-
3231 /// Rejects sitting an exam that can't be sat. A draft is a `404`, not a
3332 /// `409` — sitting is a student act, drafts are invisible to students, and a
3433 /// state-specific error would leak the existence this feature hides. A
@@ -74,12 +73,13 @@ pub async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppE
7473 ensure_student(&user)
7574 }
7675
77-/// A 403 unless `user` is enrolled in the exam's course — the same wall the
78-/// exam room checks at its door, re-applied to the sitting's content paths so
79-/// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the
80-/// rejoin lock, submitting what's already saved writes nothing new.
76+/// A 403 unless `user` is enrolled in the instance the exam belongs to — the
77+/// 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 stays
79+/// exempt: like the rejoin lock, submitting what's already saved writes
80+/// nothing new.
8181 pub async fn ensure_enrolled(exam: &Exam, user: &UserId, db: &Database) -> Result<(), AppError> {
82- if crate::db::enrollment::read_for_user(db, exam.get_course(), user)
82+ if crate::db::enrollment::read_for_user(db, exam.get_class_course(), user)
8383 .await?
8484 .is_none()
8585 {
@@ -122,12 +122,25 @@ pub async fn writable_attempt(
122122 }
123123 }
124124
125-/// The course an exam belongs to. A dangling reference means the course-delete
126-/// cascade was violated — surface it loudly as a 500, not a user-facing 404.
127-pub async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> {
128- crate::db::course::read(db, exam.get_course())
125+/// The class×course instance an exam belongs to. A dangling reference means
126+/// the instance's delete cascade was violated — surface it loudly as a 500,
127+/// not a user-facing 404.
128+pub async fn class_course_of(exam: &Exam, db: &Database) -> Result<ClassCourse, AppError> {
129+ crate::db::class_course::read(db, exam.get_class_course())
129130 .await?
130- .ok_or_else(|| AppError::Internal("exam references a missing course".into()))
131+ .ok_or_else(|| AppError::Internal("exam references a missing class instance".into()))
132+}
133+
134+/// The archived-year refusal every exam write pays: the exam's instance must
135+/// still sit under an open year. Past years are read-only, and the year — not
136+/// the dönem the exam names — is what the exam's structure belongs to.
137+///
138+/// The instance read doubles as the dangling-reference check
139+/// ([`class_course_of`]); the year itself is read by
140+/// [`crate::service::class_course::require_open`].
141+pub async fn require_open(db: &Database, exam: &Exam) -> Result<(), AppError> {
142+ let instance = class_course_of(exam, db).await?;
143+ crate::service::class_course::require_open(db, instance.get_id()).await
131144 }
132145
133146 /// Start, resume, or retake `user`'s attempt at `exam`. Returns the attempt
@@ -254,7 +267,7 @@ pub async fn start_attempt(
254267 ensure_sittable(&exam)?;
255268 ensure_student(user)?;
256269 ensure_enrolled(&exam, user.get_id(), db).await?;
257- crate::service::course::require_open(db, &course_of(&exam, db).await?).await?;
270+ crate::service::exam_attempt::require_open(db, &exam).await?;
258271 let now = Timestamp::now();
259272 if let Some(starts_at) = exam.get_starts_at()
260273 && now < starts_at
@@ -294,7 +307,7 @@ pub async fn finish_attempt(
294307 {
295308 return Err(AppError::Conflict("time is up — the attempt has expired"));
296309 }
297- crate::service::course::require_open(db, &course_of(exam, db).await?).await?;
310+ crate::service::exam_attempt::require_open(db, exam).await?;
298311 crate::db::exam_attempt::finish(db, attempt).await
299312 }
300313
@@ -338,7 +351,7 @@ pub async fn save_answer_in(
338351 ensure_student_now(attempt.get_user(), db).await?;
339352 ensure_enrolled(exam, attempt.get_user(), db).await?;
340353 check_rejoin(exam, attempt)?;
341- crate::service::course::require_open(db, &course_of(exam, db).await?).await?;
354+ crate::service::exam_attempt::require_open(db, exam).await?;
342355 let question =
343356 crate::service::exam_question::question_of_exam(exam.get_id(), question_id, db).await?;
344357 crate::db::exam_answer::save(
@@ -453,15 +466,38 @@ mod tests {
453466 .execute(db)
454467 .await
455468 .unwrap();
456- let course = crate::db::course::a_test_course(db).await;
469+ let (class_course, _course) = crate::db::course::a_test_instance(db).await;
470+ // A dönem for the exam to be sat in: the year it belongs to is real
471+ // (the create claims it), and the shape is the calendar's own.
472+ let manager = crate::db::class_member::tests::fixture_user(db, "manager").await;
473+ let year = crate::db::academic_year::create(
474+ db,
475+ &manager,
476+ crate::domain::academic_year::AcademicYearName::try_new("2026-2027").unwrap(),
477+ Timestamp::from_millis(0),
478+ Timestamp::from_millis(1),
479+ Vec::new(),
480+ )
481+ .await
482+ .unwrap();
483+ let term = crate::db::term::create(
484+ db,
485+ crate::domain::term::TermName::try_new("1. Dönem").unwrap(),
486+ *year.get_id(),
487+ Timestamp::from_millis(0),
488+ Timestamp::from_millis(1),
489+ )
490+ .await
491+ .unwrap();
457492 let kinds = Settings::defaults().get_exam_kinds().to_vec();
458493 let exam = crate::db::exam::create(
459494 db,
460495 &creator,
461- &course,
496+ &class_course,
497+ term.get_id(),
462498 ExamTitle::try_new("practice").unwrap(),
463499 ExamDescription::try_new("").unwrap(),
464- ExamKind::try_new("quiz", &kinds).unwrap(),
500+ ExamKind::try_new("yazili", &kinds).unwrap(),
465501 ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
466502 .unwrap(),
467503 ExamAttemptLimit::try_new(max_attempts).unwrap(),
src/service/exam_result.rsmodified+11 -11
@@ -1,16 +1,16 @@
11 //! Exam-mark workflows: the grading gate chain, ungrading behind the
2-//! archived-term gate, and the read doors the web layer takes. The mark's
2+//! archived-year gate, and the read doors the web layer takes. The mark's
33 //! own claim-riding transaction lives in [`crate::db::exam_result`].
44
55 use crate::database::Database;
66 use crate::db;
7-use crate::domain::course::CourseId;
7+use crate::domain::class_course::ClassCourseId;
88 use crate::domain::exam::{Exam, ExamId};
99 use crate::domain::exam_result::{ExamResult, Mark};
1010 use crate::domain::role::Role;
1111 use crate::domain::user::UserId;
1212 use crate::error::{AppError, ValidationError};
13-use crate::service::exam_attempt::{course_of, read_latest_for_user};
13+use crate::service::exam_attempt::{read_latest_for_user, require_open};
1414
1515 /// Grade a student's current sitting: every wall the handler used to run
1616 /// (draft, retired kind, self-grade, target existence/role/enrollment), then
@@ -49,7 +49,7 @@ pub async fn grade(
4949 let exam = crate::service::exam::read(db, exam_id)
5050 .await?
5151 .ok_or(AppError::NotFound)?;
52- crate::service::course::require_open(db, &course_of(&exam, db).await?).await?;
52+ require_open(db, &exam).await?;
5353 // Pre-flight: `db::exam_result::grade` re-makes this check inside the
5454 // mark's own transaction, so a re-draft landing after this read cannot
5555 // leave a mark on a hidden exam.
@@ -91,8 +91,8 @@ pub async fn grade(
9191 }));
9292 }
9393
94- // ... and be enrolled in the exam's course.
95- if crate::service::enrollment::read_for_user(db, exam.get_course(), target)
94+ // ... and be enrolled in the instance the exam belongs to.
95+ if crate::service::enrollment::read_for_user(db, exam.get_class_course(), target)
9696 .await?
9797 .is_none()
9898 {
@@ -124,7 +124,7 @@ pub async fn remove(
124124 exam: &Exam,
125125 target: &UserId,
126126 ) -> Result<Option<ExamResult>, AppError> {
127- crate::service::course::require_open(db, &course_of(exam, db).await?).await?;
127+ require_open(db, exam).await?;
128128 db::exam_result::remove(db, exam.get_id(), target, exam.get_kind().as_str()).await
129129 }
130130
@@ -151,12 +151,12 @@ pub async fn list_all_for_exam_user(
151151 db::exam_result::list_all_for_exam_user(db, exam, user).await
152152 }
153153
154-/// The user's graded results restricted to one course's exams — the raw
155-/// rows behind the per-course block of the marks report.
154+/// The user's graded results restricted to one instance's exams — the raw
155+/// rows behind the per-instance block of the marks report.
156156 pub async fn list_for_user_in_course(
157157 db: &Database,
158- course: &CourseId,
158+ class_course: &ClassCourseId,
159159 user: &UserId,
160160 ) -> Result<Vec<ExamResult>, AppError> {
161- db::exam_result::list_for_user_in_course(db, course, user).await
161+ db::exam_result::list_for_user_in_course(db, class_course, user).await
162162 }
src/service/fee_plan_assignment.rsmodified+2 -4

Diff too large; view file

@@ -359,8 +359,7 @@ mod tests {
359359 })
360360 };
361361 let assign = {
362- let (db, plan, manager, student) =
363- (db.clone(), plan.clone(), manager, student);
362+ let (db, plan, manager, student) = (db.clone(), plan.clone(), manager, student);
364363 tokio::spawn(async move { assign(&db, &plan, &student, &manager).await })
365364 };
366365 let (edit, assign) = (edit.await.unwrap(), assign.await.unwrap());
@@ -461,8 +460,7 @@ mod tests {
461460 })
462461 };
463462 let assign = {
464- let (db, plan, manager, student) =
465- (db.clone(), plan.clone(), manager, student);
463+ let (db, plan, manager, student) = (db.clone(), plan.clone(), manager, student);
466464 tokio::spawn(async move {
src/service/homework.rsmodified+40 -29

Diff too large; view file

src/service/homework_result.rsmodified+7 -7

Diff too large; view file

src/service/homework_submission.rsmodified+2 -2

Diff too large; view file

src/service/karne.rsadded+281 -0

Diff too large; view file

src/service/mod.rsmodified+2 -0

Diff too large; view file

src/service/payment_ledger.rsmodified+4 -10

Diff too large; view file

src/service/session_attendance.rsmodified+3 -3

Diff too large; view file

src/service/settings.rsmodified+60 -21

Diff too large; view file

src/service/term.rsmodified+30 -9

Diff too large; view file

src/service/user.rsmodified+5 -1

Diff too large; view file

src/web/academic_years.rsadded+394 -0

Diff too large; view file

src/web/appointments.rsmodified+19 -10

Diff too large; view file

src/web/attendance.rsmodified+257 -62

Diff too large; view file

src/web/board_ws.rsmodified+4 -3

Diff too large; view file

src/web/boards.rsmodified+12 -17

Diff too large; view file

src/web/classes.rsmodified+210 -120

Diff too large; view file

src/web/course_notes.rsmodified+31 -41

Diff too large; view file

src/web/courses.rsmodified+229 -864

Diff too large; view file

src/web/dto.rsmodified+46 -41

Diff too large; view file

src/web/events.rsmodified+6 -7

Diff too large; view file

src/web/exam_ws.rsmodified+7 -8

Diff too large; view file

src/web/exams/attempts.rsmodified+22 -21

Diff too large; view file

src/web/exams/images.rsmodified+36 -36

Diff too large; view file

src/web/exams/mod.rsmodified+72 -74

Diff too large; view file

src/web/exams/questions.rsmodified+73 -68

Diff too large; view file

src/web/exams/review.rsmodified+16 -16

Diff too large; view file

src/web/homework.rsmodified+144 -128

Diff too large; view file

src/web/instances.rsadded+1141 -0

Diff too large; view file

src/web/limits.rsmodified+12 -2

Diff too large; view file

src/web/marks.rsmodified+233 -38

Diff too large; view file

src/web/meals.rsmodified+4 -8

Diff too large; view file

src/web/messages.rsmodified+1 -6

Diff too large; view file

src/web/mod.rsmodified+39 -29

Diff too large; view file

src/web/module_gate.rsmodified+10 -10

Diff too large; view file

src/web/payments.rsmodified+4 -5

Diff too large; view file

src/web/sessions.rsmodified+70 -58

Diff too large; view file

src/web/settings.rsmodified+60 -4

Diff too large; view file

src/web/subjects.rsmodified+9 -13

Diff too large; view file