From 7c481f7049ed9e14d32b6be4fc81ff55a9fe488d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 24 Sep 2026 13:28:01 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(schedule):=20holiday=20calenda?= =?UTF-8?q?r,=20slot=20topics,=20and=20the=20weekly-plan=20materializer=20?= =?UTF-8?q?core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- ...f299e307fbb6650c56d36d0ae9fb5ea49f91e.json | 191 ++++++++++++++++ ...b1ea60bd13fbe21a3432d1f6952742af99a4.json} | 18 +- ...f98ac80a882f8df310ccd44ab7f1ca4f0e338.json | 106 +++++++++ ...5f2978dca0f70af92972b00f2051ae2629e46.json | 100 +++++++++ ...a0c1ec8ed25a17bb2bd5aee6384db55f7ec24.json | 93 ++++++++ ...d8745b37d88ff00f48812498dc87c9b5fb51d.json | 58 ----- ...6baf35ab1eec36c62b3aa211ad29b79706abc.json | 71 ++++++ ...2a9931bd0291119e82af19090f9dc0b21a92.json} | 18 +- ...fc19920fd500e599d05d975c994eedc7c658b.json | 100 +++++++++ ...8fdeee58a09969da7a658de9a963c8682d27.json} | 21 +- ...6ec449a1c87f23c19374820611b784a1e28f1.json | 28 +++ ...9b4142938d5cedafea71addf525e5053d98b1.json | 101 +++++++++ README.md | 2 +- ...0260924000001_holidays_and_materialize.sql | 36 ++++ src/constant.rs | 26 +++ src/db/class_course.rs | 35 +++ src/db/course_session.rs | 95 +++++++- src/db/holiday.rs | 160 ++++++++++++++ src/db/mod.rs | 1 + src/db/weekly_slot.rs | 27 ++- src/domain/calendar.rs | 142 ++++++++++++ src/domain/holiday.rs | 191 ++++++++++++++++ src/domain/mod.rs | 2 + src/domain/weekly_slot.rs | 72 ++++++- src/service/course_session.rs | 203 +++++++++++++++++- src/service/holiday.rs | 68 ++++++ src/service/mod.rs | 1 + src/service/weekly_slot.rs | 63 +++--- src/web/attendance.rs | 47 +--- src/web/weekly_plan.rs | 12 +- tests/spec_bounds.rs | 9 + 31 files changed, 1929 insertions(+), 168 deletions(-) create mode 100644 .sqlx/query-01cb8fb2444f413ced7939feba2f299e307fbb6650c56d36d0ae9fb5ea49f91e.json rename .sqlx/{query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.json => query-34e21f7794cb59e3565397da7620b1ea60bd13fbe21a3432d1f6952742af99a4.json} (68%) create mode 100644 .sqlx/query-3f1fd92a954287a6f430fa659bef98ac80a882f8df310ccd44ab7f1ca4f0e338.json create mode 100644 .sqlx/query-5f4933f457252ca6c2346f8510f5f2978dca0f70af92972b00f2051ae2629e46.json create mode 100644 .sqlx/query-815fe85883c8355c4e150ebfaffa0c1ec8ed25a17bb2bd5aee6384db55f7ec24.json delete mode 100644 .sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.json create mode 100644 .sqlx/query-92a71caf8853da726ac8db8da956baf35ab1eec36c62b3aa211ad29b79706abc.json rename .sqlx/{query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.json => query-af710dcd8d7a967a46895f14eb832a9931bd0291119e82af19090f9dc0b21a92.json} (67%) create mode 100644 .sqlx/query-c3274251614e38dd624befe49c4fc19920fd500e599d05d975c994eedc7c658b.json rename .sqlx/{query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.json => query-e584ccedaaab3dcaf93bcdc9564f8fdeee58a09969da7a658de9a963c8682d27.json} (52%) create mode 100644 .sqlx/query-ecbad4a883751a9e609b406830c6ec449a1c87f23c19374820611b784a1e28f1.json create mode 100644 .sqlx/query-f7e609db6b3f1cc793bcf8f26739b4142938d5cedafea71addf525e5053d98b1.json create mode 100644 migrations/school/20260924000001_holidays_and_materialize.sql create mode 100644 src/db/holiday.rs create mode 100644 src/domain/calendar.rs create mode 100644 src/domain/holiday.rs create mode 100644 src/service/holiday.rs diff --git a/.sqlx/query-01cb8fb2444f413ced7939feba2f299e307fbb6650c56d36d0ae9fb5ea49f91e.json b/.sqlx/query-01cb8fb2444f413ced7939feba2f299e307fbb6650c56d36d0ae9fb5ea49f91e.json new file mode 100644 index 0000000..d76ab63 --- /dev/null +++ b/.sqlx/query-01cb8fb2444f413ced7939feba2f299e307fbb6650c56d36d0ae9fb5ea49f91e.json @@ -0,0 +1,191 @@ +{ + "db_name": "PostgreSQL", + "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", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "class: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "class" + } + } + }, + { + "ordinal": 2, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "course" + } + } + }, + { + "ordinal": 3, + "name": "offering: CourseOfferingId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "offering" + } + } + }, + { + "ordinal": 4, + "name": "attached_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_by" + } + } + }, + { + "ordinal": 5, + "name": "source?: ClassBlueprintId", + "type_info": "Int2", + "origin": { + "Table": { + "table": "class_blueprint", + "name": "grade_level" + } + } + }, + { + "ordinal": 6, + "name": "title?: CourseTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_course", + "name": "title" + } + } + }, + { + "ordinal": 7, + "name": "description?: CourseDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_course", + "name": "description" + } + } + }, + { + "ordinal": 8, + "name": "ders_saati?: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 9, + "name": "counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "counts_toward_karne" + } + } + }, + { + "ordinal": 10, + "name": "subjects_inherited", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "subjects_inherited" + } + } + }, + { + "ordinal": 11, + "name": "exam_weights_inherited", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "exam_weights_inherited" + } + } + }, + { + "ordinal": 12, + "name": "weekly_plan_inherited", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "weekly_plan_inherited" + } + } + }, + { + "ordinal": 13, + "name": "enrollment_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "enrollment_count" + } + } + }, + { + "ordinal": 14, + "name": "attached_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_at" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + true, + true, + null, + true, + false, + false, + false, + false, + false + ] + }, + "hash": "01cb8fb2444f413ced7939feba2f299e307fbb6650c56d36d0ae9fb5ea49f91e" +} diff --git a/.sqlx/query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.json b/.sqlx/query-34e21f7794cb59e3565397da7620b1ea60bd13fbe21a3432d1f6952742af99a4.json similarity index 68% rename from .sqlx/query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.json rename to .sqlx/query-34e21f7794cb59e3565397da7620b1ea60bd13fbe21a3432d1f6952742af99a4.json index b99935e..a41fc52 100644 --- a/.sqlx/query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.json +++ b/.sqlx/query-34e21f7794cb59e3565397da7620b1ea60bd13fbe21a3432d1f6952742af99a4.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "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", + "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", "describe": { "columns": [ { @@ -36,6 +36,17 @@ "name": "ends_at!: SlotMinute", "type_info": "Int8", "origin": "Expression" + }, + { + "ordinal": 4, + "name": "topic?: SessionTopic", + "type_info": "Text", + "origin": { + "Table": { + "table": "offering_slot", + "name": "topic" + } + } } ], "parameters": { @@ -47,8 +58,9 @@ false, false, null, - null + null, + true ] }, - "hash": "b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9" + "hash": "34e21f7794cb59e3565397da7620b1ea60bd13fbe21a3432d1f6952742af99a4" } diff --git a/.sqlx/query-3f1fd92a954287a6f430fa659bef98ac80a882f8df310ccd44ab7f1ca4f0e338.json b/.sqlx/query-3f1fd92a954287a6f430fa659bef98ac80a882f8df310ccd44ab7f1ca4f0e338.json new file mode 100644 index 0000000..422229f --- /dev/null +++ b/.sqlx/query-3f1fd92a954287a6f430fa659bef98ac80a882f8df310ccd44ab7f1ca4f0e338.json @@ -0,0 +1,106 @@ +{ + "db_name": "PostgreSQL", + "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\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: HolidayId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "holiday", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name: HolidayName", + "type_info": "Text", + "origin": { + "Table": { + "table": "holiday", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "starts_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "starts_at" + } + } + }, + { + "ordinal": 3, + "name": "ends_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "ends_at" + } + } + }, + { + "ordinal": 4, + "name": "kind: HolidayKind", + "type_info": "Text", + "origin": { + "Table": { + "table": "holiday", + "name": "kind" + } + } + }, + { + "ordinal": 5, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "holiday", + "name": "creator" + } + } + }, + { + "ordinal": 6, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "created_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Int8", + "Int8", + "Text", + "Uuid", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "3f1fd92a954287a6f430fa659bef98ac80a882f8df310ccd44ab7f1ca4f0e338" +} diff --git a/.sqlx/query-5f4933f457252ca6c2346f8510f5f2978dca0f70af92972b00f2051ae2629e46.json b/.sqlx/query-5f4933f457252ca6c2346f8510f5f2978dca0f70af92972b00f2051ae2629e46.json new file mode 100644 index 0000000..6aa36aa --- /dev/null +++ b/.sqlx/query-5f4933f457252ca6c2346f8510f5f2978dca0f70af92972b00f2051ae2629e46.json @@ -0,0 +1,100 @@ +{ + "db_name": "PostgreSQL", + "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\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: HolidayId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "holiday", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name: HolidayName", + "type_info": "Text", + "origin": { + "Table": { + "table": "holiday", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "starts_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "starts_at" + } + } + }, + { + "ordinal": 3, + "name": "ends_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "ends_at" + } + } + }, + { + "ordinal": 4, + "name": "kind: HolidayKind", + "type_info": "Text", + "origin": { + "Table": { + "table": "holiday", + "name": "kind" + } + } + }, + { + "ordinal": 5, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "holiday", + "name": "creator" + } + } + }, + { + "ordinal": 6, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "created_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "5f4933f457252ca6c2346f8510f5f2978dca0f70af92972b00f2051ae2629e46" +} diff --git a/.sqlx/query-815fe85883c8355c4e150ebfaffa0c1ec8ed25a17bb2bd5aee6384db55f7ec24.json b/.sqlx/query-815fe85883c8355c4e150ebfaffa0c1ec8ed25a17bb2bd5aee6384db55f7ec24.json new file mode 100644 index 0000000..faeae3c --- /dev/null +++ b/.sqlx/query-815fe85883c8355c4e150ebfaffa0c1ec8ed25a17bb2bd5aee6384db55f7ec24.json @@ -0,0 +1,93 @@ +{ + "db_name": "PostgreSQL", + "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\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: CourseSessionId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_session", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "class_course: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_session", + "name": "class_course" + } + } + }, + { + "ordinal": 2, + "name": "teacher: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_session", + "name": "teacher" + } + } + }, + { + "ordinal": 3, + "name": "topic: SessionTopic", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_session", + "name": "topic" + } + } + }, + { + "ordinal": 4, + "name": "starts_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_session", + "name": "starts_at" + } + } + }, + { + "ordinal": 5, + "name": "ends_at?: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_session", + "name": "ends_at" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray", + "UuidArray", + "UuidArray", + "TextArray", + "Int8Array", + "Int8Array" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + true + ] + }, + "hash": "815fe85883c8355c4e150ebfaffa0c1ec8ed25a17bb2bd5aee6384db55f7ec24" +} diff --git a/.sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.json b/.sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.json deleted file mode 100644 index a42ea1d..0000000 --- a/.sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "db_name": "PostgreSQL", - "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)", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: WeeklySlotId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_course_slot", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "weekday: Weekday", - "type_info": "Int2", - "origin": { - "Table": { - "table": "class_course_slot", - "name": "weekday" - } - } - }, - { - "ordinal": 2, - "name": "starts_at!: SlotMinute", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 3, - "name": "ends_at!: SlotMinute", - "type_info": "Int8", - "origin": "Expression" - } - ], - "parameters": { - "Left": [ - "Uuid", - "Uuid", - "Int2", - "Int8", - "Int8" - ] - }, - "nullable": [ - false, - false, - null, - null - ] - }, - "hash": "855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d" -} diff --git a/.sqlx/query-92a71caf8853da726ac8db8da956baf35ab1eec36c62b3aa211ad29b79706abc.json b/.sqlx/query-92a71caf8853da726ac8db8da956baf35ab1eec36c62b3aa211ad29b79706abc.json new file mode 100644 index 0000000..7b051a5 --- /dev/null +++ b/.sqlx/query-92a71caf8853da726ac8db8da956baf35ab1eec36c62b3aa211ad29b79706abc.json @@ -0,0 +1,71 @@ +{ + "db_name": "PostgreSQL", + "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)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: WeeklySlotId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course_slot", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "weekday: Weekday", + "type_info": "Int2", + "origin": { + "Table": { + "table": "class_course_slot", + "name": "weekday" + } + } + }, + { + "ordinal": 2, + "name": "starts_at!: SlotMinute", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 3, + "name": "ends_at!: SlotMinute", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 4, + "name": "topic?: SessionTopic", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_course_slot", + "name": "topic" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Int2", + "Int8", + "Int8", + "Text" + ] + }, + "nullable": [ + false, + false, + null, + null, + true + ] + }, + "hash": "92a71caf8853da726ac8db8da956baf35ab1eec36c62b3aa211ad29b79706abc" +} diff --git a/.sqlx/query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.json b/.sqlx/query-af710dcd8d7a967a46895f14eb832a9931bd0291119e82af19090f9dc0b21a92.json similarity index 67% rename from .sqlx/query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.json rename to .sqlx/query-af710dcd8d7a967a46895f14eb832a9931bd0291119e82af19090f9dc0b21a92.json index 8c91e8a..9e053ba 100644 --- a/.sqlx/query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.json +++ b/.sqlx/query-af710dcd8d7a967a46895f14eb832a9931bd0291119e82af19090f9dc0b21a92.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "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", + "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", "describe": { "columns": [ { @@ -36,6 +36,17 @@ "name": "ends_at!: SlotMinute", "type_info": "Int8", "origin": "Expression" + }, + { + "ordinal": 4, + "name": "topic?: SessionTopic", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_course_slot", + "name": "topic" + } + } } ], "parameters": { @@ -47,8 +58,9 @@ false, false, null, - null + null, + true ] }, - "hash": "e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351" + "hash": "af710dcd8d7a967a46895f14eb832a9931bd0291119e82af19090f9dc0b21a92" } diff --git a/.sqlx/query-c3274251614e38dd624befe49c4fc19920fd500e599d05d975c994eedc7c658b.json b/.sqlx/query-c3274251614e38dd624befe49c4fc19920fd500e599d05d975c994eedc7c658b.json new file mode 100644 index 0000000..47abe1d --- /dev/null +++ b/.sqlx/query-c3274251614e38dd624befe49c4fc19920fd500e599d05d975c994eedc7c658b.json @@ -0,0 +1,100 @@ +{ + "db_name": "PostgreSQL", + "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", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: HolidayId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "holiday", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name: HolidayName", + "type_info": "Text", + "origin": { + "Table": { + "table": "holiday", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "starts_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "starts_at" + } + } + }, + { + "ordinal": 3, + "name": "ends_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "ends_at" + } + } + }, + { + "ordinal": 4, + "name": "kind: HolidayKind", + "type_info": "Text", + "origin": { + "Table": { + "table": "holiday", + "name": "kind" + } + } + }, + { + "ordinal": 5, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "holiday", + "name": "creator" + } + } + }, + { + "ordinal": 6, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "created_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "c3274251614e38dd624befe49c4fc19920fd500e599d05d975c994eedc7c658b" +} diff --git a/.sqlx/query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.json b/.sqlx/query-e584ccedaaab3dcaf93bcdc9564f8fdeee58a09969da7a658de9a963c8682d27.json similarity index 52% rename from .sqlx/query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.json rename to .sqlx/query-e584ccedaaab3dcaf93bcdc9564f8fdeee58a09969da7a658de9a963c8682d27.json index 795c7a6..6b871b4 100644 --- a/.sqlx/query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.json +++ b/.sqlx/query-e584ccedaaab3dcaf93bcdc9564f8fdeee58a09969da7a658de9a963c8682d27.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "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\"", + "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\"", "describe": { "columns": [ { @@ -36,6 +36,17 @@ "name": "ends_at!: SlotMinute", "type_info": "Int8", "origin": "Expression" + }, + { + "ordinal": 4, + "name": "topic?: SessionTopic", + "type_info": "Text", + "origin": { + "Table": { + "table": "offering_slot", + "name": "topic" + } + } } ], "parameters": { @@ -44,15 +55,17 @@ "Uuid", "Int2", "Int8", - "Int8" + "Int8", + "Text" ] }, "nullable": [ false, false, null, - null + null, + true ] }, - "hash": "d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738" + "hash": "e584ccedaaab3dcaf93bcdc9564f8fdeee58a09969da7a658de9a963c8682d27" } diff --git a/.sqlx/query-ecbad4a883751a9e609b406830c6ec449a1c87f23c19374820611b784a1e28f1.json b/.sqlx/query-ecbad4a883751a9e609b406830c6ec449a1c87f23c19374820611b784a1e28f1.json new file mode 100644 index 0000000..418cfd0 --- /dev/null +++ b/.sqlx/query-ecbad4a883751a9e609b406830c6ec449a1c87f23c19374820611b784a1e28f1.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT starts_at FROM course_session WHERE class_course = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "starts_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_session", + "name": "starts_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "ecbad4a883751a9e609b406830c6ec449a1c87f23c19374820611b784a1e28f1" +} diff --git a/.sqlx/query-f7e609db6b3f1cc793bcf8f26739b4142938d5cedafea71addf525e5053d98b1.json b/.sqlx/query-f7e609db6b3f1cc793bcf8f26739b4142938d5cedafea71addf525e5053d98b1.json new file mode 100644 index 0000000..ea59cd0 --- /dev/null +++ b/.sqlx/query-f7e609db6b3f1cc793bcf8f26739b4142938d5cedafea71addf525e5053d98b1.json @@ -0,0 +1,101 @@ +{ + "db_name": "PostgreSQL", + "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", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: HolidayId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "holiday", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name: HolidayName", + "type_info": "Text", + "origin": { + "Table": { + "table": "holiday", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "starts_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "starts_at" + } + } + }, + { + "ordinal": 3, + "name": "ends_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "ends_at" + } + } + }, + { + "ordinal": 4, + "name": "kind: HolidayKind", + "type_info": "Text", + "origin": { + "Table": { + "table": "holiday", + "name": "kind" + } + } + }, + { + "ordinal": 5, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "holiday", + "name": "creator" + } + } + }, + { + "ordinal": 6, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "holiday", + "name": "created_at" + } + } + } + ], + "parameters": { + "Left": [ + "Int8", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "f7e609db6b3f1cc793bcf8f26739b4142938d5cedafea71addf525e5053d98b1" +} diff --git a/README.md b/README.md index 98fb412..5adfb25 100644 --- a/README.md +++ b/README.md @@ -733,7 +733,7 @@ drift from it**, which is enforced rather than asked for: and fails unless each one is either referenced by `src/web/limits.rs` or listed as a deliberate exclusion *with a reason*. A new constant breaks the suite until someone decides, consciously, whether clients need it. -- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 239 published +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 241 published bounds back out of the emitted JSON, and asserts each equals its constant. This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal only** — a `const` there does not compile — so the annotations are diff --git a/migrations/school/20260924000001_holidays_and_materialize.sql b/migrations/school/20260924000001_holidays_and_materialize.sql new file mode 100644 index 0000000..e512f50 --- /dev/null +++ b/migrations/school/20260924000001_holidays_and_materialize.sql @@ -0,0 +1,36 @@ +-- Holiday calendar + weekly-plan materializer support. +-- +-- `holiday` is the school-wide non-teaching calendar: named instant ranges +-- (the same shape `term`, `event`, `exam` and `academic_year` already use — +-- four of five dated resources are instants; no day type is introduced). +-- The weekly-plan materializer reads it to skip non-teaching days. +-- +-- `offering_slot` / `class_course_slot` gain an optional `topic`: without it +-- every generated lesson of a section shares one topic, which is useless for +-- attendance and homework. +-- +-- `course_session (class_course, starts_at)` becomes UNIQUE: two lessons of +-- one section cannot start at the same instant. This is what makes a +-- concurrent materialize idempotent (`ON CONFLICT DO NOTHING`), and it turns +-- the duplicate-start instant from a silent twin lesson into a conflict the +-- single-session create route answers with a coded 409. The deployed demo +-- school held no duplicate pair when this landed. +-- +-- No tenant column: tenancy is one Postgres database per school. + +CREATE TABLE holiday ( + id uuid PRIMARY KEY, + name TEXT NOT NULL, + starts_at BIGINT NOT NULL, + ends_at BIGINT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('resmi', 'dini', 'idari', 'ara')), + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL +); +CREATE INDEX holiday_starts_at ON holiday (starts_at); + +ALTER TABLE offering_slot ADD COLUMN topic TEXT NULL; +ALTER TABLE class_course_slot ADD COLUMN topic TEXT NULL; + +CREATE UNIQUE INDEX course_session_class_course_starts_at + ON course_session (class_course, starts_at); diff --git a/src/constant.rs b/src/constant.rs index eb482e9..8bbf8a4 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -239,6 +239,32 @@ pub const MAX_APPOINTMENT_REASON_LEN: usize = 1_000; /// (a decade out) is refused instead of writing thousands of rows. pub const MAX_SLOT_OCCURRENCES: usize = 52; +/// A holiday is named for a human reader ("29 Ekim Cumhuriyet Bayramı"). +pub const MAX_HOLIDAY_NAME_LEN: usize = 100; + +/// The only accepted holiday kinds. `resmi`: an official public holiday. +/// `dini`: a religious observance. `idari`: an administrative closure the +/// school itself declares. `ara`: a break inside the year (yarım yıl arası). +pub const HOLIDAY_KINDS: [&str; 4] = ["resmi", "dini", "idari", "ara"]; + +/// The holiday table's name, for the same builder-shaped writes every other +/// table names through its constant. +pub const HOLIDAY_TABLE: &str = "holiday"; + +/// The longest `from`/`to` span one materialize call may cover, in days. A +/// school year fits; a decade is a typo and is refused. +pub const MAX_MATERIALIZE_DAYS: i64 = 366; + +/// The most lessons one materialize call may write. Forty slots a week is the +/// plan cap, so a full year is far under this; the ceiling is what stops a +/// runaway range from writing thousands of rows in one request. +pub const MAX_MATERIALIZE_SESSIONS: usize = 500; + +/// How many sections one catalogue course row may embed. A course taught in +/// more sections than this still lists them at `/instances`; the catalogue +/// row carries the untruncated total beside the array. +pub const MAX_COURSE_SECTIONS: usize = 50; + /// The default meal slots; schools replace the list via `PATCH /settings`, and /// a published menu snapshots the slot it was written for, so retiring a slot /// never rewrites history. diff --git a/src/db/class_course.rs b/src/db/class_course.rs index 756a053..a0ba7b6 100644 --- a/src/db/class_course.rs +++ b/src/db/class_course.rs @@ -146,6 +146,41 @@ pub async fn list_for_class_ids( Ok(rows) } +/// Every instance of any of `courses` (one query, unpaged) — the batched twin +/// of [`list_for_course`]: the catalogue page reads one query per page, not +/// one per course. Ids that name no course are simply absent from the result. +pub async fn list_for_course_ids( + db: &Database, + courses: &[CourseId], +) -> Result, AppError> { + if courses.is_empty() { + return Ok(Vec::new()); + } + let ids: Vec = courses.iter().map(CourseId::uuid).collect(); + let rows = sqlx::query_as!( + ClassCourse, + r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", + cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId", + cc.attached_by AS "attached_by: UserId", + b.grade_level AS "source?: ClassBlueprintId", + cc.title AS "title?: CourseTitle", + cc.description AS "description?: CourseDescription", + cc.ders_saati::bigint AS "ders_saati?: DersSaati", + cc.counts_toward_karne, + cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited, + cc.enrollment_count, + cc.attached_at AS "attached_at: Timestamp" + FROM class_course cc + LEFT JOIN class_blueprint b ON b.id = cc.source + WHERE cc.course = ANY($1) + ORDER BY cc.attached_at DESC, cc.id DESC"#, + &ids, + ) + .fetch_all(db) + .await?; + Ok(rows) +} + /// Load every instance behind `ids` (one query) — the join half of the reads /// that already hold instance ids (a marks report's per-instance blocks). pub async fn list_by_ids( diff --git a/src/db/course_session.rs b/src/db/course_session.rs index 5be10c8..62eb827 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -6,7 +6,9 @@ //! [`crate::service::course_session`]. use crate::constant::COURSE_SESSION_TABLE; -use crate::database::{Database, foreign_key_violation, tx_with_retry}; +use crate::database::{ + Database, foreign_key_violation, tx_with_retry, unique_violation, +}; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::class_course::ClassCourseId; @@ -58,10 +60,101 @@ pub async fn create( match created { Ok(created) => Ok(created), Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound), + // `23505` — the section's own `UNIQUE (class_course, starts_at)`: a + // lesson already starts at that instant (a hand-created one, or one a + // concurrent materialize just minted). The same refusal the + // weekly-plan duplicate answers with. + Err(err) if unique_violation(&err).is_some() => Err(AppError::ConflictCoded { + code: "session_time_taken", + message: "this section already has a lesson starting then".into(), + }), Err(err) => Err(err.into()), } } +/// One session to batch-insert: everything the materializer already decided. +/// The wire shape of [`insert_many`], not a door of its own. +#[derive(Debug, Clone)] +pub struct NewSession { + pub id: CourseSessionId, + pub class_course: ClassCourseId, + pub teacher: UserId, + pub topic: SessionTopic, + pub starts_at: Timestamp, + pub ends_at: Timestamp, +} + +/// Insert a batch of generated sessions in one statement, skipping the starts +/// this section already holds (`ON CONFLICT DO NOTHING` against +/// `UNIQUE (class_course, starts_at)`). The returned rows are exactly the rows +/// that landed, so the caller's `created` count is truthful. No transaction of +/// its own: the caller's (or none — the conflict skip makes a partial batch a +/// safe outcome either way). Empty input never touches the database. +pub async fn insert_many( + db: &Database, + rows: &[NewSession], +) -> Result, AppError> { + if rows.is_empty() { + return Ok(Vec::new()); + } + let mut conn = db.acquire().await?; + insert_many_tx(&mut conn, rows).await +} + +/// The transaction-scoped twin of [`insert_many`]: the very same statement, +/// bound to the caller's own connection, so a batch its transaction rolls back +/// never lands. The materializer is the caller — its row lock and its insert +/// must be the one transaction, and a pooled insert inside that window would +/// commit on its own. +pub(crate) async fn insert_many_tx( + tx: &mut sqlx::PgConnection, + rows: &[NewSession], +) -> Result, AppError> { + if rows.is_empty() { + return Ok(Vec::new()); + } + let ids: Vec = rows.iter().map(|row| row.id.uuid()).collect(); + let class_courses: Vec = rows.iter().map(|row| row.class_course.uuid()).collect(); + let teachers: Vec = rows.iter().map(|row| row.teacher.uuid()).collect(); + let topics: Vec = rows.iter().map(|row| row.topic.as_str().to_owned()).collect(); + let starts: Vec = rows.iter().map(|row| row.starts_at.as_millis()).collect(); + let ends: Vec = rows.iter().map(|row| row.ends_at.as_millis()).collect(); + let inserted = sqlx::query_as!( + CourseSession, + r#"INSERT INTO course_session (id, class_course, teacher, topic, starts_at, ends_at) + SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::uuid[], $4::text[], $5::bigint[], $6::bigint[]) + ON CONFLICT (class_course, starts_at) DO NOTHING + RETURNING id AS "id: CourseSessionId", + class_course AS "class_course: ClassCourseId", + teacher AS "teacher: UserId", topic AS "topic: SessionTopic", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at?: Timestamp""#, + &ids, + &class_courses, + &teachers, + &topics, + &starts, + &ends, + ) + .fetch_all(&mut *tx) + .await?; + Ok(inserted) +} + +/// The instants this section already holds a lesson at — the materializer's +/// skip set, one read for the whole range. +pub async fn existing_starts( + db: &Database, + instance: &ClassCourseId, +) -> Result, AppError> { + let rows = sqlx::query_scalar!( + r#"SELECT starts_at FROM course_session WHERE class_course = $1"#, + instance.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows.into_iter().collect()) +} + pub async fn read(db: &Database, id: &CourseSessionId) -> Result, AppError> { let session = sqlx::query_as!( CourseSession, diff --git a/src/db/holiday.rs b/src/db/holiday.rs new file mode 100644 index 0000000..0172e20 --- /dev/null +++ b/src/db/holiday.rs @@ -0,0 +1,160 @@ +//! The `holiday` table: the row mint, the read, the field-scoped PATCH whose +//! `WHERE` re-checks the merged range, the delete, and the two listings — a +//! paged calendar view and the materializer's overlap read. The type lives in +//! [`crate::domain::holiday`]. + +use crate::constant::HOLIDAY_TABLE; +use crate::database::Database; +use crate::db::field_update::FieldUpdate; +use crate::db::page::{Param, PagedList}; +use crate::domain::holiday::{Holiday, HolidayId, HolidayKind, HolidayName}; +use crate::domain::timestamp::{Timestamp, range_error}; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// A PATCH of one holiday row: only the fields the request carried are +/// written, `None` = omitted = keep. +#[derive(Debug, Clone, Default)] +pub struct HolidayPatch { + pub name: Option, + pub starts_at: Option, + pub ends_at: Option, + pub kind: Option, +} + +pub async fn create( + db: &Database, + name: &HolidayName, + starts_at: Timestamp, + ends_at: Timestamp, + kind: &HolidayKind, + creator: &UserId, +) -> Result { + let holiday = Holiday { + id: HolidayId::generate(), + name: name.clone(), + starts_at, + ends_at, + kind: kind.clone(), + creator: *creator, + created_at: Timestamp::now(), + }; + let created = sqlx::query_as!( + Holiday, + r#"INSERT INTO holiday (id, name, starts_at, ends_at, kind, creator, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7) + RETURNING id AS "id: HolidayId", name AS "name: HolidayName", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", + kind AS "kind: HolidayKind", creator AS "creator: UserId", + created_at AS "created_at: Timestamp""#, + holiday.id.uuid(), + holiday.name.as_str(), + holiday.starts_at.as_millis(), + holiday.ends_at.as_millis(), + holiday.kind.as_str(), + holiday.creator.uuid(), + holiday.created_at.as_millis(), + ) + .fetch_one(db) + .await?; + Ok(created) +} + +/// The holiday `id` names, or `Err(NotFound)` when absent. +pub async fn read(db: &Database, id: &HolidayId) -> Result { + sqlx::query_as!( + Holiday, + r#"SELECT id AS "id: HolidayId", name AS "name: HolidayName", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", + kind AS "kind: HolidayKind", creator AS "creator: UserId", + created_at AS "created_at: Timestamp" + FROM holiday WHERE id = $1"#, + id.uuid(), + ) + .fetch_optional(db) + .await? + .ok_or(AppError::NotFound) +} + +/// Write only the fields the PATCH carried, and re-check the merged +/// `starts_at <= ends_at` in the `UPDATE`'s own `WHERE` — two PATCHes each +/// moving one end of the range cannot commit an inverted holiday between +/// them. +pub async fn update( + db: &Database, + id: &HolidayId, + patch: HolidayPatch, +) -> Result { + FieldUpdate::new(HOLIDAY_TABLE, id.uuid()) + .set("name", patch.name.map(|name| name.as_str().to_owned())) + .set("starts_at", patch.starts_at.map(|at| at.as_millis())) + .set("ends_at", patch.ends_at.map(|at| at.as_millis())) + .set("kind", patch.kind.map(|kind| kind.as_str().to_owned())) + .ordered("starts_at", "ends_at", range_error()) + .run::(db) + .await +} + +/// Delete the holiday. A holiday is referenced by nothing — the materializer +/// only *reads* it — so nothing can refuse the delete but its own absence. +pub async fn delete(db: &Database, id: &HolidayId) -> Result { + let deleted = sqlx::query_as!( + Holiday, + r#"DELETE FROM holiday WHERE id = $1 + RETURNING id AS "id: HolidayId", name AS "name: HolidayName", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", + kind AS "kind: HolidayKind", creator AS "creator: UserId", + created_at AS "created_at: Timestamp""#, + id.uuid(), + ) + .fetch_optional(db) + .await?; + deleted.ok_or(AppError::NotFound) +} + +/// Holidays, newest start first, paged. `from`/`to` are inclusive bounds with +/// overlap semantics — a holiday is listed when it *reaches into* the range, +/// not only when it lies inside it. +pub async fn list( + db: &Database, + from: Option, + to: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + format!( + "{HOLIDAY_TABLE} WHERE ($1::bigint IS NULL OR ends_at >= $1) \ + AND ($2::bigint IS NULL OR starts_at <= $2)" + ), + "ORDER BY starts_at DESC, id DESC", + ) + .bind(Param::OptI64(from.map(|at| at.as_millis()))) + .bind(Param::OptI64(to.map(|at| at.as_millis()))) + .run::(limit, offset, db) + .await +} + +/// Every holiday reaching into `[from, to]`, unpaged, earliest first — the +/// materializer's read. Same overlap semantics as [`list`]. +pub async fn list_between( + db: &Database, + from: Timestamp, + to: Timestamp, +) -> Result, AppError> { + let rows = sqlx::query_as!( + Holiday, + r#"SELECT id AS "id: HolidayId", name AS "name: HolidayName", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", + kind AS "kind: HolidayKind", creator AS "creator: UserId", + created_at AS "created_at: Timestamp" + FROM holiday + WHERE ends_at >= $1 AND starts_at <= $2 + ORDER BY starts_at"#, + from.as_millis(), + to.as_millis(), + ) + .fetch_all(db) + .await?; + Ok(rows) +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 68f040c..9f03189 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -38,6 +38,7 @@ pub mod exam_weight; pub mod fee_plan; pub mod fee_plan_assignment; pub mod field_update; +pub mod holiday; pub mod homework; pub mod homework_file; pub mod homework_result; diff --git a/src/db/weekly_slot.rs b/src/db/weekly_slot.rs index 25a82a0..9a29a20 100644 --- a/src/db/weekly_slot.rs +++ b/src/db/weekly_slot.rs @@ -21,6 +21,7 @@ use sqlx::postgres::PgConnection; use crate::database::{Database, unique_violation}; use crate::domain::class_course::ClassCourseId; use crate::domain::course_offering::CourseOfferingId; +use crate::domain::course_session::SessionTopic; use crate::domain::weekly_slot::{SlotMinute, Weekday, WeeklySlot, WeeklySlotId}; use crate::error::AppError; @@ -52,7 +53,8 @@ pub(crate) async fn list_for_offering_on( r#"SELECT id AS "id: WeeklySlotId", weekday AS "weekday: Weekday", (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute", - (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute" + (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute", + topic AS "topic?: SessionTopic" FROM offering_slot WHERE offering = $1 ORDER BY weekday, starts_at"#, @@ -72,7 +74,8 @@ pub(crate) async fn list_for_class_on( r#"SELECT id AS "id: WeeklySlotId", weekday AS "weekday: Weekday", (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute", - (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute" + (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute", + topic AS "topic?: SessionTopic" FROM class_course_slot WHERE class_course = $1 ORDER BY weekday, starts_at"#, @@ -132,19 +135,22 @@ pub(crate) async fn add_for_offering_tx( ) -> Result { sqlx::query_as!( WeeklySlot, - r#"INSERT INTO offering_slot (id, offering, weekday, starts_at, ends_at) + r#"INSERT INTO offering_slot (id, offering, weekday, starts_at, ends_at, topic) VALUES ($1, $2, $3, ($4::bigint * interval '1 minute')::time, - ($5::bigint * interval '1 minute')::time) + ($5::bigint * interval '1 minute')::time, + $6) RETURNING id AS "id: WeeklySlotId", weekday AS "weekday: Weekday", (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute", - (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute""#, + (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute", + topic AS "topic?: SessionTopic""#, slot.get_id().uuid(), offering.uuid(), slot.get_weekday().get(), slot.get_starts_at().get(), slot.get_ends_at().get(), + slot.get_topic().map(|topic| topic.as_str()), ) .fetch_one(&mut *tx) .await @@ -173,11 +179,12 @@ pub(crate) async fn add_for_class_tx( sqlx::query_as!( WeeklySlot, r#"WITH ins AS ( - INSERT INTO class_course_slot (id, class_course, weekday, starts_at, ends_at) + INSERT INTO class_course_slot (id, class_course, weekday, starts_at, ends_at, topic) VALUES ($1, $2, $3, ($4::bigint * interval '1 minute')::time, - ($5::bigint * interval '1 minute')::time) - RETURNING id, weekday, starts_at, ends_at + ($5::bigint * interval '1 minute')::time, + $6) + RETURNING id, weekday, starts_at, ends_at, topic ), flip AS ( UPDATE class_course SET weekly_plan_inherited = FALSE WHERE id = $2 AND EXISTS (SELECT 1 FROM ins) @@ -186,7 +193,8 @@ pub(crate) async fn add_for_class_tx( SELECT ins.id AS "id: WeeklySlotId", ins.weekday AS "weekday: Weekday", (EXTRACT(EPOCH FROM ins.starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute", - (EXTRACT(EPOCH FROM ins.ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute" + (EXTRACT(EPOCH FROM ins.ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute", + ins.topic AS "topic?: SessionTopic" FROM ins WHERE EXISTS (SELECT 1 FROM flip)"#, slot.get_id().uuid(), @@ -194,6 +202,7 @@ pub(crate) async fn add_for_class_tx( slot.get_weekday().get(), slot.get_starts_at().get(), slot.get_ends_at().get(), + slot.get_topic().map(|topic| topic.as_str()), ) .fetch_optional(&mut *tx) .await? diff --git a/src/domain/calendar.rs b/src/domain/calendar.rs new file mode 100644 index 0000000..c085233 --- /dev/null +++ b/src/domain/calendar.rs @@ -0,0 +1,142 @@ +//! The school's day math, in one place: zone offset, the calendar day an +//! instant falls on, the instant a day starts at, the ISO weekday, and day +//! ranges. +//! +//! Everything here is fixed-offset arithmetic — the allow-list in +//! [`crate::constant::TIMEZONES`] names zones whose offset is constant +//! (Turkey has run on UTC+3 with no DST since 2016), so the backend buckets +//! days without carrying a timezone database. Consumers read the school's +//! zone off its settings +//! ([`Settings::get_timezone`](crate::domain::settings::Settings::get_timezone)) +//! and pass the offset down, because "a day" is a calendar day at the school, +//! not a UTC one. + +use chrono::Datelike; + +/// The school's day boundary as a fixed offset in minutes. +/// +/// An unrecognised name falls back to [`crate::constant::DEFAULT_TIMEZONE`]'s +/// offset, which is what an unset setting gets anyway. +pub fn zone_offset_minutes(timezone: &str) -> i32 { + match timezone { + "UTC" => 0, + _ => 3 * 60, + } +} + +/// The calendar day an instant falls on, in the school's zone. +pub fn zoned_day(millis: i64, offset_minutes: i32) -> chrono::NaiveDate { + let shifted = millis + i64::from(offset_minutes) * 60_000; + chrono::DateTime::from_timestamp_millis(shifted) + .expect("timestamps are within chrono's representable range") + .date_naive() +} + +/// The instant `day` begins at, in the school's zone: midnight local time as +/// a UTC millisecond count. The inverse of [`zoned_day`] at day granularity — +/// a round trip through both lands on the same date. +pub fn day_start_millis(day: chrono::NaiveDate, offset_minutes: i32) -> i64 { + day.and_hms_opt(0, 0, 0) + .expect("midnight is a valid time") + .and_utc() + .timestamp_millis() + - i64::from(offset_minutes) * 60_000 +} + +/// The ISO weekday of `day`: `1` = Monday through `7` = Sunday, the same +/// scale the weekly plan's `weekday` column carries. +pub fn iso_weekday(day: chrono::NaiveDate) -> i16 { + day.weekday().num_days_from_monday() as i16 + 1 +} + +/// How many days `from..=to` spans, endpoints included. An inverted range +/// (`to` before `from`) answers a negative count; the generator works over +/// [`days_between`] instead, whose answer is simply empty there. +pub fn days_inclusive(from: chrono::NaiveDate, to: chrono::NaiveDate) -> i64 { + (to - from).num_days() + 1 +} + +/// Every calendar day from `from` through `to`, endpoints included. An +/// inverted range names no day at all. +/// +/// Walked one `succ_opt` at a time rather than collected from `from..=to`: +/// `RangeInclusive` is only an iterator through chrono's private +/// `Step`, so the range form does not compile here. The walk stops at the +/// last representable date instead of panicking. +pub fn days_between(from: chrono::NaiveDate, to: chrono::NaiveDate) -> Vec { + let mut days = Vec::new(); + let mut day = from; + while day <= to { + days.push(day); + match day.succ_opt() { + Some(next) => day = next, + None => break, + } + } + days +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::timestamp::Timestamp; + + #[test] + fn the_zone_offset_follows_the_allow_list() { + assert_eq!(zone_offset_minutes("UTC"), 0); + assert_eq!(zone_offset_minutes("Europe/Istanbul"), 3 * 60); + } + + /// The day bucket is the school's day, not UTC's: 22:30 UTC in summer + /// Istanbul is already tomorrow. This is the whole reason the timezone is + /// read off the settings. + #[test] + fn the_day_bucket_follows_the_school_zone() { + let at = Timestamp::from_millis(1_767_216_600_000); // 2025-12-31T21:30Z + assert_eq!( + zoned_day(at.as_millis(), zone_offset_minutes("UTC")).to_string(), + "2025-12-31" + ); + assert_eq!( + zoned_day(at.as_millis(), zone_offset_minutes("Europe/Istanbul")).to_string(), + "2026-01-01" + ); + } + + #[test] + fn iso_weekday_is_the_monday_one_scale() { + // 2026-09-28 is a Monday, 2026-10-04 the Sunday that ends it. + let monday = chrono::NaiveDate::from_ymd_opt(2026, 9, 28).unwrap(); + let sunday = chrono::NaiveDate::from_ymd_opt(2026, 10, 4).unwrap(); + assert_eq!(iso_weekday(monday), 1); + assert_eq!(iso_weekday(sunday), 7); + } + + #[test] + fn day_ranges_are_inclusive() { + let monday = chrono::NaiveDate::from_ymd_opt(2026, 9, 28).unwrap(); + let next_monday = chrono::NaiveDate::from_ymd_opt(2026, 10, 5).unwrap(); + // A single day spans one day. + assert_eq!(days_inclusive(monday, monday), 1); + assert_eq!(days_between(monday, monday), vec![monday]); + // Monday through the next Monday is eight days, endpoints named. + assert_eq!(days_inclusive(monday, next_monday), 8); + let days = days_between(monday, next_monday); + assert_eq!(days.len(), 8); + assert_eq!(days[0], monday); + assert_eq!(days[7], next_monday); + // An inverted range names no day. + assert!(days_between(next_monday, monday).is_empty()); + } + + #[test] + fn day_start_round_trips_through_zoned_day() { + let day = chrono::NaiveDate::from_ymd_opt(2026, 9, 28).unwrap(); + for offset in [0, 3 * 60] { + let start = day_start_millis(day, offset); + assert_eq!(zoned_day(start, offset), day); + // Midnight local: the day before, this instant is still evening. + assert_eq!(zoned_day(start - 1, offset), day.pred_opt().unwrap()); + } + } +} diff --git a/src/domain/holiday.rs b/src/domain/holiday.rs new file mode 100644 index 0000000..e6a55ab --- /dev/null +++ b/src/domain/holiday.rs @@ -0,0 +1,191 @@ +//! The holiday calendar: one named, school-wide non-teaching range. Both ends +//! are *instants* (unix millis), exactly like `term`, `event`, `exam` and +//! `academic_year` — the materializer compares instants, so no separate day +//! type exists. + +use uuid::Uuid; + +use crate::constant::{HOLIDAY_KINDS, MAX_HOLIDAY_NAME_LEN}; +use crate::domain::monotonic_id::next_uuid; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::ValidationError; +use crate::validate::validate_required; + +/// Typed holiday row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct HolidayId(Uuid); + +impl HolidayId { + /// Minted from the process-wide monotonic generator, not a random v4: + /// holidays sort `starts_at DESC, id DESC` and the id breaks the tie + /// between two holidays starting at the same instant. + pub fn generate() -> Self { + Self(next_uuid()) + } + + /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that + /// cannot take the newtype. Static `query!` binds take `self` directly. + pub fn uuid(&self) -> Uuid { + self.0 + } + + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. + pub fn from_key(key: &str) -> Self { + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) + } + + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() + } +} + +/// The holiday's display name ("29 Ekim Cumhuriyet Bayramı"). +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct HolidayName(String); + +impl HolidayName { + pub fn try_new(value: &str) -> Result { + validate_required("name", value, MAX_HOLIDAY_NAME_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// Why the school is closed, from a closed list: `resmi` (official), `dini` +/// (religious), `idari` (administrative), `ara` (a break inside the year). +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct HolidayKind(String); + +impl HolidayKind { + /// The accepted spellings — the wire form of the DDL's `CHECK`. + pub const ALL: [&str; 4] = HOLIDAY_KINDS; + + pub fn try_new(value: &str) -> Result { + if !Self::ALL.contains(&value) { + return Err(ValidationError::Unknown { + field: "kind", + value: value.to_owned(), + }); + } + Ok(Self(value.to_owned())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// One school-wide non-teaching range: from `starts_at` through `ends_at` +/// (inclusive instants), named, and stamped by the manager who declared it. +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct Holiday { + pub(crate) id: HolidayId, + pub(crate) name: HolidayName, + pub(crate) starts_at: Timestamp, + pub(crate) ends_at: Timestamp, + pub(crate) kind: HolidayKind, + pub(crate) creator: UserId, + pub(crate) created_at: Timestamp, +} + +impl Holiday { + pub fn get_id(&self) -> &HolidayId { + &self.id + } + + pub fn get_name(&self) -> &HolidayName { + &self.name + } + + pub fn get_starts_at(&self) -> Timestamp { + self.starts_at + } + + pub fn get_ends_at(&self) -> Timestamp { + self.ends_at + } + + pub fn get_kind(&self) -> &HolidayKind { + &self.kind + } + + pub fn get_creator(&self) -> &UserId { + &self.creator + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + /// Whether this holiday reaches into `[from, to]`. Touching counts: a + /// holiday ending exactly when the range begins (or beginning exactly + /// when it ends) still blocks the day it touches. + pub fn overlaps(&self, from: Timestamp, to: Timestamp) -> bool { + self.ends_at >= from && self.starts_at <= to + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::user::UserId; + + fn a_holiday(starts_at: i64, ends_at: i64) -> Holiday { + Holiday { + id: HolidayId::generate(), + name: HolidayName::try_new("29 Ekim").unwrap(), + starts_at: Timestamp::from_millis(starts_at), + ends_at: Timestamp::from_millis(ends_at), + kind: HolidayKind::try_new("resmi").unwrap(), + creator: UserId::generate(), + created_at: Timestamp::now(), + } + } + + #[test] + fn name_is_required_and_bounded() { + assert!(HolidayName::try_new("29 Ekim").is_ok()); + // Blank (whitespace-only) names are refused like an empty one. + assert!(HolidayName::try_new(" ").is_err()); + assert!(HolidayName::try_new("").is_err()); + assert!(HolidayName::try_new(&"x".repeat(MAX_HOLIDAY_NAME_LEN + 1)).is_err()); + assert!(HolidayName::try_new(&"x".repeat(MAX_HOLIDAY_NAME_LEN)).is_ok()); + } + + #[test] + fn kind_is_a_closed_list() { + for kind in HolidayKind::ALL { + assert!(HolidayKind::try_new(kind).is_ok()); + } + assert!(matches!( + HolidayKind::try_new("x"), + Err(ValidationError::Unknown { field: "kind", .. }) + )); + } + + #[test] + fn overlaps_at_both_touching_edges() { + // The holiday spans [100, 200]. + let holiday = a_holiday(100, 200); + // Touching on either edge is still a block. + assert!(holiday.overlaps(Timestamp::from_millis(200), Timestamp::from_millis(300))); + assert!(holiday.overlaps(Timestamp::from_millis(0), Timestamp::from_millis(100))); + // One millisecond past either edge is not. + assert!(!holiday.overlaps(Timestamp::from_millis(201), Timestamp::from_millis(300))); + assert!(!holiday.overlaps(Timestamp::from_millis(0), Timestamp::from_millis(99))); + // And a range inside the holiday is, of course. + assert!(holiday.overlaps(Timestamp::from_millis(150), Timestamp::from_millis(160))); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 098befe..0f88eb2 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -15,6 +15,7 @@ pub mod bank_question_image; pub mod board; pub mod board_stroke; pub mod builder; +pub mod calendar; pub mod chatbot_message; pub mod chatbot_thread; pub mod class_blueprint; @@ -39,6 +40,7 @@ pub mod exam_weight; pub mod fee_plan; pub mod fee_plan_assignment; pub mod grade; +pub mod holiday; pub mod homework; pub mod homework_file; pub mod homework_result; diff --git a/src/domain/weekly_slot.rs b/src/domain/weekly_slot.rs index f528ef1..e42f2e8 100644 --- a/src/domain/weekly_slot.rs +++ b/src/domain/weekly_slot.rs @@ -16,14 +16,16 @@ //! list comes back in is `weekday` first, then `starts_at` — Monday through //! Sunday, each day dawn to dusk. //! -//! **No scheduler.** Nothing generates dated `course_session` rows from a -//! weekly plan — `course_session` stays the per-lesson occurrence, written by -//! its own routes. This module is template + override + resolution only. +//! **Not a store for lessons.** This module is template + override + +//! resolution only: the dated `course_session` rows are minted on demand by +//! [`crate::service::course_session::materialize`], which reads this +//! resolution and the school's holiday calendar. //! //! The slot bounds live in [`crate::constant`] beside every other published //! bound, so `GET /limits` and the completeness guard see them. use crate::constant::{MAX_SLOT_MINUTE, MAX_WEEKLY_SLOTS, MIN_SLOT_MINUTE}; +use crate::domain::course_session::SessionTopic; use crate::domain::monotonic_id::next_uuid; use crate::error::ValidationError; @@ -107,7 +109,8 @@ impl SlotMinute { } } -/// One weekly plan line: on `weekday`, from `starts_at` to `ends_at`. +/// One weekly plan line: on `weekday`, from `starts_at` to `ends_at`, with an +/// optional lesson topic the materializer copies onto the generated sessions. /// /// The list a resolver returns is ordered `weekday` first, then `starts_at`. #[derive(Debug, Clone, PartialEq, Eq, sqlx::FromRow)] @@ -116,18 +119,21 @@ pub struct WeeklySlot { pub(crate) weekday: Weekday, pub(crate) starts_at: SlotMinute, pub(crate) ends_at: SlotMinute, + pub(crate) topic: Option, } impl WeeklySlot { /// The slot `id` names, or a validation error when the window is not one /// (`ends_at` must land strictly after `starts_at` — equal times are an /// empty window, inverted ones a typo). The store's - /// `CHECK (ends_at > starts_at)` is the same rule at rest. + /// `CHECK (ends_at > starts_at)` is the same rule at rest. `topic` rides + /// along unjudged for overlap: it is content, not a timetable line. pub fn new( id: WeeklySlotId, weekday: Weekday, starts_at: SlotMinute, ends_at: SlotMinute, + topic: Option, ) -> Result { if starts_at.get() >= ends_at.get() { return Err(ValidationError::Invalid { @@ -140,6 +146,7 @@ impl WeeklySlot { weekday, starts_at, ends_at, + topic, }) } @@ -159,6 +166,13 @@ impl WeeklySlot { self.ends_at } + /// The lesson topic the slot carries, `None` = the generated session + /// falls back to the instance's resolved title (then the literal + /// `"Ders"`). + pub fn get_topic(&self) -> Option<&SessionTopic> { + self.topic.as_ref() + } + /// Whether this and `other` cannot both stand in one owner's plan: the /// same weekday with intersecting windows. Touching endpoints are fine — /// a lesson may start the minute another ends. @@ -210,10 +224,46 @@ mod tests { day(weekday), mins(starts), mins(ends), + None, ) .unwrap() } + #[test] + fn topic_is_optional_and_survives_construction() { + // A slot without a topic reads back `None`. + let bare = slot(1, 540, 600); + assert!(bare.get_topic().is_none()); + // A topic rides along verbatim. + let topic = SessionTopic::try_new("Photosynthesis").unwrap(); + let themed = WeeklySlot::new( + WeeklySlotId::generate(), + day(2), + mins(540), + mins(600), + Some(topic.clone()), + ) + .unwrap(); + assert_eq!(themed.get_topic(), Some(&topic)); + } + + #[test] + fn overlap_is_independent_of_the_topic() { + let bare = slot(1, 540, 600); + let themed = WeeklySlot::new( + WeeklySlotId::generate(), + day(1), + mins(540), + mins(600), + Some(SessionTopic::try_new("Cells").unwrap()), + ) + .unwrap(); + // The same window with a different (or absent) topic still collides — + // the topic is content, not a timetable line. + assert!(bare.overlaps(&themed)); + assert!(themed.overlaps(&bare)); + } + #[test] fn weekdays_are_the_iso_scale() { assert!(Weekday::new(1).is_ok()); @@ -233,10 +283,16 @@ mod tests { #[test] fn a_slot_window_must_be_non_empty_and_forward() { // Zero-length and inverted windows are refused. - assert!(WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(600)).is_err()); - assert!(WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(540)).is_err()); + assert!( + WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(600), None).is_err() + ); + assert!( + WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(540), None).is_err() + ); // A one-minute window stands. - assert!(WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(601)).is_ok()); + assert!( + WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(601), None).is_ok() + ); } #[test] diff --git a/src/service/course_session.rs b/src/service/course_session.rs index 745c098..6e0d51a 100644 --- a/src/service/course_session.rs +++ b/src/service/course_session.rs @@ -3,11 +3,20 @@ //! write. The queries live in [`crate::db::course_session`]; the //! timetable's wire shaping and the course-rights checks stay in the web //! layer. +//! +//! The one workflow with a plan behind it is [`materialize`]: it expands an +//! instance's *resolved* weekly plan ([`crate::service::weekly_slot`]) into +//! dated lessons over a range, bounded by the school-wide holiday calendar +//! ([`crate::service::holiday::blocked_days`]). It is an explicit route's +//! work, not a scheduler: nothing generates lessons on its own. -use crate::database::Database; -use crate::db::course_session; -use crate::domain::class_course::ClassCourseId; +use crate::constant::{MAX_MATERIALIZE_DAYS, MAX_MATERIALIZE_SESSIONS, MILLIS_PER_DAY}; +use crate::database::{Database, tx_with_retry}; +use crate::db::course_session::{self, NewSession}; +use crate::domain::calendar; +use crate::domain::class_course::{ClassCourse, ClassCourseId}; use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; +use crate::domain::holiday::HolidayName; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; @@ -93,3 +102,191 @@ pub async fn update( pub async fn delete(db: &Database, session: CourseSession) -> Result { course_session::delete(db, session).await } + +/// One non-teaching day the generator refused to schedule on: the calendar +/// day in the school's zone, and the holiday that reaches into it. +#[derive(Debug, Clone)] +pub struct BlockedDay { + pub day: chrono::NaiveDate, + pub holiday: HolidayName, +} + +/// What one [`materialize`] call did — or, on a dry run, would have done. +/// +/// `created` carries the rows the database actually inserted (empty on a dry +/// run), so a lesson a concurrent writer already put at the same instant is +/// reported as skipped, never counted. `candidates` is the size the range +/// asked for, `slots` the resolved plan's size, and `blocked` one entry per +/// holiday-blocked *day*. +#[derive(Debug, Clone)] +pub struct MaterializeOutcome { + pub applied: bool, + pub slots: usize, + pub candidates: usize, + pub created: Vec, + pub skipped_existing: usize, + pub skipped_holiday: usize, + pub blocked: Vec, + pub range_days: i64, +} + +/// Expand `instance`'s resolved weekly plan into dated lessons over +/// `[from, to]` (inclusive instants), one lesson per plan slot per matching +/// weekday, skipping the days a holiday reaches into and the instants the +/// section already holds a lesson at. +/// +/// `apply == false` is a dry run: it reads, decides, and writes nothing. +/// `apply == true` writes the collected rows in this transaction and returns +/// exactly the rows that landed — the whole feature is additive, nothing is +/// ever deleted or updated, and a second run over the same range is a no-op +/// (`UNIQUE (class_course, starts_at)`). Weekends are not special-cased: a +/// school may run Saturday, so only the plan and the holidays decide. +/// +/// `offset_minutes` is the school's zone offset +/// ([`crate::domain::calendar::zone_offset_minutes`]); the range's instants +/// name *school* days, and each lesson lands at its slot's minute of that +/// local day. +/// +/// Refusals: an archived year, an empty plan (409 +/// `instance_has_no_weekly_plan`), no assigned teacher (409 +/// `instance_has_no_teacher`, the lesson's teacher is the instance's first +/// assigned one), a range longer than a year or one that would mint more than +/// [`MAX_MATERIALIZE_SESSIONS`] lessons (400), and a gone instance +/// ([`AppError::NotFound`]). +pub async fn materialize( + db: &Database, + instance: &ClassCourse, + from: Timestamp, + to: Timestamp, + apply: bool, + offset_minutes: i32, +) -> Result { + let instance_id = instance.get_id().clone(); + let days = calendar::days_between( + calendar::zoned_day(from.as_millis(), offset_minutes), + calendar::zoned_day(to.as_millis(), offset_minutes), + ); + let range_days = days.len() as i64; + if range_days > MAX_MATERIALIZE_DAYS { + return Err(AppError::Validation(ValidationError::Invalid { + field: "to", + reason: "the range must not span more than a year", + })); + } + + // Every decision below is made while holding the instance's row lock, and + // the generated rows are written on that same connection: a rival + // materialize run waits here instead of racing the existence read, and a + // refusal rolls back whatever it had collected. + tx_with_retry(db, false, async move |tx| { + // The archived-year wall every instance write passes: a past year is + // read-only, and this run mints lesson rows. + crate::service::class_course::require_open(db, &instance_id).await?; + // The serialization point. `FOR NO KEY UPDATE` rather than + // `FOR UPDATE`: the batch insert below takes this same row's + // foreign-key `FOR KEY SHARE`, which `FOR UPDATE` would block on. + crate::db::weekly_slot::lock_class_tx(tx, &instance_id).await?; + + let slots = crate::service::weekly_slot::resolved_for_instance(db, instance).await?; + if slots.is_empty() { + return Err(AppError::ConflictCoded { + code: "instance_has_no_weekly_plan", + message: "this section's weekly plan is empty — add a slot first".into(), + }); + } + let teachers = + crate::db::class_course_teacher::list_for_instance(db, &instance_id).await?; + let Some(teacher) = teachers.first().copied() else { + return Err(AppError::ConflictCoded { + code: "instance_has_no_teacher", + message: "assign a teacher to this section before generating lessons".into(), + }); + }; + + // The topic chain: the slot's own first, the instance's *resolved* + // title second (the one display chain every surface rides), the + // literal `"Ders"` last. The resolved title is bounded by + // `MAX_COURSE_TITLE_LEN`, so it always fits a `SessionTopic`. + let resolved = crate::service::instance_resolve::resolved_content(db, &[instance]).await?; + let fallback_topic = resolved + .get(&instance_id.key()) + .map(|content| content.title.as_str()) + .filter(|title| !title.is_empty()) + .and_then(|title| SessionTopic::try_new(title).ok()) + .unwrap_or(SessionTopic::try_new("Ders")?); + + let holidays = crate::service::holiday::blocked_days(db, from, to).await?; + let existing = course_session::existing_starts(db, &instance_id).await?; + + let mut rows: Vec = Vec::new(); + let mut blocked: Vec = Vec::new(); + let mut skipped_existing = 0usize; + for day in &days { + let day_start = calendar::day_start_millis(*day, offset_minutes); + // Day granularity, not slot granularity: a day a holiday reaches + // into is named once and contributes nothing, whether or not the + // plan runs a lesson that weekday. + let day_end = day_start + MILLIS_PER_DAY - 1; + if let Some(holiday) = holidays.iter().find(|holiday| { + holiday.overlaps( + Timestamp::from_millis(day_start), + Timestamp::from_millis(day_end), + ) + }) { + blocked.push(BlockedDay { + day: *day, + holiday: holiday.get_name().clone(), + }); + continue; + } + let weekday = calendar::iso_weekday(*day); + for slot in slots + .iter() + .filter(|slot| slot.get_weekday().get() == weekday) + { + let starts_at = day_start + slot.get_starts_at().get() * 60_000; + if existing.contains(&starts_at) { + skipped_existing += 1; + continue; + } + rows.push(NewSession { + id: CourseSessionId::generate(), + class_course: instance_id.clone(), + teacher, + topic: slot + .get_topic() + .cloned() + .unwrap_or_else(|| fallback_topic.clone()), + starts_at: Timestamp::from_millis(starts_at), + ends_at: Timestamp::from_millis( + day_start + slot.get_ends_at().get() * 60_000, + ), + }); + } + } + + let candidates = rows.len(); + if candidates > MAX_MATERIALIZE_SESSIONS { + return Err(AppError::Validation(ValidationError::Invalid { + field: "to", + reason: "this range would create more than 500 lessons — narrow it".into(), + })); + } + let created = if apply { + course_session::insert_many_tx(tx, &rows).await? + } else { + Vec::new() + }; + Ok(MaterializeOutcome { + applied: apply, + slots: slots.len(), + candidates, + created, + skipped_existing, + skipped_holiday: blocked.len(), + blocked, + range_days, + }) + }) + .await +} diff --git a/src/service/holiday.rs b/src/service/holiday.rs new file mode 100644 index 0000000..99aeee0 --- /dev/null +++ b/src/service/holiday.rs @@ -0,0 +1,68 @@ +//! Holiday workflows: the school-wide non-teaching calendar is plain CRUD — +//! the rows carry no refcounts, no archive stamp, no cross-table rule — so +//! every door here is a thin pass-through over [`crate::db::holiday`]. The one +//! workflow-shaped read is [`blocked_days`], the weekly-plan materializer's +//! "which of these instants may not hold a lesson" read. + +use crate::database::Database; +use crate::db::holiday::{self, HolidayPatch}; +use crate::domain::holiday::{Holiday, HolidayId, HolidayKind, HolidayName}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Declare a school-wide holiday. Manager-gated at the route; the range +/// ordering is re-checked by the web layer's pre-flight and again at any +/// PATCH by the `WHERE` in [`update`]. +pub async fn create( + db: &Database, + name: &HolidayName, + starts_at: Timestamp, + ends_at: Timestamp, + kind: &HolidayKind, + creator: &UserId, +) -> Result { + holiday::create(db, name, starts_at, ends_at, kind, creator).await +} + +/// The holiday `id` names, or `Err(NotFound)`. +pub async fn read(db: &Database, id: &HolidayId) -> Result { + holiday::read(db, id).await +} + +/// Patch only what the request carried; the merged range is re-checked in the +/// `UPDATE`'s own `WHERE`. +pub async fn update( + db: &Database, + id: &HolidayId, + patch: HolidayPatch, +) -> Result { + holiday::update(db, id, patch).await +} + +/// Delete the holiday. Nothing references it — the materializer only reads — +/// so the delete is unconditional. +pub async fn delete(db: &Database, id: &HolidayId) -> Result { + holiday::delete(db, id).await +} + +/// The paged calendar view, `from`/`to` with overlap semantics. +pub async fn list( + db: &Database, + from: Option, + to: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + holiday::list(db, from, to, limit, offset).await +} + +/// Every holiday reaching into `[from, to]` — the materializer's read. A +/// read-only door: it never writes. +pub async fn blocked_days( + db: &Database, + from: Timestamp, + to: Timestamp, +) -> Result, AppError> { + holiday::list_between(db, from, to).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 5c7be73..44489c3 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -37,6 +37,7 @@ pub mod homework; pub mod homework_file; pub mod homework_result; pub mod homework_submission; +pub mod holiday; pub mod instance; pub mod instance_resolve; pub mod karne; diff --git a/src/service/weekly_slot.rs b/src/service/weekly_slot.rs index fba4529..c69571c 100644 --- a/src/service/weekly_slot.rs +++ b/src/service/weekly_slot.rs @@ -5,15 +5,16 @@ //! `weekly_plan_inherited` in the same statement — see //! [`crate::db::weekly_slot`]). //! -//! **No scheduler.** Nothing here generates dated `course_session` rows from -//! a weekly plan — `course_session` stays the per-lesson occurrence, written -//! by its own routes. This module is template + override + resolution only; a -//! scheduler needs its own spec. +//! **Not a scheduler.** Nothing runs on its own: this module is template + +//! override + resolution only, and the explicit materialize door +//! ([`crate::service::course_session::materialize`]) is the one caller that +//! turns a resolution into dated lessons. use crate::database::{Database, tx_with_retry}; use crate::db::weekly_slot as slot_db; use crate::domain::class_course::{ClassCourse, ClassCourseId}; use crate::domain::course_offering::CourseOfferingId; +use crate::domain::course_session::SessionTopic; use crate::domain::weekly_slot::{ SlotAddError, SlotMinute, Weekday, WeeklySlot, WeeklySlotId, check_add, }; @@ -58,15 +59,18 @@ async fn resolved_own( /// refused with 409 `slot_overlap` when a template slot already occupies an /// intersecting window on that weekday (the exact duplicate overlaps too), /// 409 `slot_cap` when the week already holds [`MAX_WEEKLY_SLOTS`] slots, -/// and 400 for a malformed weekday, minute, or empty window. +/// and 400 for a malformed weekday, minute, or empty window. `topic` is the +/// optional lesson topic the materializer copies onto generated sessions — +/// content, never an overlap input. pub async fn add_for_offering( db: &Database, offering: &CourseOfferingId, weekday: Weekday, starts_at: SlotMinute, ends_at: SlotMinute, + topic: Option, ) -> Result { - let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at)?; + let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at, topic)?; let owner = offering.clone(); tx_with_retry(db, false, async move |tx| { // The row lock serializes the pre-check and the insert: under READ @@ -89,8 +93,9 @@ pub async fn add_for_class( weekday: Weekday, starts_at: SlotMinute, ends_at: SlotMinute, + topic: Option, ) -> Result { - let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at)?; + let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at, topic)?; let owner = instance.clone(); tx_with_retry(db, false, async move |tx| { slot_db::lock_class_tx(tx, &owner).await?; @@ -198,13 +203,13 @@ mod tests { let instance = an_instance(&db, "5-A").await; let offering = instance.get_offering().clone(); - add_for_offering(&db, &offering, day(2), mins(600), mins(660)) + add_for_offering(&db, &offering, day(2), mins(600), mins(660), None) .await .unwrap(); - add_for_offering(&db, &offering, day(1), mins(600), mins(660)) + add_for_offering(&db, &offering, day(1), mins(600), mins(660), None) .await .unwrap(); - add_for_offering(&db, &offering, day(1), mins(480), mins(540)) + add_for_offering(&db, &offering, day(1), mins(480), mins(540), None) .await .unwrap(); @@ -229,11 +234,11 @@ mod tests { let (db, _leases) = crate::database::init_test_db().await; let instance = an_instance(&db, "5-B").await; let offering = instance.get_offering().clone(); - add_for_offering(&db, &offering, day(1), mins(480), mins(540)) + add_for_offering(&db, &offering, day(1), mins(480), mins(540), None) .await .unwrap(); - add_for_class(&db, instance.get_id(), day(3), mins(540), mins(600)) + add_for_class(&db, instance.get_id(), day(3), mins(540), mins(600), None) .await .unwrap(); // The write flipped the flag: re-read so the resolver follows the @@ -269,7 +274,7 @@ mod tests { async fn an_overlapping_slot_is_refused() { let (db, _leases) = crate::database::init_test_db().await; let instance = an_instance(&db, "5-C").await; - add_for_class(&db, instance.get_id(), day(1), mins(540), mins(600)) + add_for_class(&db, instance.get_id(), day(1), mins(540), mins(600), None) .await .unwrap(); @@ -280,7 +285,7 @@ mod tests { (530, 630, "the wider window"), ] { let attempt = - add_for_class(&db, instance.get_id(), day(1), mins(starts), mins(ends)).await; + add_for_class(&db, instance.get_id(), day(1), mins(starts), mins(ends), None).await; assert_eq!( coded(&attempt), "slot_overlap", @@ -289,10 +294,10 @@ mod tests { } // Touching endpoints and a different weekday are not overlaps. - add_for_class(&db, instance.get_id(), day(1), mins(600), mins(660)) + add_for_class(&db, instance.get_id(), day(1), mins(600), mins(660), None) .await .unwrap(); - add_for_class(&db, instance.get_id(), day(2), mins(540), mins(600)) + add_for_class(&db, instance.get_id(), day(2), mins(540), mins(600), None) .await .unwrap(); assert_eq!( @@ -307,12 +312,12 @@ mod tests { assert!(Weekday::new(0).is_err()); assert!(SlotMinute::new(-1).is_err()); let empty_window = - add_for_class(&db, instance.get_id(), day(1), mins(600), mins(600)).await; + add_for_class(&db, instance.get_id(), day(1), mins(600), mins(600), None).await; assert!( matches!(empty_window, Err(AppError::Validation(_))), "{empty_window:?}" ); - let inverted = add_for_class(&db, instance.get_id(), day(1), mins(1439), mins(600)).await; + let inverted = add_for_class(&db, instance.get_id(), day(1), mins(1439), mins(600), None).await; assert!( matches!(inverted, Err(AppError::Validation(_))), "{inverted:?}" @@ -330,13 +335,7 @@ mod tests { // 480+(i/7) — five or six per weekday, all touching, none crossing. for i in 0..crate::constant::MAX_WEEKLY_SLOTS { let i = i as i64; - add_for_class( - &db, - instance.get_id(), - day(((i % 7) + 1) as i16), - mins(480 + i / 7), - mins(481 + i / 7), - ) + add_for_class(&db, instance.get_id(), day(((i % 7) + 1) as i16), mins(480 + i / 7), mins(481 + i / 7), None) .await .unwrap(); } @@ -349,7 +348,7 @@ mod tests { ); // Room on Sunday's timeline, but the plan is full. - let one_more = add_for_class(&db, instance.get_id(), day(7), mins(700), mins(760)).await; + let one_more = add_for_class(&db, instance.get_id(), day(7), mins(700), mins(760), None).await; assert_eq!(coded(&one_more), "slot_cap"); assert_eq!( slot_db::list_for_class(&db, instance.get_id()) @@ -367,10 +366,10 @@ mod tests { let (db, _leases) = crate::database::init_test_db().await; let instance = an_instance(&db, "5-E").await; let offering = instance.get_offering().clone(); - add_for_offering(&db, &offering, day(1), mins(480), mins(540)) + add_for_offering(&db, &offering, day(1), mins(480), mins(540), None) .await .unwrap(); - add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540)) + add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540), None) .await .unwrap(); assert!( @@ -403,10 +402,10 @@ mod tests { let instance = an_instance(&db, "5-F").await; let other = an_instance(&db, "5-G").await; - add_for_class(&db, instance.get_id(), day(1), mins(480), mins(540)) + add_for_class(&db, instance.get_id(), day(1), mins(480), mins(540), None) .await .unwrap(); - add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540)) + add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540), None) .await .unwrap(); let own = slot_db::list_for_class(&db, instance.get_id()) @@ -450,10 +449,10 @@ mod tests { let instance = an_instance(&db, "5-H").await; let offering = instance.get_offering().clone(); - add_for_offering(&db, &offering, day(1), mins(540), mins(600)) + add_for_offering(&db, &offering, day(1), mins(540), mins(600), None) .await .unwrap(); - let clash = add_for_offering(&db, &offering, day(1), mins(570), mins(630)).await; + let clash = add_for_offering(&db, &offering, day(1), mins(570), mins(630), None).await; assert_eq!(coded(&clash), "slot_overlap"); let slots = slot_db::list_for_offering(&db, &offering).await.unwrap(); diff --git a/src/web/attendance.rs b/src/web/attendance.rs index eba74b6..0a7cac7 100644 --- a/src/web/attendance.rs +++ b/src/web/attendance.rs @@ -21,6 +21,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::attendance::AttendanceStatus; +use crate::domain::calendar::{zone_offset_minutes, zoned_day}; use crate::domain::class_course::{ClassCourse, ClassCourseId}; use crate::domain::course::{Course, CourseId}; use crate::domain::role::Role; @@ -150,30 +151,6 @@ struct AttendanceReport { devamsizlik: Vec, } -/// The school's day boundary as a fixed offset in minutes. -/// -/// The allow-list in [`crate::constant::TIMEZONES`] names zones whose offset -/// is constant (Turkey has run on UTC+3 with no DST since 2016), so the -/// backend buckets days without carrying a timezone database — the same -/// arithmetic the settings module's own list is built on. An unrecognised name -/// falls back to [`crate::constant::DEFAULT_TIMEZONE`]'s offset, which is what -/// an unset setting -/// gets anyway. -fn zone_offset_minutes(timezone: &str) -> i32 { - match timezone { - "UTC" => 0, - _ => 3 * 60, - } -} - -/// The calendar day an instant falls on, in the school's zone. -fn zoned_day(millis: i64, offset_minutes: i32) -> chrono::NaiveDate { - let shifted = millis + i64::from(offset_minutes) * 60_000; - chrono::DateTime::from_timestamp_millis(shifted) - .expect("timestamps are within chrono's representable range") - .date_naive() -} - /// The term an instant falls in: the containing term with the latest start, /// or `None` when the calendar does not cover it. fn term_of(instant: i64, terms: &[Term]) -> Option<&Term> { @@ -436,23 +413,5 @@ async fn user_report( Ok(Json(build_report(&target, viewer, &st.db).await?)) } -#[cfg(test)] -mod tests { - use super::*; - - /// The day bucket is the school's day, not UTC's: 22:30 UTC in summer - /// Istanbul is already tomorrow. This is the whole reason the timezone is - /// read off the settings. - #[test] - fn the_day_bucket_follows_the_school_zone() { - let at = crate::domain::timestamp::Timestamp::from_millis(1_767_216_600_000); // 2025-12-31T21:30Z - assert_eq!( - zoned_day(at.as_millis(), zone_offset_minutes("UTC")).to_string(), - "2025-12-31" - ); - assert_eq!( - zoned_day(at.as_millis(), zone_offset_minutes("Europe/Istanbul")).to_string(), - "2026-01-01" - ); - } -} +// The day-bucketing unit test moved with its arithmetic to +// `src/domain/calendar.rs` (`the_day_bucket_follows_the_school_zone`). diff --git a/src/web/weekly_plan.rs b/src/web/weekly_plan.rs index 493f363..436b2b5 100644 --- a/src/web/weekly_plan.rs +++ b/src/web/weekly_plan.rs @@ -190,6 +190,7 @@ async fn add_offering_slot( weekday, starts_at, ends_at, + None, ) .await?; Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot)))) @@ -295,8 +296,15 @@ async fn add_instance_slot( service::class_course::require_open(&st.db, instance.get_id()).await?; let (weekday, starts_at, ends_at) = parse_slot(&req)?; let slot = - service::weekly_slot::add_for_class(&st.db, instance.get_id(), weekday, starts_at, ends_at) - .await?; + service::weekly_slot::add_for_class( + &st.db, + instance.get_id(), + weekday, + starts_at, + ends_at, + None, + ) + .await?; Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot)))) } diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 1026b8a..4cac23c 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -1193,6 +1193,15 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { // instance cannot be made to dominate the year average by a typo. ("UpdateInstance", "ders_saati", "minimum", MIN_DERS_SAATI), ("UpdateInstance", "ders_saati", "maximum", MAX_DERS_SAATI), + // The holiday calendar's one free-text field, and the optional topic + // a weekly-plan slot may stamp onto every lesson it generates. + ( + "CreateHoliday", + "name", + "maxLength", + MAX_HOLIDAY_NAME_LEN as i64, + ), + ("CreateSlot", "topic", "maxLength", MAX_SESSION_TOPIC_LEN as i64), // The offering spine (course × grade_level templates) and the // per-class instance overrides: same bounds as the catalog course // they inherit from.