forge
Explore
Log in

Don't you dare go Hollow

Holiday calendar, slot topics, and the weekly-plan materializer core

Browse files at this commit

7c481f7049ed9e14d32b6be4fc81ff55a9fe488dAhmet Kaan GümüşParent: 450bc8c
  • feat
    • holiday calendar, slot topics, and the weekly-plan materializer core
Show full message
✨ feat(schedule): holiday calendar, slot topics, and the weekly-plan materializer core

Schema (migrations/school/20260924000001_holidays_and_materialize.sql): a
school-wide `holiday` table over instant ranges, an optional `topic` on both
weekly-plan slot tables, and UNIQUE (class_course, starts_at) on
course_session so two lessons of one section cannot start together.

Domain: `holiday` (name/kind/range newtypes, inclusive `overlaps`) and
`calendar` (the school-zone day math hoisted out of web/attendance, which now
imports it). `WeeklySlot` carries an optional topic; `overlaps` is unchanged.

Db: `holiday` CRUD + overlap-paged list + the materializer's unpaged read;
`course_session::insert_many` (one unnest INSERT .. ON CONFLICT DO NOTHING
RETURNING, so the reported rows are the rows actually inserted) plus
`existing_starts`; a duplicate start on the single-session route now answers
409 session_time_taken instead of a 500.

Service: `holiday` pass-throughs and `course_session::materialize` — one
transaction, archived-year wall, row lock on the instance, refusals coded
instance_has_no_weekly_plan / instance_has_no_teacher, a range cap of 366 days
and a candidate cap of 500, holidays and already-scheduled starts skipped and
counted, nothing ever deleted. Dry run is side-effect free.

The HTTP surface, per-section course lists, and the integration suite follow in
later commits.

31 changed files +1929 -168

.sqlx/query-01cb8fb2444f413ced7939feba2f299e307fbb6650c56d36d0ae9fb5ea49f91e.jsonadded+191 -0
@@ -0,0 +1,191 @@
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.offering AS \"offering: CourseOfferingId\",\n cc.attached_by AS \"attached_by: UserId\",\n b.grade_level AS \"source?: ClassBlueprintId\",\n cc.title AS \"title?: CourseTitle\",\n cc.description AS \"description?: CourseDescription\",\n cc.ders_saati::bigint AS \"ders_saati?: DersSaati\",\n cc.counts_toward_karne,\n cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,\n 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.course = 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": "offering: CourseOfferingId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "class_course",
46+ "name": "offering"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "attached_by: UserId",
53+ "type_info": "Uuid",
54+ "origin": {
55+ "Table": {
56+ "table": "class_course",
57+ "name": "attached_by"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "source?: ClassBlueprintId",
64+ "type_info": "Int2",
65+ "origin": {
66+ "Table": {
67+ "table": "class_blueprint",
68+ "name": "grade_level"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "title?: CourseTitle",
75+ "type_info": "Text",
76+ "origin": {
77+ "Table": {
78+ "table": "class_course",
79+ "name": "title"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "description?: CourseDescription",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "class_course",
90+ "name": "description"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "ders_saati?: DersSaati",
97+ "type_info": "Int8",
98+ "origin": "Expression"
99+ },
100+ {
101+ "ordinal": 9,
102+ "name": "counts_toward_karne",
103+ "type_info": "Bool",
104+ "origin": {
105+ "Table": {
106+ "table": "class_course",
107+ "name": "counts_toward_karne"
108+ }
109+ }
110+ },
111+ {
112+ "ordinal": 10,
113+ "name": "subjects_inherited",
114+ "type_info": "Bool",
115+ "origin": {
116+ "Table": {
117+ "table": "class_course",
118+ "name": "subjects_inherited"
119+ }
120+ }
121+ },
122+ {
123+ "ordinal": 11,
124+ "name": "exam_weights_inherited",
125+ "type_info": "Bool",
126+ "origin": {
127+ "Table": {
128+ "table": "class_course",
129+ "name": "exam_weights_inherited"
130+ }
131+ }
132+ },
133+ {
134+ "ordinal": 12,
135+ "name": "weekly_plan_inherited",
136+ "type_info": "Bool",
137+ "origin": {
138+ "Table": {
139+ "table": "class_course",
140+ "name": "weekly_plan_inherited"
141+ }
142+ }
143+ },
144+ {
145+ "ordinal": 13,
146+ "name": "enrollment_count",
147+ "type_info": "Int8",
148+ "origin": {
149+ "Table": {
150+ "table": "class_course",
151+ "name": "enrollment_count"
152+ }
153+ }
154+ },
155+ {
156+ "ordinal": 14,
157+ "name": "attached_at: Timestamp",
158+ "type_info": "Int8",
159+ "origin": {
160+ "Table": {
161+ "table": "class_course",
162+ "name": "attached_at"
163+ }
164+ }
165+ }
166+ ],
167+ "parameters": {
168+ "Left": [
169+ "UuidArray"
170+ ]
171+ },
172+ "nullable": [
173+ false,
174+ false,
175+ false,
176+ false,
177+ false,
178+ false,
179+ true,
180+ true,
181+ null,
182+ true,
183+ false,
184+ false,
185+ false,
186+ false,
187+ false
188+ ]
189+ },
190+ "hash": "01cb8fb2444f413ced7939feba2f299e307fbb6650c56d36d0ae9fb5ea49f91e"
191+}
.sqlx/query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.json → .sqlx/query-34e21f7794cb59e3565397da7620b1ea60bd13fbe21a3432d1f6952742af99a4.jsonrenamed+15 -3
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: WeeklySlotId\",\n weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\"\n FROM offering_slot\n WHERE offering = $1\n ORDER BY weekday, starts_at",3+ "query": "SELECT id AS \"id: WeeklySlotId\",\n weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\",\n topic AS \"topic?: SessionTopic\"\n FROM offering_slot\n WHERE offering = $1\n ORDER BY weekday, starts_at",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -36,6 +36,17 @@
36 "name": "ends_at!: SlotMinute",36 "name": "ends_at!: SlotMinute",
37 "type_info": "Int8",37 "type_info": "Int8",
38 "origin": "Expression"38 "origin": "Expression"
39+ },
40+ {
41+ "ordinal": 4,
42+ "name": "topic?: SessionTopic",
43+ "type_info": "Text",
44+ "origin": {
45+ "Table": {
46+ "table": "offering_slot",
47+ "name": "topic"
48+ }
49+ }
39 }50 }
40 ],51 ],
41 "parameters": {52 "parameters": {
@@ -47,8 +58,9 @@
47 false,58 false,
48 false,59 false,
49 null,60 null,
50- null61+ null,
62+ true
51 ]63 ]
52 },64 },
53- "hash": "b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9"65+ "hash": "34e21f7794cb59e3565397da7620b1ea60bd13fbe21a3432d1f6952742af99a4"
54 }66 }
.sqlx/query-3f1fd92a954287a6f430fa659bef98ac80a882f8df310ccd44ab7f1ca4f0e338.jsonadded+106 -0
@@ -0,0 +1,106 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO holiday (id, name, starts_at, ends_at, kind, creator, created_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n RETURNING id AS \"id: HolidayId\", name AS \"name: HolidayName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n kind AS \"kind: HolidayKind\", creator AS \"creator: UserId\",\n created_at AS \"created_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: HolidayId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "holiday",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "name: HolidayName",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "holiday",
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": "holiday",
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": "holiday",
46+ "name": "ends_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "kind: HolidayKind",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "holiday",
57+ "name": "kind"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "creator: UserId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "holiday",
68+ "name": "creator"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "created_at: Timestamp",
75+ "type_info": "Int8",
76+ "origin": {
77+ "Table": {
78+ "table": "holiday",
79+ "name": "created_at"
80+ }
81+ }
82+ }
83+ ],
84+ "parameters": {
85+ "Left": [
86+ "Uuid",
87+ "Text",
88+ "Int8",
89+ "Int8",
90+ "Text",
91+ "Uuid",
92+ "Int8"
93+ ]
94+ },
95+ "nullable": [
96+ false,
97+ false,
98+ false,
99+ false,
100+ false,
101+ false,
102+ false
103+ ]
104+ },
105+ "hash": "3f1fd92a954287a6f430fa659bef98ac80a882f8df310ccd44ab7f1ca4f0e338"
106+}
.sqlx/query-5f4933f457252ca6c2346f8510f5f2978dca0f70af92972b00f2051ae2629e46.jsonadded+100 -0
@@ -0,0 +1,100 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM holiday WHERE id = $1\n RETURNING id AS \"id: HolidayId\", name AS \"name: HolidayName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n kind AS \"kind: HolidayKind\", creator AS \"creator: UserId\",\n created_at AS \"created_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: HolidayId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "holiday",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "name: HolidayName",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "holiday",
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": "holiday",
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": "holiday",
46+ "name": "ends_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "kind: HolidayKind",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "holiday",
57+ "name": "kind"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "creator: UserId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "holiday",
68+ "name": "creator"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "created_at: Timestamp",
75+ "type_info": "Int8",
76+ "origin": {
77+ "Table": {
78+ "table": "holiday",
79+ "name": "created_at"
80+ }
81+ }
82+ }
83+ ],
84+ "parameters": {
85+ "Left": [
86+ "Uuid"
87+ ]
88+ },
89+ "nullable": [
90+ false,
91+ false,
92+ false,
93+ false,
94+ false,
95+ false,
96+ false
97+ ]
98+ },
99+ "hash": "5f4933f457252ca6c2346f8510f5f2978dca0f70af92972b00f2051ae2629e46"
100+}
.sqlx/query-815fe85883c8355c4e150ebfaffa0c1ec8ed25a17bb2bd5aee6384db55f7ec24.jsonadded+93 -0
@@ -0,0 +1,93 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO course_session (id, class_course, teacher, topic, starts_at, ends_at)\n SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::uuid[], $4::text[], $5::bigint[], $6::bigint[])\n ON CONFLICT (class_course, starts_at) DO NOTHING\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\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: CourseSessionId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "course_session",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "class_course: ClassCourseId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "course_session",
24+ "name": "class_course"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "teacher: UserId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "course_session",
35+ "name": "teacher"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "topic: SessionTopic",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "course_session",
46+ "name": "topic"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "starts_at: Timestamp",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "course_session",
57+ "name": "starts_at"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "ends_at?: Timestamp",
64+ "type_info": "Int8",
65+ "origin": {
66+ "Table": {
67+ "table": "course_session",
68+ "name": "ends_at"
69+ }
70+ }
71+ }
72+ ],
73+ "parameters": {
74+ "Left": [
75+ "UuidArray",
76+ "UuidArray",
77+ "UuidArray",
78+ "TextArray",
79+ "Int8Array",
80+ "Int8Array"
81+ ]
82+ },
83+ "nullable": [
84+ false,
85+ false,
86+ false,
87+ false,
88+ false,
89+ true
90+ ]
91+ },
92+ "hash": "815fe85883c8355c4e150ebfaffa0c1ec8ed25a17bb2bd5aee6384db55f7ec24"
93+}
.sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.jsondeleted+0 -58
@@ -1,58 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "WITH ins AS (\n INSERT INTO class_course_slot (id, class_course, weekday, starts_at, ends_at)\n VALUES ($1, $2, $3,\n ($4::bigint * interval '1 minute')::time,\n ($5::bigint * interval '1 minute')::time)\n RETURNING id, weekday, starts_at, ends_at\n ), flip AS (\n UPDATE class_course SET weekly_plan_inherited = FALSE\n WHERE id = $2 AND EXISTS (SELECT 1 FROM ins)\n RETURNING id\n )\n SELECT ins.id AS \"id: WeeklySlotId\",\n ins.weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM ins.starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ins.ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\"\n FROM ins\n WHERE EXISTS (SELECT 1 FROM flip)",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "id: WeeklySlotId",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "class_course_slot",
13- "name": "id"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "weekday: Weekday",
20- "type_info": "Int2",
21- "origin": {
22- "Table": {
23- "table": "class_course_slot",
24- "name": "weekday"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "starts_at!: SlotMinute",
31- "type_info": "Int8",
32- "origin": "Expression"
33- },
34- {
35- "ordinal": 3,
36- "name": "ends_at!: SlotMinute",
37- "type_info": "Int8",
38- "origin": "Expression"
39- }
40- ],
41- "parameters": {
42- "Left": [
43- "Uuid",
44- "Uuid",
45- "Int2",
46- "Int8",
47- "Int8"
48- ]
49- },
50- "nullable": [
51- false,
52- false,
53- null,
54- null
55- ]
56- },
57- "hash": "855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d"
58-}
.sqlx/query-92a71caf8853da726ac8db8da956baf35ab1eec36c62b3aa211ad29b79706abc.jsonadded+71 -0
@@ -0,0 +1,71 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH ins AS (\n INSERT INTO class_course_slot (id, class_course, weekday, starts_at, ends_at, topic)\n VALUES ($1, $2, $3,\n ($4::bigint * interval '1 minute')::time,\n ($5::bigint * interval '1 minute')::time,\n $6)\n RETURNING id, weekday, starts_at, ends_at, topic\n ), flip AS (\n UPDATE class_course SET weekly_plan_inherited = FALSE\n WHERE id = $2 AND EXISTS (SELECT 1 FROM ins)\n RETURNING id\n )\n SELECT ins.id AS \"id: WeeklySlotId\",\n ins.weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM ins.starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ins.ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\",\n ins.topic AS \"topic?: SessionTopic\"\n FROM ins\n WHERE EXISTS (SELECT 1 FROM flip)",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: WeeklySlotId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_course_slot",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "weekday: Weekday",
20+ "type_info": "Int2",
21+ "origin": {
22+ "Table": {
23+ "table": "class_course_slot",
24+ "name": "weekday"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "starts_at!: SlotMinute",
31+ "type_info": "Int8",
32+ "origin": "Expression"
33+ },
34+ {
35+ "ordinal": 3,
36+ "name": "ends_at!: SlotMinute",
37+ "type_info": "Int8",
38+ "origin": "Expression"
39+ },
40+ {
41+ "ordinal": 4,
42+ "name": "topic?: SessionTopic",
43+ "type_info": "Text",
44+ "origin": {
45+ "Table": {
46+ "table": "class_course_slot",
47+ "name": "topic"
48+ }
49+ }
50+ }
51+ ],
52+ "parameters": {
53+ "Left": [
54+ "Uuid",
55+ "Uuid",
56+ "Int2",
57+ "Int8",
58+ "Int8",
59+ "Text"
60+ ]
61+ },
62+ "nullable": [
63+ false,
64+ false,
65+ null,
66+ null,
67+ true
68+ ]
69+ },
70+ "hash": "92a71caf8853da726ac8db8da956baf35ab1eec36c62b3aa211ad29b79706abc"
71+}
.sqlx/query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.json → .sqlx/query-af710dcd8d7a967a46895f14eb832a9931bd0291119e82af19090f9dc0b21a92.jsonrenamed+15 -3
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: WeeklySlotId\",\n weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\"\n FROM class_course_slot\n WHERE class_course = $1\n ORDER BY weekday, starts_at",3+ "query": "SELECT id AS \"id: WeeklySlotId\",\n weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\",\n topic AS \"topic?: SessionTopic\"\n FROM class_course_slot\n WHERE class_course = $1\n ORDER BY weekday, starts_at",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -36,6 +36,17 @@
36 "name": "ends_at!: SlotMinute",36 "name": "ends_at!: SlotMinute",
37 "type_info": "Int8",37 "type_info": "Int8",
38 "origin": "Expression"38 "origin": "Expression"
39+ },
40+ {
41+ "ordinal": 4,
42+ "name": "topic?: SessionTopic",
43+ "type_info": "Text",
44+ "origin": {
45+ "Table": {
46+ "table": "class_course_slot",
47+ "name": "topic"
48+ }
49+ }
39 }50 }
40 ],51 ],
41 "parameters": {52 "parameters": {
@@ -47,8 +58,9 @@
47 false,58 false,
48 false,59 false,
49 null,60 null,
50- null61+ null,
62+ true
51 ]63 ]
52 },64 },
53- "hash": "e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351"65+ "hash": "af710dcd8d7a967a46895f14eb832a9931bd0291119e82af19090f9dc0b21a92"
54 }66 }
.sqlx/query-c3274251614e38dd624befe49c4fc19920fd500e599d05d975c994eedc7c658b.jsonadded+100 -0
@@ -0,0 +1,100 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: HolidayId\", name AS \"name: HolidayName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n kind AS \"kind: HolidayKind\", creator AS \"creator: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM holiday WHERE id = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: HolidayId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "holiday",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "name: HolidayName",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "holiday",
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": "holiday",
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": "holiday",
46+ "name": "ends_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "kind: HolidayKind",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "holiday",
57+ "name": "kind"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "creator: UserId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "holiday",
68+ "name": "creator"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "created_at: Timestamp",
75+ "type_info": "Int8",
76+ "origin": {
77+ "Table": {
78+ "table": "holiday",
79+ "name": "created_at"
80+ }
81+ }
82+ }
83+ ],
84+ "parameters": {
85+ "Left": [
86+ "Uuid"
87+ ]
88+ },
89+ "nullable": [
90+ false,
91+ false,
92+ false,
93+ false,
94+ false,
95+ false,
96+ false
97+ ]
98+ },
99+ "hash": "c3274251614e38dd624befe49c4fc19920fd500e599d05d975c994eedc7c658b"
100+}
.sqlx/query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.json → .sqlx/query-e584ccedaaab3dcaf93bcdc9564f8fdeee58a09969da7a658de9a963c8682d27.jsonrenamed+17 -4
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "INSERT INTO offering_slot (id, offering, weekday, starts_at, ends_at)\n VALUES ($1, $2, $3,\n ($4::bigint * interval '1 minute')::time,\n ($5::bigint * interval '1 minute')::time)\n RETURNING id AS \"id: WeeklySlotId\",\n weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\"",3+ "query": "INSERT INTO offering_slot (id, offering, weekday, starts_at, ends_at, topic)\n VALUES ($1, $2, $3,\n ($4::bigint * interval '1 minute')::time,\n ($5::bigint * interval '1 minute')::time,\n $6)\n RETURNING id AS \"id: WeeklySlotId\",\n weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\",\n topic AS \"topic?: SessionTopic\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -36,6 +36,17 @@
36 "name": "ends_at!: SlotMinute",36 "name": "ends_at!: SlotMinute",
37 "type_info": "Int8",37 "type_info": "Int8",
38 "origin": "Expression"38 "origin": "Expression"
39+ },
40+ {
41+ "ordinal": 4,
42+ "name": "topic?: SessionTopic",
43+ "type_info": "Text",
44+ "origin": {
45+ "Table": {
46+ "table": "offering_slot",
47+ "name": "topic"
48+ }
49+ }
39 }50 }
40 ],51 ],
41 "parameters": {52 "parameters": {
@@ -44,15 +55,17 @@
44 "Uuid",55 "Uuid",
45 "Int2",56 "Int2",
46 "Int8",57 "Int8",
47- "Int8"58+ "Int8",
59+ "Text"
48 ]60 ]
49 },61 },
50 "nullable": [62 "nullable": [
51 false,63 false,
52 false,64 false,
53 null,65 null,
54- null66+ null,
67+ true
55 ]68 ]
56 },69 },
57- "hash": "d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738"70+ "hash": "e584ccedaaab3dcaf93bcdc9564f8fdeee58a09969da7a658de9a963c8682d27"
58 }71 }
.sqlx/query-ecbad4a883751a9e609b406830c6ec449a1c87f23c19374820611b784a1e28f1.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT starts_at FROM course_session WHERE class_course = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "starts_at",
9+ "type_info": "Int8",
10+ "origin": {
11+ "Table": {
12+ "table": "course_session",
13+ "name": "starts_at"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "ecbad4a883751a9e609b406830c6ec449a1c87f23c19374820611b784a1e28f1"
28+}
.sqlx/query-f7e609db6b3f1cc793bcf8f26739b4142938d5cedafea71addf525e5053d98b1.jsonadded+101 -0
@@ -0,0 +1,101 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: HolidayId\", name AS \"name: HolidayName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n kind AS \"kind: HolidayKind\", creator AS \"creator: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM holiday\n WHERE ends_at >= $1 AND starts_at <= $2\n ORDER BY starts_at",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: HolidayId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "holiday",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "name: HolidayName",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "holiday",
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": "holiday",
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": "holiday",
46+ "name": "ends_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "kind: HolidayKind",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "holiday",
57+ "name": "kind"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "creator: UserId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "holiday",
68+ "name": "creator"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "created_at: Timestamp",
75+ "type_info": "Int8",
76+ "origin": {
77+ "Table": {
78+ "table": "holiday",
79+ "name": "created_at"
80+ }
81+ }
82+ }
83+ ],
84+ "parameters": {
85+ "Left": [
86+ "Int8",
87+ "Int8"
88+ ]
89+ },
90+ "nullable": [
91+ false,
92+ false,
93+ false,
94+ false,
95+ false,
96+ false,
97+ false
98+ ]
99+ },
100+ "hash": "f7e609db6b3f1cc793bcf8f26739b4142938d5cedafea71addf525e5053d98b1"
101+}
README.mdmodified+1 -1
@@ -733,7 +733,7 @@ drift from it**, which is enforced rather than asked for:
733 and fails unless each one is either referenced by `src/web/limits.rs` or733 and fails unless each one is either referenced by `src/web/limits.rs` or
734 listed as a deliberate exclusion *with a reason*. A new constant breaks the734 listed as a deliberate exclusion *with a reason*. A new constant breaks the
735 suite until someone decides, consciously, whether clients need it.735 suite until someone decides, consciously, whether clients need it.
736-- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 239 published736+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 241 published
737 bounds back out of the emitted JSON, and asserts each equals its constant.737 bounds back out of the emitted JSON, and asserts each equals its constant.
738 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal738 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal
739 only** — a `const` there does not compile — so the annotations are739 only** — a `const` there does not compile — so the annotations are
migrations/school/20260924000001_holidays_and_materialize.sqladded+36 -0
@@ -0,0 +1,36 @@
1+-- Holiday calendar + weekly-plan materializer support.
2+--
3+-- `holiday` is the school-wide non-teaching calendar: named instant ranges
4+-- (the same shape `term`, `event`, `exam` and `academic_year` already use —
5+-- four of five dated resources are instants; no day type is introduced).
6+-- The weekly-plan materializer reads it to skip non-teaching days.
7+--
8+-- `offering_slot` / `class_course_slot` gain an optional `topic`: without it
9+-- every generated lesson of a section shares one topic, which is useless for
10+-- attendance and homework.
11+--
12+-- `course_session (class_course, starts_at)` becomes UNIQUE: two lessons of
13+-- one section cannot start at the same instant. This is what makes a
14+-- concurrent materialize idempotent (`ON CONFLICT DO NOTHING`), and it turns
15+-- the duplicate-start instant from a silent twin lesson into a conflict the
16+-- single-session create route answers with a coded 409. The deployed demo
17+-- school held no duplicate pair when this landed.
18+--
19+-- No tenant column: tenancy is one Postgres database per school.
20+
21+CREATE TABLE holiday (
22+ id uuid PRIMARY KEY,
23+ name TEXT NOT NULL,
24+ starts_at BIGINT NOT NULL,
25+ ends_at BIGINT NOT NULL,
26+ kind TEXT NOT NULL CHECK (kind IN ('resmi', 'dini', 'idari', 'ara')),
27+ creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
28+ created_at BIGINT NOT NULL
29+);
30+CREATE INDEX holiday_starts_at ON holiday (starts_at);
31+
32+ALTER TABLE offering_slot ADD COLUMN topic TEXT NULL;
33+ALTER TABLE class_course_slot ADD COLUMN topic TEXT NULL;
34+
35+CREATE UNIQUE INDEX course_session_class_course_starts_at
36+ ON course_session (class_course, starts_at);
src/constant.rsmodified+26 -0
@@ -239,6 +239,32 @@ pub const MAX_APPOINTMENT_REASON_LEN: usize = 1_000;
239 /// (a decade out) is refused instead of writing thousands of rows.239 /// (a decade out) is refused instead of writing thousands of rows.
240 pub const MAX_SLOT_OCCURRENCES: usize = 52;240 pub const MAX_SLOT_OCCURRENCES: usize = 52;
241 241
242+/// A holiday is named for a human reader ("29 Ekim Cumhuriyet Bayramı").
243+pub const MAX_HOLIDAY_NAME_LEN: usize = 100;
244+
245+/// The only accepted holiday kinds. `resmi`: an official public holiday.
246+/// `dini`: a religious observance. `idari`: an administrative closure the
247+/// school itself declares. `ara`: a break inside the year (yarım yıl arası).
248+pub const HOLIDAY_KINDS: [&str; 4] = ["resmi", "dini", "idari", "ara"];
249+
250+/// The holiday table's name, for the same builder-shaped writes every other
251+/// table names through its constant.
252+pub const HOLIDAY_TABLE: &str = "holiday";
253+
254+/// The longest `from`/`to` span one materialize call may cover, in days. A
255+/// school year fits; a decade is a typo and is refused.
256+pub const MAX_MATERIALIZE_DAYS: i64 = 366;
257+
258+/// The most lessons one materialize call may write. Forty slots a week is the
259+/// plan cap, so a full year is far under this; the ceiling is what stops a
260+/// runaway range from writing thousands of rows in one request.
261+pub const MAX_MATERIALIZE_SESSIONS: usize = 500;
262+
263+/// How many sections one catalogue course row may embed. A course taught in
264+/// more sections than this still lists them at `/instances`; the catalogue
265+/// row carries the untruncated total beside the array.
266+pub const MAX_COURSE_SECTIONS: usize = 50;
267+
242 /// The default meal slots; schools replace the list via `PATCH /settings`, and268 /// The default meal slots; schools replace the list via `PATCH /settings`, and
243 /// a published menu snapshots the slot it was written for, so retiring a slot269 /// a published menu snapshots the slot it was written for, so retiring a slot
244 /// never rewrites history.270 /// never rewrites history.
src/db/class_course.rsmodified+35 -0
@@ -146,6 +146,41 @@ pub async fn list_for_class_ids(
146 Ok(rows)146 Ok(rows)
147 }147 }
148 148
149+/// Every instance of any of `courses` (one query, unpaged) — the batched twin
150+/// of [`list_for_course`]: the catalogue page reads one query per page, not
151+/// one per course. Ids that name no course are simply absent from the result.
152+pub async fn list_for_course_ids(
153+ db: &Database,
154+ courses: &[CourseId],
155+) -> Result<Vec<ClassCourse>, AppError> {
156+ if courses.is_empty() {
157+ return Ok(Vec::new());
158+ }
159+ let ids: Vec<uuid::Uuid> = courses.iter().map(CourseId::uuid).collect();
160+ let rows = sqlx::query_as!(
161+ ClassCourse,
162+ r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId",
163+ cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId",
164+ cc.attached_by AS "attached_by: UserId",
165+ b.grade_level AS "source?: ClassBlueprintId",
166+ cc.title AS "title?: CourseTitle",
167+ cc.description AS "description?: CourseDescription",
168+ cc.ders_saati::bigint AS "ders_saati?: DersSaati",
169+ cc.counts_toward_karne,
170+ cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,
171+ cc.enrollment_count,
172+ cc.attached_at AS "attached_at: Timestamp"
173+ FROM class_course cc
174+ LEFT JOIN class_blueprint b ON b.id = cc.source
175+ WHERE cc.course = ANY($1)
176+ ORDER BY cc.attached_at DESC, cc.id DESC"#,
177+ &ids,
178+ )
179+ .fetch_all(db)
180+ .await?;
181+ Ok(rows)
182+}
183+
149 /// Load every instance behind `ids` (one query) — the join half of the reads184 /// Load every instance behind `ids` (one query) — the join half of the reads
150 /// that already hold instance ids (a marks report's per-instance blocks).185 /// that already hold instance ids (a marks report's per-instance blocks).
151 pub async fn list_by_ids(186 pub async fn list_by_ids(
src/db/course_session.rsmodified+94 -1
@@ -6,7 +6,9 @@
6 //! [`crate::service::course_session`].6 //! [`crate::service::course_session`].
7 7
8 use crate::constant::COURSE_SESSION_TABLE;8 use crate::constant::COURSE_SESSION_TABLE;
9-use crate::database::{Database, foreign_key_violation, tx_with_retry};9+use crate::database::{
10+ Database, foreign_key_violation, tx_with_retry, unique_violation,
11+};
10 use crate::db::field_update::FieldUpdate;12 use crate::db::field_update::FieldUpdate;
11 use crate::db::page::PagedList;13 use crate::db::page::PagedList;
12 use crate::domain::class_course::ClassCourseId;14 use crate::domain::class_course::ClassCourseId;
@@ -58,10 +60,101 @@ pub async fn create(
58 match created {60 match created {
59 Ok(created) => Ok(created),61 Ok(created) => Ok(created),
60 Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),62 Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),
63+ // `23505` — the section's own `UNIQUE (class_course, starts_at)`: a
64+ // lesson already starts at that instant (a hand-created one, or one a
65+ // concurrent materialize just minted). The same refusal the
66+ // weekly-plan duplicate answers with.
67+ Err(err) if unique_violation(&err).is_some() => Err(AppError::ConflictCoded {
68+ code: "session_time_taken",
69+ message: "this section already has a lesson starting then".into(),
70+ }),
61 Err(err) => Err(err.into()),71 Err(err) => Err(err.into()),
62 }72 }
63 }73 }
64 74
75+/// One session to batch-insert: everything the materializer already decided.
76+/// The wire shape of [`insert_many`], not a door of its own.
77+#[derive(Debug, Clone)]
78+pub struct NewSession {
79+ pub id: CourseSessionId,
80+ pub class_course: ClassCourseId,
81+ pub teacher: UserId,
82+ pub topic: SessionTopic,
83+ pub starts_at: Timestamp,
84+ pub ends_at: Timestamp,
85+}
86+
87+/// Insert a batch of generated sessions in one statement, skipping the starts
88+/// this section already holds (`ON CONFLICT DO NOTHING` against
89+/// `UNIQUE (class_course, starts_at)`). The returned rows are exactly the rows
90+/// that landed, so the caller's `created` count is truthful. No transaction of
91+/// its own: the caller's (or none — the conflict skip makes a partial batch a
92+/// safe outcome either way). Empty input never touches the database.
93+pub async fn insert_many(
94+ db: &Database,
95+ rows: &[NewSession],
96+) -> Result<Vec<CourseSession>, AppError> {
97+ if rows.is_empty() {
98+ return Ok(Vec::new());
99+ }
100+ let mut conn = db.acquire().await?;
101+ insert_many_tx(&mut conn, rows).await
102+}
103+
104+/// The transaction-scoped twin of [`insert_many`]: the very same statement,
105+/// bound to the caller's own connection, so a batch its transaction rolls back
106+/// never lands. The materializer is the caller — its row lock and its insert
107+/// must be the one transaction, and a pooled insert inside that window would
108+/// commit on its own.
109+pub(crate) async fn insert_many_tx(
110+ tx: &mut sqlx::PgConnection,
111+ rows: &[NewSession],
112+) -> Result<Vec<CourseSession>, AppError> {
113+ if rows.is_empty() {
114+ return Ok(Vec::new());
115+ }
116+ let ids: Vec<uuid::Uuid> = rows.iter().map(|row| row.id.uuid()).collect();
117+ let class_courses: Vec<uuid::Uuid> = rows.iter().map(|row| row.class_course.uuid()).collect();
118+ let teachers: Vec<uuid::Uuid> = rows.iter().map(|row| row.teacher.uuid()).collect();
119+ let topics: Vec<String> = rows.iter().map(|row| row.topic.as_str().to_owned()).collect();
120+ let starts: Vec<i64> = rows.iter().map(|row| row.starts_at.as_millis()).collect();
121+ let ends: Vec<i64> = rows.iter().map(|row| row.ends_at.as_millis()).collect();
122+ let inserted = sqlx::query_as!(
123+ CourseSession,
124+ r#"INSERT INTO course_session (id, class_course, teacher, topic, starts_at, ends_at)
125+ SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::uuid[], $4::text[], $5::bigint[], $6::bigint[])
126+ ON CONFLICT (class_course, starts_at) DO NOTHING
127+ RETURNING id AS "id: CourseSessionId",
128+ class_course AS "class_course: ClassCourseId",
129+ teacher AS "teacher: UserId", topic AS "topic: SessionTopic",
130+ starts_at AS "starts_at: Timestamp", ends_at AS "ends_at?: Timestamp""#,
131+ &ids,
132+ &class_courses,
133+ &teachers,
134+ &topics,
135+ &starts,
136+ &ends,
137+ )
138+ .fetch_all(&mut *tx)
139+ .await?;
140+ Ok(inserted)
141+}
142+
143+/// The instants this section already holds a lesson at — the materializer's
144+/// skip set, one read for the whole range.
145+pub async fn existing_starts(
146+ db: &Database,
147+ instance: &ClassCourseId,
148+) -> Result<std::collections::HashSet<i64>, AppError> {
149+ let rows = sqlx::query_scalar!(
150+ r#"SELECT starts_at FROM course_session WHERE class_course = $1"#,
151+ instance.uuid(),
152+ )
153+ .fetch_all(db)
154+ .await?;
155+ Ok(rows.into_iter().collect())
156+}
157+
65 pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> {158 pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> {
66 let session = sqlx::query_as!(159 let session = sqlx::query_as!(
67 CourseSession,160 CourseSession,
src/db/holiday.rsadded+160 -0
@@ -0,0 +1,160 @@
1+//! The `holiday` table: the row mint, the read, the field-scoped PATCH whose
2+//! `WHERE` re-checks the merged range, the delete, and the two listings — a
3+//! paged calendar view and the materializer's overlap read. The type lives in
4+//! [`crate::domain::holiday`].
5+
6+use crate::constant::HOLIDAY_TABLE;
7+use crate::database::Database;
8+use crate::db::field_update::FieldUpdate;
9+use crate::db::page::{Param, PagedList};
10+use crate::domain::holiday::{Holiday, HolidayId, HolidayKind, HolidayName};
11+use crate::domain::timestamp::{Timestamp, range_error};
12+use crate::domain::user::UserId;
13+use crate::error::AppError;
14+
15+/// A PATCH of one holiday row: only the fields the request carried are
16+/// written, `None` = omitted = keep.
17+#[derive(Debug, Clone, Default)]
18+pub struct HolidayPatch {
19+ pub name: Option<HolidayName>,
20+ pub starts_at: Option<Timestamp>,
21+ pub ends_at: Option<Timestamp>,
22+ pub kind: Option<HolidayKind>,
23+}
24+
25+pub async fn create(
26+ db: &Database,
27+ name: &HolidayName,
28+ starts_at: Timestamp,
29+ ends_at: Timestamp,
30+ kind: &HolidayKind,
31+ creator: &UserId,
32+) -> Result<Holiday, AppError> {
33+ let holiday = Holiday {
34+ id: HolidayId::generate(),
35+ name: name.clone(),
36+ starts_at,
37+ ends_at,
38+ kind: kind.clone(),
39+ creator: *creator,
40+ created_at: Timestamp::now(),
41+ };
42+ let created = sqlx::query_as!(
43+ Holiday,
44+ r#"INSERT INTO holiday (id, name, starts_at, ends_at, kind, creator, created_at)
45+ VALUES ($1, $2, $3, $4, $5, $6, $7)
46+ RETURNING id AS "id: HolidayId", name AS "name: HolidayName",
47+ starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
48+ kind AS "kind: HolidayKind", creator AS "creator: UserId",
49+ created_at AS "created_at: Timestamp""#,
50+ holiday.id.uuid(),
51+ holiday.name.as_str(),
52+ holiday.starts_at.as_millis(),
53+ holiday.ends_at.as_millis(),
54+ holiday.kind.as_str(),
55+ holiday.creator.uuid(),
56+ holiday.created_at.as_millis(),
57+ )
58+ .fetch_one(db)
59+ .await?;
60+ Ok(created)
61+}
62+
63+/// The holiday `id` names, or `Err(NotFound)` when absent.
64+pub async fn read(db: &Database, id: &HolidayId) -> Result<Holiday, AppError> {
65+ sqlx::query_as!(
66+ Holiday,
67+ r#"SELECT id AS "id: HolidayId", name AS "name: HolidayName",
68+ starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
69+ kind AS "kind: HolidayKind", creator AS "creator: UserId",
70+ created_at AS "created_at: Timestamp"
71+ FROM holiday WHERE id = $1"#,
72+ id.uuid(),
73+ )
74+ .fetch_optional(db)
75+ .await?
76+ .ok_or(AppError::NotFound)
77+}
78+
79+/// Write only the fields the PATCH carried, and re-check the merged
80+/// `starts_at <= ends_at` in the `UPDATE`'s own `WHERE` — two PATCHes each
81+/// moving one end of the range cannot commit an inverted holiday between
82+/// them.
83+pub async fn update(
84+ db: &Database,
85+ id: &HolidayId,
86+ patch: HolidayPatch,
87+) -> Result<Holiday, AppError> {
88+ FieldUpdate::new(HOLIDAY_TABLE, id.uuid())
89+ .set("name", patch.name.map(|name| name.as_str().to_owned()))
90+ .set("starts_at", patch.starts_at.map(|at| at.as_millis()))
91+ .set("ends_at", patch.ends_at.map(|at| at.as_millis()))
92+ .set("kind", patch.kind.map(|kind| kind.as_str().to_owned()))
93+ .ordered("starts_at", "ends_at", range_error())
94+ .run::<Holiday>(db)
95+ .await
96+}
97+
98+/// Delete the holiday. A holiday is referenced by nothing — the materializer
99+/// only *reads* it — so nothing can refuse the delete but its own absence.
100+pub async fn delete(db: &Database, id: &HolidayId) -> Result<Holiday, AppError> {
101+ let deleted = sqlx::query_as!(
102+ Holiday,
103+ r#"DELETE FROM holiday WHERE id = $1
104+ RETURNING id AS "id: HolidayId", name AS "name: HolidayName",
105+ starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
106+ kind AS "kind: HolidayKind", creator AS "creator: UserId",
107+ created_at AS "created_at: Timestamp""#,
108+ id.uuid(),
109+ )
110+ .fetch_optional(db)
111+ .await?;
112+ deleted.ok_or(AppError::NotFound)
113+}
114+
115+/// Holidays, newest start first, paged. `from`/`to` are inclusive bounds with
116+/// overlap semantics — a holiday is listed when it *reaches into* the range,
117+/// not only when it lies inside it.
118+pub async fn list(
119+ db: &Database,
120+ from: Option<Timestamp>,
121+ to: Option<Timestamp>,
122+ limit: Option<i64>,
123+ offset: i64,
124+) -> Result<(Vec<Holiday>, i64), AppError> {
125+ PagedList::new(
126+ format!(
127+ "{HOLIDAY_TABLE} WHERE ($1::bigint IS NULL OR ends_at >= $1) \
128+ AND ($2::bigint IS NULL OR starts_at <= $2)"
129+ ),
130+ "ORDER BY starts_at DESC, id DESC",
131+ )
132+ .bind(Param::OptI64(from.map(|at| at.as_millis())))
133+ .bind(Param::OptI64(to.map(|at| at.as_millis())))
134+ .run::<Holiday>(limit, offset, db)
135+ .await
136+}
137+
138+/// Every holiday reaching into `[from, to]`, unpaged, earliest first — the
139+/// materializer's read. Same overlap semantics as [`list`].
140+pub async fn list_between(
141+ db: &Database,
142+ from: Timestamp,
143+ to: Timestamp,
144+) -> Result<Vec<Holiday>, AppError> {
145+ let rows = sqlx::query_as!(
146+ Holiday,
147+ r#"SELECT id AS "id: HolidayId", name AS "name: HolidayName",
148+ starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
149+ kind AS "kind: HolidayKind", creator AS "creator: UserId",
150+ created_at AS "created_at: Timestamp"
151+ FROM holiday
152+ WHERE ends_at >= $1 AND starts_at <= $2
153+ ORDER BY starts_at"#,
154+ from.as_millis(),
155+ to.as_millis(),
156+ )
157+ .fetch_all(db)
158+ .await?;
159+ Ok(rows)
160+}
src/db/mod.rsmodified+1 -0
@@ -38,6 +38,7 @@ pub mod exam_weight;
38 pub mod fee_plan;38 pub mod fee_plan;
39 pub mod fee_plan_assignment;39 pub mod fee_plan_assignment;
40 pub mod field_update;40 pub mod field_update;
41+pub mod holiday;
41 pub mod homework;42 pub mod homework;
42 pub mod homework_file;43 pub mod homework_file;
43 pub mod homework_result;44 pub mod homework_result;
src/db/weekly_slot.rsmodified+18 -9
@@ -21,6 +21,7 @@ use sqlx::postgres::PgConnection;
21 use crate::database::{Database, unique_violation};21 use crate::database::{Database, unique_violation};
22 use crate::domain::class_course::ClassCourseId;22 use crate::domain::class_course::ClassCourseId;
23 use crate::domain::course_offering::CourseOfferingId;23 use crate::domain::course_offering::CourseOfferingId;
24+use crate::domain::course_session::SessionTopic;
24 use crate::domain::weekly_slot::{SlotMinute, Weekday, WeeklySlot, WeeklySlotId};25 use crate::domain::weekly_slot::{SlotMinute, Weekday, WeeklySlot, WeeklySlotId};
25 use crate::error::AppError;26 use crate::error::AppError;
26 27
@@ -52,7 +53,8 @@ pub(crate) async fn list_for_offering_on(
52 r#"SELECT id AS "id: WeeklySlotId",53 r#"SELECT id AS "id: WeeklySlotId",
53 weekday AS "weekday: Weekday",54 weekday AS "weekday: Weekday",
54 (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute",55 (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute",
55- (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute"56+ (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute",
57+ topic AS "topic?: SessionTopic"
56 FROM offering_slot58 FROM offering_slot
57 WHERE offering = $159 WHERE offering = $1
58 ORDER BY weekday, starts_at"#,60 ORDER BY weekday, starts_at"#,
@@ -72,7 +74,8 @@ pub(crate) async fn list_for_class_on(
72 r#"SELECT id AS "id: WeeklySlotId",74 r#"SELECT id AS "id: WeeklySlotId",
73 weekday AS "weekday: Weekday",75 weekday AS "weekday: Weekday",
74 (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute",76 (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute",
75- (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute"77+ (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute",
78+ topic AS "topic?: SessionTopic"
76 FROM class_course_slot79 FROM class_course_slot
77 WHERE class_course = $180 WHERE class_course = $1
78 ORDER BY weekday, starts_at"#,81 ORDER BY weekday, starts_at"#,
@@ -132,19 +135,22 @@ pub(crate) async fn add_for_offering_tx(
132 ) -> Result<WeeklySlot, AppError> {135 ) -> Result<WeeklySlot, AppError> {
133 sqlx::query_as!(136 sqlx::query_as!(
134 WeeklySlot,137 WeeklySlot,
135- r#"INSERT INTO offering_slot (id, offering, weekday, starts_at, ends_at)138+ r#"INSERT INTO offering_slot (id, offering, weekday, starts_at, ends_at, topic)
136 VALUES ($1, $2, $3,139 VALUES ($1, $2, $3,
137 ($4::bigint * interval '1 minute')::time,140 ($4::bigint * interval '1 minute')::time,
138- ($5::bigint * interval '1 minute')::time)141+ ($5::bigint * interval '1 minute')::time,
142+ $6)
139 RETURNING id AS "id: WeeklySlotId",143 RETURNING id AS "id: WeeklySlotId",
140 weekday AS "weekday: Weekday",144 weekday AS "weekday: Weekday",
141 (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute",145 (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute",
142- (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute""#,146+ (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute",
147+ topic AS "topic?: SessionTopic""#,
143 slot.get_id().uuid(),148 slot.get_id().uuid(),
144 offering.uuid(),149 offering.uuid(),
145 slot.get_weekday().get(),150 slot.get_weekday().get(),
146 slot.get_starts_at().get(),151 slot.get_starts_at().get(),
147 slot.get_ends_at().get(),152 slot.get_ends_at().get(),
153+ slot.get_topic().map(|topic| topic.as_str()),
148 )154 )
149 .fetch_one(&mut *tx)155 .fetch_one(&mut *tx)
150 .await156 .await
@@ -173,11 +179,12 @@ pub(crate) async fn add_for_class_tx(
173 sqlx::query_as!(179 sqlx::query_as!(
174 WeeklySlot,180 WeeklySlot,
175 r#"WITH ins AS (181 r#"WITH ins AS (
176- INSERT INTO class_course_slot (id, class_course, weekday, starts_at, ends_at)182+ INSERT INTO class_course_slot (id, class_course, weekday, starts_at, ends_at, topic)
177 VALUES ($1, $2, $3,183 VALUES ($1, $2, $3,
178 ($4::bigint * interval '1 minute')::time,184 ($4::bigint * interval '1 minute')::time,
179- ($5::bigint * interval '1 minute')::time)185+ ($5::bigint * interval '1 minute')::time,
180- RETURNING id, weekday, starts_at, ends_at186+ $6)
187+ RETURNING id, weekday, starts_at, ends_at, topic
181 ), flip AS (188 ), flip AS (
182 UPDATE class_course SET weekly_plan_inherited = FALSE189 UPDATE class_course SET weekly_plan_inherited = FALSE
183 WHERE id = $2 AND EXISTS (SELECT 1 FROM ins)190 WHERE id = $2 AND EXISTS (SELECT 1 FROM ins)
@@ -186,7 +193,8 @@ pub(crate) async fn add_for_class_tx(
186 SELECT ins.id AS "id: WeeklySlotId",193 SELECT ins.id AS "id: WeeklySlotId",
187 ins.weekday AS "weekday: Weekday",194 ins.weekday AS "weekday: Weekday",
188 (EXTRACT(EPOCH FROM ins.starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute",195 (EXTRACT(EPOCH FROM ins.starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute",
189- (EXTRACT(EPOCH FROM ins.ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute"196+ (EXTRACT(EPOCH FROM ins.ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute",
197+ ins.topic AS "topic?: SessionTopic"
190 FROM ins198 FROM ins
191 WHERE EXISTS (SELECT 1 FROM flip)"#,199 WHERE EXISTS (SELECT 1 FROM flip)"#,
192 slot.get_id().uuid(),200 slot.get_id().uuid(),
@@ -194,6 +202,7 @@ pub(crate) async fn add_for_class_tx(
194 slot.get_weekday().get(),202 slot.get_weekday().get(),
195 slot.get_starts_at().get(),203 slot.get_starts_at().get(),
196 slot.get_ends_at().get(),204 slot.get_ends_at().get(),
205+ slot.get_topic().map(|topic| topic.as_str()),
197 )206 )
198 .fetch_optional(&mut *tx)207 .fetch_optional(&mut *tx)
199 .await?208 .await?
src/domain/calendar.rsadded+142 -0
@@ -0,0 +1,142 @@
1+//! The school's day math, in one place: zone offset, the calendar day an
2+//! instant falls on, the instant a day starts at, the ISO weekday, and day
3+//! ranges.
4+//!
5+//! Everything here is fixed-offset arithmetic — the allow-list in
6+//! [`crate::constant::TIMEZONES`] names zones whose offset is constant
7+//! (Turkey has run on UTC+3 with no DST since 2016), so the backend buckets
8+//! days without carrying a timezone database. Consumers read the school's
9+//! zone off its settings
10+//! ([`Settings::get_timezone`](crate::domain::settings::Settings::get_timezone))
11+//! and pass the offset down, because "a day" is a calendar day at the school,
12+//! not a UTC one.
13+
14+use chrono::Datelike;
15+
16+/// The school's day boundary as a fixed offset in minutes.
17+///
18+/// An unrecognised name falls back to [`crate::constant::DEFAULT_TIMEZONE`]'s
19+/// offset, which is what an unset setting gets anyway.
20+pub fn zone_offset_minutes(timezone: &str) -> i32 {
21+ match timezone {
22+ "UTC" => 0,
23+ _ => 3 * 60,
24+ }
25+}
26+
27+/// The calendar day an instant falls on, in the school's zone.
28+pub fn zoned_day(millis: i64, offset_minutes: i32) -> chrono::NaiveDate {
29+ let shifted = millis + i64::from(offset_minutes) * 60_000;
30+ chrono::DateTime::from_timestamp_millis(shifted)
31+ .expect("timestamps are within chrono's representable range")
32+ .date_naive()
33+}
34+
35+/// The instant `day` begins at, in the school's zone: midnight local time as
36+/// a UTC millisecond count. The inverse of [`zoned_day`] at day granularity —
37+/// a round trip through both lands on the same date.
38+pub fn day_start_millis(day: chrono::NaiveDate, offset_minutes: i32) -> i64 {
39+ day.and_hms_opt(0, 0, 0)
40+ .expect("midnight is a valid time")
41+ .and_utc()
42+ .timestamp_millis()
43+ - i64::from(offset_minutes) * 60_000
44+}
45+
46+/// The ISO weekday of `day`: `1` = Monday through `7` = Sunday, the same
47+/// scale the weekly plan's `weekday` column carries.
48+pub fn iso_weekday(day: chrono::NaiveDate) -> i16 {
49+ day.weekday().num_days_from_monday() as i16 + 1
50+}
51+
52+/// How many days `from..=to` spans, endpoints included. An inverted range
53+/// (`to` before `from`) answers a negative count; the generator works over
54+/// [`days_between`] instead, whose answer is simply empty there.
55+pub fn days_inclusive(from: chrono::NaiveDate, to: chrono::NaiveDate) -> i64 {
56+ (to - from).num_days() + 1
57+}
58+
59+/// Every calendar day from `from` through `to`, endpoints included. An
60+/// inverted range names no day at all.
61+///
62+/// Walked one `succ_opt` at a time rather than collected from `from..=to`:
63+/// `RangeInclusive<NaiveDate>` is only an iterator through chrono's private
64+/// `Step`, so the range form does not compile here. The walk stops at the
65+/// last representable date instead of panicking.
66+pub fn days_between(from: chrono::NaiveDate, to: chrono::NaiveDate) -> Vec<chrono::NaiveDate> {
67+ let mut days = Vec::new();
68+ let mut day = from;
69+ while day <= to {
70+ days.push(day);
71+ match day.succ_opt() {
72+ Some(next) => day = next,
73+ None => break,
74+ }
75+ }
76+ days
77+}
78+
79+#[cfg(test)]
80+mod tests {
81+ use super::*;
82+ use crate::domain::timestamp::Timestamp;
83+
84+ #[test]
85+ fn the_zone_offset_follows_the_allow_list() {
86+ assert_eq!(zone_offset_minutes("UTC"), 0);
87+ assert_eq!(zone_offset_minutes("Europe/Istanbul"), 3 * 60);
88+ }
89+
90+ /// The day bucket is the school's day, not UTC's: 22:30 UTC in summer
91+ /// Istanbul is already tomorrow. This is the whole reason the timezone is
92+ /// read off the settings.
93+ #[test]
94+ fn the_day_bucket_follows_the_school_zone() {
95+ let at = Timestamp::from_millis(1_767_216_600_000); // 2025-12-31T21:30Z
96+ assert_eq!(
97+ zoned_day(at.as_millis(), zone_offset_minutes("UTC")).to_string(),
98+ "2025-12-31"
99+ );
100+ assert_eq!(
101+ zoned_day(at.as_millis(), zone_offset_minutes("Europe/Istanbul")).to_string(),
102+ "2026-01-01"
103+ );
104+ }
105+
106+ #[test]
107+ fn iso_weekday_is_the_monday_one_scale() {
108+ // 2026-09-28 is a Monday, 2026-10-04 the Sunday that ends it.
109+ let monday = chrono::NaiveDate::from_ymd_opt(2026, 9, 28).unwrap();
110+ let sunday = chrono::NaiveDate::from_ymd_opt(2026, 10, 4).unwrap();
111+ assert_eq!(iso_weekday(monday), 1);
112+ assert_eq!(iso_weekday(sunday), 7);
113+ }
114+
115+ #[test]
116+ fn day_ranges_are_inclusive() {
117+ let monday = chrono::NaiveDate::from_ymd_opt(2026, 9, 28).unwrap();
118+ let next_monday = chrono::NaiveDate::from_ymd_opt(2026, 10, 5).unwrap();
119+ // A single day spans one day.
120+ assert_eq!(days_inclusive(monday, monday), 1);
121+ assert_eq!(days_between(monday, monday), vec![monday]);
122+ // Monday through the next Monday is eight days, endpoints named.
123+ assert_eq!(days_inclusive(monday, next_monday), 8);
124+ let days = days_between(monday, next_monday);
125+ assert_eq!(days.len(), 8);
126+ assert_eq!(days[0], monday);
127+ assert_eq!(days[7], next_monday);
128+ // An inverted range names no day.
129+ assert!(days_between(next_monday, monday).is_empty());
130+ }
131+
132+ #[test]
133+ fn day_start_round_trips_through_zoned_day() {
134+ let day = chrono::NaiveDate::from_ymd_opt(2026, 9, 28).unwrap();
135+ for offset in [0, 3 * 60] {
136+ let start = day_start_millis(day, offset);
137+ assert_eq!(zoned_day(start, offset), day);
138+ // Midnight local: the day before, this instant is still evening.
139+ assert_eq!(zoned_day(start - 1, offset), day.pred_opt().unwrap());
140+ }
141+ }
142+}
src/domain/holiday.rsadded+191 -0
@@ -0,0 +1,191 @@
1+//! The holiday calendar: one named, school-wide non-teaching range. Both ends
2+//! are *instants* (unix millis), exactly like `term`, `event`, `exam` and
3+//! `academic_year` — the materializer compares instants, so no separate day
4+//! type exists.
5+
6+use uuid::Uuid;
7+
8+use crate::constant::{HOLIDAY_KINDS, MAX_HOLIDAY_NAME_LEN};
9+use crate::domain::monotonic_id::next_uuid;
10+use crate::domain::timestamp::Timestamp;
11+use crate::domain::user::UserId;
12+use crate::error::ValidationError;
13+use crate::validate::validate_required;
14+
15+/// Typed holiday row id. A UUIDv7 minted by the process-wide monotonic
16+/// generator, so `id` order is mint order.
17+#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
18+#[sqlx(transparent)]
19+pub struct HolidayId(Uuid);
20+
21+impl HolidayId {
22+ /// Minted from the process-wide monotonic generator, not a random v4:
23+ /// holidays sort `starts_at DESC, id DESC` and the id breaks the tie
24+ /// between two holidays starting at the same instant.
25+ pub fn generate() -> Self {
26+ Self(next_uuid())
27+ }
28+
29+ /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
30+ /// cannot take the newtype. Static `query!` binds take `self` directly.
31+ pub fn uuid(&self) -> Uuid {
32+ self.0
33+ }
34+
35+ /// Parse a wire key. A key that parses as no UUID — a malformed path
36+ /// segment — reads as the nil id, which matches no row: exactly the 404 a
37+ /// dangling record key produced under the old store, without turning a
38+ /// typo into a panic.
39+ pub fn from_key(key: &str) -> Self {
40+ Self(Uuid::parse_str(key).unwrap_or(Uuid::nil()))
41+ }
42+
43+ /// The hyphenated wire form.
44+ pub fn key(&self) -> String {
45+ self.0.to_string()
46+ }
47+}
48+
49+/// The holiday's display name ("29 Ekim Cumhuriyet Bayramı").
50+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
51+#[sqlx(transparent)]
52+pub struct HolidayName(String);
53+
54+impl HolidayName {
55+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
56+ validate_required("name", value, MAX_HOLIDAY_NAME_LEN)?;
57+ Ok(Self(value.to_string()))
58+ }
59+
60+ pub fn as_str(&self) -> &str {
61+ &self.0
62+ }
63+}
64+
65+/// Why the school is closed, from a closed list: `resmi` (official), `dini`
66+/// (religious), `idari` (administrative), `ara` (a break inside the year).
67+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
68+#[sqlx(transparent)]
69+pub struct HolidayKind(String);
70+
71+impl HolidayKind {
72+ /// The accepted spellings — the wire form of the DDL's `CHECK`.
73+ pub const ALL: [&str; 4] = HOLIDAY_KINDS;
74+
75+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
76+ if !Self::ALL.contains(&value) {
77+ return Err(ValidationError::Unknown {
78+ field: "kind",
79+ value: value.to_owned(),
80+ });
81+ }
82+ Ok(Self(value.to_owned()))
83+ }
84+
85+ pub fn as_str(&self) -> &str {
86+ &self.0
87+ }
88+}
89+
90+/// One school-wide non-teaching range: from `starts_at` through `ends_at`
91+/// (inclusive instants), named, and stamped by the manager who declared it.
92+#[derive(Debug, Clone, sqlx::FromRow)]
93+pub struct Holiday {
94+ pub(crate) id: HolidayId,
95+ pub(crate) name: HolidayName,
96+ pub(crate) starts_at: Timestamp,
97+ pub(crate) ends_at: Timestamp,
98+ pub(crate) kind: HolidayKind,
99+ pub(crate) creator: UserId,
100+ pub(crate) created_at: Timestamp,
101+}
102+
103+impl Holiday {
104+ pub fn get_id(&self) -> &HolidayId {
105+ &self.id
106+ }
107+
108+ pub fn get_name(&self) -> &HolidayName {
109+ &self.name
110+ }
111+
112+ pub fn get_starts_at(&self) -> Timestamp {
113+ self.starts_at
114+ }
115+
116+ pub fn get_ends_at(&self) -> Timestamp {
117+ self.ends_at
118+ }
119+
120+ pub fn get_kind(&self) -> &HolidayKind {
121+ &self.kind
122+ }
123+
124+ pub fn get_creator(&self) -> &UserId {
125+ &self.creator
126+ }
127+
128+ pub fn get_created_at(&self) -> Timestamp {
129+ self.created_at
130+ }
131+
132+ /// Whether this holiday reaches into `[from, to]`. Touching counts: a
133+ /// holiday ending exactly when the range begins (or beginning exactly
134+ /// when it ends) still blocks the day it touches.
135+ pub fn overlaps(&self, from: Timestamp, to: Timestamp) -> bool {
136+ self.ends_at >= from && self.starts_at <= to
137+ }
138+}
139+
140+#[cfg(test)]
141+mod tests {
142+ use super::*;
143+ use crate::domain::user::UserId;
144+
145+ fn a_holiday(starts_at: i64, ends_at: i64) -> Holiday {
146+ Holiday {
147+ id: HolidayId::generate(),
148+ name: HolidayName::try_new("29 Ekim").unwrap(),
149+ starts_at: Timestamp::from_millis(starts_at),
150+ ends_at: Timestamp::from_millis(ends_at),
151+ kind: HolidayKind::try_new("resmi").unwrap(),
152+ creator: UserId::generate(),
153+ created_at: Timestamp::now(),
154+ }
155+ }
156+
157+ #[test]
158+ fn name_is_required_and_bounded() {
159+ assert!(HolidayName::try_new("29 Ekim").is_ok());
160+ // Blank (whitespace-only) names are refused like an empty one.
161+ assert!(HolidayName::try_new(" ").is_err());
162+ assert!(HolidayName::try_new("").is_err());
163+ assert!(HolidayName::try_new(&"x".repeat(MAX_HOLIDAY_NAME_LEN + 1)).is_err());
164+ assert!(HolidayName::try_new(&"x".repeat(MAX_HOLIDAY_NAME_LEN)).is_ok());
165+ }
166+
167+ #[test]
168+ fn kind_is_a_closed_list() {
169+ for kind in HolidayKind::ALL {
170+ assert!(HolidayKind::try_new(kind).is_ok());
171+ }
172+ assert!(matches!(
173+ HolidayKind::try_new("x"),
174+ Err(ValidationError::Unknown { field: "kind", .. })
175+ ));
176+ }
177+
178+ #[test]
179+ fn overlaps_at_both_touching_edges() {
180+ // The holiday spans [100, 200].
181+ let holiday = a_holiday(100, 200);
182+ // Touching on either edge is still a block.
183+ assert!(holiday.overlaps(Timestamp::from_millis(200), Timestamp::from_millis(300)));
184+ assert!(holiday.overlaps(Timestamp::from_millis(0), Timestamp::from_millis(100)));
185+ // One millisecond past either edge is not.
186+ assert!(!holiday.overlaps(Timestamp::from_millis(201), Timestamp::from_millis(300)));
187+ assert!(!holiday.overlaps(Timestamp::from_millis(0), Timestamp::from_millis(99)));
188+ // And a range inside the holiday is, of course.
189+ assert!(holiday.overlaps(Timestamp::from_millis(150), Timestamp::from_millis(160)));
190+ }
191+}
src/domain/mod.rsmodified+2 -0
@@ -15,6 +15,7 @@ pub mod bank_question_image;
15 pub mod board;15 pub mod board;
16 pub mod board_stroke;16 pub mod board_stroke;
17 pub mod builder;17 pub mod builder;
18+pub mod calendar;
18 pub mod chatbot_message;19 pub mod chatbot_message;
19 pub mod chatbot_thread;20 pub mod chatbot_thread;
20 pub mod class_blueprint;21 pub mod class_blueprint;
@@ -39,6 +40,7 @@ pub mod exam_weight;
39 pub mod fee_plan;40 pub mod fee_plan;
40 pub mod fee_plan_assignment;41 pub mod fee_plan_assignment;
41 pub mod grade;42 pub mod grade;
43+pub mod holiday;
42 pub mod homework;44 pub mod homework;
43 pub mod homework_file;45 pub mod homework_file;
44 pub mod homework_result;46 pub mod homework_result;
src/domain/weekly_slot.rsmodified+64 -8
@@ -16,14 +16,16 @@
16 //! list comes back in is `weekday` first, then `starts_at` — Monday through16 //! list comes back in is `weekday` first, then `starts_at` — Monday through
17 //! Sunday, each day dawn to dusk.17 //! Sunday, each day dawn to dusk.
18 //!18 //!
19-//! **No scheduler.** Nothing generates dated `course_session` rows from a19+//! **Not a store for lessons.** This module is template + override +
20-//! weekly plan — `course_session` stays the per-lesson occurrence, written by20+//! resolution only: the dated `course_session` rows are minted on demand by
21-//! its own routes. This module is template + override + resolution only.21+//! [`crate::service::course_session::materialize`], which reads this
22+//! resolution and the school's holiday calendar.
22 //!23 //!
23 //! The slot bounds live in [`crate::constant`] beside every other published24 //! The slot bounds live in [`crate::constant`] beside every other published
24 //! bound, so `GET /limits` and the completeness guard see them.25 //! bound, so `GET /limits` and the completeness guard see them.
25 26
26 use crate::constant::{MAX_SLOT_MINUTE, MAX_WEEKLY_SLOTS, MIN_SLOT_MINUTE};27 use crate::constant::{MAX_SLOT_MINUTE, MAX_WEEKLY_SLOTS, MIN_SLOT_MINUTE};
28+use crate::domain::course_session::SessionTopic;
27 use crate::domain::monotonic_id::next_uuid;29 use crate::domain::monotonic_id::next_uuid;
28 use crate::error::ValidationError;30 use crate::error::ValidationError;
29 31
@@ -107,7 +109,8 @@ impl SlotMinute {
107 }109 }
108 }110 }
109 111
110-/// One weekly plan line: on `weekday`, from `starts_at` to `ends_at`.112+/// One weekly plan line: on `weekday`, from `starts_at` to `ends_at`, with an
113+/// optional lesson topic the materializer copies onto the generated sessions.
111 ///114 ///
112 /// The list a resolver returns is ordered `weekday` first, then `starts_at`.115 /// The list a resolver returns is ordered `weekday` first, then `starts_at`.
113 #[derive(Debug, Clone, PartialEq, Eq, sqlx::FromRow)]116 #[derive(Debug, Clone, PartialEq, Eq, sqlx::FromRow)]
@@ -116,18 +119,21 @@ pub struct WeeklySlot {
116 pub(crate) weekday: Weekday,119 pub(crate) weekday: Weekday,
117 pub(crate) starts_at: SlotMinute,120 pub(crate) starts_at: SlotMinute,
118 pub(crate) ends_at: SlotMinute,121 pub(crate) ends_at: SlotMinute,
122+ pub(crate) topic: Option<SessionTopic>,
119 }123 }
120 124
121 impl WeeklySlot {125 impl WeeklySlot {
122 /// The slot `id` names, or a validation error when the window is not one126 /// The slot `id` names, or a validation error when the window is not one
123 /// (`ends_at` must land strictly after `starts_at` — equal times are an127 /// (`ends_at` must land strictly after `starts_at` — equal times are an
124 /// empty window, inverted ones a typo). The store's128 /// empty window, inverted ones a typo). The store's
125- /// `CHECK (ends_at > starts_at)` is the same rule at rest.129+ /// `CHECK (ends_at > starts_at)` is the same rule at rest. `topic` rides
130+ /// along unjudged for overlap: it is content, not a timetable line.
126 pub fn new(131 pub fn new(
127 id: WeeklySlotId,132 id: WeeklySlotId,
128 weekday: Weekday,133 weekday: Weekday,
129 starts_at: SlotMinute,134 starts_at: SlotMinute,
130 ends_at: SlotMinute,135 ends_at: SlotMinute,
136+ topic: Option<SessionTopic>,
131 ) -> Result<Self, ValidationError> {137 ) -> Result<Self, ValidationError> {
132 if starts_at.get() >= ends_at.get() {138 if starts_at.get() >= ends_at.get() {
133 return Err(ValidationError::Invalid {139 return Err(ValidationError::Invalid {
@@ -140,6 +146,7 @@ impl WeeklySlot {
140 weekday,146 weekday,
141 starts_at,147 starts_at,
142 ends_at,148 ends_at,
149+ topic,
143 })150 })
144 }151 }
145 152
@@ -159,6 +166,13 @@ impl WeeklySlot {
159 self.ends_at166 self.ends_at
160 }167 }
161 168
169+ /// The lesson topic the slot carries, `None` = the generated session
170+ /// falls back to the instance's resolved title (then the literal
171+ /// `"Ders"`).
172+ pub fn get_topic(&self) -> Option<&SessionTopic> {
173+ self.topic.as_ref()
174+ }
175+
162 /// Whether this and `other` cannot both stand in one owner's plan: the176 /// Whether this and `other` cannot both stand in one owner's plan: the
163 /// same weekday with intersecting windows. Touching endpoints are fine —177 /// same weekday with intersecting windows. Touching endpoints are fine —
164 /// a lesson may start the minute another ends.178 /// a lesson may start the minute another ends.
@@ -210,10 +224,46 @@ mod tests {
210 day(weekday),224 day(weekday),
211 mins(starts),225 mins(starts),
212 mins(ends),226 mins(ends),
227+ None,
213 )228 )
214 .unwrap()229 .unwrap()
215 }230 }
216 231
232+ #[test]
233+ fn topic_is_optional_and_survives_construction() {
234+ // A slot without a topic reads back `None`.
235+ let bare = slot(1, 540, 600);
236+ assert!(bare.get_topic().is_none());
237+ // A topic rides along verbatim.
238+ let topic = SessionTopic::try_new("Photosynthesis").unwrap();
239+ let themed = WeeklySlot::new(
240+ WeeklySlotId::generate(),
241+ day(2),
242+ mins(540),
243+ mins(600),
244+ Some(topic.clone()),
245+ )
246+ .unwrap();
247+ assert_eq!(themed.get_topic(), Some(&topic));
248+ }
249+
250+ #[test]
251+ fn overlap_is_independent_of_the_topic() {
252+ let bare = slot(1, 540, 600);
253+ let themed = WeeklySlot::new(
254+ WeeklySlotId::generate(),
255+ day(1),
256+ mins(540),
257+ mins(600),
258+ Some(SessionTopic::try_new("Cells").unwrap()),
259+ )
260+ .unwrap();
261+ // The same window with a different (or absent) topic still collides —
262+ // the topic is content, not a timetable line.
263+ assert!(bare.overlaps(&themed));
264+ assert!(themed.overlaps(&bare));
265+ }
266+
217 #[test]267 #[test]
218 fn weekdays_are_the_iso_scale() {268 fn weekdays_are_the_iso_scale() {
219 assert!(Weekday::new(1).is_ok());269 assert!(Weekday::new(1).is_ok());
@@ -233,10 +283,16 @@ mod tests {
233 #[test]283 #[test]
234 fn a_slot_window_must_be_non_empty_and_forward() {284 fn a_slot_window_must_be_non_empty_and_forward() {
235 // Zero-length and inverted windows are refused.285 // Zero-length and inverted windows are refused.
236- assert!(WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(600)).is_err());286+ assert!(
237- assert!(WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(540)).is_err());287+ WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(600), None).is_err()
288+ );
289+ assert!(
290+ WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(540), None).is_err()
291+ );
238 // A one-minute window stands.292 // A one-minute window stands.
239- assert!(WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(601)).is_ok());293+ assert!(
294+ WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(601), None).is_ok()
295+ );
240 }296 }
241 297
242 #[test]298 #[test]
src/service/course_session.rsmodified+200 -3
@@ -3,11 +3,20 @@
3 //! write. The queries live in [`crate::db::course_session`]; the3 //! write. The queries live in [`crate::db::course_session`]; the
4 //! timetable's wire shaping and the course-rights checks stay in the web4 //! timetable's wire shaping and the course-rights checks stay in the web
5 //! layer.5 //! layer.
6+//!
7+//! The one workflow with a plan behind it is [`materialize`]: it expands an
8+//! instance's *resolved* weekly plan ([`crate::service::weekly_slot`]) into
9+//! dated lessons over a range, bounded by the school-wide holiday calendar
10+//! ([`crate::service::holiday::blocked_days`]). It is an explicit route's
11+//! work, not a scheduler: nothing generates lessons on its own.
6 12
7-use crate::database::Database;13+use crate::constant::{MAX_MATERIALIZE_DAYS, MAX_MATERIALIZE_SESSIONS, MILLIS_PER_DAY};
8-use crate::db::course_session;14+use crate::database::{Database, tx_with_retry};
9-use crate::domain::class_course::ClassCourseId;15+use crate::db::course_session::{self, NewSession};
16+use crate::domain::calendar;
17+use crate::domain::class_course::{ClassCourse, ClassCourseId};
10 use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};18 use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};
19+use crate::domain::holiday::HolidayName;
11 use crate::domain::role::Role;20 use crate::domain::role::Role;
12 use crate::domain::timestamp::Timestamp;21 use crate::domain::timestamp::Timestamp;
13 use crate::domain::user::{User, UserId};22 use crate::domain::user::{User, UserId};
@@ -93,3 +102,191 @@ pub async fn update(
93 pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {102 pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {
94 course_session::delete(db, session).await103 course_session::delete(db, session).await
95 }104 }
105+
106+/// One non-teaching day the generator refused to schedule on: the calendar
107+/// day in the school's zone, and the holiday that reaches into it.
108+#[derive(Debug, Clone)]
109+pub struct BlockedDay {
110+ pub day: chrono::NaiveDate,
111+ pub holiday: HolidayName,
112+}
113+
114+/// What one [`materialize`] call did — or, on a dry run, would have done.
115+///
116+/// `created` carries the rows the database actually inserted (empty on a dry
117+/// run), so a lesson a concurrent writer already put at the same instant is
118+/// reported as skipped, never counted. `candidates` is the size the range
119+/// asked for, `slots` the resolved plan's size, and `blocked` one entry per
120+/// holiday-blocked *day*.
121+#[derive(Debug, Clone)]
122+pub struct MaterializeOutcome {
123+ pub applied: bool,
124+ pub slots: usize,
125+ pub candidates: usize,
126+ pub created: Vec<CourseSession>,
127+ pub skipped_existing: usize,
128+ pub skipped_holiday: usize,
129+ pub blocked: Vec<BlockedDay>,
130+ pub range_days: i64,
131+}
132+
133+/// Expand `instance`'s resolved weekly plan into dated lessons over
134+/// `[from, to]` (inclusive instants), one lesson per plan slot per matching
135+/// weekday, skipping the days a holiday reaches into and the instants the
136+/// section already holds a lesson at.
137+///
138+/// `apply == false` is a dry run: it reads, decides, and writes nothing.
139+/// `apply == true` writes the collected rows in this transaction and returns
140+/// exactly the rows that landed — the whole feature is additive, nothing is
141+/// ever deleted or updated, and a second run over the same range is a no-op
142+/// (`UNIQUE (class_course, starts_at)`). Weekends are not special-cased: a
143+/// school may run Saturday, so only the plan and the holidays decide.
144+///
145+/// `offset_minutes` is the school's zone offset
146+/// ([`crate::domain::calendar::zone_offset_minutes`]); the range's instants
147+/// name *school* days, and each lesson lands at its slot's minute of that
148+/// local day.
149+///
150+/// Refusals: an archived year, an empty plan (409
151+/// `instance_has_no_weekly_plan`), no assigned teacher (409
152+/// `instance_has_no_teacher`, the lesson's teacher is the instance's first
153+/// assigned one), a range longer than a year or one that would mint more than
154+/// [`MAX_MATERIALIZE_SESSIONS`] lessons (400), and a gone instance
155+/// ([`AppError::NotFound`]).
156+pub async fn materialize(
157+ db: &Database,
158+ instance: &ClassCourse,
159+ from: Timestamp,
160+ to: Timestamp,
161+ apply: bool,
162+ offset_minutes: i32,
163+) -> Result<MaterializeOutcome, AppError> {
164+ let instance_id = instance.get_id().clone();
165+ let days = calendar::days_between(
166+ calendar::zoned_day(from.as_millis(), offset_minutes),
167+ calendar::zoned_day(to.as_millis(), offset_minutes),
168+ );
169+ let range_days = days.len() as i64;
170+ if range_days > MAX_MATERIALIZE_DAYS {
171+ return Err(AppError::Validation(ValidationError::Invalid {
172+ field: "to",
173+ reason: "the range must not span more than a year",
174+ }));
175+ }
176+
177+ // Every decision below is made while holding the instance's row lock, and
178+ // the generated rows are written on that same connection: a rival
179+ // materialize run waits here instead of racing the existence read, and a
180+ // refusal rolls back whatever it had collected.
181+ tx_with_retry(db, false, async move |tx| {
182+ // The archived-year wall every instance write passes: a past year is
183+ // read-only, and this run mints lesson rows.
184+ crate::service::class_course::require_open(db, &instance_id).await?;
185+ // The serialization point. `FOR NO KEY UPDATE` rather than
186+ // `FOR UPDATE`: the batch insert below takes this same row's
187+ // foreign-key `FOR KEY SHARE`, which `FOR UPDATE` would block on.
188+ crate::db::weekly_slot::lock_class_tx(tx, &instance_id).await?;
189+
190+ let slots = crate::service::weekly_slot::resolved_for_instance(db, instance).await?;
191+ if slots.is_empty() {
192+ return Err(AppError::ConflictCoded {
193+ code: "instance_has_no_weekly_plan",
194+ message: "this section's weekly plan is empty — add a slot first".into(),
195+ });
196+ }
197+ let teachers =
198+ crate::db::class_course_teacher::list_for_instance(db, &instance_id).await?;
199+ let Some(teacher) = teachers.first().copied() else {
200+ return Err(AppError::ConflictCoded {
201+ code: "instance_has_no_teacher",
202+ message: "assign a teacher to this section before generating lessons".into(),
203+ });
204+ };
205+
206+ // The topic chain: the slot's own first, the instance's *resolved*
207+ // title second (the one display chain every surface rides), the
208+ // literal `"Ders"` last. The resolved title is bounded by
209+ // `MAX_COURSE_TITLE_LEN`, so it always fits a `SessionTopic`.
210+ let resolved = crate::service::instance_resolve::resolved_content(db, &[instance]).await?;
211+ let fallback_topic = resolved
212+ .get(&instance_id.key())
213+ .map(|content| content.title.as_str())
214+ .filter(|title| !title.is_empty())
215+ .and_then(|title| SessionTopic::try_new(title).ok())
216+ .unwrap_or(SessionTopic::try_new("Ders")?);
217+
218+ let holidays = crate::service::holiday::blocked_days(db, from, to).await?;
219+ let existing = course_session::existing_starts(db, &instance_id).await?;
220+
221+ let mut rows: Vec<NewSession> = Vec::new();
222+ let mut blocked: Vec<BlockedDay> = Vec::new();
223+ let mut skipped_existing = 0usize;
224+ for day in &days {
225+ let day_start = calendar::day_start_millis(*day, offset_minutes);
226+ // Day granularity, not slot granularity: a day a holiday reaches
227+ // into is named once and contributes nothing, whether or not the
228+ // plan runs a lesson that weekday.
229+ let day_end = day_start + MILLIS_PER_DAY - 1;
230+ if let Some(holiday) = holidays.iter().find(|holiday| {
231+ holiday.overlaps(
232+ Timestamp::from_millis(day_start),
233+ Timestamp::from_millis(day_end),
234+ )
235+ }) {
236+ blocked.push(BlockedDay {
237+ day: *day,
238+ holiday: holiday.get_name().clone(),
239+ });
240+ continue;
241+ }
242+ let weekday = calendar::iso_weekday(*day);
243+ for slot in slots
244+ .iter()
245+ .filter(|slot| slot.get_weekday().get() == weekday)
246+ {
247+ let starts_at = day_start + slot.get_starts_at().get() * 60_000;
248+ if existing.contains(&starts_at) {
249+ skipped_existing += 1;
250+ continue;
251+ }
252+ rows.push(NewSession {
253+ id: CourseSessionId::generate(),
254+ class_course: instance_id.clone(),
255+ teacher,
256+ topic: slot
257+ .get_topic()
258+ .cloned()
259+ .unwrap_or_else(|| fallback_topic.clone()),
260+ starts_at: Timestamp::from_millis(starts_at),
261+ ends_at: Timestamp::from_millis(
262+ day_start + slot.get_ends_at().get() * 60_000,
263+ ),
264+ });
265+ }
266+ }
267+
268+ let candidates = rows.len();
269+ if candidates > MAX_MATERIALIZE_SESSIONS {
270+ return Err(AppError::Validation(ValidationError::Invalid {
271+ field: "to",
272+ reason: "this range would create more than 500 lessons — narrow it".into(),
273+ }));
274+ }
275+ let created = if apply {
276+ course_session::insert_many_tx(tx, &rows).await?
277+ } else {
278+ Vec::new()
279+ };
280+ Ok(MaterializeOutcome {
281+ applied: apply,
282+ slots: slots.len(),
283+ candidates,
284+ created,
285+ skipped_existing,
286+ skipped_holiday: blocked.len(),
287+ blocked,
288+ range_days,
289+ })
290+ })
291+ .await
292+}
src/service/holiday.rsadded+68 -0
@@ -0,0 +1,68 @@
1+//! Holiday workflows: the school-wide non-teaching calendar is plain CRUD —
2+//! the rows carry no refcounts, no archive stamp, no cross-table rule — so
3+//! every door here is a thin pass-through over [`crate::db::holiday`]. The one
4+//! workflow-shaped read is [`blocked_days`], the weekly-plan materializer's
5+//! "which of these instants may not hold a lesson" read.
6+
7+use crate::database::Database;
8+use crate::db::holiday::{self, HolidayPatch};
9+use crate::domain::holiday::{Holiday, HolidayId, HolidayKind, HolidayName};
10+use crate::domain::timestamp::Timestamp;
11+use crate::domain::user::UserId;
12+use crate::error::AppError;
13+
14+/// Declare a school-wide holiday. Manager-gated at the route; the range
15+/// ordering is re-checked by the web layer's pre-flight and again at any
16+/// PATCH by the `WHERE` in [`update`].
17+pub async fn create(
18+ db: &Database,
19+ name: &HolidayName,
20+ starts_at: Timestamp,
21+ ends_at: Timestamp,
22+ kind: &HolidayKind,
23+ creator: &UserId,
24+) -> Result<Holiday, AppError> {
25+ holiday::create(db, name, starts_at, ends_at, kind, creator).await
26+}
27+
28+/// The holiday `id` names, or `Err(NotFound)`.
29+pub async fn read(db: &Database, id: &HolidayId) -> Result<Holiday, AppError> {
30+ holiday::read(db, id).await
31+}
32+
33+/// Patch only what the request carried; the merged range is re-checked in the
34+/// `UPDATE`'s own `WHERE`.
35+pub async fn update(
36+ db: &Database,
37+ id: &HolidayId,
38+ patch: HolidayPatch,
39+) -> Result<Holiday, AppError> {
40+ holiday::update(db, id, patch).await
41+}
42+
43+/// Delete the holiday. Nothing references it — the materializer only reads —
44+/// so the delete is unconditional.
45+pub async fn delete(db: &Database, id: &HolidayId) -> Result<Holiday, AppError> {
46+ holiday::delete(db, id).await
47+}
48+
49+/// The paged calendar view, `from`/`to` with overlap semantics.
50+pub async fn list(
51+ db: &Database,
52+ from: Option<Timestamp>,
53+ to: Option<Timestamp>,
54+ limit: Option<i64>,
55+ offset: i64,
56+) -> Result<(Vec<Holiday>, i64), AppError> {
57+ holiday::list(db, from, to, limit, offset).await
58+}
59+
60+/// Every holiday reaching into `[from, to]` — the materializer's read. A
61+/// read-only door: it never writes.
62+pub async fn blocked_days(
63+ db: &Database,
64+ from: Timestamp,
65+ to: Timestamp,
66+) -> Result<Vec<Holiday>, AppError> {
67+ holiday::list_between(db, from, to).await
68+}
src/service/mod.rsmodified+1 -0
@@ -37,6 +37,7 @@ pub mod homework;
37 pub mod homework_file;37 pub mod homework_file;
38 pub mod homework_result;38 pub mod homework_result;
39 pub mod homework_submission;39 pub mod homework_submission;
40+pub mod holiday;
40 pub mod instance;41 pub mod instance;
41 pub mod instance_resolve;42 pub mod instance_resolve;
42 pub mod karne;43 pub mod karne;
src/service/weekly_slot.rsmodified+31 -32
@@ -5,15 +5,16 @@
5 //! `weekly_plan_inherited` in the same statement — see5 //! `weekly_plan_inherited` in the same statement — see
6 //! [`crate::db::weekly_slot`]).6 //! [`crate::db::weekly_slot`]).
7 //!7 //!
8-//! **No scheduler.** Nothing here generates dated `course_session` rows from8+//! **Not a scheduler.** Nothing runs on its own: this module is template +
9-//! a weekly plan — `course_session` stays the per-lesson occurrence, written9+//! override + resolution only, and the explicit materialize door
10-//! by its own routes. This module is template + override + resolution only; a10+//! ([`crate::service::course_session::materialize`]) is the one caller that
11-//! scheduler needs its own spec.11+//! turns a resolution into dated lessons.
12 12
13 use crate::database::{Database, tx_with_retry};13 use crate::database::{Database, tx_with_retry};
14 use crate::db::weekly_slot as slot_db;14 use crate::db::weekly_slot as slot_db;
15 use crate::domain::class_course::{ClassCourse, ClassCourseId};15 use crate::domain::class_course::{ClassCourse, ClassCourseId};
16 use crate::domain::course_offering::CourseOfferingId;16 use crate::domain::course_offering::CourseOfferingId;
17+use crate::domain::course_session::SessionTopic;
17 use crate::domain::weekly_slot::{18 use crate::domain::weekly_slot::{
18 SlotAddError, SlotMinute, Weekday, WeeklySlot, WeeklySlotId, check_add,19 SlotAddError, SlotMinute, Weekday, WeeklySlot, WeeklySlotId, check_add,
19 };20 };
@@ -58,15 +59,18 @@ async fn resolved_own(
58 /// refused with 409 `slot_overlap` when a template slot already occupies an59 /// refused with 409 `slot_overlap` when a template slot already occupies an
59 /// intersecting window on that weekday (the exact duplicate overlaps too),60 /// intersecting window on that weekday (the exact duplicate overlaps too),
60 /// 409 `slot_cap` when the week already holds [`MAX_WEEKLY_SLOTS`] slots,61 /// 409 `slot_cap` when the week already holds [`MAX_WEEKLY_SLOTS`] slots,
61-/// and 400 for a malformed weekday, minute, or empty window.62+/// and 400 for a malformed weekday, minute, or empty window. `topic` is the
63+/// optional lesson topic the materializer copies onto generated sessions —
64+/// content, never an overlap input.
62 pub async fn add_for_offering(65 pub async fn add_for_offering(
63 db: &Database,66 db: &Database,
64 offering: &CourseOfferingId,67 offering: &CourseOfferingId,
65 weekday: Weekday,68 weekday: Weekday,
66 starts_at: SlotMinute,69 starts_at: SlotMinute,
67 ends_at: SlotMinute,70 ends_at: SlotMinute,
71+ topic: Option<SessionTopic>,
68 ) -> Result<WeeklySlot, AppError> {72 ) -> Result<WeeklySlot, AppError> {
69- let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at)?;73+ let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at, topic)?;
70 let owner = offering.clone();74 let owner = offering.clone();
71 tx_with_retry(db, false, async move |tx| {75 tx_with_retry(db, false, async move |tx| {
72 // The row lock serializes the pre-check and the insert: under READ76 // The row lock serializes the pre-check and the insert: under READ
@@ -89,8 +93,9 @@ pub async fn add_for_class(
89 weekday: Weekday,93 weekday: Weekday,
90 starts_at: SlotMinute,94 starts_at: SlotMinute,
91 ends_at: SlotMinute,95 ends_at: SlotMinute,
96+ topic: Option<SessionTopic>,
92 ) -> Result<WeeklySlot, AppError> {97 ) -> Result<WeeklySlot, AppError> {
93- let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at)?;98+ let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at, topic)?;
94 let owner = instance.clone();99 let owner = instance.clone();
95 tx_with_retry(db, false, async move |tx| {100 tx_with_retry(db, false, async move |tx| {
96 slot_db::lock_class_tx(tx, &owner).await?;101 slot_db::lock_class_tx(tx, &owner).await?;
@@ -198,13 +203,13 @@ mod tests {
198 let instance = an_instance(&db, "5-A").await;203 let instance = an_instance(&db, "5-A").await;
199 let offering = instance.get_offering().clone();204 let offering = instance.get_offering().clone();
200 205
201- add_for_offering(&db, &offering, day(2), mins(600), mins(660))206+ add_for_offering(&db, &offering, day(2), mins(600), mins(660), None)
202 .await207 .await
203 .unwrap();208 .unwrap();
204- add_for_offering(&db, &offering, day(1), mins(600), mins(660))209+ add_for_offering(&db, &offering, day(1), mins(600), mins(660), None)
205 .await210 .await
206 .unwrap();211 .unwrap();
207- add_for_offering(&db, &offering, day(1), mins(480), mins(540))212+ add_for_offering(&db, &offering, day(1), mins(480), mins(540), None)
208 .await213 .await
209 .unwrap();214 .unwrap();
210 215
@@ -229,11 +234,11 @@ mod tests {
229 let (db, _leases) = crate::database::init_test_db().await;234 let (db, _leases) = crate::database::init_test_db().await;
230 let instance = an_instance(&db, "5-B").await;235 let instance = an_instance(&db, "5-B").await;
231 let offering = instance.get_offering().clone();236 let offering = instance.get_offering().clone();
232- add_for_offering(&db, &offering, day(1), mins(480), mins(540))237+ add_for_offering(&db, &offering, day(1), mins(480), mins(540), None)
233 .await238 .await
234 .unwrap();239 .unwrap();
235 240
236- add_for_class(&db, instance.get_id(), day(3), mins(540), mins(600))241+ add_for_class(&db, instance.get_id(), day(3), mins(540), mins(600), None)
237 .await242 .await
238 .unwrap();243 .unwrap();
239 // The write flipped the flag: re-read so the resolver follows the244 // The write flipped the flag: re-read so the resolver follows the
@@ -269,7 +274,7 @@ mod tests {
269 async fn an_overlapping_slot_is_refused() {274 async fn an_overlapping_slot_is_refused() {
270 let (db, _leases) = crate::database::init_test_db().await;275 let (db, _leases) = crate::database::init_test_db().await;
271 let instance = an_instance(&db, "5-C").await;276 let instance = an_instance(&db, "5-C").await;
272- add_for_class(&db, instance.get_id(), day(1), mins(540), mins(600))277+ add_for_class(&db, instance.get_id(), day(1), mins(540), mins(600), None)
273 .await278 .await
274 .unwrap();279 .unwrap();
275 280
@@ -280,7 +285,7 @@ mod tests {
280 (530, 630, "the wider window"),285 (530, 630, "the wider window"),
281 ] {286 ] {
282 let attempt =287 let attempt =
283- add_for_class(&db, instance.get_id(), day(1), mins(starts), mins(ends)).await;288+ add_for_class(&db, instance.get_id(), day(1), mins(starts), mins(ends), None).await;
284 assert_eq!(289 assert_eq!(
285 coded(&attempt),290 coded(&attempt),
286 "slot_overlap",291 "slot_overlap",
@@ -289,10 +294,10 @@ mod tests {
289 }294 }
290 295
291 // Touching endpoints and a different weekday are not overlaps.296 // Touching endpoints and a different weekday are not overlaps.
292- add_for_class(&db, instance.get_id(), day(1), mins(600), mins(660))297+ add_for_class(&db, instance.get_id(), day(1), mins(600), mins(660), None)
293 .await298 .await
294 .unwrap();299 .unwrap();
295- add_for_class(&db, instance.get_id(), day(2), mins(540), mins(600))300+ add_for_class(&db, instance.get_id(), day(2), mins(540), mins(600), None)
296 .await301 .await
297 .unwrap();302 .unwrap();
298 assert_eq!(303 assert_eq!(
@@ -307,12 +312,12 @@ mod tests {
307 assert!(Weekday::new(0).is_err());312 assert!(Weekday::new(0).is_err());
308 assert!(SlotMinute::new(-1).is_err());313 assert!(SlotMinute::new(-1).is_err());
309 let empty_window =314 let empty_window =
310- add_for_class(&db, instance.get_id(), day(1), mins(600), mins(600)).await;315+ add_for_class(&db, instance.get_id(), day(1), mins(600), mins(600), None).await;
311 assert!(316 assert!(
312 matches!(empty_window, Err(AppError::Validation(_))),317 matches!(empty_window, Err(AppError::Validation(_))),
313 "{empty_window:?}"318 "{empty_window:?}"
314 );319 );
315- let inverted = add_for_class(&db, instance.get_id(), day(1), mins(1439), mins(600)).await;320+ let inverted = add_for_class(&db, instance.get_id(), day(1), mins(1439), mins(600), None).await;
316 assert!(321 assert!(
317 matches!(inverted, Err(AppError::Validation(_))),322 matches!(inverted, Err(AppError::Validation(_))),
318 "{inverted:?}"323 "{inverted:?}"
@@ -330,13 +335,7 @@ mod tests {
330 // 480+(i/7) — five or six per weekday, all touching, none crossing.335 // 480+(i/7) — five or six per weekday, all touching, none crossing.
331 for i in 0..crate::constant::MAX_WEEKLY_SLOTS {336 for i in 0..crate::constant::MAX_WEEKLY_SLOTS {
332 let i = i as i64;337 let i = i as i64;
333- add_for_class(338+ add_for_class(&db, instance.get_id(), day(((i % 7) + 1) as i16), mins(480 + i / 7), mins(481 + i / 7), None)
334- &db,
335- instance.get_id(),
336- day(((i % 7) + 1) as i16),
337- mins(480 + i / 7),
338- mins(481 + i / 7),
339- )
340 .await339 .await
341 .unwrap();340 .unwrap();
342 }341 }
@@ -349,7 +348,7 @@ mod tests {
349 );348 );
350 349
351 // Room on Sunday's timeline, but the plan is full.350 // Room on Sunday's timeline, but the plan is full.
352- let one_more = add_for_class(&db, instance.get_id(), day(7), mins(700), mins(760)).await;351+ let one_more = add_for_class(&db, instance.get_id(), day(7), mins(700), mins(760), None).await;
353 assert_eq!(coded(&one_more), "slot_cap");352 assert_eq!(coded(&one_more), "slot_cap");
354 assert_eq!(353 assert_eq!(
355 slot_db::list_for_class(&db, instance.get_id())354 slot_db::list_for_class(&db, instance.get_id())
@@ -367,10 +366,10 @@ mod tests {
367 let (db, _leases) = crate::database::init_test_db().await;366 let (db, _leases) = crate::database::init_test_db().await;
368 let instance = an_instance(&db, "5-E").await;367 let instance = an_instance(&db, "5-E").await;
369 let offering = instance.get_offering().clone();368 let offering = instance.get_offering().clone();
370- add_for_offering(&db, &offering, day(1), mins(480), mins(540))369+ add_for_offering(&db, &offering, day(1), mins(480), mins(540), None)
371 .await370 .await
372 .unwrap();371 .unwrap();
373- add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540))372+ add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540), None)
374 .await373 .await
375 .unwrap();374 .unwrap();
376 assert!(375 assert!(
@@ -403,10 +402,10 @@ mod tests {
403 let instance = an_instance(&db, "5-F").await;402 let instance = an_instance(&db, "5-F").await;
404 let other = an_instance(&db, "5-G").await;403 let other = an_instance(&db, "5-G").await;
405 404
406- add_for_class(&db, instance.get_id(), day(1), mins(480), mins(540))405+ add_for_class(&db, instance.get_id(), day(1), mins(480), mins(540), None)
407 .await406 .await
408 .unwrap();407 .unwrap();
409- add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540))408+ add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540), None)
410 .await409 .await
411 .unwrap();410 .unwrap();
412 let own = slot_db::list_for_class(&db, instance.get_id())411 let own = slot_db::list_for_class(&db, instance.get_id())
@@ -450,10 +449,10 @@ mod tests {
450 let instance = an_instance(&db, "5-H").await;449 let instance = an_instance(&db, "5-H").await;
451 let offering = instance.get_offering().clone();450 let offering = instance.get_offering().clone();
452 451
453- add_for_offering(&db, &offering, day(1), mins(540), mins(600))452+ add_for_offering(&db, &offering, day(1), mins(540), mins(600), None)
454 .await453 .await
455 .unwrap();454 .unwrap();
456- let clash = add_for_offering(&db, &offering, day(1), mins(570), mins(630)).await;455+ let clash = add_for_offering(&db, &offering, day(1), mins(570), mins(630), None).await;
457 assert_eq!(coded(&clash), "slot_overlap");456 assert_eq!(coded(&clash), "slot_overlap");
458 457
459 let slots = slot_db::list_for_offering(&db, &offering).await.unwrap();458 let slots = slot_db::list_for_offering(&db, &offering).await.unwrap();
src/web/attendance.rsmodified+3 -44
@@ -21,6 +21,7 @@ use utoipa_axum::routes;
21 21
22 use crate::database::Database;22 use crate::database::Database;
23 use crate::domain::attendance::AttendanceStatus;23 use crate::domain::attendance::AttendanceStatus;
24+use crate::domain::calendar::{zone_offset_minutes, zoned_day};
24 use crate::domain::class_course::{ClassCourse, ClassCourseId};25 use crate::domain::class_course::{ClassCourse, ClassCourseId};
25 use crate::domain::course::{Course, CourseId};26 use crate::domain::course::{Course, CourseId};
26 use crate::domain::role::Role;27 use crate::domain::role::Role;
@@ -150,30 +151,6 @@ struct AttendanceReport {
150 devamsizlik: Vec<TermAbsence>,151 devamsizlik: Vec<TermAbsence>,
151 }152 }
152 153
153-/// The school's day boundary as a fixed offset in minutes.
154-///
155-/// The allow-list in [`crate::constant::TIMEZONES`] names zones whose offset
156-/// is constant (Turkey has run on UTC+3 with no DST since 2016), so the
157-/// backend buckets days without carrying a timezone database — the same
158-/// arithmetic the settings module's own list is built on. An unrecognised name
159-/// falls back to [`crate::constant::DEFAULT_TIMEZONE`]'s offset, which is what
160-/// an unset setting
161-/// gets anyway.
162-fn zone_offset_minutes(timezone: &str) -> i32 {
163- match timezone {
164- "UTC" => 0,
165- _ => 3 * 60,
166- }
167-}
168-
169-/// The calendar day an instant falls on, in the school's zone.
170-fn zoned_day(millis: i64, offset_minutes: i32) -> chrono::NaiveDate {
171- let shifted = millis + i64::from(offset_minutes) * 60_000;
172- chrono::DateTime::from_timestamp_millis(shifted)
173- .expect("timestamps are within chrono's representable range")
174- .date_naive()
175-}
176-
177 /// The term an instant falls in: the containing term with the latest start,154 /// The term an instant falls in: the containing term with the latest start,
178 /// or `None` when the calendar does not cover it.155 /// or `None` when the calendar does not cover it.
179 fn term_of(instant: i64, terms: &[Term]) -> Option<&Term> {156 fn term_of(instant: i64, terms: &[Term]) -> Option<&Term> {
@@ -436,23 +413,5 @@ async fn user_report(
436 Ok(Json(build_report(&target, viewer, &st.db).await?))413 Ok(Json(build_report(&target, viewer, &st.db).await?))
437 }414 }
438 415
439-#[cfg(test)]416+// The day-bucketing unit test moved with its arithmetic to
440-mod tests {417+// `src/domain/calendar.rs` (`the_day_bucket_follows_the_school_zone`).
441- use super::*;
442-
443- /// The day bucket is the school's day, not UTC's: 22:30 UTC in summer
444- /// Istanbul is already tomorrow. This is the whole reason the timezone is
445- /// read off the settings.
446- #[test]
447- fn the_day_bucket_follows_the_school_zone() {
448- let at = crate::domain::timestamp::Timestamp::from_millis(1_767_216_600_000); // 2025-12-31T21:30Z
449- assert_eq!(
450- zoned_day(at.as_millis(), zone_offset_minutes("UTC")).to_string(),
451- "2025-12-31"
452- );
453- assert_eq!(
454- zoned_day(at.as_millis(), zone_offset_minutes("Europe/Istanbul")).to_string(),
455- "2026-01-01"
456- );
457- }
458-}
src/web/weekly_plan.rsmodified+10 -2
@@ -190,6 +190,7 @@ async fn add_offering_slot(
190 weekday,190 weekday,
191 starts_at,191 starts_at,
192 ends_at,192 ends_at,
193+ None,
193 )194 )
194 .await?;195 .await?;
195 Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot))))196 Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot))))
@@ -295,8 +296,15 @@ async fn add_instance_slot(
295 service::class_course::require_open(&st.db, instance.get_id()).await?;296 service::class_course::require_open(&st.db, instance.get_id()).await?;
296 let (weekday, starts_at, ends_at) = parse_slot(&req)?;297 let (weekday, starts_at, ends_at) = parse_slot(&req)?;
297 let slot =298 let slot =
298- service::weekly_slot::add_for_class(&st.db, instance.get_id(), weekday, starts_at, ends_at)299+ service::weekly_slot::add_for_class(
299- .await?;300+ &st.db,
301+ instance.get_id(),
302+ weekday,
303+ starts_at,
304+ ends_at,
305+ None,
306+ )
307+ .await?;
300 Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot))))308 Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot))))
301 }309 }
302 310
tests/spec_bounds.rsmodified+9 -0
@@ -1193,6 +1193,15 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
1193 // instance cannot be made to dominate the year average by a typo.1193 // instance cannot be made to dominate the year average by a typo.
1194 ("UpdateInstance", "ders_saati", "minimum", MIN_DERS_SAATI),1194 ("UpdateInstance", "ders_saati", "minimum", MIN_DERS_SAATI),
1195 ("UpdateInstance", "ders_saati", "maximum", MAX_DERS_SAATI),1195 ("UpdateInstance", "ders_saati", "maximum", MAX_DERS_SAATI),
1196+ // The holiday calendar's one free-text field, and the optional topic
1197+ // a weekly-plan slot may stamp onto every lesson it generates.
1198+ (
1199+ "CreateHoliday",
1200+ "name",
1201+ "maxLength",
1202+ MAX_HOLIDAY_NAME_LEN as i64,
1203+ ),
1204+ ("CreateSlot", "topic", "maxLength", MAX_SESSION_TOPIC_LEN as i64),
1196 // The offering spine (course × grade_level templates) and the1205 // The offering spine (course × grade_level templates) and the
1197 // per-class instance overrides: same bounds as the catalog course1206 // per-class instance overrides: same bounds as the catalog course
1198 // they inherit from.1207 // they inherit from.