From 450bc8c32802abea05546130b0aee876bc779e98 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 03:06:52 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(courses):=20grade-ladder=20cou?= =?UTF-8?q?rse=20templates=20with=20per-class=20overrides?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit course_offering per (course x grade_level 0..=12), per-class overrides on class_course (nullable scalars + *_inherited flags), subjects/weights/ weekly-plan axis tables, instance_resolve with batched twin, resolved title/description on instance-scoped reads, six new route groups, integration scenario test, README regenerated. Evolution migrations squashed into the base schema (20260912000002_courses + 20260916000001_k12_remodel). Local-Gate: 246daa3fb3ee7b0ff507a95d6ab346bab1333a37 (1556 passed, 455s) --- ...d4cec5a553470ca82ed9abe7d8c96426f89e8.json | 195 +++++++ ...8bdd2080d1028cac51b4d02c2da17c8801164.json | 35 ++ ...8cd309907f23262685f8b3b267399f06ff730.json | 16 - ...f9fe07682ffe64656eb896e5dbdea552e8b68.json | 140 +++++ ...6f399e9e872828bbc54476e5e4530e4ff3c1.json} | 6 +- ...548c092d1b2f3e0a04f88c804af7418806ccb.json | 131 +++++ ...a8ef1e9b997124fbd33f132b1f13de461bc82.json | 28 + ...fef8aaaa1dccc39fa5013ef8c63cd921eab13.json | 15 + ...64ff391ff866bf6d31b7be0d46b79a3ac8105.json | 30 ++ ...9b0e620016bea2e6948b77bfa5de11cec9a31.json | 31 ++ ...d74d83bc6c46ca3f091a8414971b90b962f4d.json | 29 + ...4dd78b17477cef8b90dd3bc4a86f802e6ceeb.json | 28 + ...1a44966ab7ed9ef418dd84fe2015c37660ff0.json | 18 + ...2c856cf4cf7ca6e66506edce327c303c16fc.json} | 14 +- ...24808b8cd035c6b6701f307b822c6e0f849a.json} | 12 +- ...8ea1bfd4efce1a726282cfb739be6451a0714.json | 14 + ...46675840688b5154d1068cf160c27939ea9fb.json | 36 ++ ...288588f6d126cb4b3258c7470ee3b7bbc041a.json | 16 + ...b5d5e4c1009828660062c0c8a90c31f871bd2.json | 24 + ...413eae6d9a3ab48889a56ece629279f2c156e.json | 28 + ...0d06dce0779211543a72b1f6f769d9f00ed8.json} | 12 +- ...a67ee265f58c23aeab000e821aa10277500d4.json | 198 +++++++ ...559353e088b89cc026bc1baf7edc7f085419b.json | 121 ----- ...2d449430f363319ce19ab195f2429eb9a5c55.json | 139 +++++ ...3aa1520d57597b73bd54ff9a22fb3efb596d3.json | 132 +++++ ...dce4afa5cd33c7bae3aa67c62488d31eb8c1f.json | 119 ----- ...e8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.json | 119 ----- ...76ac6ba2b766dcd148e2a69cbe89ea9af3e8d.json | 64 +++ ...aa93dbea4b41fb0aca74bdc7eea4c67516b61.json | 30 ++ ...ac084feae1400c53631f766fbcb8ef5bd280a.json | 29 + ...10dcb368c1a315ee6809f8f34e837b7eae57f.json | 191 +++++++ ...3953c2f44a93f7c597debe56eb6b21ce7fcf.json} | 6 +- ...55cf0a3cf01b761da187bd50deec4523d60f.json} | 6 +- ...dfe02ba5c16d2b9a46646d5649fc1f9fd4fd.json} | 12 +- ...d8745b37d88ff00f48812498dc87c9b5fb51d.json | 58 ++ ...36252078a07cc4b7807788e08b171c8cdf9a.json} | 14 +- ...e4031a4b0a06e9b4e2710b9943252462d7dc.json} | 12 +- ...5b6c98f1aa548e5adf13260939390db5aab0f.json | 15 + ...340ede5fb34c70b0b0d837a378fe6b92afc94.json | 28 + ...efee61e93775bc39519714dc122790a448285.json | 15 + ...020cd6fd3ea903470e9b153d02352b12118cc.json | 191 +++++++ ...ee2772a3590e71d0e0a23fcecb8dba228e81.json} | 6 +- ...4169bab3769effe0dccbed8587f89d788a1f2.json | 88 +++ ...dcc078b9ce93ba209d3b2ca1d16382b62f45.json} | 5 +- ...3c5b62ea7b6ac7f3046b6fd1c784cb5979618.json | 36 ++ ...961930cf26070e0e85da66011c4adb85de2f3.json | 119 ----- ...537a93f34014875f1df15279d500f0c2927e7.json | 15 + ...3146a6c02d1d932da63f364a78a56dee79eed.json | 28 + ...0fbb18af95e8b1bb437b87bd31e38fb804bdc.json | 64 +++ ...015ab473efa48671c58ff10f33ed8b89dc803.json | 28 + ...2cb568bbcfcb88386270920f3eb6579a526e.json} | 12 +- ...e4955db70f6a5073d3b14098fe591d23366f9.json | 54 ++ ...bd4484136dd6aa75069f987075137e1b99b00.json | 16 + ...e81ff85548c6aeb096ee914d5349bf525137a.json | 131 +++++ ...62f553ea0b23b4fd1569241119aac0f8d62cc.json | 36 ++ ...d4be6648243c4627e8719fff5cc4d38efb738.json | 58 ++ ...26f4da6f49846a4e7ee948a173ef54aafed1a.json | 191 +++++++ ...11bc25d774d21850be124025fda552104867b.json | 35 ++ ...b2ff94efb5d2bef4ec746afdd68d65746d351.json | 54 ++ ...ff1cf34e8727b6c3ac7222620b87b0dc1eeb1.json | 23 + ...53af6c4abd32821251f7804ef02c4e637cf8.json} | 6 +- ...f5fe6328a014793d2fefc12cd0cc4c4d6421e.json | 88 --- ...983881eafa5fafeb80813293bd778717080f.json} | 12 +- ...61f7c1d3953b66c413aa1b0f0349fa350f8ab.json | 35 ++ ...054de776315e010bfd709f5408df7259ed02b.json | 31 ++ README.md | 70 ++- src/constant.rs | 30 +- src/db/class_blueprint.rs | 58 +- src/db/class_course.rs | 185 +++++-- src/db/class_group.rs | 81 ++- src/db/class_member.rs | 7 +- src/db/class_pump.rs | 123 ++++- src/db/course.rs | 4 +- src/db/course_offering.rs | 429 +++++++++++++++ src/db/course_session.rs | 2 +- src/db/event.rs | 2 +- src/db/exam.rs | 2 +- src/db/exam_result.rs | 13 +- src/db/exam_weight.rs | 239 +++++++++ src/db/mod.rs | 4 + src/db/offering_subject.rs | 244 +++++++++ src/db/weekly_slot.rs | 275 ++++++++++ src/domain/academic_year.rs | 69 +-- src/domain/class_blueprint.rs | 112 ++-- src/domain/class_course.rs | 122 ++++- src/domain/class_group.rs | 43 +- src/domain/course_offering.rs | 120 +++++ src/domain/exam_question.rs | 6 +- src/domain/exam_weight.rs | 81 +++ src/domain/grade.rs | 89 ++++ src/domain/homework.rs | 8 + src/domain/mod.rs | 5 + src/domain/offering_subject.rs | 82 +++ src/domain/weekly_slot.rs | 297 +++++++++++ src/lib.rs | 55 +- src/service/academic_year.rs | 27 +- src/service/class_blueprint.rs | 31 +- src/service/class_course.rs | 173 +++++- src/service/class_group.rs | 19 +- src/service/course_offering.rs | 95 ++++ src/service/exam.rs | 2 +- src/service/exam_weight.rs | 404 ++++++++++++++ src/service/homework.rs | 9 + src/service/instance_resolve.rs | 185 +++++++ src/service/karne.rs | 129 +++-- src/service/mod.rs | 5 + src/service/offering_subject.rs | 470 ++++++++++++++++ src/service/rag_scope.rs | 38 +- src/service/subject.rs | 36 +- src/service/weekly_slot.rs | 479 +++++++++++++++++ src/web/academic_years.rs | 27 +- src/web/attendance.rs | 16 +- src/web/classes.rs | 269 +++++----- src/web/courses.rs | 5 + src/web/exam_weights.rs | 368 +++++++++++++ src/web/exams/questions.rs | 38 +- src/web/homework.rs | 10 +- src/web/instances.rs | 219 ++++++-- src/web/limits.rs | 29 +- src/web/marks.rs | 52 +- src/web/mod.rs | 6 +- src/web/offering_subjects.rs | 317 +++++++++++ src/web/offerings.rs | 376 +++++++++++++ src/web/users.rs | 11 +- src/web/weekly_plan.rs | 371 +++++++++++++ tests/ai_bridge.rs | 6 +- tests/board_invite.rs | 2 +- tests/common/mod.rs | 135 ++++- tests/e2e.rs | 52 +- tests/integration.rs | 501 +++++++++++++++++- tests/pagination.rs | 2 +- tests/partial_patch_terms.rs | 2 +- tests/persistence.rs | 7 +- tests/regress_blueprints.rs | 185 ++++--- tests/regress_classes.rs | 116 ++-- tests/regress_course_child_orphans.rs | 3 +- tests/regress_event_class_audience.rs | 2 +- tests/regress_profile.rs | 8 +- tests/regress_review.rs | 11 +- tests/regress_role_sweep.rs | 3 +- tests/spec_bounds.rs | 102 +++- 141 files changed, 10247 insertions(+), 1491 deletions(-) create mode 100644 .sqlx/query-0d43379f5a5659b67aac90cf445d4cec5a553470ca82ed9abe7d8c96426f89e8.json create mode 100644 .sqlx/query-104be5e218ca66359da27921b718bdd2080d1028cac51b4d02c2da17c8801164.json delete mode 100644 .sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.json create mode 100644 .sqlx/query-14cec436a7e98559a57cb1d7774f9fe07682ffe64656eb896e5dbdea552e8b68.json rename .sqlx/{query-c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224.json => query-18985d632ae94316c8d8264120ba6f399e9e872828bbc54476e5e4530e4ff3c1.json} (68%) create mode 100644 .sqlx/query-1b758d64428adc0646ba71730da548c092d1b2f3e0a04f88c804af7418806ccb.json create mode 100644 .sqlx/query-1e414f1562d1ce9ffecbefc3a59a8ef1e9b997124fbd33f132b1f13de461bc82.json create mode 100644 .sqlx/query-1e86c1b69c7cd6921d5eb58a699fef8aaaa1dccc39fa5013ef8c63cd921eab13.json create mode 100644 .sqlx/query-2075dc47197914af259df4c078864ff391ff866bf6d31b7be0d46b79a3ac8105.json create mode 100644 .sqlx/query-20f46ea5136009f0e249054393e9b0e620016bea2e6948b77bfa5de11cec9a31.json create mode 100644 .sqlx/query-226d8fedbdfff68ad589198c3b5d74d83bc6c46ca3f091a8414971b90b962f4d.json create mode 100644 .sqlx/query-241dacf040e632e2f52a4d880204dd78b17477cef8b90dd3bc4a86f802e6ceeb.json create mode 100644 .sqlx/query-25314c9439acdb33cc922ecfbb01a44966ab7ed9ef418dd84fe2015c37660ff0.json rename .sqlx/{query-fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee.json => query-300ce2f167cc68e369e3c160d8f92c856cf4cf7ca6e66506edce327c303c16fc.json} (71%) rename .sqlx/{query-34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806.json => query-33bbec94bbb7505d5fa5a5f410dc24808b8cd035c6b6701f307b822c6e0f849a.json} (81%) create mode 100644 .sqlx/query-3a49e0572c8418cd692b7bda75b8ea1bfd4efce1a726282cfb739be6451a0714.json create mode 100644 .sqlx/query-3e9f95bb451cba4b6329f8b668746675840688b5154d1068cf160c27939ea9fb.json create mode 100644 .sqlx/query-43080d91adcc0a8157749588483288588f6d126cb4b3258c7470ee3b7bbc041a.json create mode 100644 .sqlx/query-438ec451416f46f1acf945aa928b5d5e4c1009828660062c0c8a90c31f871bd2.json create mode 100644 .sqlx/query-45c0a9450aa19fa07de87083711413eae6d9a3ab48889a56ece629279f2c156e.json rename .sqlx/{query-b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681.json => query-493f0cef9fc99fe448ea60cff7490d06dce0779211543a72b1f6f769d9f00ed8.json} (81%) create mode 100644 .sqlx/query-53ee62a6c31f6ef2484ff5eabf8a67ee265f58c23aeab000e821aa10277500d4.json delete mode 100644 .sqlx/query-551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b.json create mode 100644 .sqlx/query-56a731baf00b6a3d69e425c7ae42d449430f363319ce19ab195f2429eb9a5c55.json create mode 100644 .sqlx/query-57ddd7816e29e63fb63429671883aa1520d57597b73bd54ff9a22fb3efb596d3.json delete mode 100644 .sqlx/query-5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f.json delete mode 100644 .sqlx/query-63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.json create mode 100644 .sqlx/query-6423c5c6d3d4fd79ca2dbe114a576ac6ba2b766dcd148e2a69cbe89ea9af3e8d.json create mode 100644 .sqlx/query-704e608a4d2d4c1e7f7c074fc50aa93dbea4b41fb0aca74bdc7eea4c67516b61.json create mode 100644 .sqlx/query-72e1bd0ea654b5fedc586273f41ac084feae1400c53631f766fbcb8ef5bd280a.json create mode 100644 .sqlx/query-744c8ef425e5e4fe9af88506e0210dcb368c1a315ee6809f8f34e837b7eae57f.json rename .sqlx/{query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.json => query-7a23cb18cccbbda676484bfcedcb3953c2f44a93f7c597debe56eb6b21ce7fcf.json} (69%) rename .sqlx/{query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.json => query-7bb873764f075c33eb5e71d0941255cf0a3cf01b761da187bd50deec4523d60f.json} (76%) rename .sqlx/{query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.json => query-80ca84ff3ec8a4ede6d8f9a9ccaedfe02ba5c16d2b9a46646d5649fc1f9fd4fd.json} (66%) create mode 100644 .sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.json rename .sqlx/{query-b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59.json => query-85cd8f96075296070428fcbe59a136252078a07cc4b7807788e08b171c8cdf9a.json} (73%) rename .sqlx/{query-b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5.json => query-860e57dee5cc91e6477ac1e7650ae4031a4b0a06e9b4e2710b9943252462d7dc.json} (80%) create mode 100644 .sqlx/query-8613f11afd0f7a09653c3bde7a25b6c98f1aa548e5adf13260939390db5aab0f.json create mode 100644 .sqlx/query-90313888df75e74f326c9731c88340ede5fb34c70b0b0d837a378fe6b92afc94.json create mode 100644 .sqlx/query-92a2fd1dbde98ae6cb59dd691c4efee61e93775bc39519714dc122790a448285.json create mode 100644 .sqlx/query-9f90a0a4125b00161e377a19a73020cd6fd3ea903470e9b153d02352b12118cc.json rename .sqlx/{query-0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4.json => query-a3db9a0caa7b47888741c892b1bdee2772a3590e71d0e0a23fcecb8dba228e81.json} (80%) create mode 100644 .sqlx/query-a63cae3c38fc5ab52786505d1944169bab3769effe0dccbed8587f89d788a1f2.json rename .sqlx/{query-cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7.json => query-a7aed9e7c0d53a5e944ad27f13c7dcc078b9ce93ba209d3b2ca1d16382b62f45.json} (70%) create mode 100644 .sqlx/query-a8ca6711e03ab03d9d6526c95853c5b62ea7b6ac7f3046b6fd1c784cb5979618.json delete mode 100644 .sqlx/query-a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3.json create mode 100644 .sqlx/query-a91d1a048aed0671318c7c2faf3537a93f34014875f1df15279d500f0c2927e7.json create mode 100644 .sqlx/query-ab7ce121deae040653c2886cda93146a6c02d1d932da63f364a78a56dee79eed.json create mode 100644 .sqlx/query-ad70c205e5c81bbb3fb230215a00fbb18af95e8b1bb437b87bd31e38fb804bdc.json create mode 100644 .sqlx/query-b026b654310663a018f93884e2a015ab473efa48671c58ff10f33ed8b89dc803.json rename .sqlx/{query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.json => query-b3e310ca3331217df9d486461ce82cb568bbcfcb88386270920f3eb6579a526e.json} (65%) create mode 100644 .sqlx/query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.json create mode 100644 .sqlx/query-bd186c14f1a5c0dc4b4f7fb543ebd4484136dd6aa75069f987075137e1b99b00.json create mode 100644 .sqlx/query-d692aa84085905ea3e70d4a94b5e81ff85548c6aeb096ee914d5349bf525137a.json create mode 100644 .sqlx/query-d863a8f429da502da7981c356a262f553ea0b23b4fd1569241119aac0f8d62cc.json create mode 100644 .sqlx/query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.json create mode 100644 .sqlx/query-e0876982733c62617ab8446239526f4da6f49846a4e7ee948a173ef54aafed1a.json create mode 100644 .sqlx/query-e17820680b6881ea134fe37906611bc25d774d21850be124025fda552104867b.json create mode 100644 .sqlx/query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.json create mode 100644 .sqlx/query-e6c03c7c747131bd9060a3f8a8eff1cf34e8727b6c3ac7222620b87b0dc1eeb1.json rename .sqlx/{query-5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b.json => query-e8784821e75fe4ab681ff91695d953af6c4abd32821251f7804ef02c4e637cf8.json} (79%) delete mode 100644 .sqlx/query-eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e.json rename .sqlx/{query-b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f.json => query-f0638db11ad696e78ee6a72951c1983881eafa5fafeb80813293bd778717080f.json} (81%) create mode 100644 .sqlx/query-f085293284bed3226150271a91561f7c1d3953b66c413aa1b0f0349fa350f8ab.json create mode 100644 .sqlx/query-f46c1dcb86e2a1a7a542afaed21054de776315e010bfd709f5408df7259ed02b.json create mode 100644 src/db/course_offering.rs create mode 100644 src/db/exam_weight.rs create mode 100644 src/db/offering_subject.rs create mode 100644 src/db/weekly_slot.rs create mode 100644 src/domain/course_offering.rs create mode 100644 src/domain/exam_weight.rs create mode 100644 src/domain/grade.rs create mode 100644 src/domain/offering_subject.rs create mode 100644 src/domain/weekly_slot.rs create mode 100644 src/service/course_offering.rs create mode 100644 src/service/exam_weight.rs create mode 100644 src/service/instance_resolve.rs create mode 100644 src/service/offering_subject.rs create mode 100644 src/service/weekly_slot.rs create mode 100644 src/web/exam_weights.rs create mode 100644 src/web/offering_subjects.rs create mode 100644 src/web/offerings.rs create mode 100644 src/web/weekly_plan.rs diff --git a/.sqlx/query-0d43379f5a5659b67aac90cf445d4cec5a553470ca82ed9abe7d8c96426f89e8.json b/.sqlx/query-0d43379f5a5659b67aac90cf445d4cec5a553470ca82ed9abe7d8c96426f89e8.json new file mode 100644 index 0000000..bf3dcaa --- /dev/null +++ b/.sqlx/query-0d43379f5a5659b67aac90cf445d4cec5a553470ca82ed9abe7d8c96426f89e8.json @@ -0,0 +1,195 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH updated AS (\n UPDATE class_course\n SET title = COALESCE($2, title),\n description = COALESCE($3, description),\n ders_saati = COALESCE($4::bigint, ders_saati::bigint)::smallint,\n counts_toward_karne = COALESCE($5, counts_toward_karne)\n WHERE id = $1\n RETURNING *)\n SELECT u.id AS \"id: ClassCourseId\", u.class AS \"class: ClassGroupId\",\n u.course AS \"course: CourseId\", u.offering AS \"offering: CourseOfferingId\",\n u.attached_by AS \"attached_by: UserId\",\n b.grade_level AS \"source?: ClassBlueprintId\",\n u.title AS \"title?: CourseTitle\",\n u.description AS \"description?: CourseDescription\",\n u.ders_saati::bigint AS \"ders_saati?: DersSaati\",\n u.counts_toward_karne,\n u.subjects_inherited, u.exam_weights_inherited, u.weekly_plan_inherited,\n u.enrollment_count,\n u.attached_at AS \"attached_at: Timestamp\"\n FROM updated u\n LEFT JOIN class_blueprint b ON b.id = u.source", + "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": [ + "Uuid", + "Text", + "Text", + "Int8", + "Bool" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + true, + true, + true, + null, + true, + false, + false, + false, + false, + false + ] + }, + "hash": "0d43379f5a5659b67aac90cf445d4cec5a553470ca82ed9abe7d8c96426f89e8" +} diff --git a/.sqlx/query-104be5e218ca66359da27921b718bdd2080d1028cac51b4d02c2da17c8801164.json b/.sqlx/query-104be5e218ca66359da27921b718bdd2080d1028cac51b4d02c2da17c8801164.json new file mode 100644 index 0000000..273e1c7 --- /dev/null +++ b/.sqlx/query-104be5e218ca66359da27921b718bdd2080d1028cac51b4d02c2da17c8801164.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT default_ders_saati::bigint AS \"default_ders_saati?: DersSaati\",\n default_counts_toward_karne\n FROM course_offering WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "default_ders_saati?: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "default_counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "course_offering", + "name": "default_counts_toward_karne" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null, + true + ] + }, + "hash": "104be5e218ca66359da27921b718bdd2080d1028cac51b4d02c2da17c8801164" +} diff --git a/.sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.json b/.sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.json deleted file mode 100644 index b16a72b..0000000 --- a/.sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO class_blueprint (id, grade, creator)\n VALUES ($1, $2, $3)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Text", - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730" -} diff --git a/.sqlx/query-14cec436a7e98559a57cb1d7774f9fe07682ffe64656eb896e5dbdea552e8b68.json b/.sqlx/query-14cec436a7e98559a57cb1d7774f9fe07682ffe64656eb896e5dbdea552e8b68.json new file mode 100644 index 0000000..2e162ae --- /dev/null +++ b/.sqlx/query-14cec436a7e98559a57cb1d7774f9fe07682ffe64656eb896e5dbdea552e8b68.json @@ -0,0 +1,140 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH updated AS (\n UPDATE course_offering SET\n title = CASE WHEN $2 THEN $3::text ELSE title END,\n description = CASE WHEN $4 THEN $5::text ELSE description END,\n default_ders_saati = CASE WHEN $6 THEN\n COALESCE($7::bigint, default_ders_saati::bigint)::smallint\n ELSE default_ders_saati END,\n default_counts_toward_karne = CASE WHEN $8 THEN $9\n ELSE default_counts_toward_karne END,\n updated_at = $10\n WHERE id = $1\n RETURNING id, course, grade_level, title, description,\n default_ders_saati, default_counts_toward_karne,\n created_by, created_at, updated_at)\n SELECT u.id AS \"id: CourseOfferingId\",\n u.course AS \"course: CourseId\",\n u.grade_level AS \"grade_level: GradeLevel\",\n u.title AS \"title?: CourseTitle\",\n u.description AS \"description?: CourseDescription\",\n u.default_ders_saati::bigint AS \"default_ders_saati?: DersSaati\",\n u.default_counts_toward_karne,\n u.created_by AS \"created_by: UserId\",\n u.created_at AS \"created_at: Timestamp\",\n u.updated_at AS \"updated_at: Timestamp\"\n FROM updated u", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: CourseOfferingId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "course" + } + } + }, + { + "ordinal": 2, + "name": "grade_level: GradeLevel", + "type_info": "Int2", + "origin": { + "Table": { + "table": "course_offering", + "name": "grade_level" + } + } + }, + { + "ordinal": 3, + "name": "title?: CourseTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_offering", + "name": "title" + } + } + }, + { + "ordinal": 4, + "name": "description?: CourseDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_offering", + "name": "description" + } + } + }, + { + "ordinal": 5, + "name": "default_ders_saati?: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "default_counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "course_offering", + "name": "default_counts_toward_karne" + } + } + }, + { + "ordinal": 7, + "name": "created_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "created_by" + } + } + }, + { + "ordinal": 8, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_offering", + "name": "created_at" + } + } + }, + { + "ordinal": 9, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_offering", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Bool", + "Text", + "Bool", + "Text", + "Bool", + "Int8", + "Bool", + "Bool", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + true, + true, + null, + true, + false, + false, + false + ] + }, + "hash": "14cec436a7e98559a57cb1d7774f9fe07682ffe64656eb896e5dbdea552e8b68" +} diff --git a/.sqlx/query-c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224.json b/.sqlx/query-18985d632ae94316c8d8264120ba6f399e9e872828bbc54476e5e4530e4ff3c1.json similarity index 68% rename from .sqlx/query-c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224.json rename to .sqlx/query-18985d632ae94316c8d8264120ba6f399e9e872828bbc54476e5e4530e4ff3c1.json index 936e46a..5756aa5 100644 --- a/.sqlx/query-c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224.json +++ b/.sqlx/query-18985d632ae94316c8d8264120ba6f399e9e872828bbc54476e5e4530e4ff3c1.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id FROM class_blueprint WHERE grade = $1 FOR KEY SHARE", + "query": "SELECT id FROM class_blueprint WHERE grade_level = $1 FOR KEY SHARE", "describe": { "columns": [ { @@ -17,12 +17,12 @@ ], "parameters": { "Left": [ - "Text" + "Int2" ] }, "nullable": [ false ] }, - "hash": "c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224" + "hash": "18985d632ae94316c8d8264120ba6f399e9e872828bbc54476e5e4530e4ff3c1" } diff --git a/.sqlx/query-1b758d64428adc0646ba71730da548c092d1b2f3e0a04f88c804af7418806ccb.json b/.sqlx/query-1b758d64428adc0646ba71730da548c092d1b2f3e0a04f88c804af7418806ccb.json new file mode 100644 index 0000000..0f08f67 --- /dev/null +++ b/.sqlx/query-1b758d64428adc0646ba71730da548c092d1b2f3e0a04f88c804af7418806ccb.json @@ -0,0 +1,131 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: CourseOfferingId\",\n course AS \"course: CourseId\",\n grade_level AS \"grade_level: GradeLevel\",\n title AS \"title?: CourseTitle\",\n description AS \"description?: CourseDescription\",\n default_ders_saati::bigint AS \"default_ders_saati?: DersSaati\",\n default_counts_toward_karne,\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\",\n updated_at AS \"updated_at: Timestamp\"\n FROM course_offering WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: CourseOfferingId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "course" + } + } + }, + { + "ordinal": 2, + "name": "grade_level: GradeLevel", + "type_info": "Int2", + "origin": { + "Table": { + "table": "course_offering", + "name": "grade_level" + } + } + }, + { + "ordinal": 3, + "name": "title?: CourseTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_offering", + "name": "title" + } + } + }, + { + "ordinal": 4, + "name": "description?: CourseDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_offering", + "name": "description" + } + } + }, + { + "ordinal": 5, + "name": "default_ders_saati?: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "default_counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "course_offering", + "name": "default_counts_toward_karne" + } + } + }, + { + "ordinal": 7, + "name": "created_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "created_by" + } + } + }, + { + "ordinal": 8, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_offering", + "name": "created_at" + } + } + }, + { + "ordinal": 9, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_offering", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + true, + true, + null, + true, + false, + false, + false + ] + }, + "hash": "1b758d64428adc0646ba71730da548c092d1b2f3e0a04f88c804af7418806ccb" +} diff --git a/.sqlx/query-1e414f1562d1ce9ffecbefc3a59a8ef1e9b997124fbd33f132b1f13de461bc82.json b/.sqlx/query-1e414f1562d1ce9ffecbefc3a59a8ef1e9b997124fbd33f132b1f13de461bc82.json new file mode 100644 index 0000000..ee30537 --- /dev/null +++ b/.sqlx/query-1e414f1562d1ce9ffecbefc3a59a8ef1e9b997124fbd33f132b1f13de461bc82.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH kicked AS (\n DELETE FROM class_course_exam_weight WHERE class_course = $1\n ), updated AS (\n UPDATE class_course\n SET exam_weights_inherited = TRUE\n WHERE id = $1\n RETURNING id\n )\n SELECT u.id AS \"id: ClassCourseId\" FROM updated u", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "1e414f1562d1ce9ffecbefc3a59a8ef1e9b997124fbd33f132b1f13de461bc82" +} diff --git a/.sqlx/query-1e86c1b69c7cd6921d5eb58a699fef8aaaa1dccc39fa5013ef8c63cd921eab13.json b/.sqlx/query-1e86c1b69c7cd6921d5eb58a699fef8aaaa1dccc39fa5013ef8c63cd921eab13.json new file mode 100644 index 0000000..ada953e --- /dev/null +++ b/.sqlx/query-1e86c1b69c7cd6921d5eb58a699fef8aaaa1dccc39fa5013ef8c63cd921eab13.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM offering_exam_weight WHERE offering = $1 AND kind = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text" + ] + }, + "nullable": [] + }, + "hash": "1e86c1b69c7cd6921d5eb58a699fef8aaaa1dccc39fa5013ef8c63cd921eab13" +} diff --git a/.sqlx/query-2075dc47197914af259df4c078864ff391ff866bf6d31b7be0d46b79a3ac8105.json b/.sqlx/query-2075dc47197914af259df4c078864ff391ff866bf6d31b7be0d46b79a3ac8105.json new file mode 100644 index 0000000..e1c8d18 --- /dev/null +++ b/.sqlx/query-2075dc47197914af259df4c078864ff391ff866bf6d31b7be0d46b79a3ac8105.json @@ -0,0 +1,30 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH updated AS (\n UPDATE class_course\n SET exam_weights_inherited = FALSE\n WHERE id = $1\n RETURNING id\n ), written AS (\n INSERT INTO class_course_exam_weight (class_course, kind, weight)\n SELECT $1, $2, $3::bigint::smallint\n WHERE EXISTS (SELECT 1 FROM updated)\n ON CONFLICT (class_course, kind) DO UPDATE SET weight = EXCLUDED.weight\n RETURNING class_course\n )\n SELECT u.id AS \"id: ClassCourseId\" FROM updated u", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Int8" + ] + }, + "nullable": [ + false + ] + }, + "hash": "2075dc47197914af259df4c078864ff391ff866bf6d31b7be0d46b79a3ac8105" +} diff --git a/.sqlx/query-20f46ea5136009f0e249054393e9b0e620016bea2e6948b77bfa5de11cec9a31.json b/.sqlx/query-20f46ea5136009f0e249054393e9b0e620016bea2e6948b77bfa5de11cec9a31.json new file mode 100644 index 0000000..d2266e7 --- /dev/null +++ b/.sqlx/query-20f46ea5136009f0e249054393e9b0e620016bea2e6948b77bfa5de11cec9a31.json @@ -0,0 +1,31 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH dropped AS (\n DELETE FROM class_course_subject\n WHERE class_course = $1 AND subject = $2\n RETURNING subject\n ), flipped AS (\n UPDATE class_course\n SET subjects_inherited = FALSE\n WHERE id = $1 AND EXISTS (SELECT 1 FROM dropped)\n RETURNING id\n )\n SELECT EXISTS (SELECT 1 FROM flipped) AS \"live!\",\n EXISTS (SELECT 1 FROM dropped) AS \"dropped!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "live!", + "type_info": "Bool", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "dropped!", + "type_info": "Bool", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + null, + null + ] + }, + "hash": "20f46ea5136009f0e249054393e9b0e620016bea2e6948b77bfa5de11cec9a31" +} diff --git a/.sqlx/query-226d8fedbdfff68ad589198c3b5d74d83bc6c46ca3f091a8414971b90b962f4d.json b/.sqlx/query-226d8fedbdfff68ad589198c3b5d74d83bc6c46ca3f091a8414971b90b962f4d.json new file mode 100644 index 0000000..992cef1 --- /dev/null +++ b/.sqlx/query-226d8fedbdfff68ad589198c3b5d74d83bc6c46ca3f091a8414971b90b962f4d.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: CourseOfferingId\" FROM course_offering\n WHERE course = $1 AND grade_level = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: CourseOfferingId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Int2" + ] + }, + "nullable": [ + false + ] + }, + "hash": "226d8fedbdfff68ad589198c3b5d74d83bc6c46ca3f091a8414971b90b962f4d" +} diff --git a/.sqlx/query-241dacf040e632e2f52a4d880204dd78b17477cef8b90dd3bc4a86f802e6ceeb.json b/.sqlx/query-241dacf040e632e2f52a4d880204dd78b17477cef8b90dd3bc4a86f802e6ceeb.json new file mode 100644 index 0000000..b394267 --- /dev/null +++ b/.sqlx/query-241dacf040e632e2f52a4d880204dd78b17477cef8b90dd3bc4a86f802e6ceeb.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: ClassCourseId\" FROM class_course WHERE id = $1\n FOR NO KEY UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "241dacf040e632e2f52a4d880204dd78b17477cef8b90dd3bc4a86f802e6ceeb" +} diff --git a/.sqlx/query-25314c9439acdb33cc922ecfbb01a44966ab7ed9ef418dd84fe2015c37660ff0.json b/.sqlx/query-25314c9439acdb33cc922ecfbb01a44966ab7ed9ef418dd84fe2015c37660ff0.json new file mode 100644 index 0000000..d5798ec --- /dev/null +++ b/.sqlx/query-25314c9439acdb33cc922ecfbb01a44966ab7ed9ef418dd84fe2015c37660ff0.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO course_offering (id, course, grade_level, created_by, created_at, updated_at)\n VALUES ($1, $2, $3, $4, $5, $5)\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Int2", + "Uuid", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "25314c9439acdb33cc922ecfbb01a44966ab7ed9ef418dd84fe2015c37660ff0" +} diff --git a/.sqlx/query-fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee.json b/.sqlx/query-300ce2f167cc68e369e3c160d8f92c856cf4cf7ca6e66506edce327c303c16fc.json similarity index 71% rename from .sqlx/query-fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee.json rename to .sqlx/query-300ce2f167cc68e369e3c160d8f92c856cf4cf7ca6e66506edce327c303c16fc.json index 2b7b905..5a0f2e6 100644 --- a/.sqlx/query-fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee.json +++ b/.sqlx/query-300ce2f167cc68e369e3c160d8f92c856cf4cf7ca6e66506edce327c303c16fc.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO class_group (id, creator, name, grade, year, teacher)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"", + "query": "INSERT INTO class_group (id, creator, name, grade_level, year, teacher)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade_level AS \"grade_level: GradeLevel\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"", "describe": { "columns": [ { @@ -38,12 +38,12 @@ }, { "ordinal": 3, - "name": "grade: ClassGrade", - "type_info": "Text", + "name": "grade_level: GradeLevel", + "type_info": "Int2", "origin": { "Table": { "table": "class_group", - "name": "grade" + "name": "grade_level" } } }, @@ -75,7 +75,7 @@ "Uuid", "Uuid", "Text", - "Text", + "Int2", "Uuid", "Uuid" ] @@ -84,10 +84,10 @@ false, false, false, - true, + false, true, true ] }, - "hash": "fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee" + "hash": "300ce2f167cc68e369e3c160d8f92c856cf4cf7ca6e66506edce327c303c16fc" } diff --git a/.sqlx/query-34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806.json b/.sqlx/query-33bbec94bbb7505d5fa5a5f410dc24808b8cd035c6b6701f307b822c6e0f849a.json similarity index 81% rename from .sqlx/query-34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806.json rename to .sqlx/query-33bbec94bbb7505d5fa5a5f410dc24808b8cd035c6b6701f307b822c6e0f849a.json index c7b41ee..05e78e3 100644 --- a/.sqlx/query-34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806.json +++ b/.sqlx/query-33bbec94bbb7505d5fa5a5f410dc24808b8cd035c6b6701f307b822c6e0f849a.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = ANY($1)", + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade_level AS \"grade_level: GradeLevel\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = ANY($1)", "describe": { "columns": [ { @@ -38,12 +38,12 @@ }, { "ordinal": 3, - "name": "grade: ClassGrade", - "type_info": "Text", + "name": "grade_level: GradeLevel", + "type_info": "Int2", "origin": { "Table": { "table": "class_group", - "name": "grade" + "name": "grade_level" } } }, @@ -79,10 +79,10 @@ false, false, false, - true, + false, true, true ] }, - "hash": "34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806" + "hash": "33bbec94bbb7505d5fa5a5f410dc24808b8cd035c6b6701f307b822c6e0f849a" } diff --git a/.sqlx/query-3a49e0572c8418cd692b7bda75b8ea1bfd4efce1a726282cfb739be6451a0714.json b/.sqlx/query-3a49e0572c8418cd692b7bda75b8ea1bfd4efce1a726282cfb739be6451a0714.json new file mode 100644 index 0000000..cfb0b8e --- /dev/null +++ b/.sqlx/query-3a49e0572c8418cd692b7bda75b8ea1bfd4efce1a726282cfb739be6451a0714.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM course_offering\n WHERE id = $1\n AND NOT EXISTS (SELECT 1 FROM class_course cc WHERE cc.offering = $1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "3a49e0572c8418cd692b7bda75b8ea1bfd4efce1a726282cfb739be6451a0714" +} diff --git a/.sqlx/query-3e9f95bb451cba4b6329f8b668746675840688b5154d1068cf160c27939ea9fb.json b/.sqlx/query-3e9f95bb451cba4b6329f8b668746675840688b5154d1068cf160c27939ea9fb.json new file mode 100644 index 0000000..abef7c5 --- /dev/null +++ b/.sqlx/query-3e9f95bb451cba4b6329f8b668746675840688b5154d1068cf160c27939ea9fb.json @@ -0,0 +1,36 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH kicked AS (\n DELETE FROM class_course_exam_weight\n WHERE class_course = $1 AND kind = $2\n RETURNING class_course\n ), updated AS (\n UPDATE class_course\n SET exam_weights_inherited =\n CASE WHEN EXISTS (SELECT 1 FROM kicked)\n THEN FALSE ELSE exam_weights_inherited END\n WHERE id = $1\n RETURNING exam_weights_inherited\n )\n SELECT u.exam_weights_inherited AS \"inherited: bool\",\n (SELECT count(*)::bigint FROM kicked) AS \"removed!: i64\"\n FROM updated u", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "inherited: bool", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "exam_weights_inherited" + } + } + }, + { + "ordinal": 1, + "name": "removed!: i64", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "3e9f95bb451cba4b6329f8b668746675840688b5154d1068cf160c27939ea9fb" +} diff --git a/.sqlx/query-43080d91adcc0a8157749588483288588f6d126cb4b3258c7470ee3b7bbc041a.json b/.sqlx/query-43080d91adcc0a8157749588483288588f6d126cb4b3258c7470ee3b7bbc041a.json new file mode 100644 index 0000000..173302b --- /dev/null +++ b/.sqlx/query-43080d91adcc0a8157749588483288588f6d126cb4b3258c7470ee3b7bbc041a.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO class_blueprint (id, grade_level, creator)\n VALUES ($1, $2, $3)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Int2", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "43080d91adcc0a8157749588483288588f6d126cb4b3258c7470ee3b7bbc041a" +} diff --git a/.sqlx/query-438ec451416f46f1acf945aa928b5d5e4c1009828660062c0c8a90c31f871bd2.json b/.sqlx/query-438ec451416f46f1acf945aa928b5d5e4c1009828660062c0c8a90c31f871bd2.json new file mode 100644 index 0000000..cf6cae9 --- /dev/null +++ b/.sqlx/query-438ec451416f46f1acf945aa928b5d5e4c1009828660062c0c8a90c31f871bd2.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT CASE WHEN cc.subjects_inherited\n THEN EXISTS (SELECT 1\n FROM offering_subject os\n WHERE os.offering = cc.offering AND os.subject = $2)\n ELSE EXISTS (SELECT 1\n FROM class_course_subject ccs\n WHERE ccs.class_course = cc.id AND ccs.subject = $2)\n END AS \"member!\"\n FROM class_course cc\n WHERE cc.id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "member!", + "type_info": "Bool", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "438ec451416f46f1acf945aa928b5d5e4c1009828660062c0c8a90c31f871bd2" +} diff --git a/.sqlx/query-45c0a9450aa19fa07de87083711413eae6d9a3ab48889a56ece629279f2c156e.json b/.sqlx/query-45c0a9450aa19fa07de87083711413eae6d9a3ab48889a56ece629279f2c156e.json new file mode 100644 index 0000000..57e113a --- /dev/null +++ b/.sqlx/query-45c0a9450aa19fa07de87083711413eae6d9a3ab48889a56ece629279f2c156e.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH del AS (\n DELETE FROM class_course_slot WHERE class_course = $1\n RETURNING id\n ), flip AS (\n UPDATE class_course SET weekly_plan_inherited = TRUE\n WHERE id = $1\n RETURNING id\n )\n SELECT id AS \"id: ClassCourseId\" FROM flip", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "45c0a9450aa19fa07de87083711413eae6d9a3ab48889a56ece629279f2c156e" +} diff --git a/.sqlx/query-b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681.json b/.sqlx/query-493f0cef9fc99fe448ea60cff7490d06dce0779211543a72b1f6f769d9f00ed8.json similarity index 81% rename from .sqlx/query-b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681.json rename to .sqlx/query-493f0cef9fc99fe448ea60cff7490d06dce0779211543a72b1f6f769d9f00ed8.json index 6ce08c0..a387d8b 100644 --- a/.sqlx/query-b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681.json +++ b/.sqlx/query-493f0cef9fc99fe448ea60cff7490d06dce0779211543a72b1f6f769d9f00ed8.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE teacher = $1 ORDER BY id DESC", + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade_level AS \"grade_level: GradeLevel\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE year = $1 ORDER BY id", "describe": { "columns": [ { @@ -38,12 +38,12 @@ }, { "ordinal": 3, - "name": "grade: ClassGrade", - "type_info": "Text", + "name": "grade_level: GradeLevel", + "type_info": "Int2", "origin": { "Table": { "table": "class_group", - "name": "grade" + "name": "grade_level" } } }, @@ -79,10 +79,10 @@ false, false, false, - true, + false, true, true ] }, - "hash": "b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681" + "hash": "493f0cef9fc99fe448ea60cff7490d06dce0779211543a72b1f6f769d9f00ed8" } diff --git a/.sqlx/query-53ee62a6c31f6ef2484ff5eabf8a67ee265f58c23aeab000e821aa10277500d4.json b/.sqlx/query-53ee62a6c31f6ef2484ff5eabf8a67ee265f58c23aeab000e821aa10277500d4.json new file mode 100644 index 0000000..79cc736 --- /dev/null +++ b/.sqlx/query-53ee62a6c31f6ef2484ff5eabf8a67ee265f58c23aeab000e821aa10277500d4.json @@ -0,0 +1,198 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH updated AS (\n UPDATE class_course SET\n title = CASE WHEN $2 THEN NULL ELSE title END,\n description = CASE WHEN $3 THEN NULL ELSE description END,\n ders_saati = CASE WHEN $4 THEN NULL ELSE ders_saati END,\n counts_toward_karne = CASE WHEN $5 THEN NULL ELSE counts_toward_karne END,\n subjects_inherited = CASE WHEN $6 THEN TRUE ELSE subjects_inherited END,\n exam_weights_inherited = CASE WHEN $7 THEN TRUE ELSE exam_weights_inherited END,\n weekly_plan_inherited = CASE WHEN $8 THEN TRUE ELSE weekly_plan_inherited END\n WHERE id = $1\n RETURNING *)\n SELECT u.id AS \"id: ClassCourseId\", u.class AS \"class: ClassGroupId\",\n u.course AS \"course: CourseId\", u.offering AS \"offering: CourseOfferingId\",\n u.attached_by AS \"attached_by: UserId\",\n b.grade_level AS \"source?: ClassBlueprintId\",\n u.title AS \"title?: CourseTitle\",\n u.description AS \"description?: CourseDescription\",\n u.ders_saati::bigint AS \"ders_saati?: DersSaati\",\n u.counts_toward_karne,\n u.subjects_inherited, u.exam_weights_inherited, u.weekly_plan_inherited,\n u.enrollment_count,\n u.attached_at AS \"attached_at: Timestamp\"\n FROM updated u\n LEFT JOIN class_blueprint b ON b.id = u.source", + "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": [ + "Uuid", + "Bool", + "Bool", + "Bool", + "Bool", + "Bool", + "Bool", + "Bool" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + true, + true, + true, + null, + true, + false, + false, + false, + false, + false + ] + }, + "hash": "53ee62a6c31f6ef2484ff5eabf8a67ee265f58c23aeab000e821aa10277500d4" +} diff --git a/.sqlx/query-551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b.json b/.sqlx/query-551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b.json deleted file mode 100644 index b439b20..0000000 --- a/.sqlx/query-551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b.json +++ /dev/null @@ -1,121 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "WITH updated AS (\n UPDATE class_course\n SET ders_saati = COALESCE($2::bigint, ders_saati::bigint)::smallint,\n counts_toward_karne = COALESCE($3, counts_toward_karne)\n WHERE id = $1\n RETURNING *)\n SELECT u.id AS \"id: ClassCourseId\", u.class AS \"class: ClassGroupId\",\n u.course AS \"course: CourseId\", u.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n u.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n u.counts_toward_karne, u.enrollment_count,\n u.attached_at AS \"attached_at: Timestamp\"\n FROM updated u\n LEFT JOIN class_blueprint b ON b.id = u.source", - "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": "attached_by: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_course", - "name": "attached_by" - } - } - }, - { - "ordinal": 4, - "name": "source?: ClassBlueprintId", - "type_info": "Text", - "origin": { - "Table": { - "table": "class_blueprint", - "name": "grade" - } - } - }, - { - "ordinal": 5, - "name": "ders_saati!: DersSaati", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 6, - "name": "counts_toward_karne", - "type_info": "Bool", - "origin": { - "Table": { - "table": "class_course", - "name": "counts_toward_karne" - } - } - }, - { - "ordinal": 7, - "name": "enrollment_count", - "type_info": "Int8", - "origin": { - "Table": { - "table": "class_course", - "name": "enrollment_count" - } - } - }, - { - "ordinal": 8, - "name": "attached_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "class_course", - "name": "attached_at" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Int8", - "Bool" - ] - }, - "nullable": [ - false, - false, - false, - false, - true, - null, - false, - false, - false - ] - }, - "hash": "551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b" -} diff --git a/.sqlx/query-56a731baf00b6a3d69e425c7ae42d449430f363319ce19ab195f2429eb9a5c55.json b/.sqlx/query-56a731baf00b6a3d69e425c7ae42d449430f363319ce19ab195f2429eb9a5c55.json new file mode 100644 index 0000000..86a02f1 --- /dev/null +++ b/.sqlx/query-56a731baf00b6a3d69e425c7ae42d449430f363319ce19ab195f2429eb9a5c55.json @@ -0,0 +1,139 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO course_offering\n (id, course, grade_level, title, description,\n default_ders_saati, default_counts_toward_karne,\n created_by, created_at, updated_at)\n VALUES ($1, $2, $3, $4, $5, $6::bigint, $7, $8, $9, $9)\n RETURNING id AS \"id: CourseOfferingId\",\n course AS \"course: CourseId\",\n grade_level AS \"grade_level: GradeLevel\",\n title AS \"title?: CourseTitle\",\n description AS \"description?: CourseDescription\",\n default_ders_saati::bigint AS \"default_ders_saati?: DersSaati\",\n default_counts_toward_karne,\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\",\n updated_at AS \"updated_at: Timestamp\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: CourseOfferingId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "course" + } + } + }, + { + "ordinal": 2, + "name": "grade_level: GradeLevel", + "type_info": "Int2", + "origin": { + "Table": { + "table": "course_offering", + "name": "grade_level" + } + } + }, + { + "ordinal": 3, + "name": "title?: CourseTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_offering", + "name": "title" + } + } + }, + { + "ordinal": 4, + "name": "description?: CourseDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_offering", + "name": "description" + } + } + }, + { + "ordinal": 5, + "name": "default_ders_saati?: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "default_counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "course_offering", + "name": "default_counts_toward_karne" + } + } + }, + { + "ordinal": 7, + "name": "created_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "created_by" + } + } + }, + { + "ordinal": 8, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_offering", + "name": "created_at" + } + } + }, + { + "ordinal": 9, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_offering", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Int2", + "Text", + "Text", + "Int8", + "Bool", + "Uuid", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + true, + true, + null, + true, + false, + false, + false + ] + }, + "hash": "56a731baf00b6a3d69e425c7ae42d449430f363319ce19ab195f2429eb9a5c55" +} diff --git a/.sqlx/query-57ddd7816e29e63fb63429671883aa1520d57597b73bd54ff9a22fb3efb596d3.json b/.sqlx/query-57ddd7816e29e63fb63429671883aa1520d57597b73bd54ff9a22fb3efb596d3.json new file mode 100644 index 0000000..a50f081 --- /dev/null +++ b/.sqlx/query-57ddd7816e29e63fb63429671883aa1520d57597b73bd54ff9a22fb3efb596d3.json @@ -0,0 +1,132 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: CourseOfferingId\",\n course AS \"course: CourseId\",\n grade_level AS \"grade_level: GradeLevel\",\n title AS \"title?: CourseTitle\",\n description AS \"description?: CourseDescription\",\n default_ders_saati::bigint AS \"default_ders_saati?: DersSaati\",\n default_counts_toward_karne,\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\",\n updated_at AS \"updated_at: Timestamp\"\n FROM course_offering WHERE course = $1 AND grade_level = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: CourseOfferingId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "course" + } + } + }, + { + "ordinal": 2, + "name": "grade_level: GradeLevel", + "type_info": "Int2", + "origin": { + "Table": { + "table": "course_offering", + "name": "grade_level" + } + } + }, + { + "ordinal": 3, + "name": "title?: CourseTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_offering", + "name": "title" + } + } + }, + { + "ordinal": 4, + "name": "description?: CourseDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_offering", + "name": "description" + } + } + }, + { + "ordinal": 5, + "name": "default_ders_saati?: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "default_counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "course_offering", + "name": "default_counts_toward_karne" + } + } + }, + { + "ordinal": 7, + "name": "created_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "created_by" + } + } + }, + { + "ordinal": 8, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_offering", + "name": "created_at" + } + } + }, + { + "ordinal": 9, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_offering", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Int2" + ] + }, + "nullable": [ + false, + false, + false, + true, + true, + null, + true, + false, + false, + false + ] + }, + "hash": "57ddd7816e29e63fb63429671883aa1520d57597b73bd54ff9a22fb3efb596d3" +} diff --git a/.sqlx/query-5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f.json b/.sqlx/query-5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f.json deleted file mode 100644 index a60756a..0000000 --- a/.sqlx/query-5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.id = ANY($1)\n ORDER BY cc.attached_at DESC, cc.id DESC", - "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": "attached_by: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_course", - "name": "attached_by" - } - } - }, - { - "ordinal": 4, - "name": "source?: ClassBlueprintId", - "type_info": "Text", - "origin": { - "Table": { - "table": "class_blueprint", - "name": "grade" - } - } - }, - { - "ordinal": 5, - "name": "ders_saati!: DersSaati", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 6, - "name": "counts_toward_karne", - "type_info": "Bool", - "origin": { - "Table": { - "table": "class_course", - "name": "counts_toward_karne" - } - } - }, - { - "ordinal": 7, - "name": "enrollment_count", - "type_info": "Int8", - "origin": { - "Table": { - "table": "class_course", - "name": "enrollment_count" - } - } - }, - { - "ordinal": 8, - "name": "attached_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "class_course", - "name": "attached_at" - } - } - } - ], - "parameters": { - "Left": [ - "UuidArray" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - null, - false, - false, - false - ] - }, - "hash": "5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f" -} diff --git a/.sqlx/query-63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.json b/.sqlx/query-63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.json deleted file mode 100644 index 868dee0..0000000 --- a/.sqlx/query-63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.class = ANY($1)\n ORDER BY cc.attached_at DESC, cc.id DESC", - "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": "attached_by: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_course", - "name": "attached_by" - } - } - }, - { - "ordinal": 4, - "name": "source?: ClassBlueprintId", - "type_info": "Text", - "origin": { - "Table": { - "table": "class_blueprint", - "name": "grade" - } - } - }, - { - "ordinal": 5, - "name": "ders_saati!: DersSaati", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 6, - "name": "counts_toward_karne", - "type_info": "Bool", - "origin": { - "Table": { - "table": "class_course", - "name": "counts_toward_karne" - } - } - }, - { - "ordinal": 7, - "name": "enrollment_count", - "type_info": "Int8", - "origin": { - "Table": { - "table": "class_course", - "name": "enrollment_count" - } - } - }, - { - "ordinal": 8, - "name": "attached_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "class_course", - "name": "attached_at" - } - } - } - ], - "parameters": { - "Left": [ - "UuidArray" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - null, - false, - false, - false - ] - }, - "hash": "63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414" -} diff --git a/.sqlx/query-6423c5c6d3d4fd79ca2dbe114a576ac6ba2b766dcd148e2a69cbe89ea9af3e8d.json b/.sqlx/query-6423c5c6d3d4fd79ca2dbe114a576ac6ba2b766dcd148e2a69cbe89ea9af3e8d.json new file mode 100644 index 0000000..8ce54c0 --- /dev/null +++ b/.sqlx/query-6423c5c6d3d4fd79ca2dbe114a576ac6ba2b766dcd148e2a69cbe89ea9af3e8d.json @@ -0,0 +1,64 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT s.id AS \"id: SubjectId\",\n s.course AS \"course: CourseId\",\n s.name AS \"name: SubjectName\",\n s.description AS \"description: SubjectDescription\"\n FROM offering_subject os\n JOIN subject s ON s.id = os.subject\n WHERE os.offering = $1\n ORDER BY s.name ASC, s.id ASC", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: SubjectId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "subject", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "subject", + "name": "course" + } + } + }, + { + "ordinal": 2, + "name": "name: SubjectName", + "type_info": "Text", + "origin": { + "Table": { + "table": "subject", + "name": "name" + } + } + }, + { + "ordinal": 3, + "name": "description: SubjectDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "subject", + "name": "description" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "6423c5c6d3d4fd79ca2dbe114a576ac6ba2b766dcd148e2a69cbe89ea9af3e8d" +} diff --git a/.sqlx/query-704e608a4d2d4c1e7f7c074fc50aa93dbea4b41fb0aca74bdc7eea4c67516b61.json b/.sqlx/query-704e608a4d2d4c1e7f7c074fc50aa93dbea4b41fb0aca74bdc7eea4c67516b61.json new file mode 100644 index 0000000..05dfe4a --- /dev/null +++ b/.sqlx/query-704e608a4d2d4c1e7f7c074fc50aa93dbea4b41fb0aca74bdc7eea4c67516b61.json @@ -0,0 +1,30 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH swept AS (\n DELETE FROM class_course_subject\n WHERE class_course = $1\n RETURNING subject\n ), restored AS (\n UPDATE class_course\n SET subjects_inherited = TRUE\n WHERE id = $1\n RETURNING id\n )\n SELECT (SELECT count(*) FROM swept) AS \"swept!: i64\",\n EXISTS (SELECT 1 FROM restored) AS \"live!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "swept!: i64", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "live!", + "type_info": "Bool", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null, + null + ] + }, + "hash": "704e608a4d2d4c1e7f7c074fc50aa93dbea4b41fb0aca74bdc7eea4c67516b61" +} diff --git a/.sqlx/query-72e1bd0ea654b5fedc586273f41ac084feae1400c53631f766fbcb8ef5bd280a.json b/.sqlx/query-72e1bd0ea654b5fedc586273f41ac084feae1400c53631f766fbcb8ef5bd280a.json new file mode 100644 index 0000000..54b05b3 --- /dev/null +++ b/.sqlx/query-72e1bd0ea654b5fedc586273f41ac084feae1400c53631f766fbcb8ef5bd280a.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH del AS (\n DELETE FROM class_course_slot WHERE id = $1 AND class_course = $2\n RETURNING id\n ), flip AS (\n UPDATE class_course SET weekly_plan_inherited = FALSE\n WHERE id = $2 AND EXISTS (SELECT 1 FROM del)\n RETURNING id\n )\n SELECT id AS \"id: ClassCourseId\" FROM flip", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "72e1bd0ea654b5fedc586273f41ac084feae1400c53631f766fbcb8ef5bd280a" +} diff --git a/.sqlx/query-744c8ef425e5e4fe9af88506e0210dcb368c1a315ee6809f8f34e837b7eae57f.json b/.sqlx/query-744c8ef425e5e4fe9af88506e0210dcb368c1a315ee6809f8f34e837b7eae57f.json new file mode 100644 index 0000000..bfb7204 --- /dev/null +++ b/.sqlx/query-744c8ef425e5e4fe9af88506e0210dcb368c1a315ee6809f8f34e837b7eae57f.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.id = 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": "744c8ef425e5e4fe9af88506e0210dcb368c1a315ee6809f8f34e837b7eae57f" +} diff --git a/.sqlx/query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.json b/.sqlx/query-7a23cb18cccbbda676484bfcedcb3953c2f44a93f7c597debe56eb6b21ce7fcf.json similarity index 69% rename from .sqlx/query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.json rename to .sqlx/query-7a23cb18cccbbda676484bfcedcb3953c2f44a93f7c597debe56eb6b21ce7fcf.json index d06bd79..45e5ac2 100644 --- a/.sqlx/query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.json +++ b/.sqlx/query-7a23cb18cccbbda676484bfcedcb3953c2f44a93f7c597debe56eb6b21ce7fcf.json @@ -1,15 +1,15 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM blueprint_course\n WHERE course = $2\n AND blueprint = (SELECT id FROM class_blueprint WHERE grade = $1)", + "query": "DELETE FROM blueprint_course\n WHERE course = $2\n AND blueprint = (SELECT id FROM class_blueprint WHERE grade_level = $1)", "describe": { "columns": [], "parameters": { "Left": [ - "Text", + "Int2", "Uuid" ] }, "nullable": [] }, - "hash": "a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad" + "hash": "7a23cb18cccbbda676484bfcedcb3953c2f44a93f7c597debe56eb6b21ce7fcf" } diff --git a/.sqlx/query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.json b/.sqlx/query-7bb873764f075c33eb5e71d0941255cf0a3cf01b761da187bd50deec4523d60f.json similarity index 76% rename from .sqlx/query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.json rename to .sqlx/query-7bb873764f075c33eb5e71d0941255cf0a3cf01b761da187bd50deec4523d60f.json index 040daef..e310fe6 100644 --- a/.sqlx/query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.json +++ b/.sqlx/query-7bb873764f075c33eb5e71d0941255cf0a3cf01b761da187bd50deec4523d60f.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"key: uuid::Uuid\" FROM class_blueprint\n WHERE grade = $1 FOR UPDATE", + "query": "SELECT id AS \"key: uuid::Uuid\" FROM class_blueprint\n WHERE grade_level = $1 FOR UPDATE", "describe": { "columns": [ { @@ -17,12 +17,12 @@ ], "parameters": { "Left": [ - "Text" + "Int2" ] }, "nullable": [ false ] }, - "hash": "8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2" + "hash": "7bb873764f075c33eb5e71d0941255cf0a3cf01b761da187bd50deec4523d60f" } diff --git a/.sqlx/query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.json b/.sqlx/query-80ca84ff3ec8a4ede6d8f9a9ccaedfe02ba5c16d2b9a46646d5649fc1f9fd4fd.json similarity index 66% rename from .sqlx/query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.json rename to .sqlx/query-80ca84ff3ec8a4ede6d8f9a9ccaedfe02ba5c16d2b9a46646d5649fc1f9fd4fd.json index 334fdf5..9b8c7b6 100644 --- a/.sqlx/query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.json +++ b/.sqlx/query-80ca84ff3ec8a4ede6d8f9a9ccaedfe02ba5c16d2b9a46646d5649fc1f9fd4fd.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"key: uuid::Uuid\", grade AS \"grade: ClassGrade\",\n creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade = $1", + "query": "SELECT id AS \"key: uuid::Uuid\", grade_level AS \"grade_level: GradeLevel\",\n creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade_level = $1", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "grade: ClassGrade", - "type_info": "Text", + "name": "grade_level: GradeLevel", + "type_info": "Int2", "origin": { "Table": { "table": "class_blueprint", - "name": "grade" + "name": "grade_level" } } }, @@ -39,7 +39,7 @@ ], "parameters": { "Left": [ - "Text" + "Int2" ] }, "nullable": [ @@ -48,5 +48,5 @@ false ] }, - "hash": "c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5" + "hash": "80ca84ff3ec8a4ede6d8f9a9ccaedfe02ba5c16d2b9a46646d5649fc1f9fd4fd" } diff --git a/.sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.json b/.sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.json new file mode 100644 index 0000000..a42ea1d --- /dev/null +++ b/.sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.json @@ -0,0 +1,58 @@ +{ + "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-b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59.json b/.sqlx/query-85cd8f96075296070428fcbe59a136252078a07cc4b7807788e08b171c8cdf9a.json similarity index 73% rename from .sqlx/query-b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59.json rename to .sqlx/query-85cd8f96075296070428fcbe59a136252078a07cc4b7807788e08b171c8cdf9a.json index d829ca5..787eb21 100644 --- a/.sqlx/query-b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59.json +++ b/.sqlx/query-85cd8f96075296070428fcbe59a136252078a07cc4b7807788e08b171c8cdf9a.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE academic_year SET class_count = class_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO class_group (id, creator, name, grade, year, teacher)\n SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"", + "query": "WITH seat AS (\n UPDATE academic_year SET class_count = class_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO class_group (id, creator, name, grade_level, year, teacher)\n SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade_level AS \"grade_level: GradeLevel\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"", "describe": { "columns": [ { @@ -38,12 +38,12 @@ }, { "ordinal": 3, - "name": "grade: ClassGrade", - "type_info": "Text", + "name": "grade_level: GradeLevel", + "type_info": "Int2", "origin": { "Table": { "table": "class_group", - "name": "grade" + "name": "grade_level" } } }, @@ -76,7 +76,7 @@ "Uuid", "Uuid", "Text", - "Text", + "Int2", "Uuid" ] }, @@ -84,10 +84,10 @@ false, false, false, - true, + false, true, true ] }, - "hash": "b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59" + "hash": "85cd8f96075296070428fcbe59a136252078a07cc4b7807788e08b171c8cdf9a" } diff --git a/.sqlx/query-b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5.json b/.sqlx/query-860e57dee5cc91e6477ac1e7650ae4031a4b0a06e9b4e2710b9943252462d7dc.json similarity index 80% rename from .sqlx/query-b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5.json rename to .sqlx/query-860e57dee5cc91e6477ac1e7650ae4031a4b0a06e9b4e2710b9943252462d7dc.json index 429505c..8561ca1 100644 --- a/.sqlx/query-b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5.json +++ b/.sqlx/query-860e57dee5cc91e6477ac1e7650ae4031a4b0a06e9b4e2710b9943252462d7dc.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = $1", + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade_level AS \"grade_level: GradeLevel\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE teacher = $1 ORDER BY id DESC", "describe": { "columns": [ { @@ -38,12 +38,12 @@ }, { "ordinal": 3, - "name": "grade: ClassGrade", - "type_info": "Text", + "name": "grade_level: GradeLevel", + "type_info": "Int2", "origin": { "Table": { "table": "class_group", - "name": "grade" + "name": "grade_level" } } }, @@ -79,10 +79,10 @@ false, false, false, - true, + false, true, true ] }, - "hash": "b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5" + "hash": "860e57dee5cc91e6477ac1e7650ae4031a4b0a06e9b4e2710b9943252462d7dc" } diff --git a/.sqlx/query-8613f11afd0f7a09653c3bde7a25b6c98f1aa548e5adf13260939390db5aab0f.json b/.sqlx/query-8613f11afd0f7a09653c3bde7a25b6c98f1aa548e5adf13260939390db5aab0f.json new file mode 100644 index 0000000..5f95fab --- /dev/null +++ b/.sqlx/query-8613f11afd0f7a09653c3bde7a25b6c98f1aa548e5adf13260939390db5aab0f.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO offering_subject (offering, subject)\n VALUES ($1, $2)\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "8613f11afd0f7a09653c3bde7a25b6c98f1aa548e5adf13260939390db5aab0f" +} diff --git a/.sqlx/query-90313888df75e74f326c9731c88340ede5fb34c70b0b0d837a378fe6b92afc94.json b/.sqlx/query-90313888df75e74f326c9731c88340ede5fb34c70b0b0d837a378fe6b92afc94.json new file mode 100644 index 0000000..e5c52d0 --- /dev/null +++ b/.sqlx/query-90313888df75e74f326c9731c88340ede5fb34c70b0b0d837a378fe6b92afc94.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT grade_level AS \"grade_level: GradeLevel\" FROM class_group\n WHERE id = $1 FOR KEY SHARE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "grade_level: GradeLevel", + "type_info": "Int2", + "origin": { + "Table": { + "table": "class_group", + "name": "grade_level" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "90313888df75e74f326c9731c88340ede5fb34c70b0b0d837a378fe6b92afc94" +} diff --git a/.sqlx/query-92a2fd1dbde98ae6cb59dd691c4efee61e93775bc39519714dc122790a448285.json b/.sqlx/query-92a2fd1dbde98ae6cb59dd691c4efee61e93775bc39519714dc122790a448285.json new file mode 100644 index 0000000..719958d --- /dev/null +++ b/.sqlx/query-92a2fd1dbde98ae6cb59dd691c4efee61e93775bc39519714dc122790a448285.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM offering_subject\n WHERE offering = $1 AND subject = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "92a2fd1dbde98ae6cb59dd691c4efee61e93775bc39519714dc122790a448285" +} diff --git a/.sqlx/query-9f90a0a4125b00161e377a19a73020cd6fd3ea903470e9b153d02352b12118cc.json b/.sqlx/query-9f90a0a4125b00161e377a19a73020cd6fd3ea903470e9b153d02352b12118cc.json new file mode 100644 index 0000000..e2e25c2 --- /dev/null +++ b/.sqlx/query-9f90a0a4125b00161e377a19a73020cd6fd3ea903470e9b153d02352b12118cc.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.id = $1", + "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": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + true, + true, + true, + null, + true, + false, + false, + false, + false, + false + ] + }, + "hash": "9f90a0a4125b00161e377a19a73020cd6fd3ea903470e9b153d02352b12118cc" +} diff --git a/.sqlx/query-0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4.json b/.sqlx/query-a3db9a0caa7b47888741c892b1bdee2772a3590e71d0e0a23fcecb8dba228e81.json similarity index 80% rename from .sqlx/query-0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4.json rename to .sqlx/query-a3db9a0caa7b47888741c892b1bdee2772a3590e71d0e0a23fcecb8dba228e81.json index bf05a39..7a8529a 100644 --- a/.sqlx/query-0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4.json +++ b/.sqlx/query-a3db9a0caa7b47888741c892b1bdee2772a3590e71d0e0a23fcecb8dba228e81.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course\n WHERE class = $1 AND course = $2\n AND source = (SELECT id FROM class_blueprint WHERE grade = $3)\n FOR UPDATE", + "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course\n WHERE class = $1 AND course = $2\n AND source = (SELECT id FROM class_blueprint WHERE grade_level = $3)\n FOR UPDATE", "describe": { "columns": [ { @@ -19,12 +19,12 @@ "Left": [ "Uuid", "Uuid", - "Text" + "Int2" ] }, "nullable": [ false ] }, - "hash": "0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4" + "hash": "a3db9a0caa7b47888741c892b1bdee2772a3590e71d0e0a23fcecb8dba228e81" } diff --git a/.sqlx/query-a63cae3c38fc5ab52786505d1944169bab3769effe0dccbed8587f89d788a1f2.json b/.sqlx/query-a63cae3c38fc5ab52786505d1944169bab3769effe0dccbed8587f89d788a1f2.json new file mode 100644 index 0000000..e441cde --- /dev/null +++ b/.sqlx/query-a63cae3c38fc5ab52786505d1944169bab3769effe0dccbed8587f89d788a1f2.json @@ -0,0 +1,88 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade_level AS \"grade_level: GradeLevel\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE grade_level = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "creator" + } + } + }, + { + "ordinal": 2, + "name": "name: ClassName", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_group", + "name": "name" + } + } + }, + { + "ordinal": 3, + "name": "grade_level: GradeLevel", + "type_info": "Int2", + "origin": { + "Table": { + "table": "class_group", + "name": "grade_level" + } + } + }, + { + "ordinal": 4, + "name": "year: AcademicYearId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "year" + } + } + }, + { + "ordinal": 5, + "name": "teacher: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "teacher" + } + } + } + ], + "parameters": { + "Left": [ + "Int2" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + true + ] + }, + "hash": "a63cae3c38fc5ab52786505d1944169bab3769effe0dccbed8587f89d788a1f2" +} diff --git a/.sqlx/query-cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7.json b/.sqlx/query-a7aed9e7c0d53a5e944ad27f13c7dcc078b9ce93ba209d3b2ca1d16382b62f45.json similarity index 70% rename from .sqlx/query-cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7.json rename to .sqlx/query-a7aed9e7c0d53a5e944ad27f13c7dcc078b9ce93ba209d3b2ca1d16382b62f45.json index 749c634..885b4f5 100644 --- a/.sqlx/query-cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7.json +++ b/.sqlx/query-a7aed9e7c0d53a5e944ad27f13c7dcc078b9ce93ba209d3b2ca1d16382b62f45.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE class_group SET class_course_count = class_course_count + 1\n WHERE id = $1 AND class_course_count < $2\n RETURNING 1)\n INSERT INTO class_course (id, class, course, attached_by, attached_at, source)\n SELECT $3, $1, $4, $5, $6, $7 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"", + "query": "WITH seat AS (\n UPDATE class_group SET class_course_count = class_course_count + 1\n WHERE id = $1 AND class_course_count < $2\n RETURNING 1)\n INSERT INTO class_course (id, class, course, attached_by, attached_at, source, offering)\n SELECT $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"", "describe": { "columns": [ { @@ -18,6 +18,7 @@ "Uuid", "Uuid", "Int8", + "Uuid", "Uuid" ] }, @@ -25,5 +26,5 @@ null ] }, - "hash": "cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7" + "hash": "a7aed9e7c0d53a5e944ad27f13c7dcc078b9ce93ba209d3b2ca1d16382b62f45" } diff --git a/.sqlx/query-a8ca6711e03ab03d9d6526c95853c5b62ea7b6ac7f3046b6fd1c784cb5979618.json b/.sqlx/query-a8ca6711e03ab03d9d6526c95853c5b62ea7b6ac7f3046b6fd1c784cb5979618.json new file mode 100644 index 0000000..4aed6e3 --- /dev/null +++ b/.sqlx/query-a8ca6711e03ab03d9d6526c95853c5b62ea7b6ac7f3046b6fd1c784cb5979618.json @@ -0,0 +1,36 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT kind, weight::bigint AS \"weight!: i64\"\n FROM class_course_exam_weight WHERE class_course = $1 AND kind = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "kind", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_course_exam_weight", + "name": "kind" + } + } + }, + { + "ordinal": 1, + "name": "weight!: i64", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "a8ca6711e03ab03d9d6526c95853c5b62ea7b6ac7f3046b6fd1c784cb5979618" +} diff --git a/.sqlx/query-a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3.json b/.sqlx/query-a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3.json deleted file mode 100644 index c11596d..0000000 --- a/.sqlx/query-a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.id = $1", - "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": "attached_by: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_course", - "name": "attached_by" - } - } - }, - { - "ordinal": 4, - "name": "source?: ClassBlueprintId", - "type_info": "Text", - "origin": { - "Table": { - "table": "class_blueprint", - "name": "grade" - } - } - }, - { - "ordinal": 5, - "name": "ders_saati!: DersSaati", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 6, - "name": "counts_toward_karne", - "type_info": "Bool", - "origin": { - "Table": { - "table": "class_course", - "name": "counts_toward_karne" - } - } - }, - { - "ordinal": 7, - "name": "enrollment_count", - "type_info": "Int8", - "origin": { - "Table": { - "table": "class_course", - "name": "enrollment_count" - } - } - }, - { - "ordinal": 8, - "name": "attached_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "class_course", - "name": "attached_at" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - false, - false, - false, - false, - true, - null, - false, - false, - false - ] - }, - "hash": "a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3" -} diff --git a/.sqlx/query-a91d1a048aed0671318c7c2faf3537a93f34014875f1df15279d500f0c2927e7.json b/.sqlx/query-a91d1a048aed0671318c7c2faf3537a93f34014875f1df15279d500f0c2927e7.json new file mode 100644 index 0000000..29c5cd5 --- /dev/null +++ b/.sqlx/query-a91d1a048aed0671318c7c2faf3537a93f34014875f1df15279d500f0c2927e7.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM offering_slot WHERE id = $1 AND offering = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "a91d1a048aed0671318c7c2faf3537a93f34014875f1df15279d500f0c2927e7" +} diff --git a/.sqlx/query-ab7ce121deae040653c2886cda93146a6c02d1d932da63f364a78a56dee79eed.json b/.sqlx/query-ab7ce121deae040653c2886cda93146a6c02d1d932da63f364a78a56dee79eed.json new file mode 100644 index 0000000..4977f1d --- /dev/null +++ b/.sqlx/query-ab7ce121deae040653c2886cda93146a6c02d1d932da63f364a78a56dee79eed.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: CourseOfferingId\" FROM course_offering WHERE id = $1\n FOR NO KEY UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: CourseOfferingId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "ab7ce121deae040653c2886cda93146a6c02d1d932da63f364a78a56dee79eed" +} diff --git a/.sqlx/query-ad70c205e5c81bbb3fb230215a00fbb18af95e8b1bb437b87bd31e38fb804bdc.json b/.sqlx/query-ad70c205e5c81bbb3fb230215a00fbb18af95e8b1bb437b87bd31e38fb804bdc.json new file mode 100644 index 0000000..bd33994 --- /dev/null +++ b/.sqlx/query-ad70c205e5c81bbb3fb230215a00fbb18af95e8b1bb437b87bd31e38fb804bdc.json @@ -0,0 +1,64 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT s.id AS \"id: SubjectId\",\n s.course AS \"course: CourseId\",\n s.name AS \"name: SubjectName\",\n s.description AS \"description: SubjectDescription\"\n FROM class_course_subject ccs\n JOIN subject s ON s.id = ccs.subject\n WHERE ccs.class_course = $1\n ORDER BY s.name ASC, s.id ASC", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: SubjectId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "subject", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "subject", + "name": "course" + } + } + }, + { + "ordinal": 2, + "name": "name: SubjectName", + "type_info": "Text", + "origin": { + "Table": { + "table": "subject", + "name": "name" + } + } + }, + { + "ordinal": 3, + "name": "description: SubjectDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "subject", + "name": "description" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "ad70c205e5c81bbb3fb230215a00fbb18af95e8b1bb437b87bd31e38fb804bdc" +} diff --git a/.sqlx/query-b026b654310663a018f93884e2a015ab473efa48671c58ff10f33ed8b89dc803.json b/.sqlx/query-b026b654310663a018f93884e2a015ab473efa48671c58ff10f33ed8b89dc803.json new file mode 100644 index 0000000..ce8f272 --- /dev/null +++ b/.sqlx/query-b026b654310663a018f93884e2a015ab473efa48671c58ff10f33ed8b89dc803.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT kind AS \"kind: CourseKind\" FROM course WHERE id = $1 FOR KEY SHARE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "kind: CourseKind", + "type_info": "Text", + "origin": { + "Table": { + "table": "course", + "name": "kind" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "b026b654310663a018f93884e2a015ab473efa48671c58ff10f33ed8b89dc803" +} diff --git a/.sqlx/query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.json b/.sqlx/query-b3e310ca3331217df9d486461ce82cb568bbcfcb88386270920f3eb6579a526e.json similarity index 65% rename from .sqlx/query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.json rename to .sqlx/query-b3e310ca3331217df9d486461ce82cb568bbcfcb88386270920f3eb6579a526e.json index 929f610..2f85364 100644 --- a/.sqlx/query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.json +++ b/.sqlx/query-b3e310ca3331217df9d486461ce82cb568bbcfcb88386270920f3eb6579a526e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"key: uuid::Uuid\", grade AS \"grade: ClassGrade\",\n creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade = $1 FOR UPDATE", + "query": "SELECT id AS \"key: uuid::Uuid\", grade_level AS \"grade_level: GradeLevel\",\n creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade_level = $1 FOR UPDATE", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "grade: ClassGrade", - "type_info": "Text", + "name": "grade_level: GradeLevel", + "type_info": "Int2", "origin": { "Table": { "table": "class_blueprint", - "name": "grade" + "name": "grade_level" } } }, @@ -39,7 +39,7 @@ ], "parameters": { "Left": [ - "Text" + "Int2" ] }, "nullable": [ @@ -48,5 +48,5 @@ false ] }, - "hash": "5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c" + "hash": "b3e310ca3331217df9d486461ce82cb568bbcfcb88386270920f3eb6579a526e" } diff --git a/.sqlx/query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.json b/.sqlx/query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.json new file mode 100644 index 0000000..b99935e --- /dev/null +++ b/.sqlx/query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.json @@ -0,0 +1,54 @@ +{ + "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", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: WeeklySlotId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "offering_slot", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "weekday: Weekday", + "type_info": "Int2", + "origin": { + "Table": { + "table": "offering_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" + ] + }, + "nullable": [ + false, + false, + null, + null + ] + }, + "hash": "b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9" +} diff --git a/.sqlx/query-bd186c14f1a5c0dc4b4f7fb543ebd4484136dd6aa75069f987075137e1b99b00.json b/.sqlx/query-bd186c14f1a5c0dc4b4f7fb543ebd4484136dd6aa75069f987075137e1b99b00.json new file mode 100644 index 0000000..2a10766 --- /dev/null +++ b/.sqlx/query-bd186c14f1a5c0dc4b4f7fb543ebd4484136dd6aa75069f987075137e1b99b00.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO offering_exam_weight (offering, kind, weight)\n VALUES ($1, $2, $3::bigint::smallint)\n ON CONFLICT (offering, kind) DO UPDATE SET weight = EXCLUDED.weight", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "bd186c14f1a5c0dc4b4f7fb543ebd4484136dd6aa75069f987075137e1b99b00" +} diff --git a/.sqlx/query-d692aa84085905ea3e70d4a94b5e81ff85548c6aeb096ee914d5349bf525137a.json b/.sqlx/query-d692aa84085905ea3e70d4a94b5e81ff85548c6aeb096ee914d5349bf525137a.json new file mode 100644 index 0000000..c9ff34a --- /dev/null +++ b/.sqlx/query-d692aa84085905ea3e70d4a94b5e81ff85548c6aeb096ee914d5349bf525137a.json @@ -0,0 +1,131 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: CourseOfferingId\",\n course AS \"course: CourseId\",\n grade_level AS \"grade_level: GradeLevel\",\n title AS \"title?: CourseTitle\",\n description AS \"description?: CourseDescription\",\n default_ders_saati::bigint AS \"default_ders_saati?: DersSaati\",\n default_counts_toward_karne,\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\",\n updated_at AS \"updated_at: Timestamp\"\n FROM course_offering WHERE id = ANY($1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: CourseOfferingId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "course" + } + } + }, + { + "ordinal": 2, + "name": "grade_level: GradeLevel", + "type_info": "Int2", + "origin": { + "Table": { + "table": "course_offering", + "name": "grade_level" + } + } + }, + { + "ordinal": 3, + "name": "title?: CourseTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_offering", + "name": "title" + } + } + }, + { + "ordinal": 4, + "name": "description?: CourseDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_offering", + "name": "description" + } + } + }, + { + "ordinal": 5, + "name": "default_ders_saati?: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "default_counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "course_offering", + "name": "default_counts_toward_karne" + } + } + }, + { + "ordinal": 7, + "name": "created_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_offering", + "name": "created_by" + } + } + }, + { + "ordinal": 8, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_offering", + "name": "created_at" + } + } + }, + { + "ordinal": 9, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_offering", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false, + false, + false, + true, + true, + null, + true, + false, + false, + false + ] + }, + "hash": "d692aa84085905ea3e70d4a94b5e81ff85548c6aeb096ee914d5349bf525137a" +} diff --git a/.sqlx/query-d863a8f429da502da7981c356a262f553ea0b23b4fd1569241119aac0f8d62cc.json b/.sqlx/query-d863a8f429da502da7981c356a262f553ea0b23b4fd1569241119aac0f8d62cc.json new file mode 100644 index 0000000..8b778e0 --- /dev/null +++ b/.sqlx/query-d863a8f429da502da7981c356a262f553ea0b23b4fd1569241119aac0f8d62cc.json @@ -0,0 +1,36 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT kind, weight::bigint AS \"weight!: i64\"\n FROM offering_exam_weight WHERE offering = $1 AND kind = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "kind", + "type_info": "Text", + "origin": { + "Table": { + "table": "offering_exam_weight", + "name": "kind" + } + } + }, + { + "ordinal": 1, + "name": "weight!: i64", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "d863a8f429da502da7981c356a262f553ea0b23b4fd1569241119aac0f8d62cc" +} diff --git a/.sqlx/query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.json b/.sqlx/query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.json new file mode 100644 index 0000000..795c7a6 --- /dev/null +++ b/.sqlx/query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.json @@ -0,0 +1,58 @@ +{ + "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\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: WeeklySlotId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "offering_slot", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "weekday: Weekday", + "type_info": "Int2", + "origin": { + "Table": { + "table": "offering_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": "d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738" +} diff --git a/.sqlx/query-e0876982733c62617ab8446239526f4da6f49846a4e7ee948a173ef54aafed1a.json b/.sqlx/query-e0876982733c62617ab8446239526f4da6f49846a4e7ee948a173ef54aafed1a.json new file mode 100644 index 0000000..e737428 --- /dev/null +++ b/.sqlx/query-e0876982733c62617ab8446239526f4da6f49846a4e7ee948a173ef54aafed1a.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.class = 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": "e0876982733c62617ab8446239526f4da6f49846a4e7ee948a173ef54aafed1a" +} diff --git a/.sqlx/query-e17820680b6881ea134fe37906611bc25d774d21850be124025fda552104867b.json b/.sqlx/query-e17820680b6881ea134fe37906611bc25d774d21850be124025fda552104867b.json new file mode 100644 index 0000000..cc73c79 --- /dev/null +++ b/.sqlx/query-e17820680b6881ea134fe37906611bc25d774d21850be124025fda552104867b.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT kind, weight::bigint AS \"weight!: i64\"\n FROM offering_exam_weight WHERE offering = $1\n ORDER BY kind", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "kind", + "type_info": "Text", + "origin": { + "Table": { + "table": "offering_exam_weight", + "name": "kind" + } + } + }, + { + "ordinal": 1, + "name": "weight!: i64", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "e17820680b6881ea134fe37906611bc25d774d21850be124025fda552104867b" +} diff --git a/.sqlx/query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.json b/.sqlx/query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.json new file mode 100644 index 0000000..8c91e8a --- /dev/null +++ b/.sqlx/query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.json @@ -0,0 +1,54 @@ +{ + "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", + "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" + ] + }, + "nullable": [ + false, + false, + null, + null + ] + }, + "hash": "e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351" +} diff --git a/.sqlx/query-e6c03c7c747131bd9060a3f8a8eff1cf34e8727b6c3ac7222620b87b0dc1eeb1.json b/.sqlx/query-e6c03c7c747131bd9060a3f8a8eff1cf34e8727b6c3ac7222620b87b0dc1eeb1.json new file mode 100644 index 0000000..8794d8d --- /dev/null +++ b/.sqlx/query-e6c03c7c747131bd9060a3f8a8eff1cf34e8727b6c3ac7222620b87b0dc1eeb1.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT 1 AS \"one\" FROM course_offering WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "one", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "e6c03c7c747131bd9060a3f8a8eff1cf34e8727b6c3ac7222620b87b0dc1eeb1" +} diff --git a/.sqlx/query-5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b.json b/.sqlx/query-e8784821e75fe4ab681ff91695d953af6c4abd32821251f7804ef02c4e637cf8.json similarity index 79% rename from .sqlx/query-5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b.json rename to .sqlx/query-e8784821e75fe4ab681ff91695d953af6c4abd32821251f7804ef02c4e637cf8.json index ff8d6cc..8607f82 100644 --- a/.sqlx/query-5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b.json +++ b/.sqlx/query-e8784821e75fe4ab681ff91695d953af6c4abd32821251f7804ef02c4e637cf8.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT class AS \"class: ClassGroupId\", course AS \"course: CourseId\"\n FROM class_course\n WHERE source = (SELECT id FROM class_blueprint WHERE grade = $1)\n AND course <> ALL($2)", + "query": "SELECT class AS \"class: ClassGroupId\", course AS \"course: CourseId\"\n FROM class_course\n WHERE source = (SELECT id FROM class_blueprint WHERE grade_level = $1)\n AND course <> ALL($2)", "describe": { "columns": [ { @@ -28,7 +28,7 @@ ], "parameters": { "Left": [ - "Text", + "Int2", "UuidArray" ] }, @@ -37,5 +37,5 @@ false ] }, - "hash": "5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b" + "hash": "e8784821e75fe4ab681ff91695d953af6c4abd32821251f7804ef02c4e637cf8" } diff --git a/.sqlx/query-eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e.json b/.sqlx/query-eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e.json deleted file mode 100644 index a7f553e..0000000 --- a/.sqlx/query-eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE grade = $1", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: ClassGroupId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_group", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "creator: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_group", - "name": "creator" - } - } - }, - { - "ordinal": 2, - "name": "name: ClassName", - "type_info": "Text", - "origin": { - "Table": { - "table": "class_group", - "name": "name" - } - } - }, - { - "ordinal": 3, - "name": "grade: ClassGrade", - "type_info": "Text", - "origin": { - "Table": { - "table": "class_group", - "name": "grade" - } - } - }, - { - "ordinal": 4, - "name": "year: AcademicYearId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_group", - "name": "year" - } - } - }, - { - "ordinal": 5, - "name": "teacher: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_group", - "name": "teacher" - } - } - } - ], - "parameters": { - "Left": [ - "Text" - ] - }, - "nullable": [ - false, - false, - false, - true, - true, - true - ] - }, - "hash": "eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e" -} diff --git a/.sqlx/query-b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f.json b/.sqlx/query-f0638db11ad696e78ee6a72951c1983881eafa5fafeb80813293bd778717080f.json similarity index 81% rename from .sqlx/query-b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f.json rename to .sqlx/query-f0638db11ad696e78ee6a72951c1983881eafa5fafeb80813293bd778717080f.json index 60ae29d..270ec14 100644 --- a/.sqlx/query-b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f.json +++ b/.sqlx/query-f0638db11ad696e78ee6a72951c1983881eafa5fafeb80813293bd778717080f.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE year = $1 ORDER BY id", + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade_level AS \"grade_level: GradeLevel\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = $1", "describe": { "columns": [ { @@ -38,12 +38,12 @@ }, { "ordinal": 3, - "name": "grade: ClassGrade", - "type_info": "Text", + "name": "grade_level: GradeLevel", + "type_info": "Int2", "origin": { "Table": { "table": "class_group", - "name": "grade" + "name": "grade_level" } } }, @@ -79,10 +79,10 @@ false, false, false, - true, + false, true, true ] }, - "hash": "b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f" + "hash": "f0638db11ad696e78ee6a72951c1983881eafa5fafeb80813293bd778717080f" } diff --git a/.sqlx/query-f085293284bed3226150271a91561f7c1d3953b66c413aa1b0f0349fa350f8ab.json b/.sqlx/query-f085293284bed3226150271a91561f7c1d3953b66c413aa1b0f0349fa350f8ab.json new file mode 100644 index 0000000..812ae86 --- /dev/null +++ b/.sqlx/query-f085293284bed3226150271a91561f7c1d3953b66c413aa1b0f0349fa350f8ab.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT kind, weight::bigint AS \"weight!: i64\"\n FROM class_course_exam_weight WHERE class_course = $1\n ORDER BY kind", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "kind", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_course_exam_weight", + "name": "kind" + } + } + }, + { + "ordinal": 1, + "name": "weight!: i64", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "f085293284bed3226150271a91561f7c1d3953b66c413aa1b0f0349fa350f8ab" +} diff --git a/.sqlx/query-f46c1dcb86e2a1a7a542afaed21054de776315e010bfd709f5408df7259ed02b.json b/.sqlx/query-f46c1dcb86e2a1a7a542afaed21054de776315e010bfd709f5408df7259ed02b.json new file mode 100644 index 0000000..3a381a4 --- /dev/null +++ b/.sqlx/query-f46c1dcb86e2a1a7a542afaed21054de776315e010bfd709f5408df7259ed02b.json @@ -0,0 +1,31 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH flipped AS (\n UPDATE class_course\n SET subjects_inherited = FALSE\n WHERE id = $1\n RETURNING id\n ), inserted AS (\n INSERT INTO class_course_subject (class_course, subject)\n SELECT $1, $2\n WHERE EXISTS (SELECT 1 FROM flipped)\n ON CONFLICT DO NOTHING\n RETURNING subject\n )\n SELECT EXISTS (SELECT 1 FROM flipped) AS \"live!\",\n EXISTS (SELECT 1 FROM inserted) AS \"added!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "live!", + "type_info": "Bool", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "added!", + "type_info": "Bool", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + null, + null + ] + }, + "hash": "f46c1dcb86e2a1a7a542afaed21054de776315e010bfd709f5408df7259ed02b" +} diff --git a/README.md b/README.md index f0e80b5..98fb412 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,17 @@ teaching happens in the **instance** — one class section × one course, create when the course is attached to the section (`POST /classes/{id}/instances`) and living at `/instances/{id}` with its own `ders_saati` (weekly lesson hours, its weight in the karne average), `counts_toward_karne` flag, teachers, roster, -exams, lesson sessions and homework. Two sections that attach Matematik get +exams, lesson sessions and homework. Between catalog and instance sits the +**grade-level template**: attaching a course to a section resolves (or mints) +an **offering** (`/offerings`) — one row per course × `grade_level` carrying +the grade's title, description, weekly-hours and report-card defaults, syllabus +topics, exam-kind weights and weekly plan. The instance **overrides or +inherits**, never merges: an unset scalar follows the offering (and through it +the catalog row or the constant), a set is flag-driven and authoritative even +when empty, and every instance-scoped read — instance, marks, attendance, +karne — displays the **resolved** result, so a 9th-grade and a 12th-grade +section teaching the same ders each show their own grade's content. Two sections +that attach Matematik get **two** instances and share nothing: adding a student to 5-A enrolls them in 5-A's Matematik only, and an exam written on 5-A's Matematik is invisible to 5-B — unless the exam is **announced** to 5-B as an *ortak sınav* @@ -723,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 220 published +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 239 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 @@ -1213,8 +1223,8 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/chatbot/threads/{id}/messages` | student | Ask the chatbot: `{content}`, at most the school's `max_chatbot_message_len`. Answers `202 {message_id, status: "pending"}` the moment both rows are written — the answer itself lands later, in the reserved assistant row. `503` when no AI service offers `chat.reply`, and nothing is written; `429` + `Retry-After` over the per-user send limit. | | GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn. The non-SSE fallback for `/stream`, reading the same row — including the projection that presents a long-stale `pending` as `failed`, so the two can never disagree about a turn's state. | | GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a single `done` carrying the finished message, or one `error`. The stream closes after `done`/`error` — one stream per turn, not per thread. | -| GET | `/classes` | teacher | List every class, newest first. Requires teacher+. `?grade=` narrows to one grade label, matched exactly as written — the label a blueprint is keyed by, so this is the read that shows which sections a `POST /classes/blueprints` pump covered (and `?grade=` on its own lists the sections with no grade at all). An unknown label is an empty page, not a `404`. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope whose `total` counts every class under the same filter, not just this page. | -| POST | `/classes` | manager | Create a class. Requires manager+ — a class is school structure, not a teacher's own room. `grade` is a free-text label for the year ("9", "10-A"), `year` links the academic year (which is what binds the class to a report card and to the rollover), `teacher_id` names the homeroom teacher (a teacher+ account); all optional. | +| GET | `/classes` | teacher | List every class, newest first. Requires teacher+. `?grade_level=` narrows to one ladder rung — the same equality a blueprint is keyed by, so this is the read that shows which sections a `POST /classes/blueprints` pump covered. An unknown rung is an empty page, not a `404`. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope whose `total` counts every class under the same filter, not just this page. | +| POST | `/classes` | manager | Create a class. Requires manager+ — a class is school structure, not a teacher's own room. `grade_level` is the class's rung on the grade ladder (`0` = anaokulu, `1..=12`), `year` links the academic year (which is what binds the class to a report card and to the rollover), `teacher_id` names the homeroom teacher (a teacher+ account); all optional. | | GET | `/classes/blueprints` | manager | List every grade blueprint, by grade label. Requires manager+. Paged via `?limit=&offset=` (omit `limit` for all of them). | | POST | `/classes/blueprints` | manager | Create a grade's course blueprint and stock every class section already at that grade with it. Requires manager+. | | GET | `/classes/blueprints/{grade}` | manager | Fetch one grade's blueprint. Requires manager+. | @@ -1287,7 +1297,7 @@ window filtering, before paging; negative values are a `400` naming the field. | DELETE | `/exams/{id}/audience/{instance}` | teacher | Withdraw an exam from one instance's audience. Requires teacher+ and management rights over the exam's **owner** instance, like the announce itself. The owner's own pair is not withdrawable (`400`) — that is the instance the exam belongs to, and deleting the exam is what ends it; an archived year refuses the withdrawal with the same `409` its other writes answer. A pair that holds no audience row is a `404`. | | GET | `/exams/{id}/live` | teacher | A one-shot live snapshot of the exam: who's in, who's still writing (and on which sitting), who walked out of the room (`left_at`), who never showed at all (`absent`, once the window is over), time each student has left, and marks as they land — the roster of every instance the exam is addressed to, so an announced-to section's sitters are here too. Requires teacher+ and management rights over the exam's instance. Poll it to keep a monitor up to date. | | GET | `/exams/{id}/questions` | teacher | The exam's question list, `correct` choice ids included — the answer key, paged via `?limit=&offset=` (omit `limit` for the whole list). Requires teacher+ and management rights over the exam's instance. Students read questions through `GET /exams/{id}/attempt/questions`. Returns a `{items, total, limit, offset}` envelope. | -| POST | `/exams/{id}/questions` | teacher | Add a question to an exam. Requires teacher+ and management rights over the exam's instance. `subject_id` must name one of the subjects of that instance's catalog course (`GET /courses/{id}/subjects`) — every question belongs to a subject. `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` questions carry neither. Locked once attempts exist. | +| POST | `/exams/{id}/questions` | teacher | Add a question to an exam. Requires teacher+ and management rights over the exam's instance. `subject_id` must name one of the subjects the instance actually *teaches* — its resolved subject set (the offering's selection, or the section's own while it overrides; `GET /instances/{id}/subjects`) — and in every case a subject of the instance's catalog course. Every question belongs to a subject. `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` questions carry neither. Locked once attempts exist. | | POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a bank template into this exam as a fresh question. Requires teacher+, management rights over the exam's instance, and a template the caller may see (their own, or one published to the school) — anything else is a 404. `subject_id` must name one of the subjects of the instance's catalog course — the template's own subject is origin metadata and does not carry over. The template (and its blobs) stay untouched; a full copy — text, points, spec, illustration, and option pictures — lands under a new question id. Locked once attempts exist. | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question. Requires teacher+ and management rights over the exam's instance. Omitted fields keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so a kind switch must bring the matching fields along. `subject_id` re-tags within the instance's catalog course. Locked once attempts exist. An omitted `subject_id` is filled from the stored row, so any edit here — not just a re-tag — is refused with a `409` when someone else moved the question's subject after the caller read it. | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Remove a question (and every answer to it). Requires teacher+ and management rights over the exam's instance. Locked once attempts exist. | @@ -1316,7 +1326,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/homework` | student | List the homework across the caller's instances — their "my homework" view — paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every instance's homework; a teacher sees the homework of instances they run; a student sees only the homework they are assigned (whole-roster ones plus any subset that names them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. | | GET | `/homework/report/{user}` | teacher | A student's homework report across the instances their class section carries, paged via `?limit=&offset=` (omit `limit` for all of it): one row per homework in their audience — submitted/late/missing state plus the grade once one exists. Statuses and marks, never the submitted files (observers get the report, not the bytes). Requires teacher+, or a parent linked to the target student. Managers, admins, and parents see every instance; a teacher sees only the target's instances they manage. Returns a `{items, total, limit, offset}` envelope. | | GET | `/homework/{id}` | student | Fetch a single homework by id. Visible to whoever can view its instance (its enrolled students, its teachers, its class section's homeroom teacher, and managers/admins). A student the homework is *not* assigned to gets a 404 — the same no-leak an unseen exam draft gets, so a subset assignment never reveals itself to the students left out of it. To a caller without instance-management rights the `assigned` subset comes back narrowed to their own id: being named is theirs to know, the rest of the roster is not. | -| PATCH | `/homework/{id}` | teacher | Edit a homework's title, description, due date, subject, or assigned subset. Requires teacher+ and management rights over its instance. Omitted fields keep their value; a newly set `due_at` is re-checked against now and a new `subject_id` re-checked against the instance's course. Narrowing `assigned` is refused (409) while it would orphan an existing submission or result. | +| PATCH | `/homework/{id}` | teacher | Edit a homework's title, description, due date, subject, or assigned subset. Requires teacher+ and management rights over its instance. Omitted fields keep their value; a newly set `due_at` is re-checked against now and a new `subject_id` re-checked against the instance's resolved subject set (the offering's selection, or the section's own while it overrides). Narrowing `assigned` is refused (409) while it would orphan an existing submission or result. | | DELETE | `/homework/{id}` | teacher | Delete a homework and everything under it — submissions, their files, and results — then unlink the file blobs from disk. Requires teacher+ and management rights over its instance. The cascade is one transaction whose homework-row lock keeps a submission from landing under the homework mid-delete; the blob names are collected inside that transaction, before the rows are wiped, and removed after, so a crash in between strands at worst an unreachable file. | | GET | `/homework/{id}/result` | student | The caller's own grade for a homework. Any authenticated user may read their own; `404` while ungraded (or when the homework doesn't exist). This is the one read a student graded `missing` *without* ever submitting has — their submission endpoints 404 while nothing is submitted. | | POST | `/homework/{id}/results` | teacher | Record (or overwrite) a student's grade for a homework: a status (`done`/`incomplete`/`missing`) plus an optional 0–100 mark. Requires teacher+ and management rights over the homework's instance; the target must be a live student, enrolled in the instance, and in the homework's audience. Nobody grades themselves. Grading before the due date, or before any submission exists (`missing` for work never handed in), is allowed. A stored grade freezes the student's submission until it is removed. | @@ -1346,18 +1356,31 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/insights/sweep` | manager | Delete every `zeka_*` row whose retention window has closed. | | GET | `/instances/me` | student | The instances the caller may act in or see, paged via `?limit=&offset=` (omit `limit` for all of them), newest first; returns a `{items, total, limit, offset}` envelope. The route a student reads to find the courses their section is being taught, and a teacher the ones they run. | | GET | `/instances/{id}` | student | Fetch one instance by id. Visible to its enrolled students, its assigned teachers, its section's homeroom teacher, and managers/admins. | -| PATCH | `/instances/{id}` | teacher | Update one instance's own policy. Requires teacher+ and a right over this instance: manager+, one of its assigned teachers, or its section's homeroom teacher. Omitted fields keep their value; both are non-clearable. | +| PATCH | `/instances/{id}` | teacher | Update one instance's own policy overrides. Requires teacher+ and a right over this instance: manager+, one of its assigned teachers, or its section's homeroom teacher. Omitted fields keep their value; a PATCH **sets**, it never clears — `POST /{id}/reset` is the clear door. | | GET | `/instances/{id}/enrollments` | teacher | List this instance's roster, paged via `?limit=&offset=` (omit `limit` for the whole roster). Requires teacher+ and a right over the instance — students see their own instances via `GET /instances/me`. Returns a `{items, total, limit, offset}` envelope. | | POST | `/instances/{id}/enrollments` | teacher | Enroll a student into this instance (idempotent upsert). Requires teacher+ and a right over the instance. Only students can be enrolled — enrollment is student membership, and it gates sitting exams, being graded, and the roster. The row is hand-placed (`source` `null`), so no section sweep can take it back. | | DELETE | `/instances/{id}/enrollments/{user}` | teacher | Unenroll a student from this instance. Requires teacher+ and a right over the instance. Existing exam results are kept (they disappear from the student's marks report until re-enrolled). | +| GET | `/instances/{id}/exam-weights` | student | The section's resolved exam-kind weights and its override switch. Visible to the same eyes as the rest of the instance's reads. | +| PATCH | `/instances/{id}/exam-weights` | teacher | Set (or rewrite) one kind's weight on the section — and take its weight set own: the flag flips in the same statement, so from here on the section's own rows (these included) are the whole map, even where they are absent. Requires teacher+ and a right over the instance (D10). | +| DELETE | `/instances/{id}/exam-weights` | teacher | The reset: drop every section weight row and follow the offering's set (then the settings, then 1) again. Idempotent. | +| DELETE | `/instances/{id}/exam-weights/{kind}` | teacher | Drop one kind's weight row from the section. Deleting still takes the set own — removing the last row *decides* on an empty set (every kind then weighs 1 here) rather than falling back. A kind with no row is a 404 that changes nothing. | | GET | `/instances/{id}/exams` | student | List one instance's exams, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the instance's enrolled students, its teachers, its section's homeroom teacher, and managers/admins — but drafts appear only to the instance's managers. Returns a `{items, total, limit, offset}` envelope. | | POST | `/instances/{id}/exams` | teacher | Create an exam inside one instance. Requires teacher+ and a right over the instance; the exam's marks count into the instance's average with its kind's weight (`GET /settings`) and into the term's report card named by `term`. Omit `mode` for an offline-graded exam nobody can sit; `sync`/`async` take a window (async also `duration_ms`), `open` is sittable anytime with an optional per-attempt `duration_ms`. `max_attempts` (default 1, `0` = unlimited) meters retakes and `allow_rejoin` (default `true`) is the exam-room door — both stay editable while the exam runs. Send `draft: true` to keep the exam private while it's still being written: only the instance's managers see it, and sitting and grading are blocked until it's published (`PATCH` `draft: false`). Only a class-delivered course (`kind` `course`) carries exams. | | GET | `/instances/{id}/homework` | student | List one instance's homework, newest first, paged via `?limit=&offset=` (omit `limit` for all of it). Visible to the instance's enrolled students, its teachers, and managers/admins — but a student sees only the homework they are assigned (whole-roster ones plus subsets that name them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. | | POST | `/instances/{id}/homework` | teacher | Assign homework inside one instance. Requires teacher+ and a right over the instance. The homework is tagged with one of the catalog course's subjects and given a future `due_at`; `assigned` optionally narrows it to a subset of the enrolled students (omit or empty = the whole roster). | +| POST | `/instances/{id}/reset` | teacher | Clear the named overrides back to inherit — the door a PATCH never is. Same gate as the PATCH: teacher+ with a right over this instance, and a live (non-archived) year. Resetting a set policy (`subjects`, `exam_weights`, `weekly_plan`) flips the section's flag back to *inherited*; deleting the section's own rows under it rides the child tables' own reset doors. | | GET | `/instances/{id}/sessions` | student | List one instance's lesson sessions, most recent first, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the instance's enrolled students, its teachers, and managers/admins. Returns a `{items, total, limit, offset}` envelope. | | POST | `/instances/{id}/sessions` | teacher | Create a lesson session inside one instance. Requires teacher+ and a right over the instance. The session's teacher defaults to the caller. | +| GET | `/instances/{id}/subjects` | student | The topics this section teaches, resolved override-or-inherit, with the switch: `subjects_inherited: false` means the listed set (even when empty) is the section's own and the offering's is ignored. Any signed-in session. | +| POST | `/instances/{id}/subjects` | teacher | Select a topic for this section's own set — the override. The switch flips to "own" in the same write, so the section's table (not the offering's set) becomes authoritative from this call on. Re-selecting an already selected topic is a no-op success. D10 gate; refuses on an archived year. | +| DELETE | `/instances/{id}/subjects` | teacher | Restore inheritance: sweep the section's own rows and flip `subjects_inherited` back to TRUE in the same statement — the offering's set applies again. A section whose own set was already empty resets cleanly. D10 gate; refuses on an archived year. | +| DELETE | `/instances/{id}/subjects/{subject}` | teacher | Drop one topic from this section's own set (keeping the set its own — clearing the syllabus needs the reset below, or deleting the last rows one by one). Dropping a topic the section never selected is a 404 and flips nothing. D10 gate; refuses on an archived year. | | POST | `/instances/{id}/teachers` | manager | Assign a teacher to this instance (idempotent). Manager+ only — staffing is the office's call. The assignee must already hold the `teacher` role or higher; the assignment gives them full management of the instance (exams, sessions, homework, roster, grading) but they keep no catalog rights over the course itself. | | DELETE | `/instances/{id}/teachers/{user}` | manager | Unassign a teacher from this instance. Manager+ only. The instance, its exams, sessions, and roster are untouched — the teacher just loses their management rights over it. A user who was never assigned is a 404. | +| GET | `/instances/{id}/weekly-plan` | student | The section's resolved weekly plan plus whose rows it is. Visible to the same eyes as the instance read: enrolled students, its teachers, its şube's homeroom teacher, and managers/admins. | +| POST | `/instances/{id}/weekly-plan` | teacher | Add one slot to the section's own week. Requires teacher+ and a right over the instance; the write flips `weekly_plan_inherited` to `false` in the same statement, so from here the section's own rows — not the offering's template — are what every read resolves. Same overlap and cap refusals as the offering side. | +| DELETE | `/instances/{id}/weekly-plan` | teacher | Reset the section's weekly plan to inherit — delete every slot of its own week and flip `weekly_plan_inherited` back to `true` in one statement, so the offering's template week is what every read resolves again. Idempotent for a section that never overrode. | +| DELETE | `/instances/{id}/weekly-plan/{slot}` | teacher | Drop one slot of the section's own week. Requires teacher+ and a right over the instance. The flag flip to `false` rides the delete in the same statement — dropping the last own row leaves the section with an authoritative *empty* plan, not a quiet return to the template (`DELETE /{id}/weekly-plan` is the way back to inherit). A slot of another instance, or one already gone, is a 404 that leaves the flag untouched. | | GET | `/limits` | no | Every fixed validation bound the API enforces. Unauthenticated: the registration and login forms need the username and password bounds before a session exists, and none of these values are secrets — they are the same rules a 400 would spell out. | | GET | `/marks/karne` | student | The current user's report card for one term: every instance of their sections that counts toward the report card, the `ders_saati`-weighted average across them, and the verdict. An archived term serves the snapshot the school froze when it was closed; an open one computes live. | | GET | `/marks/karne/{user}` | teacher | Any user's report card for one term. Requires teacher+, or a parent tied to the target student. A linked parent and manager+ read the whole report card; an exactly-teacher caller sees only the lines of the instances they run, with the term average recomputed over those and no verdict (see [`narrow_karne`]). | @@ -1400,6 +1423,20 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/notes/{id}/files` | student | Attach a file to a note owned by the current user. `multipart/form-data` with the file under a `file` field; its `filename` is required. At most 10 files per note; each file at most the school's `max_file_bytes` (settings, default 5 MiB). | | GET | `/notes/{id}/files/{file_id}` | student | Download a note file's bytes. `Content-Type` is the one declared on upload; `Content-Disposition` carries the original filename. | | DELETE | `/notes/{id}/files/{file_id}` | student | Delete a note file (row first, then its blob). | +| GET | `/offerings` | student | List the offerings, paged via `?limit=&offset=` (omit `limit` for all of them); optionally narrowed by `?course=` and/or `?grade_level=`. Returns a `{items, total, limit, offset}` envelope. | +| POST | `/offerings` | manager | Create the grade-level template for a course. Manager+. A course that is not a class-delivered ders has no grade axis and is refused (a club or etüt is joined individually, never attached); a template that already exists for the (course, grade) pair is a 409 `offering_exists`. | +| GET | `/offerings/{id}` | student | Fetch one offering by id. Any signed-in session. The body is the raw template row (nullable = inherit) — not the per-instance resolved view `GET /instances/{id}` serves. | +| PATCH | `/offerings/{id}` | manager | Field-scoped edit. Manager+. Omitted fields keep their value; an explicit `null` clears the override back to inherit (the catalog course's title or description, the constant 1 weekly hour, counted toward the karne); a value sets the grade's own. Instances that carry no override of their own follow the change immediately — that is what inherit means. | +| DELETE | `/offerings/{id}` | manager | Delete the template. Manager+. Refused with 409 `offering_in_use` while any class×course instance still teaches from it — detach the course from those classes first. Deleting a template no section uses erases only the grade's overrides; the instances keep existing (their next attach re-mints an empty template). | +| GET | `/offerings/{id}/exam-weights` | student | The grade-level template's resolved exam-kind weights. Any signed-in session. | +| PATCH | `/offerings/{id}/exam-weights` | manager | Set (or rewrite) one kind's weight on the template. Manager+. The kind must be one the school runs — a 400 carrying the machine code `unknown_exam_kind` otherwise; the weight must sit in 1..=100. Sections that still inherit the template pick the change up immediately. | +| DELETE | `/offerings/{id}/exam-weights/{kind}` | manager | Drop one kind's weight row from the template; the settings weight applies again. A kind with no row is a 404. | +| GET | `/offerings/{id}/subjects` | student | The offering's selected topics — the set every inheriting section at that grade teaches — by subject name then id. Any signed-in session. | +| POST | `/offerings/{id}/subjects` | manager | Select a topic for the offering. Manager+. Re-selecting an already selected topic is a no-op success (`200`, not a second row). | +| DELETE | `/offerings/{id}/subjects/{subject}` | manager | Drop a topic from the offering's selection. Manager+. Dropping a topic the offering never selected is a 404. | +| GET | `/offerings/{id}/weekly-plan` | student | List the offering's template week — weekday first, then start time. Any signed-in session, the same visibility as the offering read itself. | +| POST | `/offerings/{id}/weekly-plan` | manager | Add one slot to the offering's template week. Manager+. Refused with 409 `slot_overlap` when a template slot already occupies an intersecting window on that weekday (an exact duplicate overlaps too), 409 `slot_cap` when the week already holds the maximum. | +| DELETE | `/offerings/{id}/weekly-plan/{slot}` | manager | Drop one slot of the offering's template week. Manager+. A slot of another offering, or one already gone, is a 404. | | GET | `/payments/balance/me` | student | What the caller owes the school (or has on account). | | GET | `/payments/balance/{user}` | manager | One student's fee balance. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). | | POST | `/payments/credits` | manager | Record money received against one named charge. Allocation is recorded, not inferred: a payment always says which installment it settles. Partial payments accumulate; one that would take the charge past what it is worth is a `409`. A charge that was **reversed** takes no payment either — it is no longer owed — and that `409` says so, rather than reporting money that never arrived as "paid in full". | @@ -3490,12 +3527,15 @@ here: nothing refuses a roll-call row that pushes a student past them. A **class section** is the group a school actually teaches in — 9-A, 10-B — and it is the **academic anchor**: a student's membership, the courses it carries, -their exams and their homework all hang off it. Its row carries a name, an -optional free-text `grade` label in the school's own vocabulary (`"9"`, -`"Lise 2"`; `""` means no grade, exactly like omitting it) and the **academic -year** it runs in (`year`, nullable while a section is being prepared). A -section does not teach a course directly: attaching one mints an **instance** -(`/instances`) — its own row, with its own teachers, `ders_saati`, karne weight, +their exams and their homework all hang off it. Its row carries a name, its +rung on the school's grade ladder (`grade_level`, `0` = anaokulu, `1..=12` the +school years) and the **academic year** it runs in (`year`, nullable while a +section is being prepared). A section does not teach a course directly: +attaching one mints an **instance** +(`/instances`) — its own row, teaching from its grade's **offering** template +(`/offerings`, overridable per section: title, description, weekly hours, +report-card policy, syllabus, weights, weekly plan — unset fields inherit), +with its own teachers, `ders_saati`, karne weight, roster, exams, sessions and homework — and two sections that attach the same course share nothing at all. Schools that run electives or a college-style timetable simply never create one — individual enrollment and the school-scoped @@ -3675,9 +3715,9 @@ overloaded axis clears it. A Turkish school runs many şube at one grade and stocks each with the same courses. A blueprint says that list once: `POST /classes/blueprints` with a -`grade` label and `course_ids`, and every section already at that grade is +`grade_level` rung and `course_ids`, and every section already at that rung is stocked immediately. `POST /classes/{id}/blueprint` stocks one section from its -grade's template — idempotent, so it is safe on a class that already carries +rung's template — idempotent, so it is safe on a class that already carries some of the courses. The blueprint is a template, not a new kind of membership. Applying it calls diff --git a/src/constant.rs b/src/constant.rs index 95e9932..eb482e9 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -107,12 +107,17 @@ pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; pub const MAX_COURSE_TITLE_LEN: usize = 200; pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; -/// A class section is named like a course, but its optional `grade` is -/// a free-text label the school picks ("9", "10-A", "kindergarten") — a line of -/// display text, so it is bounded like the other short labels, not like a -/// description. +/// A class section is named like a course. `MAX_CLASS_GRADE_LEN` is gone with +/// the free-text grade it bounded: a class now carries a validated ladder +/// position (`MIN_GRADE_LEVEL`..=`MAX_GRADE_LEVEL`, `0` = anaokulu), which +/// needs a length bound no more than a week day does. pub const MAX_CLASS_NAME_LEN: usize = 200; -pub const MAX_CLASS_GRADE_LEN: usize = 20; + +/// The grade ladder every class section and course template sits on. `0` is +/// anaokulu (kindergarten), `1..=12` the school years; [`MAX_GRADE_LEVEL`] +/// graduating is expressed by the absence of a promotion, not a 13th rung. +pub const MIN_GRADE_LEVEL: i16 = 0; +pub const MAX_GRADE_LEVEL: i16 = 12; /// How big one class may get, on each of its two axes. These are not comfort /// numbers: attaching a course to a class writes one enrollment per member and @@ -137,6 +142,21 @@ pub const MAX_CLASS_COURSES: i64 = 50; pub const MIN_DERS_SAATI: i64 = 1; pub const MAX_DERS_SAATI: i64 = 40; +/// How many slots one owner's weekly plan may hold. A slot is where one of +/// the week's lesson hours lands, and a course teaches at most +/// `MAX_DERS_SAATI` (40) hours a week — so 40 bounds any honest timetable +/// (the bounds are the same number by construction) and stops a pathological +/// client at the bound every other weekly-hours loop already answers to. +pub const MAX_WEEKLY_SLOTS: usize = MAX_DERS_SAATI as usize; + +/// The earliest minute a weekly-plan slot may start or end: midnight. +pub const MIN_SLOT_MINUTE: i64 = 0; + +/// The latest minute a weekly-plan slot may start or end: 23:59. (A `TIME` +/// column has no `24:00` to carry a midnight end, and the +/// minutes-past-midnight wire form never lies about it.) +pub const MAX_SLOT_MINUTE: i64 = 24 * 60 - 1; + /// The default grade-display bands: the Turkish 5-point scale (85–100 = 5, /// … 0–44 = 1). Schools edit the list via `PATCH /settings`; the report-card /// verdict reads the band labelled `"2"` as the pass boundary. diff --git a/src/db/class_blueprint.rs b/src/db/class_blueprint.rs index a3fb46f..4596901 100644 --- a/src/db/class_blueprint.rs +++ b/src/db/class_blueprint.rs @@ -1,4 +1,4 @@ -//! The `class_blueprint` table: the row keyed by its grade label, the +//! The `class_blueprint` table: the row keyed by its ladder rung, the //! compare-and-set writes the edit and the delete go through, and the reads //! the sweep and the status screen are built on. The workflows that sequence //! these — and the row lock that serializes a delete against the attaches @@ -13,7 +13,8 @@ use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::class_pump; use crate::db::page::PagedList; use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId}; -use crate::domain::class_group::{ClassGrade, ClassGroupId}; +use crate::domain::class_group::ClassGroupId; +use crate::domain::grade::GradeLevel; use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_uuid; use crate::domain::user::UserId; @@ -29,17 +30,17 @@ struct BlueprintRow { /// The surrogate uuid primary key — the key the junction rows reference. #[sqlx(rename = "id")] key: uuid::Uuid, - grade: ClassGrade, + grade_level: GradeLevel, creator: UserId, } impl BlueprintRow { fn into_blueprint(self, courses: Vec) -> ClassBlueprint { ClassBlueprint { - // The API identity is the grade label, which the key column also - // stores — the id *is* the grade. - id: ClassBlueprintId::for_grade(&self.grade), - grade: self.grade, + // The API identity is the ladder rung, which the key column also + // stores — the id *is* the grade level. + id: ClassBlueprintId::for_grade(&self.grade_level), + grade_level: self.grade_level, courses, creator: self.creator, } @@ -155,16 +156,16 @@ fn no_such_course() -> AppError { /// carries a UNIQUE constraint, so the duplicate is seen rather than raced /// (`23505` on `class_blueprint_grade_key`, mapped right here: a duplicate is /// a decision, never a retry). The surrogate `id` is minted here and never -/// read back: the grade label stays the only identity the API speaks. +/// read back: the ladder rung stays the only identity the API speaks. pub async fn create( db: &Database, creator: &UserId, - grade: ClassGrade, + grade_level: GradeLevel, courses: Vec, ) -> Result { let blueprint = ClassBlueprint { - id: ClassBlueprintId::for_grade(&grade), - grade: grade.clone(), + id: ClassBlueprintId::for_grade(&grade_level), + grade_level, courses: courses.clone(), creator: *creator, }; @@ -173,10 +174,10 @@ pub async fn create( tx_with_retry(db, false, async move |tx| { courses_alive(tx, &courses).await?; let inserted = sqlx::query!( - r#"INSERT INTO class_blueprint (id, grade, creator) + r#"INSERT INTO class_blueprint (id, grade_level, creator) VALUES ($1, $2, $3)"#, id, - grade as _, + grade_level as _, creator as _ ) .execute(&mut *tx) @@ -209,9 +210,9 @@ pub async fn read( ) -> Result, AppError> { let row = sqlx::query_as!( BlueprintRow, - r#"SELECT id AS "key: uuid::Uuid", grade AS "grade: ClassGrade", + r#"SELECT id AS "key: uuid::Uuid", grade_level AS "grade_level: GradeLevel", creator AS "creator: UserId" - FROM class_blueprint WHERE grade = $1"#, + FROM class_blueprint WHERE grade_level = $1"#, id as _ ) .fetch_optional(db) @@ -225,14 +226,14 @@ pub async fn read( } } -/// Every blueprint, by grade label — the id *is* the label, so this is the +/// Every blueprint, by ladder rung — the id *is* the rung, so this is the /// only ordering that means anything here. pub async fn list_all( db: &Database, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - let (rows, total) = PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade ASC") + let (rows, total) = PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade_level ASC") .run::(limit, offset, db) .await?; Ok((with_courses(db, rows).await?, total)) @@ -261,17 +262,17 @@ pub async fn set_courses_if_unchanged( held: Vec, wanted: Vec, ) -> Result, AppError> { - let grade = id.clone(); + let grade = id.get(); let mut held = held; held.sort_by_key(|course| course.uuid()); let keys: Vec = wanted.iter().map(CourseId::uuid).collect(); tx_with_retry(db, false, async move |tx| { courses_alive(tx, &wanted).await?; let row = sqlx::query!( - r#"SELECT id AS "key: uuid::Uuid", grade AS "grade: ClassGrade", + r#"SELECT id AS "key: uuid::Uuid", grade_level AS "grade_level: GradeLevel", creator AS "creator: UserId" - FROM class_blueprint WHERE grade = $1 FOR UPDATE"#, - grade.key(), + FROM class_blueprint WHERE grade_level = $1 FOR UPDATE"#, + grade, ) .fetch_optional(&mut *tx) .await?; @@ -303,8 +304,8 @@ pub async fn set_courses_if_unchanged( .execute(&mut *tx) .await?; Ok(Some(ClassBlueprint { - id: ClassBlueprintId::for_grade(&row.grade), - grade: row.grade, + id: ClassBlueprintId::for_grade(&row.grade_level), + grade_level: row.grade_level, courses: wanted.clone(), creator: row.creator, })) @@ -328,9 +329,8 @@ pub async fn delete_if_unchanged( id: &ClassBlueprintId, held: Vec, ) -> Result { - let grade = id.clone(); tx_with_retry(db, false, async move |tx| { - delete_claimed(&mut *tx, &grade, &held).await + delete_claimed(&mut *tx, id, &held).await }) .await } @@ -361,7 +361,7 @@ async fn delete_claimed( ) -> Result { let row = sqlx::query!( r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint - WHERE grade = $1 FOR UPDATE"#, + WHERE grade_level = $1 FOR UPDATE"#, id as _, ) .fetch_optional(&mut *tx) @@ -398,7 +398,7 @@ pub(crate) async fn held_courses_for_update( ) -> Result>, AppError> { let row = sqlx::query!( r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint - WHERE grade = $1 FOR UPDATE"#, + WHERE grade_level = $1 FOR UPDATE"#, id as _, ) .fetch_optional(&mut *tx) @@ -466,7 +466,7 @@ pub async fn prune( sqlx::query!( r#"DELETE FROM blueprint_course WHERE course = $2 - AND blueprint = (SELECT id FROM class_blueprint WHERE grade = $1)"#, + AND blueprint = (SELECT id FROM class_blueprint WHERE grade_level = $1)"#, id as _, course as _, ) @@ -500,7 +500,7 @@ pub async fn sourced_links( let rows = sqlx::query!( r#"SELECT class AS "class: ClassGroupId", course AS "course: CourseId" FROM class_course - WHERE source = (SELECT id FROM class_blueprint WHERE grade = $1) + WHERE source = (SELECT id FROM class_blueprint WHERE grade_level = $1) AND course <> ALL($2)"#, id as _, keep as _ diff --git a/src/db/class_course.rs b/src/db/class_course.rs index 1481efa..756a053 100644 --- a/src/db/class_course.rs +++ b/src/db/class_course.rs @@ -4,35 +4,43 @@ //! [`crate::service::class_course`]; the transaction itself is the pump's, //! [`crate::db::class_pump`]. //! -//! An instance is the academic anchor now: it carries the weekly hours -//! (`ders_saati`), whether it counts toward the report card, the roster counter -//! its own teachers ([`crate::db::class_course_teacher`]). Reads speak the -//! *bare uuid* id of the instance; the (class, course) pair survives as the -//! UNIQUE key the attach gates on. +//! An instance is the academic anchor now: it points at its grade-level +//! **offering** template, carries its own content *overrides* (title, +//! description, and the nullable `ders_saati` / `counts_toward_karne` — a +//! `NULL` inherits from the offering chain, so every read goes through +//! [`crate::service::class_course::resolve_policy`], never a blind unwrap), +//! the three `*_inherited` set flags, and the roster counter its own teachers +//! ([`crate::db::class_course_teacher`]). Reads speak the *bare uuid* id of +//! the instance; the (class, course) pair survives as the UNIQUE key the +//! attach gates on. use crate::constant::CLASS_COURSE_TABLE; use crate::database::Database; use crate::db::class_pump::Attached; use crate::db::page::PagedList; use crate::domain::class_blueprint::ClassBlueprintId; -use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; +use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati, OverrideField}; use crate::domain::class_group::ClassGroupId; -use crate::domain::course::CourseId; +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; +use crate::domain::course_offering::CourseOfferingId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; /// The projection every instance read shares. /// -/// Two translations ride it: `source` is stored as the blueprint's surrogate +/// Three translations ride it: `source` is stored as the blueprint's surrogate /// uuid while the domain speaks the grade label the API does (a hand attach, -/// source NULL, survives the LEFT JOIN as NULL), and `ders_saati` is a +/// source NULL, survives the LEFT JOIN as NULL), `ders_saati` is a *nullable* /// `SMALLINT` column while [`DersSaati`] is an `i64` newtype — decoded /// through a `bigint` cast so the type the driver checks is the one the -/// newtype names. -const INSTANCE_COLUMNS: &str = "cc.id, cc.class, cc.course, cc.attached_by, \ - b.grade AS source, cc.ders_saati::bigint AS ders_saati, \ - cc.counts_toward_karne, cc.enrollment_count, cc.attached_at"; +/// newtype names, its `NULL` meaning *inherit* — and the overrides/flags ride +/// along as their plain column shapes. +const INSTANCE_COLUMNS: &str = "cc.id, cc.class, cc.course, cc.offering, cc.attached_by, \ + b.grade_level AS source, cc.title, cc.description, \ + cc.ders_saati::bigint AS ders_saati, cc.counts_toward_karne, \ + cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited, \ + cc.enrollment_count, cc.attached_at"; /// The attach itself, with the refusals left *unmapped*. /// @@ -117,10 +125,15 @@ pub async fn list_for_class_ids( let rows = sqlx::query_as!( ClassCourse, r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", - cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId", - b.grade AS "source?: ClassBlueprintId", - cc.ders_saati::bigint AS "ders_saati!: DersSaati", - cc.counts_toward_karne, cc.enrollment_count, + 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 @@ -146,10 +159,15 @@ pub async fn list_by_ids( let rows = sqlx::query_as!( ClassCourse, r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", - cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId", - b.grade AS "source?: ClassBlueprintId", - cc.ders_saati::bigint AS "ders_saati!: DersSaati", - cc.counts_toward_karne, cc.enrollment_count, + 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 @@ -167,10 +185,15 @@ pub async fn read(db: &Database, id: &ClassCourseId) -> Result Result, + description: Option, staff: Option, counts: Option, ) -> Result { - // `i64`, cast down by the statement itself: the column is a `SMALLINT` - // and the newtype wraps an `i64`, so naming both types explicitly is what - // keeps the driver's type check honest in either direction. + // `i64`, cast down by the statement itself: the column is a nullable + // `SMALLINT` and the newtype wraps an `i64`, so naming both types + // explicitly is what keeps the driver's type check honest in either + // direction. The text columns set-only via `COALESCE` for the same + // never-clears rule. let hours = staff.map(|hours| hours.as_i64()); + let title = title.map(|title| title.as_str().to_string()); + let description = description.map(|d| d.as_str().to_string()); let row = sqlx::query_as!( ClassCourse, r#"WITH updated AS ( UPDATE class_course - SET ders_saati = COALESCE($2::bigint, ders_saati::bigint)::smallint, - counts_toward_karne = COALESCE($3, counts_toward_karne) + SET title = COALESCE($2, title), + description = COALESCE($3, description), + ders_saati = COALESCE($4::bigint, ders_saati::bigint)::smallint, + counts_toward_karne = COALESCE($5, counts_toward_karne) WHERE id = $1 RETURNING *) SELECT u.id AS "id: ClassCourseId", u.class AS "class: ClassGroupId", - u.course AS "course: CourseId", u.attached_by AS "attached_by: UserId", - b.grade AS "source?: ClassBlueprintId", - u.ders_saati::bigint AS "ders_saati!: DersSaati", - u.counts_toward_karne, u.enrollment_count, + u.course AS "course: CourseId", u.offering AS "offering: CourseOfferingId", + u.attached_by AS "attached_by: UserId", + b.grade_level AS "source?: ClassBlueprintId", + u.title AS "title?: CourseTitle", + u.description AS "description?: CourseDescription", + u.ders_saati::bigint AS "ders_saati?: DersSaati", + u.counts_toward_karne, + u.subjects_inherited, u.exam_weights_inherited, u.weekly_plan_inherited, + u.enrollment_count, u.attached_at AS "attached_at: Timestamp" FROM updated u LEFT JOIN class_blueprint b ON b.id = u.source"#, id.uuid(), + title, + description, hours, counts, ) @@ -239,3 +277,66 @@ pub async fn update( .ok_or(AppError::NotFound)?; Ok(row) } + +/// Clear the named overrides back to **inherit**: the scalars go `NULL` (the +/// offering's default, then the constants, apply again) and a set flag goes +/// back to `TRUE` (the offering's set is authoritative again — deleting the +/// section's own set rows rides the child-table lanes' reset). The empty +/// request is refused by the service before it gets here; a gone instance is +/// the usual 404. +/// +/// The whole reset is one statement: the named clears are judged on the row +/// as it is *at the write*, so a PATCH landing between the caller's read and +/// this write cannot be silently reverted field-by-field. +pub async fn clear_overrides( + db: &Database, + id: &ClassCourseId, + fields: &[OverrideField], +) -> Result { + let title = fields.contains(&OverrideField::Title); + let description = fields.contains(&OverrideField::Description); + let staff = fields.contains(&OverrideField::DersSaati); + let counts = fields.contains(&OverrideField::CountsTowardKarne); + let subjects = fields.contains(&OverrideField::Subjects); + let exam_weights = fields.contains(&OverrideField::ExamWeights); + let weekly_plan = fields.contains(&OverrideField::WeeklyPlan); + let row = sqlx::query_as!( + ClassCourse, + r#"WITH updated AS ( + UPDATE class_course SET + title = CASE WHEN $2 THEN NULL ELSE title END, + description = CASE WHEN $3 THEN NULL ELSE description END, + ders_saati = CASE WHEN $4 THEN NULL ELSE ders_saati END, + counts_toward_karne = CASE WHEN $5 THEN NULL ELSE counts_toward_karne END, + subjects_inherited = CASE WHEN $6 THEN TRUE ELSE subjects_inherited END, + exam_weights_inherited = CASE WHEN $7 THEN TRUE ELSE exam_weights_inherited END, + weekly_plan_inherited = CASE WHEN $8 THEN TRUE ELSE weekly_plan_inherited END + WHERE id = $1 + RETURNING *) + SELECT u.id AS "id: ClassCourseId", u.class AS "class: ClassGroupId", + u.course AS "course: CourseId", u.offering AS "offering: CourseOfferingId", + u.attached_by AS "attached_by: UserId", + b.grade_level AS "source?: ClassBlueprintId", + u.title AS "title?: CourseTitle", + u.description AS "description?: CourseDescription", + u.ders_saati::bigint AS "ders_saati?: DersSaati", + u.counts_toward_karne, + u.subjects_inherited, u.exam_weights_inherited, u.weekly_plan_inherited, + u.enrollment_count, + u.attached_at AS "attached_at: Timestamp" + FROM updated u + LEFT JOIN class_blueprint b ON b.id = u.source"#, + id.uuid(), + title, + description, + staff, + counts, + subjects, + exam_weights, + weekly_plan, + ) + .fetch_optional(db) + .await? + .ok_or(AppError::NotFound)?; + Ok(row) +} diff --git a/src/db/class_group.rs b/src/db/class_group.rs index 87e4554..25c394f 100644 --- a/src/db/class_group.rs +++ b/src/db/class_group.rs @@ -8,7 +8,8 @@ use crate::database::{Database, tx_with_retry}; use crate::db::field_update::{FieldUpdate, Refcount}; use crate::db::page::PagedList; use crate::domain::academic_year::AcademicYearId; -use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; +use crate::domain::class_group::{ClassGroup, ClassGroupId, ClassName}; +use crate::domain::grade::GradeLevel; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -48,7 +49,7 @@ pub async fn create( db: &Database, creator: &UserId, name: ClassName, - grade: Option, + grade_level: GradeLevel, year: Option, teacher: Option, ) -> Result { @@ -64,16 +65,16 @@ pub async fn create( UPDATE academic_year SET class_count = class_count + 1 WHERE id = $1 RETURNING 1) - INSERT INTO class_group (id, creator, name, grade, year, teacher) + INSERT INTO class_group (id, creator, name, grade_level, year, teacher) SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat) RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", - name AS "name: ClassName", grade AS "grade: ClassGrade", + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", year AS "year: AcademicYearId", teacher AS "teacher: UserId""#, year.uuid(), id.uuid(), creator.uuid(), name.as_str(), - grade.as_ref().map(ClassGrade::as_str), + grade_level.get(), teacher.as_ref().map(UserId::uuid) ) .fetch_optional(db) @@ -97,15 +98,15 @@ pub async fn create( None => { let created = sqlx::query_as!( ClassGroup, - r#"INSERT INTO class_group (id, creator, name, grade, year, teacher) + r#"INSERT INTO class_group (id, creator, name, grade_level, year, teacher) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", - name AS "name: ClassName", grade AS "grade: ClassGrade", + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", year AS "year: AcademicYearId", teacher AS "teacher: UserId""#, id.uuid(), creator.uuid(), name.as_str(), - grade.as_ref().map(ClassGrade::as_str), + grade_level.get(), year.as_ref().map(AcademicYearId::uuid), teacher.as_ref().map(UserId::uuid) ) @@ -121,7 +122,7 @@ pub async fn read(db: &Database, id: &ClassGroupId) -> Result let class = sqlx::query_as!( ClassGroup, r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", - name AS "name: ClassName", grade AS "grade: ClassGrade", + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", year AS "year: AcademicYearId", teacher AS "teacher: UserId" FROM class_group WHERE id = $1"#, id.uuid() @@ -131,40 +132,36 @@ pub async fn read(db: &Database, id: &ClassGroupId) -> Result Ok(class) } -/// Every class, newest first — or one grade's, when `grade` narrows it: -/// `Some(Some(label))` is the sections carrying that exact label (no trim, -/// no case folding, matching [`list_for_grade`] and the -/// blueprint keyed by that very string), `Some(None)` the sections carrying -/// no grade at all, `None` the whole list. +/// Every class, newest first — or one rung's, when `grade_level` narrows it: +/// `Some(level)` is the sections carrying that exact ladder position (the +/// same equality [`list_for_grade`] and the blueprint keyed by that rung +/// use), `None` the whole list. /// /// The narrowing is the `WHERE`, so the `total` [`PagedList`] counts is the /// filtered set and a client can page through it. pub async fn list_all( db: &Database, - grade: Option>, + grade_level: Option, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - let list = match grade { + let list = match grade_level { None => PagedList::new(CLASS_GROUP_TABLE, "ORDER BY id DESC"), - Some(None) => PagedList::new( - format!("{CLASS_GROUP_TABLE} WHERE grade IS NULL"), - "ORDER BY id DESC", - ), - Some(Some(grade)) => PagedList::new( - format!("{CLASS_GROUP_TABLE} WHERE grade = $1"), + Some(grade_level) => PagedList::new( + format!("{CLASS_GROUP_TABLE} WHERE grade_level = $1"), "ORDER BY id DESC", ) - .bind(grade.as_str().to_string()), + .bind(grade_level.get() as i64), }; list.run(limit, offset, db).await } /// Write only the fields the PATCH carried — `None` means the request /// omitted it, so the column is left alone rather than re-stated from the -/// snapshot this struct was read into. `grade`, `year` and `teacher` are -/// nullable, so they take the outer/inner `Option>`: `None` = -/// omitted (keep), `Some(None)` = clear. +/// snapshot this struct was read into. `grade_level` is a plain `Option` +/// (the column is NOT NULL: a PATCH may set a rung, never clear it); +/// `year` and `teacher` are nullable, so they take the outer/inner +/// `Option>`: `None` = omitted (keep), `Some(None)` = clear. /// /// A year move claims the new year and releases the old one inside the very /// transaction that moves the link, exactly as in @@ -174,7 +171,7 @@ pub async fn update( db: &Database, class: ClassGroup, name: Option, - grade: Option>, + grade_level: Option, year: Option>, teacher: Option>, ) -> Result { @@ -182,10 +179,10 @@ pub async fn update( let expected = class.year.as_ref().map(AcademicYearId::uuid); FieldUpdate::new(CLASS_GROUP_TABLE, class.id.uuid()) .set("name", name.map(|name| name.as_str().to_string())) - .set( - "grade", - grade.map(|grade| grade.map(|grade| grade.as_str().to_string())), - ) + // `Param` has no i16 arm (and db/page.rs is a shared seam): the rung + // rides as BIGINT, which Postgres assignment-casts into the SMALLINT + // column. + .set("grade_level", grade_level.map(|grade| grade.get() as i64)) .set("year", year.map(|year| year.map(|year| year.uuid()))) // Not refcounted: a homeroom assignment is a label, so it rides the // plain `set` path and never arms the year CAS. @@ -218,7 +215,7 @@ pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result Result Result, AppError> { let classes = sqlx::query_as!( ClassGroup, r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", - name AS "name: ClassName", grade AS "grade: ClassGrade", + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", year AS "year: AcademicYearId", teacher AS "teacher: UserId" - FROM class_group WHERE grade = $1"#, - grade.as_str() + FROM class_group WHERE grade_level = $1"#, + grade_level.get() ) .fetch_all(db) .await?; @@ -258,7 +255,7 @@ pub async fn list_for_year( let classes = sqlx::query_as!( ClassGroup, r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", - name AS "name: ClassName", grade AS "grade: ClassGrade", + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", year AS "year: AcademicYearId", teacher AS "teacher: UserId" FROM class_group WHERE year = $1 ORDER BY id"#, year.uuid() @@ -287,7 +284,7 @@ pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result ClassGroupId { let manager = fixture_user(db, "manager").await; crate::db::class_group::create( db, &manager, ClassName::try_new(name).unwrap(), - None, + crate::domain::grade::GradeLevel::new(9).unwrap(), None, None, ) diff --git a/src/db/class_pump.rs b/src/db/class_pump.rs index 966904d..7f94f29 100644 --- a/src/db/class_pump.rs +++ b/src/db/class_pump.rs @@ -34,14 +34,16 @@ use sqlx::postgres::PgConnection; use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use crate::database::{Database, foreign_key_violation, tx_with_retry, unique_violation}; use crate::domain::class_blueprint::ClassBlueprintId; -use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; +use crate::domain::class_course::{ClassCourse, ClassCourseId}; use crate::domain::class_group::ClassGroupId; use crate::domain::class_member::{ClassMember, ClassMemberId}; use crate::domain::course::CourseId; +use crate::domain::course::CourseKind; +use crate::domain::grade::GradeLevel; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::AppError; +use crate::error::{AppError, ValidationError}; /// What [`attach_course`]'s attach settled. The caller answers each verdict — /// a hand attach turns them into this route's errors; a blueprint pump reads @@ -268,7 +270,7 @@ async fn early_verdicts( axis: Axis, pivot: Pivot<'_>, source: Option<&ClassBlueprintId>, -) -> Result<(Option, Option), AppError> { +) -> Result<(Option, Option, Option), AppError> { let held = match pivot { Pivot::User(user) => sqlx::query_scalar!( r#"SELECT 1 AS "one" FROM class_member @@ -289,7 +291,7 @@ async fn early_verdicts( .is_some(), }; if held { - return Ok((Some(Early::Duplicate), None)); + return Ok((Some(Early::Duplicate), None, None)); } // The lock and the resolution are one read: the stored `source` is the // blueprint's surrogate uuid, and the row this read returns it from is @@ -297,16 +299,17 @@ async fn early_verdicts( let mut source_id = None; if let Some(source) = source { let locked = sqlx::query_scalar!( - r#"SELECT id FROM class_blueprint WHERE grade = $1 FOR KEY SHARE"#, + r#"SELECT id FROM class_blueprint WHERE grade_level = $1 FOR KEY SHARE"#, source as _ ) .fetch_optional(&mut *tx) .await?; let Some(id) = locked else { - return Ok((Some(Early::SourceGone), None)); + return Ok((Some(Early::SourceGone), None, None)); }; source_id = Some(id); } + let mut kind = None; match pivot { Pivot::User(user) => { let row = sqlx::query!( @@ -316,20 +319,24 @@ async fn early_verdicts( .fetch_optional(&mut *tx) .await?; if row.map(|row| row.role) != Some(Role::Student) { - return Ok((Some(Early::PivotGone), None)); + return Ok((Some(Early::PivotGone), None, None)); } } Pivot::Course(course) => { - let alive = sqlx::query_scalar!( - r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#, + // The lock and the kind in one read: the same `FOR KEY SHARE` the + // attach needs against a concurrent course delete answers what + // kind of course it is locking — and only a class-delivered ders + // may become an instance (the gate lives in [`attach_course`]). + let locked = sqlx::query!( + r#"SELECT kind AS "kind: CourseKind" FROM course WHERE id = $1 FOR KEY SHARE"#, course as _ ) .fetch_optional(&mut *tx) - .await? - .is_some(); - if !alive { - return Ok((Some(Early::PivotGone), None)); - } + .await?; + let Some(locked_kind) = locked else { + return Ok((Some(Early::PivotGone), None, None)); + }; + kind = Some(locked_kind.kind); } } // Read off the class row inside the transaction that claims it, so the @@ -354,7 +361,7 @@ async fn early_verdicts( .await? .is_some(), }; - Ok((over.then_some(Early::Overloaded), source_id)) + Ok((over.then_some(Early::Overloaded), source_id, kind)) } /// Write the member stint and enroll the student into every instance the @@ -410,7 +417,7 @@ pub(crate) async fn add_member_sourced( let (user, by) = (*user, *by); let id = ClassMemberId::generate(); let outcome = tx_with_retry(db, false, async move |tx| { - let (early, _) = early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?; + let (early, _, _) = early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?; if let Some(early) = early { return Ok(refusal_of(early)); } @@ -498,7 +505,8 @@ pub(crate) async fn add_member_sourced( /// Students already enrolled in it keep the rows they have — no count charged, /// `source` untouched. There is no roster-size gate any more (D5: the /// counter is a count, not a capacity), so the only refusals left are the -/// class's own ceilings and a vanished pivot. +/// class's own ceilings, a vanished pivot, and a course kind that is not +/// class-delivered (a 400 straight out of the transaction). /// /// `source` is the blueprint whose behalf this attach runs on, and supplying /// it adds one more claim: that it is still there when the transaction runs @@ -507,9 +515,20 @@ pub(crate) async fn add_member_sourced( /// and passes `None`. /// /// The instance's own id is minted here (v7, so a class's instances list in -/// creation order) and its policy columns take the schema defaults: one weekly -/// hour, counted toward the report card, an empty roster. A PATCH on `/instances` -/// changes them afterwards. +/// creation order) and its content columns are born `NULL` — the *inherit* +/// state: what the section teaches is whatever its grade-level +/// [`crate::domain::course_offering::CourseOffering`] says, and through it +/// the catalog course. That template is resolved (auto-created empty, with +/// `created_by` naming the attaching actor, when the (course, grade_level) +/// pair has none yet) in this same transaction — the class row is read under +/// `FOR KEY SHARE`, so the offering the insert names is the one for the +/// grade the class carries *at the attach*, not at the caller's read. A +/// PATCH on `/instances` overrides the content afterwards. +/// +/// Only a **class-delivered** course +/// ([`CourseKind::is_class_delivered`], `kind = 'course'`) becomes an +/// instance: a club or an etüt is joined individually and is refused with a +/// 400, whatever axis asked for the attach. /// /// Two counters ride the write, both in this one transaction: the class's /// `class_course_count` (claimed by the conditional CTE, so a full or gone @@ -532,7 +551,7 @@ pub(crate) async fn attach_course( let source = source.cloned(); let id = ClassCourseId::generate(); let outcome = tx_with_retry(db, false, async move |tx| { - let (early, source_id) = early_verdicts( + let (early, source_id, kind) = early_verdicts( tx, &class, Axis::Course, @@ -543,13 +562,55 @@ pub(crate) async fn attach_course( if let Some(early) = early { return Ok(refusal_of(early)); } + let Some(kind) = kind else { + // Unreachable on this axis — the course pivot always answers its + // kind when it is alive. A future axis change should surface as + // this 500, not as a wrong-looking refusal. + return Err(AppError::Internal( + "a course attach locked a course but read no kind".into(), + )); + }; + if !kind.is_class_delivered() { + // The gate from the locked row itself, so a concurrent kind + // change cannot slip between a pre-flight check and the insert. + // A blueprint listing a study/club aborts that whole pump run + // with this 400 — fail-closed, naming the row to fix. + return Err(AppError::Validation(ValidationError::Invalid { + field: "course", + reason: "only a ders attaches to a class — a club or etüt is joined individually, not attached", + })); + } + // The class's own grade, locked: the offering the insert names is the + // one for the grade the class carries *now* (a concurrent grade move + // waits behind this KEY SHARE). A gone class answers `Gone` — the + // same verdict the seat claim below would have produced, one read + // earlier. + let grade_level = sqlx::query_scalar!( + r#"SELECT grade_level AS "grade_level: GradeLevel" FROM class_group + WHERE id = $1 FOR KEY SHARE"#, + class as _ + ) + .fetch_optional(&mut *tx) + .await?; + let Some(grade_level) = grade_level else { + return Ok(Attached::Gone); + }; + // The template the instance teaches from: found, or minted empty + // (every content column NULL — inherit the catalog) with this actor + // as its `created_by`. Race-closed inside `ensure_tx`. Minted before + // the seat claim, so a refused attach (a full class) may leave an + // empty template behind — harmless: an empty template inherits the + // catalog exactly as no template would, and the next attach at that + // grade reuses it. + let offering = + crate::db::course_offering::ensure_tx(tx, &course, grade_level, &by).await?; let inserted = match sqlx::query_scalar!( r#"WITH seat AS ( UPDATE class_group SET class_course_count = class_course_count + 1 WHERE id = $1 AND class_course_count < $2 RETURNING 1) - INSERT INTO class_course (id, class, course, attached_by, attached_at, source) - SELECT $3, $1, $4, $5, $6, $7 WHERE EXISTS (SELECT 1 FROM seat) + INSERT INTO class_course (id, class, course, attached_by, attached_at, source, offering) + SELECT $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat) RETURNING 1 AS "one""#, class as _, Axis::Course.cap(), @@ -558,6 +619,7 @@ pub(crate) async fn attach_course( by as _, attached_at as _, source_id, + offering as _, ) .fetch_optional(&mut *tx) .await @@ -621,11 +683,16 @@ pub(crate) async fn attach_course( id: id.clone(), class: class.clone(), course: course.clone(), + offering: offering.clone(), attached_by: by, - source: source.clone(), - ders_saati: DersSaati::try_new(crate::constant::MIN_DERS_SAATI) - .expect("the schema default is a valid weekly-hours count"), - counts_toward_karne: true, + source, + title: None, + description: None, + ders_saati: None, + counts_toward_karne: None, + subjects_inherited: true, + exam_weights_inherited: true, + weekly_plan_inherited: true, enrollment_count, attached_at, })) @@ -933,7 +1000,7 @@ pub(crate) async fn detach_course( sqlx::query_scalar!( r#"SELECT id AS "id: uuid::Uuid" FROM class_course WHERE class = $1 AND course = $2 - AND source = (SELECT id FROM class_blueprint WHERE grade = $3) + AND source = (SELECT id FROM class_blueprint WHERE grade_level = $3) FOR UPDATE"#, class as _, course as _, diff --git a/src/db/course.rs b/src/db/course.rs index ce6448f..6730597 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -703,7 +703,7 @@ pub(crate) async fn a_test_instance( db, &manager, ClassName::try_new("9-A").unwrap(), - None, + crate::domain::grade::GradeLevel::new(9).unwrap(), None, None, ) @@ -934,7 +934,7 @@ mod tests { db, on, crate::domain::class_group::ClassName::try_new(name).unwrap(), - None, + crate::domain::grade::GradeLevel::new(9).unwrap(), None, None, ) diff --git a/src/db/course_offering.rs b/src/db/course_offering.rs new file mode 100644 index 0000000..cb81d7f --- /dev/null +++ b/src/db/course_offering.rs @@ -0,0 +1,429 @@ +//! The `course_offering` table: the grade-level course template and the reads +//! and writes behind `/offerings`. The row shape lives in +//! [`crate::domain::course_offering`]; the workflows (the class-delivered +//! gate, the duplicate refusal) in [`crate::service::course_offering`]. +//! +//! One row per (course, grade_level) — the `UNIQUE` key the attach pump's +//! auto-create races on: [`ensure_tx`] inserts `ON CONFLICT DO NOTHING` and +//! reads the winner's id back, so two attaches landing together share one +//! template whatever the interleaving was. +//! +//! Every content column is nullable by design — `NULL` means *inherit* (from +//! the catalog course, or from the constants), never "missing". The update is +//! field-scoped in the `set_or_clear` shape the other PATCH handlers speak: +//! an absent field keeps its column, an explicit `null` clears back to +//! inherit, a value sets the override. + +use sqlx::postgres::PgConnection; + +use crate::database::{Database, unique_violation}; +use crate::db::page::PagedList; +use crate::domain::class_course::DersSaati; +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; +use crate::domain::grade::GradeLevel; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// One offering as the *runtime* row decode sees it. Identical to +/// [`CourseOffering`] except `default_ders_saati` stays the raw `SMALLINT` +/// (`Option`): the runtime [`sqlx::FromRow`] path cannot name the +/// `::bigint` cast the static `query_as!` projections use, and +/// [`DersSaati`]'s transparent `i64` would refuse a `SMALLINT` at decode. +/// [`OfferingRow::into_course_offering`] does the two-step conversions the +/// column `CHECK`s already guarantee. +#[derive(Debug, sqlx::FromRow)] +struct OfferingRow { + id: CourseOfferingId, + course: CourseId, + grade_level: GradeLevel, + title: Option, + description: Option, + default_ders_saati: Option, + default_counts_toward_karne: Option, + created_by: UserId, + created_at: Timestamp, + updated_at: Timestamp, +} + +impl OfferingRow { + fn into_course_offering(self) -> CourseOffering { + CourseOffering { + id: self.id, + course: self.course, + grade_level: self.grade_level, + title: self.title, + description: self.description, + default_ders_saati: self.default_ders_saati.map(|hours| { + DersSaati::try_new(i64::from(hours)) + .expect("the column CHECK keeps the weekly hours between 1 and 40") + }), + default_counts_toward_karne: self.default_counts_toward_karne, + created_by: self.created_by, + created_at: self.created_at, + updated_at: self.updated_at, + } + } +} + +/// One offering by id, or `None` when the id names no row. +pub async fn read(db: &Database, id: &CourseOfferingId) -> Result, AppError> { + let row = sqlx::query_as!( + CourseOffering, + r#"SELECT id AS "id: CourseOfferingId", + course AS "course: CourseId", + grade_level AS "grade_level: GradeLevel", + title AS "title?: CourseTitle", + description AS "description?: CourseDescription", + default_ders_saati::bigint AS "default_ders_saati?: DersSaati", + default_counts_toward_karne, + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp", + updated_at AS "updated_at: Timestamp" + FROM course_offering WHERE id = $1"#, + id.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(row) +} + +/// Load every offering behind `ids` (one query) — the batch half of the +/// resolved-content reads (`service::instance_resolve::resolved_content`), +/// which map a page of instances onto their templates without an N+1. +pub async fn list_by_ids( + db: &Database, + ids: &[CourseOfferingId], +) -> Result, AppError> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let keys: Vec = ids.iter().map(CourseOfferingId::uuid).collect(); + let rows = sqlx::query_as!( + CourseOffering, + r#"SELECT id AS "id: CourseOfferingId", + course AS "course: CourseId", + grade_level AS "grade_level: GradeLevel", + title AS "title?: CourseTitle", + description AS "description?: CourseDescription", + default_ders_saati::bigint AS "default_ders_saati?: DersSaati", + default_counts_toward_karne, + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp", + updated_at AS "updated_at: Timestamp" + FROM course_offering WHERE id = ANY($1)"#, + &keys, + ) + .fetch_all(db) + .await?; + Ok(rows) +} + +/// The offering a (course, grade_level) pair resolves to, or `None` when no +/// template exists there yet — the read behind "what does this grade teach +/// from" outside a pump transaction. +pub async fn find( + db: &Database, + course: &CourseId, + grade: GradeLevel, +) -> Result, AppError> { + let row = sqlx::query_as!( + CourseOffering, + r#"SELECT id AS "id: CourseOfferingId", + course AS "course: CourseId", + grade_level AS "grade_level: GradeLevel", + title AS "title?: CourseTitle", + description AS "description?: CourseDescription", + default_ders_saati::bigint AS "default_ders_saati?: DersSaati", + default_counts_toward_karne, + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp", + updated_at AS "updated_at: Timestamp" + FROM course_offering WHERE course = $1 AND grade_level = $2"#, + course.uuid(), + grade.get(), + ) + .fetch_optional(db) + .await?; + Ok(row) +} + +/// The offerings, grade ladder first, paged via `limit`/`offset`; both +/// filters are optional and combine. The page and its count share the same +/// predicate ([`PagedList`]). +pub async fn list( + db: &Database, + course: Option<&CourseId>, + grade: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + let from_where = match (course, grade) { + (Some(_), Some(_)) => "course_offering WHERE course = $1 AND grade_level = $2", + (Some(_), None) => "course_offering WHERE course = $1", + (None, Some(_)) => "course_offering WHERE grade_level = $1", + (None, None) => "course_offering", + }; + let mut page = PagedList::new(from_where, "ORDER BY grade_level, course"); + if let Some(course) = course { + page = page.bind(course.uuid()); + } + if let Some(grade) = grade { + page = page.bind(i64::from(grade.get())); + } + let (rows, total) = page.run::(limit, offset, db).await?; + Ok(( + rows.into_iter() + .map(OfferingRow::into_course_offering) + .collect(), + total, + )) +} + +/// Mint the template. The duplicate (course, grade_level) answer is a **409 +/// `offering_exists`**, not a store error: a manager creating the same +/// template twice wants to be told it exists, and the attach pump's +/// auto-create would have silently shared the row instead. +#[allow(clippy::too_many_arguments)] // the offering row, spelled field by field +pub async fn create( + db: &Database, + course: &CourseId, + grade: GradeLevel, + title: Option, + description: Option, + default_ders_saati: Option, + default_counts_toward_karne: Option, + by: &UserId, +) -> Result { + let now = Timestamp::now(); + let title = title.map(|title| title.as_str().to_string()); + let description = description.map(|d| d.as_str().to_string()); + // An `i64` bound into a `SMALLINT` column: the assignment cast is the + // statement's own, and the newtype has already range-checked the value. + let hours = default_ders_saati.map(DersSaati::as_i64); + let row = sqlx::query_as!( + CourseOffering, + r#"INSERT INTO course_offering + (id, course, grade_level, title, description, + default_ders_saati, default_counts_toward_karne, + created_by, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6::bigint, $7, $8, $9, $9) + RETURNING id AS "id: CourseOfferingId", + course AS "course: CourseId", + grade_level AS "grade_level: GradeLevel", + title AS "title?: CourseTitle", + description AS "description?: CourseDescription", + default_ders_saati::bigint AS "default_ders_saati?: DersSaati", + default_counts_toward_karne, + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp", + updated_at AS "updated_at: Timestamp""#, + CourseOfferingId::generate().uuid(), + course.uuid(), + grade.get(), + title, + description, + hours, + default_counts_toward_karne, + by.uuid(), + now.as_millis(), + ) + .fetch_one(db) + .await + .map_err(|e| { + // The table carries exactly one `UNIQUE` constraint — the (course, + // grade_level) template key — so *any* unique violation here is the + // duplicate template, whatever Postgres named it. + if unique_violation(&e).is_some() { + AppError::ConflictCoded { + code: "offering_exists", + message: "this course already has an offering for this grade".into(), + } + } else { + e.into() + } + })?; + Ok(row) +} + +/// Field-scoped PATCH in the `set_or_clear` shape: an absent field keeps its +/// column, `Some(None)` clears back to inherit (`NULL`), `Some(Some(v))` sets +/// the override. `updated_at` moves with every write that changes anything. +/// An empty request writes nothing and reads the row back. `Err(NotFound)` +/// when the offering is gone. +pub async fn update( + db: &Database, + id: &CourseOfferingId, + title: Option>, + description: Option>, + default_ders_saati: Option>, + default_counts_toward_karne: Option>, +) -> Result { + if title.is_none() + && description.is_none() + && default_ders_saati.is_none() + && default_counts_toward_karne.is_none() + { + return read(db, id).await?.ok_or(AppError::NotFound); + } + // Present-flag + nullable-value pairs: the flag decides *whether* the + // column moves, the value decides to what (a typed `NULL` is the inherit + // state). The weekly hours ride the `::bigint` round-trip cast like every + // other `DersSaati` read, and the column `CHECK` re-checks the range at + // the store. + let title_present = title.is_some(); + let title = title.flatten().map(|t| t.as_str().to_string()); + let description_present = description.is_some(); + let description = description.flatten().map(|d| d.as_str().to_string()); + let hours_present = default_ders_saati.is_some(); + let hours = default_ders_saati.flatten().map(DersSaati::as_i64); + let counts_present = default_counts_toward_karne.is_some(); + let counts = default_counts_toward_karne.flatten(); + let now = Timestamp::now(); + let row = sqlx::query_as!( + CourseOffering, + r#"WITH updated AS ( + UPDATE course_offering SET + title = CASE WHEN $2 THEN $3::text ELSE title END, + description = CASE WHEN $4 THEN $5::text ELSE description END, + default_ders_saati = CASE WHEN $6 THEN + COALESCE($7::bigint, default_ders_saati::bigint)::smallint + ELSE default_ders_saati END, + default_counts_toward_karne = CASE WHEN $8 THEN $9 + ELSE default_counts_toward_karne END, + updated_at = $10 + WHERE id = $1 + RETURNING id, course, grade_level, title, description, + default_ders_saati, default_counts_toward_karne, + created_by, created_at, updated_at) + SELECT u.id AS "id: CourseOfferingId", + u.course AS "course: CourseId", + u.grade_level AS "grade_level: GradeLevel", + u.title AS "title?: CourseTitle", + u.description AS "description?: CourseDescription", + u.default_ders_saati::bigint AS "default_ders_saati?: DersSaati", + u.default_counts_toward_karne, + u.created_by AS "created_by: UserId", + u.created_at AS "created_at: Timestamp", + u.updated_at AS "updated_at: Timestamp" + FROM updated u"#, + id.uuid(), + title_present, + title, + description_present, + description, + hours_present, + hours, + counts_present, + counts, + now.as_millis(), + ) + .fetch_optional(db) + .await? + .ok_or(AppError::NotFound)?; + Ok(row) +} + +/// The offering's two defaults, straight off its row — `(default_ders_saati, +/// default_counts_toward_karne)`, `None`s *included* (a `NULL` default is the +/// inherit state, and the caller layers its own fallbacks on top). `None` when +/// the id names no offering: the `RESTRICT` foreign key on `class_course` +/// keeps every instance's offering alive, so a missing row is the honest 404 +/// the service turns into one, not a case to paper over. +pub async fn defaults( + db: &Database, + id: &CourseOfferingId, +) -> Result, Option)>, AppError> { + let row = sqlx::query!( + r#"SELECT default_ders_saati::bigint AS "default_ders_saati?: DersSaati", + default_counts_toward_karne + FROM course_offering WHERE id = $1"#, + id.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(row.map(|row| (row.default_ders_saati, row.default_counts_toward_karne))) +} + +/// Delete the template — refused while any instance still teaches from it. +/// The refusal is a **409 `offering_in_use`** (the foreign key's `RESTRICT` +/// is the store's mirror of the same rule); a gone id is the usual 404. One +/// conditional statement is the whole invariant, so a check-then-delete race +/// cannot exist: the `NOT EXISTS` is judged on the row as it is *at the +/// delete*. +pub async fn delete(db: &Database, id: &CourseOfferingId) -> Result<(), AppError> { + let deleted = sqlx::query!( + r#"DELETE FROM course_offering + WHERE id = $1 + AND NOT EXISTS (SELECT 1 FROM class_course cc WHERE cc.offering = $1)"#, + id.uuid(), + ) + .execute(db) + .await? + .rows_affected(); + if deleted > 0 { + return Ok(()); + } + // Zero rows: in use, or already gone. The read tells the two apart. + let standing = sqlx::query_scalar!( + r#"SELECT 1 AS "one" FROM course_offering WHERE id = $1"#, + id.uuid() + ) + .fetch_optional(db) + .await? + .is_some(); + if standing { + Err(AppError::ConflictCoded { + code: "offering_in_use", + message: + "instances still teach this offering — detach the course from those classes first" + .into(), + }) + } else { + Err(AppError::NotFound) + } +} + +/// Resolve — or mint empty — the template a (course, grade_level) pair +/// teaches from, inside the caller's transaction. The attach pump's helper: +/// every instance insert needs its offering link, and an untouched grade +/// mints an *empty* template (every content column `NULL`) so it inherits the +/// catalog course until a manager fills it in. `created_by` is the actor +/// whose attach asked. +/// +/// The `ON CONFLICT DO NOTHING` + read-back pair is the race-closer: two +/// attaches landing on the same (course, grade_level) together both insert, +/// one wins, and the loser's read-back returns the winner's row — one +/// template per pair, whatever the order was. The table's only `UNIQUE` +/// constraint is that pair, so the bare `DO NOTHING` cannot swallow a +/// different conflict. +pub(crate) async fn ensure_tx( + tx: &mut PgConnection, + course: &CourseId, + grade: GradeLevel, + by: &UserId, +) -> Result { + let now = Timestamp::now(); + sqlx::query!( + r#"INSERT INTO course_offering (id, course, grade_level, created_by, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $5) + ON CONFLICT DO NOTHING"#, + CourseOfferingId::generate().uuid(), + course.uuid(), + grade.get(), + by.uuid(), + now.as_millis(), + ) + .execute(&mut *tx) + .await?; + let id = sqlx::query_scalar!( + r#"SELECT id AS "id: CourseOfferingId" FROM course_offering + WHERE course = $1 AND grade_level = $2"#, + course.uuid(), + grade.get(), + ) + .fetch_one(&mut *tx) + .await?; + Ok(id) +} diff --git a/src/db/course_session.rs b/src/db/course_session.rs index 6fa65bc..5be10c8 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -202,7 +202,7 @@ mod tests { &db, &creator, crate::domain::class_group::ClassName::try_new("9-A").unwrap(), - None, + crate::domain::grade::GradeLevel::new(9).unwrap(), None, None, ) diff --git a/src/db/event.rs b/src/db/event.rs index 27feee3..2402511 100644 --- a/src/db/event.rs +++ b/src/db/event.rs @@ -331,7 +331,7 @@ mod tests { let creator = a_person(&db, "event-guard").await; // `audience_class` is a foreign key too: the class case needs a real group. let class = ClassGroupId::generate(); - sqlx::query("INSERT INTO class_group (id, name, creator) VALUES ($1, 'g1', $2)") + sqlx::query("INSERT INTO class_group (id, name, creator, grade_level) VALUES ($1, 'g1', $2, 9)") .bind(class.uuid()) .bind(creator.uuid()) .execute(&db) diff --git a/src/db/exam.rs b/src/db/exam.rs index af2b4a8..08d91aa 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -771,7 +771,7 @@ mod tests { &db, &creator, crate::domain::class_group::ClassName::try_new("9-A").unwrap(), - None, + crate::domain::grade::GradeLevel::new(9).unwrap(), None, None, ) diff --git a/src/db/exam_result.rs b/src/db/exam_result.rs index 25bc19e..e421075 100644 --- a/src/db/exam_result.rs +++ b/src/db/exam_result.rs @@ -551,7 +551,7 @@ pub(crate) mod tests { db, &office, ClassName::try_new(name).unwrap(), - None, + crate::domain::grade::GradeLevel::new(5).unwrap(), Some(*year.get_id()), None, ) @@ -570,9 +570,10 @@ pub(crate) mod tests { let addressed = instances[1].clone(); let kinds = Settings::defaults().get_exam_kinds().to_vec(); - for (title, addressed_to_both, mark) in - [("ortak", true, ORTAK_MARK), ("tek", false, OWNER_MARK)] - { + for (title, addressed_to_both, kind, mark) in [ + ("ortak", true, "yazili", ORTAK_MARK), + ("tek", false, "sozlu", OWNER_MARK), + ] { let exam = crate::db::exam::create( db, &office, @@ -580,7 +581,7 @@ pub(crate) mod tests { term.get_id(), ExamTitle::try_new(title).unwrap(), ExamDescription::try_new("").unwrap(), - ExamKind::try_new("yazili", &kinds).unwrap(), + ExamKind::try_new(kind, &kinds).unwrap(), ExamSchedule::try_new(None, None, None, None).unwrap(), ExamAttemptLimit::try_new(1).unwrap(), true, @@ -606,7 +607,7 @@ pub(crate) mod tests { 1, Mark::try_new(mark).unwrap(), &office, - "yazili", + kind, ) .await .unwrap(); diff --git a/src/db/exam_weight.rs b/src/db/exam_weight.rs new file mode 100644 index 0000000..bd829e5 --- /dev/null +++ b/src/db/exam_weight.rs @@ -0,0 +1,239 @@ +//! The `offering_exam_weight` / `class_course_exam_weight` tables: per-kind +//! weight overrides under the grade-level template and the class section. +//! +//! Every class-owned write keeps the override flag honest **in the same +//! statement**: a data-modifying CTE flips `class_course.exam_weights_inherited` +//! to `FALSE` while the weight row is written (or dropped), so a crash between +//! "row changed" and "flag changed" is impossible and +//! `class_course`'s own module never enters the picture. The reset deletes the +//! section's rows and restores `TRUE` in one statement too — the shape +//! [`crate::db::class_course::clear_overrides`] uses for the scalar overrides. +//! +//! The chain that *reads* these rows lives in +//! [`crate::service::exam_weight`]; this file is the SQL executor only. + +use crate::database::Database; +use crate::domain::class_course::ClassCourseId; +use crate::domain::course_offering::CourseOfferingId; +use crate::domain::exam_weight::ExamWeight; +use crate::error::AppError; + +/// The offering's own weight rows, by kind — the override set of the +/// grade-level template. +pub async fn list_for_offering( + db: &Database, + offering: &CourseOfferingId, +) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT kind, weight::bigint AS "weight!: i64" + FROM offering_exam_weight WHERE offering = $1 + ORDER BY kind"#, + offering.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|row| ExamWeight { + kind: row.kind, + weight: row.weight, + }) + .collect()) +} + +/// One offering weight row, or `None` when the pair holds none — the second +/// step of [`crate::service::exam_weight::resolve`]. +pub async fn offering_weight( + db: &Database, + offering: &CourseOfferingId, + kind: &str, +) -> Result, AppError> { + let row = sqlx::query!( + r#"SELECT kind, weight::bigint AS "weight!: i64" + FROM offering_exam_weight WHERE offering = $1 AND kind = $2"#, + offering.uuid(), + kind, + ) + .fetch_optional(db) + .await?; + Ok(row.map(|row| ExamWeight { + kind: row.kind, + weight: row.weight, + })) +} + +/// Upsert one weight on the template. A duplicate (offering, kind) pair +/// *rewrites* the weight — a PATCH of an existing kind is the normal path, not +/// a conflict. +pub async fn upsert_for_offering( + db: &Database, + offering: &CourseOfferingId, + kind: &str, + weight: &ExamWeight, +) -> Result<(), AppError> { + sqlx::query!( + r#"INSERT INTO offering_exam_weight (offering, kind, weight) + VALUES ($1, $2, $3::bigint::smallint) + ON CONFLICT (offering, kind) DO UPDATE SET weight = EXCLUDED.weight"#, + offering.uuid(), + kind, + weight.get_weight(), + ) + .execute(db) + .await?; + Ok(()) +} + +/// Drop one weight row from the template. `false` when the pair held no row — +/// the caller's 404. +pub async fn delete_from_offering( + db: &Database, + offering: &CourseOfferingId, + kind: &str, +) -> Result { + let result = sqlx::query!( + r#"DELETE FROM offering_exam_weight WHERE offering = $1 AND kind = $2"#, + offering.uuid(), + kind, + ) + .execute(db) + .await?; + Ok(result.rows_affected() > 0) +} + +/// The section's own weight rows, by kind — authoritative exactly while +/// `exam_weights_inherited` is `FALSE`, **including when empty**. +pub async fn list_for_class( + db: &Database, + instance: &ClassCourseId, +) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT kind, weight::bigint AS "weight!: i64" + FROM class_course_exam_weight WHERE class_course = $1 + ORDER BY kind"#, + instance.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|row| ExamWeight { + kind: row.kind, + weight: row.weight, + }) + .collect()) +} + +/// One section weight row, or `None` — the first step of +/// [`crate::service::exam_weight::resolve`] while the section's own set is in +/// force. +pub async fn class_weight( + db: &Database, + instance: &ClassCourseId, + kind: &str, +) -> Result, AppError> { + let row = sqlx::query!( + r#"SELECT kind, weight::bigint AS "weight!: i64" + FROM class_course_exam_weight WHERE class_course = $1 AND kind = $2"#, + instance.uuid(), + kind, + ) + .fetch_optional(db) + .await?; + Ok(row.map(|row| ExamWeight { + kind: row.kind, + weight: row.weight, + })) +} + +/// Upsert one weight on the section **and** take the set own — both in the +/// statement that writes the row, so `exam_weights_inherited` can never claim +/// "inherit" over a row the section actually carries. `Err(NotFound)` when the +/// instance is gone (the CTE's UPDATE finds no row). +pub async fn upsert_for_class( + db: &Database, + instance: &ClassCourseId, + kind: &str, + weight: &ExamWeight, +) -> Result<(), AppError> { + sqlx::query!( + r#"WITH updated AS ( + UPDATE class_course + SET exam_weights_inherited = FALSE + WHERE id = $1 + RETURNING id + ), written AS ( + INSERT INTO class_course_exam_weight (class_course, kind, weight) + SELECT $1, $2, $3::bigint::smallint + WHERE EXISTS (SELECT 1 FROM updated) + ON CONFLICT (class_course, kind) DO UPDATE SET weight = EXCLUDED.weight + RETURNING class_course + ) + SELECT u.id AS "id: ClassCourseId" FROM updated u"#, + instance.uuid(), + kind, + weight.get_weight(), + ) + .fetch_optional(db) + .await? + .ok_or(AppError::NotFound)?; + Ok(()) +} + +/// Drop one weight row from the section, flipping the flag to `FALSE` **only +/// when a row was actually dropped** — a DELETE naming a kind the section +/// carries no row for mutates nothing and answers `false` (the caller's 404), +/// so a refused delete never changes the inheritance state. `Err(NotFound)` +/// when the instance itself is gone. +pub async fn delete_from_class( + db: &Database, + instance: &ClassCourseId, + kind: &str, +) -> Result { + let row = sqlx::query!( + r#"WITH kicked AS ( + DELETE FROM class_course_exam_weight + WHERE class_course = $1 AND kind = $2 + RETURNING class_course + ), updated AS ( + UPDATE class_course + SET exam_weights_inherited = + CASE WHEN EXISTS (SELECT 1 FROM kicked) + THEN FALSE ELSE exam_weights_inherited END + WHERE id = $1 + RETURNING exam_weights_inherited + ) + SELECT u.exam_weights_inherited AS "inherited: bool", + (SELECT count(*)::bigint FROM kicked) AS "removed!: i64" + FROM updated u"#, + instance.uuid(), + kind, + ) + .fetch_optional(db) + .await? + .ok_or(AppError::NotFound)?; + Ok(row.removed > 0) +} + +/// The reset door: delete every section weight row and restore +/// `exam_weights_inherited = TRUE` in one statement — the offering's set (then +/// the settings, then 1) applies again. `Err(NotFound)` when the instance is +/// gone; otherwise idempotent. +pub async fn reset_class(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> { + sqlx::query!( + r#"WITH kicked AS ( + DELETE FROM class_course_exam_weight WHERE class_course = $1 + ), updated AS ( + UPDATE class_course + SET exam_weights_inherited = TRUE + WHERE id = $1 + RETURNING id + ) + SELECT u.id AS "id: ClassCourseId" FROM updated u"#, + instance.uuid(), + ) + .fetch_optional(db) + .await? + .ok_or(AppError::NotFound)?; + Ok(()) +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 41c4390..68f040c 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -23,6 +23,7 @@ pub mod course; pub mod course_membership; pub mod course_note; pub mod course_note_file; +pub mod course_offering; pub mod course_session; pub mod dietary_profile; pub mod enrollment; @@ -33,6 +34,7 @@ pub mod exam_attempt; pub mod exam_audience; pub mod exam_question; pub mod exam_result; +pub mod exam_weight; pub mod fee_plan; pub mod fee_plan_assignment; pub mod field_update; @@ -50,6 +52,7 @@ pub mod menu_dish; pub mod message; pub mod note; pub mod note_file; +pub mod offering_subject; pub mod page; pub mod parent_link; pub mod payment_ledger; @@ -72,4 +75,5 @@ pub mod solution_image; pub mod subject; pub mod term; pub mod user; +pub mod weekly_slot; pub mod work_entry; diff --git a/src/db/offering_subject.rs b/src/db/offering_subject.rs new file mode 100644 index 0000000..912ccfd --- /dev/null +++ b/src/db/offering_subject.rs @@ -0,0 +1,244 @@ +//! The syllabus selection junctions: `offering_subject` (what the grade-level +//! template teaches) and `class_course_subject` (what one section teaches for +//! itself), over the subject rows of [`crate::db::subject`]. The row types are +//! the subjects themselves — a selection is only membership — so every read +//! here answers `Vec` in the resolved listing order: **by subject +//! name, then subject id** (deterministic under any insert order). +//! +//! The class-side writes are the override machinery: each is **one +//! data-modifying-CTE statement** that flips `class_course.subjects_inherited` +//! in the same breath it inserts, deletes or sweeps the section's rows — the +//! flag can never drift from the table it governs, and this module never +//! touches `class_course` outside that flag. The reset is the same shape in +//! reverse: sweep the rows, flip the flag back to TRUE, one statement. + +use crate::database::Database; +use crate::domain::class_course::ClassCourseId; +use crate::domain::course::CourseId; +use crate::domain::course_offering::CourseOfferingId; +use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; +use crate::error::AppError; + +/// Map the junctions' foreign-key refusals to the caller's 404: an offering, +/// a section or a subject deleted between the service's up-front read and +/// this write cannot half-land (the same mapping +/// [`crate::db::subject::create`] uses for its course key). +fn gone(err: sqlx::Error) -> AppError { + if crate::database::foreign_key_violation(&err) { + AppError::NotFound + } else { + err.into() + } +} + +/// The offering's selected topics, name-then-id order. +pub async fn list_for_offering( + db: &Database, + offering: &CourseOfferingId, +) -> Result, AppError> { + let rows = sqlx::query_as!( + Subject, + r#"SELECT s.id AS "id: SubjectId", + s.course AS "course: CourseId", + s.name AS "name: SubjectName", + s.description AS "description: SubjectDescription" + FROM offering_subject os + JOIN subject s ON s.id = os.subject + WHERE os.offering = $1 + ORDER BY s.name ASC, s.id ASC"#, + offering.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows) +} + +/// The section's own selected topics — authoritative only while +/// `subjects_inherited` is FALSE, and empty-list-is-a-set then — name-then-id +/// order. +pub async fn list_for_class_course( + db: &Database, + class_course: &ClassCourseId, +) -> Result, AppError> { + let rows = sqlx::query_as!( + Subject, + r#"SELECT s.id AS "id: SubjectId", + s.course AS "course: CourseId", + s.name AS "name: SubjectName", + s.description AS "description: SubjectDescription" + FROM class_course_subject ccs + JOIN subject s ON s.id = ccs.subject + WHERE ccs.class_course = $1 + ORDER BY s.name ASC, s.id ASC"#, + class_course.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows) +} + +/// Add one topic to the offering's selection. Idempotent: re-adding a +/// selection the offering already holds writes nothing and answers `false` +/// (`true` = newly added), matching the junction idiom. +pub async fn add_for_offering( + db: &Database, + offering: &CourseOfferingId, + subject: &SubjectId, +) -> Result { + let added = sqlx::query!( + r#"INSERT INTO offering_subject (offering, subject) + VALUES ($1, $2) + ON CONFLICT DO NOTHING"#, + offering.uuid(), + subject.uuid(), + ) + .execute(db) + .await + .map_err(gone)?; + Ok(added.rows_affected() > 0) +} + +/// Drop one topic from the offering's selection. `false` when it was not +/// selected — an honest nothing-changed, which the service answers as a 404. +pub async fn remove_for_offering( + db: &Database, + offering: &CourseOfferingId, + subject: &SubjectId, +) -> Result { + let dropped = sqlx::query!( + r#"DELETE FROM offering_subject + WHERE offering = $1 AND subject = $2"#, + offering.uuid(), + subject.uuid(), + ) + .execute(db) + .await?; + Ok(dropped.rows_affected() > 0) +} + +/// Add one topic to the section's own set, flipping `subjects_inherited` to +/// FALSE **in the same statement** — the insert and the override switch are +/// one data-modifying-CTE unit, so a reader can never see a class-owned row +/// under a still-inheriting flag. Idempotent like the offering side: the +/// second add of one topic writes no row (`added` = false) but the intent — +/// "this section owns its set" — still stands, so the flip is unconditional +/// on a live instance. `live` = false means the instance vanished mid-flight; +/// the service answers that 404. +pub async fn add_for_class_course( + db: &Database, + class_course: &ClassCourseId, + subject: &SubjectId, +) -> Result<(bool, bool), AppError> { + let row = sqlx::query!( + r#"WITH flipped AS ( + UPDATE class_course + SET subjects_inherited = FALSE + WHERE id = $1 + RETURNING id + ), inserted AS ( + INSERT INTO class_course_subject (class_course, subject) + SELECT $1, $2 + WHERE EXISTS (SELECT 1 FROM flipped) + ON CONFLICT DO NOTHING + RETURNING subject + ) + SELECT EXISTS (SELECT 1 FROM flipped) AS "live!", + EXISTS (SELECT 1 FROM inserted) AS "added!""#, + class_course.uuid(), + subject.uuid(), + ) + .fetch_one(db) + .await + .map_err(gone)?; + Ok((row.live, row.added)) +} + +/// Drop one topic from the section's own set, flipping `subjects_inherited` +/// to FALSE in the same statement — but **only when a row actually went**: +/// a delete that finds nothing flips nothing, so the service can answer 404 +/// for a missing selection without a stray side effect on the flag. (`live` +/// = false: the instance is gone mid-flight.) +pub async fn remove_for_class_course( + db: &Database, + class_course: &ClassCourseId, + subject: &SubjectId, +) -> Result<(bool, bool), AppError> { + let row = sqlx::query!( + r#"WITH dropped AS ( + DELETE FROM class_course_subject + WHERE class_course = $1 AND subject = $2 + RETURNING subject + ), flipped AS ( + UPDATE class_course + SET subjects_inherited = FALSE + WHERE id = $1 AND EXISTS (SELECT 1 FROM dropped) + RETURNING id + ) + SELECT EXISTS (SELECT 1 FROM flipped) AS "live!", + EXISTS (SELECT 1 FROM dropped) AS "dropped!""#, + class_course.uuid(), + subject.uuid(), + ) + .fetch_one(db) + .await?; + Ok((row.live, row.dropped)) +} + +/// The reset door: sweep every class-owned row and flip +/// `subjects_inherited` back to TRUE — one statement, so the set and its +/// switch agree at every instant. The flip is unconditional on a live +/// instance: clearing an already-empty own set is exactly the request that +/// must restore inheritance. Answers the swept row count; `live` = false +/// means the instance vanished mid-flight. +pub async fn reset_for_class_course( + db: &Database, + class_course: &ClassCourseId, +) -> Result<(i64, bool), AppError> { + let row = sqlx::query!( + r#"WITH swept AS ( + DELETE FROM class_course_subject + WHERE class_course = $1 + RETURNING subject + ), restored AS ( + UPDATE class_course + SET subjects_inherited = TRUE + WHERE id = $1 + RETURNING id + ) + SELECT (SELECT count(*) FROM swept) AS "swept!: i64", + EXISTS (SELECT 1 FROM restored) AS "live!""#, + class_course.uuid(), + ) + .fetch_one(db) + .await?; + Ok((row.swept, row.live)) +} + +/// The resolved-membership probe behind the exam-question/homework tag rewire: +/// does `subject` sit in what this section *teaches* — its own rows while +/// `subjects_inherited` is FALSE, else the offering's set? One statement, so +/// the flag and the rows it reads agree as of one snapshot. `None` = the +/// instance is gone. +pub async fn resolves_for_class_course( + db: &Database, + class_course: &ClassCourseId, + subject: &SubjectId, +) -> Result, AppError> { + let row = sqlx::query!( + r#"SELECT CASE WHEN cc.subjects_inherited + THEN EXISTS (SELECT 1 + FROM offering_subject os + WHERE os.offering = cc.offering AND os.subject = $2) + ELSE EXISTS (SELECT 1 + FROM class_course_subject ccs + WHERE ccs.class_course = cc.id AND ccs.subject = $2) + END AS "member!" + FROM class_course cc + WHERE cc.id = $1"#, + class_course.uuid(), + subject.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(row.map(|row| row.member)) +} diff --git a/src/db/weekly_slot.rs b/src/db/weekly_slot.rs new file mode 100644 index 0000000..25a82a0 --- /dev/null +++ b/src/db/weekly_slot.rs @@ -0,0 +1,275 @@ +//! The `offering_slot` and `class_course_slot` tables: the reads and writes +//! behind the weekly plan. The row shape lives in +//! [`crate::domain::weekly_slot`]; the workflows (the overlap and cap checks, +//! the offer-side vs class-side doors) in [`crate::service::weekly_slot`]. +//! +//! Reads are plain ordered lists (`weekday`, then `starts_at`). The class-side +//! writes are the override doors: every statement that adds or drops a +//! section's own row also flips `class_course.weekly_plan_inherited` to +//! `FALSE`, and the reset flips it back to `TRUE` while deleting the rows — +//! flag and data in one statement, so the two can never be observed +//! disagreeing. +//! +//! Times cross the statement boundary as minutes past midnight: the +//! `::bigint`-bound minute is multiplied into an `interval` and cast to +//! `TIME` on the way in, and the read casts the stored `TIME` back through +//! `EXTRACT(EPOCH ...)` — the same "the cast is the statement's own" shape +//! every `SMALLINT`↔`i64` column here uses. + +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::weekly_slot::{SlotMinute, Weekday, WeeklySlot, WeeklySlotId}; +use crate::error::AppError; + +/// One offering's slots, weekday first then start time. +pub async fn list_for_offering( + db: &Database, + offering: &CourseOfferingId, +) -> Result, AppError> { + let mut conn = db.acquire().await?; + list_for_offering_on(&mut conn, offering).await +} + +/// One section's own slots, weekday first then start time — the offering's +/// rows are *not* consulted; that choice is the resolver's, off the flag. +pub async fn list_for_class( + db: &Database, + instance: &ClassCourseId, +) -> Result, AppError> { + let mut conn = db.acquire().await?; + list_for_class_on(&mut conn, instance).await +} + +pub(crate) async fn list_for_offering_on( + db: &mut PgConnection, + offering: &CourseOfferingId, +) -> Result, AppError> { + sqlx::query_as!( + WeeklySlot, + 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" + FROM offering_slot + WHERE offering = $1 + ORDER BY weekday, starts_at"#, + offering.uuid(), + ) + .fetch_all(db) + .await + .map_err(Into::into) +} + +pub(crate) async fn list_for_class_on( + db: &mut PgConnection, + instance: &ClassCourseId, +) -> Result, AppError> { + sqlx::query_as!( + WeeklySlot, + 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" + FROM class_course_slot + WHERE class_course = $1 + ORDER BY weekday, starts_at"#, + instance.uuid(), + ) + .fetch_all(db) + .await + .map_err(Into::into) +} + +/// Take the owner's row lock inside the caller's transaction, so two adds for +/// one owner cannot both clear the overlap/cap pre-check (READ COMMITTED sees +/// the rival's uncommitted insert as absent). `FOR NO KEY UPDATE`: it +/// serializes the slot writers against each other without blocking the +/// attach pump's `FOR KEY SHARE` reads. `Err(NotFound)` when the owner is +/// gone. +pub(crate) async fn lock_offering_tx( + tx: &mut PgConnection, + offering: &CourseOfferingId, +) -> Result<(), AppError> { + sqlx::query!( + r#"SELECT id AS "id: CourseOfferingId" FROM course_offering WHERE id = $1 + FOR NO KEY UPDATE"#, + offering.uuid(), + ) + .fetch_optional(&mut *tx) + .await? + .ok_or(AppError::NotFound) + .map(|_| ()) +} + +/// The class-side twin of [`lock_offering_tx`]. +pub(crate) async fn lock_class_tx( + tx: &mut PgConnection, + instance: &ClassCourseId, +) -> Result<(), AppError> { + sqlx::query!( + r#"SELECT id AS "id: ClassCourseId" FROM class_course WHERE id = $1 + FOR NO KEY UPDATE"#, + instance.uuid(), + ) + .fetch_optional(&mut *tx) + .await? + .ok_or(AppError::NotFound) + .map(|_| ()) +} + +/// Insert one slot of the offering's template week, inside the caller's +/// transaction. The `(offering, weekday, starts_at)` `UNIQUE` — reachable +/// only by a duplicate insert that raced the caller's pre-check — answers +/// 409 `slot_overlap`, the same refusal the pre-check gives the settled +/// duplicate. +pub(crate) async fn add_for_offering_tx( + tx: &mut PgConnection, + slot: &WeeklySlot, + offering: &CourseOfferingId, +) -> Result { + sqlx::query_as!( + WeeklySlot, + r#"INSERT INTO offering_slot (id, offering, weekday, starts_at, ends_at) + VALUES ($1, $2, $3, + ($4::bigint * interval '1 minute')::time, + ($5::bigint * interval '1 minute')::time) + 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""#, + slot.get_id().uuid(), + offering.uuid(), + slot.get_weekday().get(), + slot.get_starts_at().get(), + slot.get_ends_at().get(), + ) + .fetch_one(&mut *tx) + .await + .map_err(|e| { + if unique_violation(&e).is_some() { + AppError::ConflictCoded { + code: "slot_overlap", + message: "a slot already occupies this weekday and start time".into(), + } + } else { + e.into() + } + }) +} + +/// Insert one slot of the section's own week **and flip +/// `weekly_plan_inherited = FALSE` in the same statement** — the data-modifying +/// CTE that makes the row and the override one write. A `flip` that matched no +/// row means the instance vanished mid-transaction: `Err(NotFound)` rolls the +/// insert back. +pub(crate) async fn add_for_class_tx( + tx: &mut PgConnection, + slot: &WeeklySlot, + instance: &ClassCourseId, +) -> Result { + sqlx::query_as!( + WeeklySlot, + r#"WITH ins AS ( + INSERT INTO class_course_slot (id, class_course, weekday, starts_at, ends_at) + VALUES ($1, $2, $3, + ($4::bigint * interval '1 minute')::time, + ($5::bigint * interval '1 minute')::time) + RETURNING id, weekday, starts_at, ends_at + ), flip AS ( + UPDATE class_course SET weekly_plan_inherited = FALSE + WHERE id = $2 AND EXISTS (SELECT 1 FROM ins) + RETURNING id + ) + 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" + FROM ins + WHERE EXISTS (SELECT 1 FROM flip)"#, + slot.get_id().uuid(), + instance.uuid(), + slot.get_weekday().get(), + slot.get_starts_at().get(), + slot.get_ends_at().get(), + ) + .fetch_optional(&mut *tx) + .await? + .ok_or(AppError::NotFound) +} + +/// Drop one slot of the offering's template week. A slot of another offering, +/// or one already gone, is `Err(NotFound)` — the id alone never deletes; the +/// owner scoping does. +pub async fn remove_for_offering( + db: &Database, + offering: &CourseOfferingId, + slot: &WeeklySlotId, +) -> Result<(), AppError> { + let result = sqlx::query!( + "DELETE FROM offering_slot WHERE id = $1 AND offering = $2", + slot.uuid(), + offering.uuid(), + ) + .execute(db) + .await?; + if result.rows_affected() == 0 { + return Err(AppError::NotFound); + } + Ok(()) +} + +/// Drop one slot of the section's own week **and flip the flag to `FALSE` in +/// the same statement** — dropping a row is an override decision even when it +/// empties the set (an empty own set is how a section clears its timetable). +/// `Err(NotFound)` when the id names no row of this instance: the flag stays +/// as it was. +pub async fn remove_for_class( + db: &Database, + instance: &ClassCourseId, + slot: &WeeklySlotId, +) -> Result<(), AppError> { + sqlx::query!( + r#"WITH del AS ( + DELETE FROM class_course_slot WHERE id = $1 AND class_course = $2 + RETURNING id + ), flip AS ( + UPDATE class_course SET weekly_plan_inherited = FALSE + WHERE id = $2 AND EXISTS (SELECT 1 FROM del) + RETURNING id + ) + SELECT id AS "id: ClassCourseId" FROM flip"#, + slot.uuid(), + instance.uuid(), + ) + .fetch_optional(db) + .await? + .ok_or(AppError::NotFound) + .map(|_| ()) +} + +/// Reset the section's weekly plan to inherit: delete every one of its own +/// slots and flip `weekly_plan_inherited` back to `TRUE` in the same +/// statement. Idempotent for an already-inherited section (the delete finds +/// nothing, the flip re-asserts `TRUE`); `Err(NotFound)` when the instance +/// itself is gone. +pub async fn reset_for_class(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> { + sqlx::query!( + r#"WITH del AS ( + DELETE FROM class_course_slot WHERE class_course = $1 + RETURNING id + ), flip AS ( + UPDATE class_course SET weekly_plan_inherited = TRUE + WHERE id = $1 + RETURNING id + ) + SELECT id AS "id: ClassCourseId" FROM flip"#, + instance.uuid(), + ) + .fetch_optional(db) + .await? + .ok_or(AppError::NotFound) + .map(|_| ()) +} diff --git a/src/domain/academic_year.rs b/src/domain/academic_year.rs index 31761f9..4ce0213 100644 --- a/src/domain/academic_year.rs +++ b/src/domain/academic_year.rs @@ -13,7 +13,8 @@ use serde::{Deserialize, Serialize}; use sqlx::types::Json; -use crate::constant::{MAX_ACADEMIC_YEAR_NAME_LEN, MAX_CLASS_GRADE_LEN}; +use crate::constant::MAX_ACADEMIC_YEAR_NAME_LEN; +use crate::domain::grade::GradeLevel; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -81,39 +82,28 @@ impl AcademicYearName { } /// One grade-promotion mapping: a student who finished `from_grade` moves to -/// `to_grade` at rollover. +/// `to_grade` at rollover. Both ends are ladder rungs (`GradeLevel`), stored +/// as the integers they are — the JSON column serializes them as numbers. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct GradePromotion { - from_grade: String, - to_grade: String, + from_grade: GradeLevel, + to_grade: GradeLevel, } impl GradePromotion { - pub fn try_new(from_grade: &str, to_grade: &str) -> Result { - let bound = |field: &'static str, value: &str| { - if value.is_empty() || value.chars().count() > MAX_CLASS_GRADE_LEN { - Err(ValidationError::Invalid { - field, - reason: "grade labels must be 1 to 20 characters", - }) - } else { - Ok(()) - } - }; - bound("from_grade", from_grade)?; - bound("to_grade", to_grade)?; - Ok(Self { - from_grade: from_grade.to_string(), - to_grade: to_grade.to_string(), - }) + pub fn new(from_grade: GradeLevel, to_grade: GradeLevel) -> Self { + Self { + from_grade, + to_grade, + } } - pub fn get_from_grade(&self) -> &str { - &self.from_grade + pub fn get_from_grade(&self) -> GradeLevel { + self.from_grade } - pub fn get_to_grade(&self) -> &str { - &self.to_grade + pub fn get_to_grade(&self) -> GradeLevel { + self.to_grade } } @@ -188,12 +178,12 @@ impl AcademicYear { /// The grade a section at `grade` rolls into, or `None` when the grade has no /// promotion entry (graduation). - pub fn promotion_for(&self, grade: &str) -> Option<&str> { + pub fn promotion_for(&self, grade: GradeLevel) -> Option { self.grade_promotions .0 .iter() .find(|promo| promo.from_grade == grade) - .map(|promo| promo.to_grade.as_str()) + .map(|promo| promo.to_grade) } pub fn get_class_count(&self) -> i64 { @@ -226,10 +216,14 @@ mod tests { } #[tokio::test] - async fn promotions_validate_both_labels() { - assert!(GradePromotion::try_new("5", "6").is_ok()); - assert!(GradePromotion::try_new("", "6").is_err()); - assert!(GradePromotion::try_new("5", &"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err()); + async fn promotions_carry_ladder_rungs() { + let (five, six) = ( + GradeLevel::new(5).unwrap(), + GradeLevel::new(6).unwrap(), + ); + let promo = GradePromotion::new(five, six); + assert_eq!(promo.get_from_grade(), five); + assert_eq!(promo.get_to_grade(), six); } #[tokio::test] @@ -247,10 +241,17 @@ mod tests { ts(0), ts(1000), creator, - vec![GradePromotion::try_new("5", "6").unwrap()], + vec![GradePromotion::new( + GradeLevel::new(5).unwrap(), + GradeLevel::new(6).unwrap(), + )], ) .unwrap(); - assert_eq!(year.promotion_for("5"), Some("6")); - assert_eq!(year.promotion_for("12"), None); + assert_eq!( + year.promotion_for(GradeLevel::new(5).unwrap()), + Some(GradeLevel::new(6).unwrap()) + ); + // The ladder's top rung graduates unless the school names a promotion. + assert_eq!(year.promotion_for(GradeLevel::new(12).unwrap()), None); } } diff --git a/src/domain/class_blueprint.rs b/src/domain/class_blueprint.rs index 28554af..64ce085 100644 --- a/src/domain/class_blueprint.rs +++ b/src/domain/class_blueprint.rs @@ -9,7 +9,7 @@ //! `enrollment` rows, and an elective placed by hand next to them is still an //! individual enrollment nothing here can see. //! -//! This module is the pure shape: the id (the grade label *is* the primary +//! This module is the pure shape: the id (the ladder rung *is* the unique //! key, so "one blueprint per grade" holds by construction), the row, the //! pump's report types ([`Pumped`], [`Skip`], [`SectionStatus`]) and the //! shared skip vocabulary ([`skip_reason`]). @@ -21,43 +21,55 @@ use crate::constant::MAX_CLASS_COURSES; use crate::db::class_pump::{Attached, Axis}; use crate::domain::class_course::ClassCourse; -use crate::domain::class_group::{ClassGrade, ClassGroupId}; +use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; +use crate::domain::grade::GradeLevel; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// A grade label as the table's `TEXT` primary key — one blueprint per grade -/// by construction, like the settings singleton's `'school'` row: the key is -/// a name, not a minted entity id. -#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +/// A ladder rung as the table's unique key — one blueprint per grade by +/// construction, like the settings singleton's `'school'` row: the key is a +/// position, not a minted entity id. The stored row keeps its surrogate uuid +/// primary key (what `class_course.source` references); this id is the +/// identity the API speaks, and a key that parses to no rung (`from_key`'s +/// `-1` fallback) matches no row. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] #[sqlx(transparent)] -pub struct ClassBlueprintId(String); +pub struct ClassBlueprintId(i16); impl ClassBlueprintId { - /// The key one grade label always maps to. - pub fn for_grade(grade: &ClassGrade) -> Self { - Self(grade.as_str().to_string()) + /// The key one ladder rung always maps to. + pub fn for_grade(grade: &GradeLevel) -> Self { + Self(grade.get()) } + /// Parses a wire path key. A key that is not a ladder number parses to + /// `-1`, which matches no row — the nil-uuid shape [`ClassGroupId`] + /// uses, so an unaddressable grade answers a `404`, never a decode panic. pub fn from_key(key: &str) -> Self { - Self(key.to_string()) + Self(key.trim().parse::().unwrap_or(-1)) } - pub fn key(&self) -> &str { - &self.0 + /// The inner rung, for the queries that cannot take the newtype. + pub fn get(self) -> i16 { + self.0 + } + + pub fn key(&self) -> String { + self.0.to_string() } } -/// One grade's template. The id is the grade label itself — the key one -/// grade always maps to — stored here beside the `grade` field so a read -/// never has to parse a record id back into a domain value. `courses` is -/// not a column of the row: it is the `blueprint_course` junction, joined +/// One grade's template. The id is the ladder rung itself — the key one +/// grade always maps to — stored here beside the `grade_level` field so a +/// read never has to parse a record id back into a domain value. `courses` +/// is not a column of the row: it is the `blueprint_course` junction, joined /// on by the db layer (sorted by course, which is the order every CAS /// comparison relies on). #[derive(Debug, Clone)] pub struct ClassBlueprint { pub(crate) id: ClassBlueprintId, - pub(crate) grade: ClassGrade, + pub(crate) grade_level: GradeLevel, pub(crate) courses: Vec, pub(crate) creator: UserId, } @@ -75,13 +87,12 @@ pub struct Skip { /// What a pump did: how many sections it reached, and the pairs it refused. /// -/// `matched` exists because an empty `skipped` is not success on its own. A -/// grade label is free text ([`ClassGrade`]) and -/// [`crate::db::class_group::list_for_grade`] -/// matches it exactly, so a blueprint keyed `"9 "` reaches none of the sections -/// keyed `"9"` — and with nothing to skip it answers exactly like a pump that -/// stocked every one of them. The count is the only thing that tells those -/// apart. +/// `matched` exists because an empty `skipped` is not success on its own. The +/// sections are matched by their ladder rung +/// ([`crate::db::class_group::list_for_grade`]), so a blueprint keyed `9` +/// reaches none of the sections keyed `10` — and with nothing to skip it +/// answers exactly like a pump that stocked every one of them. The count is +/// the only thing that tells those apart. /// /// A struct rather than a pair with /// [`crate::service::class_blueprint::set_courses`]'s: three @@ -129,8 +140,8 @@ impl ClassBlueprint { &self.id } - pub fn get_grade(&self) -> &ClassGrade { - &self.grade + pub fn get_grade_level(&self) -> GradeLevel { + self.grade_level } pub fn get_courses(&self) -> &[CourseId] { @@ -141,30 +152,6 @@ impl ClassBlueprint { &self.creator } - /// The grade a blueprint may be keyed on. Non-empty, because the label is - /// the primary key and there is no blueprint for "no grade"; and free of - /// the characters that would make that key unaddressable as a URL path - /// segment, the second gate [`crate::domain::menu::MenuSlot`] carries for - /// the same reason. Grades were never validated for this, so a *class* may - /// already carry a label refused here — it simply cannot have a blueprint - /// until it is renamed, which is a 400 the caller can read rather than a - /// route nobody can reach. - pub fn grade_key(value: &str) -> Result { - if value.is_empty() { - return Err(AppError::Validation(ValidationError::Empty("grade"))); - } - if value - .chars() - .any(|c| matches!(c, '/' | '\\' | '?' | '#' | '%')) - { - return Err(AppError::Validation(ValidationError::Invalid { - field: "grade", - reason: "must not contain / \\ ? # or %", - })); - } - Ok(ClassGrade::try_new(value)?) - } - /// The course list a blueprint may hold: deduplicated, and no longer than /// one class may carry — a blueprint above that ceiling would guarantee a /// skip on every class it ever reached. @@ -190,19 +177,22 @@ impl ClassBlueprint { mod tests { use super::*; + /// A blueprint's key is a ladder rung: a key that names no rung (`from_key` + /// falls back to `-1`) matches no row, so an unaddressable grade is a + /// `404` at the route rather than a decode panic — and `for_grade` is the + /// rung the class carries, byte for byte. #[test] - fn a_grade_key_must_be_addressable() { - assert!(ClassBlueprint::grade_key("").is_err()); - assert!(ClassBlueprint::grade_key("9/A").is_err()); - assert!(ClassBlueprint::grade_key("9%A").is_err()); + fn a_blueprint_key_is_a_ladder_rung() { + assert_eq!(ClassBlueprintId::from_key("9"), ClassBlueprintId(9)); + assert_eq!(ClassBlueprintId::from_key(" 9 "), ClassBlueprintId(9)); + assert_eq!(ClassBlueprintId::from_key("anaokulu"), ClassBlueprintId(-1)); + assert_eq!(ClassBlueprintId::from_key(""), ClassBlueprintId(-1)); + assert_eq!(ClassBlueprintId::from_key("9/A"), ClassBlueprintId(-1)); assert_eq!( - ClassBlueprint::grade_key("9-A") - .unwrap() - .as_str() - .to_string(), - "9-A" + ClassBlueprintId::for_grade(&GradeLevel::new(9).unwrap()), + ClassBlueprintId::from_key("9") ); - assert!(ClassBlueprint::grade_key(&"x".repeat(1000)).is_err()); + assert_eq!(ClassBlueprintId::from_key("9").key(), "9"); } /// The list is a *set*: a caller sending the same course twice must not diff --git a/src/domain/class_course.rs b/src/domain/class_course.rs index bed5b4e..cf594f7 100644 --- a/src/domain/class_course.rs +++ b/src/domain/class_course.rs @@ -4,17 +4,31 @@ //! attaching it to a class section mints one of these rows, and exams, sessions, //! roll-call, homework and enrollments all key on the instance — so two //! sections teaching the same course have separate rosters, exams, timetables -//! and teachers. The row carries the weekly hours (`ders_saati`, the report-card -//! weight) and whether it counts toward the report card. +//! and teachers. //! -//! The attach/detach workflows live in [`crate::service::class_course`]; the -//! row's reads in [`crate::db::class_course`] — this file is the row shape and -//! its id. +//! The row teaches **from its offering** — the +//! [`crate::domain::course_offering::CourseOffering`] template for the +//! course × the class's grade level, resolved (and auto-created empty) by the +//! attach pump. Every content field on the instance is an *override*: `title`, +//! `description`, `ders_saati` and `counts_toward_karne` are nullable, and a +//! `NULL` means inherit — from the offering, and through it from the catalog +//! row / the constants (1 weekly hour, counted toward the karne). The three +//! `*_inherited` flags carry the same rule for the set-valued policies +//! (subjects, exam weights, weekly plan), which cannot be `NULL`: `TRUE` = +//! follow the offering's set, `FALSE` = this section's own table is +//! authoritative, including when it is empty. Override-or-inherit, never +//! merge. +//! +//! The attach/detach workflows live in [`crate::service::class_course`] (which +//! also owns [`crate::service::class_course::resolve_policy`], the effective +//! `ders_saati`/`counts_toward_karne` a read should use); the row's reads in +//! [`crate::db::class_course`] — this file is the row shape and its id. use crate::constant::{MAX_DERS_SAATI, MIN_DERS_SAATI}; use crate::domain::class_blueprint::ClassBlueprintId; use crate::domain::class_group::ClassGroupId; -use crate::domain::course::CourseId; +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; +use crate::domain::course_offering::CourseOfferingId; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -52,6 +66,9 @@ impl ClassCourseId { /// Weekly lesson hours of an instance: the weight the instance carries in the /// year's report-card average, and the count a timetable grid would lay out. +/// As a *column* it is the instance's own override — `NULL` inherits from the +/// offering's `default_ders_saati`, and the offering's `NULL` means the +/// constant floor ([`crate::constant::MIN_DERS_SAATI`]). #[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] #[sqlx(transparent)] pub struct DersSaati(i64); @@ -67,20 +84,51 @@ impl DersSaati { Ok(Self(value)) } - pub fn as_i64(&self) -> i64 { + pub fn as_i64(self) -> i64 { self.0 } } +/// A named instance override the reset door can clear back to inherit. The +/// scalars go `NULL` (the offering's default — then the catalog row or the +/// constant — applies again); the three set flags flip back to `TRUE` (the +/// offering's set is authoritative again). The wire spellings live with the +/// reset route's parser in [`crate::service::class_course`]; this enum is the +/// closed set both sides answer to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OverrideField { + /// The section's own title. + Title, + /// The section's own description. + Description, + /// The section's own weekly hours. + DersSaati, + /// The section's own report-card policy. + CountsTowardKarne, + /// The section's own subject set (the flag; set-row deletion rides the + /// subject lane's reset). + Subjects, + /// The section's own exam-kind weights (the flag). + ExamWeights, + /// The section's own weekly plan (the flag). + WeeklyPlan, +} + /// One course taught in one class. `attached_by` is who attached it, `source` -/// the blueprint that placed it (absent for a hand attach). `ders_saati` and -/// `counts_toward_karne` are the instance's own policy — what two sections -/// teaching the same catalog course may legitimately differ on. +/// the blueprint that placed it (absent for a hand attach). The content +/// fields are the instance's own *overrides* — `None` inherits from the +/// offering ([`Self::get_offering`]), which is what two sections teaching the +/// same catalog course at the same grade usually want to differ from only +/// deliberately. #[derive(Debug, Clone, sqlx::FromRow)] pub struct ClassCourse { pub(crate) id: ClassCourseId, pub(crate) class: ClassGroupId, pub(crate) course: CourseId, + /// The grade-level template this instance teaches from — always set: the + /// attach pump resolves it (auto-creating the empty template when the + /// grade is untouched) in the same transaction as the insert. + pub(crate) offering: CourseOfferingId, pub(crate) attached_by: UserId, /// The grade blueprint that placed this attachment, absent when a human /// attached the course to this class directly — read the same way as @@ -88,8 +136,13 @@ pub struct ClassCourse { /// is a blueprint's to take back, so a hand-attached course survives every /// blueprint sweep. pub(crate) source: Option, - pub(crate) ders_saati: DersSaati, - pub(crate) counts_toward_karne: bool, + pub(crate) title: Option, + pub(crate) description: Option, + pub(crate) ders_saati: Option, + pub(crate) counts_toward_karne: Option, + pub(crate) subjects_inherited: bool, + pub(crate) exam_weights_inherited: bool, + pub(crate) weekly_plan_inherited: bool, pub(crate) enrollment_count: i64, pub(crate) attached_at: Timestamp, } @@ -107,6 +160,13 @@ impl ClassCourse { &self.course } + /// The grade-level template this instance teaches from. The effective + /// values the instance inherits ride + /// [`crate::service::class_course::resolve_policy`]. + pub fn get_offering(&self) -> &CourseOfferingId { + &self.offering + } + pub fn get_attached_by(&self) -> &UserId { &self.attached_by } @@ -116,14 +176,48 @@ impl ClassCourse { self.source.as_ref() } - pub fn get_ders_saati(&self) -> DersSaati { + /// The instance's own title override, `None` = inherit. + pub fn get_title(&self) -> Option<&CourseTitle> { + self.title.as_ref() + } + + /// The instance's own description override, `None` = inherit. + pub fn get_description(&self) -> Option<&CourseDescription> { + self.description.as_ref() + } + + /// The instance's own weekly-hours override, `None` = inherit (the + /// offering's default, else 1). The *effective* value — what a read + /// should present — is [`crate::service::class_course::resolve_policy`]'s + /// answer, not this one. + pub fn get_ders_saati(&self) -> Option { self.ders_saati } - pub fn counts_toward_karne(&self) -> bool { + /// The instance's own report-card policy override, `None` = inherit (the + /// offering's default, else counted). + pub fn counts_toward_karne(&self) -> Option { self.counts_toward_karne } + /// Whether this section follows the offering's subject set (`TRUE`) or + /// keeps its own `class_course_subject` table authoritative (`FALSE`, + /// including when that table is empty — that is how a section clears its + /// syllabus). + pub fn subjects_inherited(&self) -> bool { + self.subjects_inherited + } + + /// The same override switch for the section's exam-kind weights. + pub fn exam_weights_inherited(&self) -> bool { + self.exam_weights_inherited + } + + /// The same override switch for the section's weekly plan. + pub fn weekly_plan_inherited(&self) -> bool { + self.weekly_plan_inherited + } + pub fn get_enrollment_count(&self) -> i64 { self.enrollment_count } diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 509c731..02921da 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -16,12 +16,13 @@ //! the route-facing wrappers in [`crate::service::class_group`] — this file is //! the row shape, its newtypes and getters. -use crate::constant::{MAX_CLASS_GRADE_LEN, MAX_CLASS_NAME_LEN}; +use crate::constant::MAX_CLASS_NAME_LEN; use crate::domain::academic_year::AcademicYearId; +use crate::domain::grade::GradeLevel; use crate::domain::monotonic_id::next_uuid; use crate::domain::user::UserId; use crate::error::ValidationError; -use crate::validate::{validate_optional, validate_required}; +use crate::validate::validate_required; #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] #[sqlx(transparent)] @@ -64,24 +65,6 @@ impl ClassName { } } -/// The school's own label for the year a class sits in ("9", "10-A", -/// "kindergarten"). Free text on purpose — no school's grade ladder is the next -/// one's — and optional: a club-shaped class has no grade at all. -#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] -#[sqlx(transparent)] -pub struct ClassGrade(String); - -impl ClassGrade { - pub fn try_new(value: &str) -> Result { - validate_optional("grade", value, MAX_CLASS_GRADE_LEN)?; - Ok(Self(value.to_string())) - } - - pub fn as_str(&self) -> &str { - &self.0 - } -} - /// One class. `creator` is who made it; the two refcounts behind the delete /// guard are database-side columns only, so no whole-row save can clobber one /// (see [`crate::db::cap`]). @@ -90,12 +73,17 @@ impl ClassGrade { /// refcounted, and merely a label pointing at a teacher-or-higher account — the /// web layer holds that bar, and a demotion sweeps the column /// ([`crate::db::class_group::unassign_everywhere`]). +/// +/// `grade_level` is the section's rung on the shared grade ladder +/// ([`GradeLevel`]) — required, not a label the school makes up: a club-shaped +/// *class* still sits at a grade, and it is the school-wide club/study +/// *courses* that belong to no section at all. #[derive(Debug, Clone, sqlx::FromRow)] pub struct ClassGroup { pub(crate) id: ClassGroupId, pub(crate) creator: UserId, pub(crate) name: ClassName, - pub(crate) grade: Option, + pub(crate) grade_level: GradeLevel, pub(crate) year: Option, pub(crate) teacher: Option, } @@ -113,8 +101,8 @@ impl ClassGroup { &self.name } - pub fn get_grade(&self) -> Option<&ClassGrade> { - self.grade.as_ref() + pub fn get_grade_level(&self) -> GradeLevel { + self.grade_level } pub fn get_year(&self) -> Option<&AcademicYearId> { @@ -136,13 +124,14 @@ mod tests { use super::*; #[test] - fn name_is_required_and_grade_is_optional() { + fn name_is_required_and_the_grade_is_a_ladder_rung() { assert!(ClassName::try_new("9-A").is_ok()); assert!(ClassName::try_new("").is_err()); assert!(ClassName::try_new(" ").is_err()); assert!(ClassName::try_new(&"x".repeat(MAX_CLASS_NAME_LEN + 1)).is_err()); - assert!(ClassGrade::try_new("").is_ok()); - assert!(ClassGrade::try_new("anaokulu").is_ok()); - assert!(ClassGrade::try_new(&"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err()); + assert!(GradeLevel::new(0).is_ok()); + assert!(GradeLevel::new(12).is_ok()); + assert!(GradeLevel::new(13).is_err()); + assert!(GradeLevel::new(-1).is_err()); } } diff --git a/src/domain/course_offering.rs b/src/domain/course_offering.rs new file mode 100644 index 0000000..3bc1bc9 --- /dev/null +++ b/src/domain/course_offering.rs @@ -0,0 +1,120 @@ +//! The grade-level course **template**: one `course_offering` row per +//! (course × grade_level), the content every section at that grade teaches +//! from — title, description, the weekly-hours and report-card defaults. +//! +//! A course stays the school-wide catalog row and the identity of the ders; +//! the offering is the grade axis' slice of it. Every +//! [`crate::domain::class_course::ClassCourse`] instance points at exactly one +//! offering (its `offering` link) and may override any content field on the +//! instance row; **unset = inherit** from the offering, and the offering's +//! unset = fall back to the catalog row / the constants (1 weekly hour, +//! counted toward the karne). Override-or-inherit, never merge. +//! +//! The CRUD workflows live in [`crate::service::course_offering`], the SQL in +//! [`crate::db::course_offering`]; this file is the row shape and its id. + +use crate::domain::class_course::DersSaati; +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; +use crate::domain::grade::GradeLevel; +use crate::domain::monotonic_id::next_uuid; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; + +/// The identity of one course×grade offering. A UUIDv7 minted by the +/// process-wide monotonic generator, like every other row id in the repo. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct CourseOfferingId(uuid::Uuid); + +impl CourseOfferingId { + 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::Uuid { + self.0 + } + + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. + pub fn from_key(key: &str) -> Self { + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) + } + + /// The bare uuid wire form. + pub fn key(&self) -> String { + self.0.to_string() + } +} + +/// One course as one grade teaches it — the template a class section's +/// instance inherits from. Every content field is nullable: a `NULL` is not +/// "no value" but "inherit from the catalog course" (`title`, `description`) +/// or "use the constant" (`default_ders_saati` → 1, +/// `default_counts_toward_karne` → `TRUE`). An offering minted by the attach +/// pump starts with all of them unset, so an untouched grade teaches exactly +/// what the catalog row says. +/// +/// `created_by` is who minted the row — the manager that created it on +/// purpose, or the actor whose attach auto-created it. +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct CourseOffering { + pub(crate) id: CourseOfferingId, + pub(crate) course: CourseId, + pub(crate) grade_level: GradeLevel, + pub(crate) title: Option, + pub(crate) description: Option, + pub(crate) default_ders_saati: Option, + pub(crate) default_counts_toward_karne: Option, + pub(crate) created_by: UserId, + pub(crate) created_at: Timestamp, + pub(crate) updated_at: Timestamp, +} + +impl CourseOffering { + pub fn get_id(&self) -> &CourseOfferingId { + &self.id + } + + pub fn get_course(&self) -> &CourseId { + &self.course + } + + pub fn get_grade_level(&self) -> GradeLevel { + self.grade_level + } + + /// The offering's own title override, `None` = the catalog course's title. + pub fn get_title(&self) -> Option<&CourseTitle> { + self.title.as_ref() + } + + /// The offering's own description override, `None` = the catalog's. + pub fn get_description(&self) -> Option<&CourseDescription> { + self.description.as_ref() + } + + /// The grade's default weekly hours, `None` = the constant floor (1). + pub fn get_default_ders_saati(&self) -> Option { + self.default_ders_saati + } + + /// The grade's default report-card policy, `None` = counted (`TRUE`). + pub fn get_default_counts_toward_karne(&self) -> Option { + self.default_counts_toward_karne + } + + pub fn get_created_by(&self) -> &UserId { + &self.created_by + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + pub fn get_updated_at(&self) -> Timestamp { + self.updated_at + } +} diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index 811a88a..de44ac6 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -291,8 +291,10 @@ impl QuestionSpec { /// One question of an exam. Order within the exam is the id's creation order; /// the kind-dependent columns always satisfy the /// [`QuestionSpec`] invariants because every write goes through one. Every -/// question links to a subject of the exam's course — the handlers verify the -/// subject's course matches before any write. +/// question links to a subject of the exam's course, and — since the +/// course-template system — to one the exam's *instance* actually teaches: +/// the service validates both halves of that rule +/// ([`crate::service::subject::in_instance`]) before any write. #[derive(Debug, Clone, sqlx::FromRow)] pub struct ExamQuestion { pub(crate) id: ExamQuestionId, diff --git a/src/domain/exam_weight.rs b/src/domain/exam_weight.rs new file mode 100644 index 0000000..2a6366e --- /dev/null +++ b/src/domain/exam_weight.rs @@ -0,0 +1,81 @@ +//! Exam-kind weights an offering or a class section overrides: one row per +//! (owner, kind) naming a kind that exists in `settings.exam_kinds` and the +//! weight it carries *there*. +//! +//! The rows are the override levels of the resolution chain +//! ([`crate::service::exam_weight::resolve`]); this file is the row shape, its +//! bounds and the constant floor. The school's settings keep the *default* +//! weight of every kind — an override reweights one grade or one section, and +//! the settings vocabulary is exactly what the rows may name. + +use crate::constant::{MAX_EXAM_KIND_WEIGHT, MIN_EXAM_KIND_WEIGHT}; +use crate::error::ValidationError; + +/// The weight a kind resolves to when nothing in the chain names it: a retired +/// kind (settings edits never rewrite history) and an own-set-in-force section +/// with no row for the kind both count an exam of it once. +pub const FALLBACK_WEIGHT: i64 = 1; + +/// One weight override: `kind` is the settings kind exactly as spelled there +/// (the service layer refuses anything else before a row is written), `weight` +/// the weight it takes in averages computed under the owning level. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::FromRow)] +pub struct ExamWeight { + pub(crate) kind: String, + pub(crate) weight: i64, +} + +impl ExamWeight { + /// Bounds check only — `weight` must sit inside the same 1..=100 window + /// the settings themselves enforce + /// ([`crate::constant::MIN_EXAM_KIND_WEIGHT`]/[`MAX_EXAM_KIND_WEIGHT`]). + /// Whether `kind` names a kind the school runs is the service layer's + /// settings lookup; this constructor cannot see a store. + pub fn try_new(kind: impl Into, weight: i64) -> Result { + if !(MIN_EXAM_KIND_WEIGHT..=MAX_EXAM_KIND_WEIGHT).contains(&weight) { + return Err(ValidationError::Invalid { + field: "weight", + reason: "must be between 1 and 100", + }); + } + Ok(Self { + kind: kind.into(), + weight, + }) + } + + pub fn get_kind(&self) -> &str { + &self.kind + } + + pub fn get_weight(&self) -> i64 { + self.weight + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bounds_reuse_the_settings_window() { + assert!(ExamWeight::try_new("final", MIN_EXAM_KIND_WEIGHT).is_ok()); + assert!(ExamWeight::try_new("final", MAX_EXAM_KIND_WEIGHT).is_ok()); + let zero = ExamWeight::try_new("final", MIN_EXAM_KIND_WEIGHT - 1).unwrap_err(); + let over = ExamWeight::try_new("final", MAX_EXAM_KIND_WEIGHT + 1).unwrap_err(); + for err in [zero, over] { + assert!( + matches!(&err, ValidationError::Invalid { field: "weight", .. }), + "a weight outside 1..=100 is a `weight` validation error: {err:?}" + ); + } + } + + #[test] + fn the_floor_is_one_and_the_kind_rides_verbatim() { + assert_eq!(FALLBACK_WEIGHT, 1); + let row = ExamWeight::try_new("Final", 2).unwrap(); + assert_eq!(row.get_kind(), "Final", "kind case is the caller's to match"); + assert_eq!(row.get_weight(), 2); + } +} diff --git a/src/domain/grade.rs b/src/domain/grade.rs new file mode 100644 index 0000000..4cffc24 --- /dev/null +++ b/src/domain/grade.rs @@ -0,0 +1,89 @@ +//! The grade ladder: the validated position a class section — and, one layer +//! up, its course blueprint — occupies on the school's single axis of years. +//! +//! It replaces the old free-text `ClassGrade`: "9", "10-A" and "anaokulu" were +//! three spellings no query could order, group or blueprint against without a +//! school-wide convention nobody enforced. The ladder is an integer +//! `0..=12` — `0` is anaokulu, `1..=12` the school years — so "every section +//! at one grade" is one equality and the blueprint is keyed by the same value +//! the class carries. +//! +//! The wire format is the **integer** itself: every DTO carries +//! `grade_level: 0..=12`, and the only strings are [`GradeLevel::label`]'s +//! display/AI-scope labels (`"Anaokulu"`, `"1"`..`"12"`), which are rendered, +//! never parsed back. +//! +//! The bounds live in [`crate::constant`] beside every other published limit +//! (`GET /limits` serves them); this module owns the type. + +use crate::constant::{MAX_GRADE_LEVEL, MIN_GRADE_LEVEL}; +use crate::error::ValidationError; + +/// One rung of the grade ladder: `0` = anaokulu, `1..=12` = school years. +/// +/// `sqlx(transparent)` over the `i16` is what makes the column a plain +/// `SMALLINT` — the driver checks the type, the `CHECK +/// (grade_level BETWEEN 0 AND 12)` in the DDL is the stored mirror of +/// [`GradeLevel::new`], and nothing out of range can be constructed in Rust. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, sqlx::Type, serde::Serialize, serde::Deserialize, +)] +#[sqlx(transparent)] +#[serde(transparent)] +pub struct GradeLevel(i16); + +impl GradeLevel { + /// The rung `raw` names, or a validation error when it is off the ladder — + /// the `400` both the class and the blueprint write paths answer with. + pub fn new(raw: i16) -> Result { + if !(MIN_GRADE_LEVEL..=MAX_GRADE_LEVEL).contains(&raw) { + return Err(ValidationError::Invalid { + field: "grade_level", + reason: "must be 0 (anaokulu) through 12", + }); + } + Ok(Self(raw)) + } + + /// Kindergarten, the ladder's floor. + pub fn anaokulu() -> Self { + Self(MIN_GRADE_LEVEL) + } + + /// The integer the wire and the `grade_level` column carry. + pub fn get(self) -> i16 { + self.0 + } + + /// The display label: `"Anaokulu"` at the floor, the year number + /// everywhere else. The one spelling the AI scope (`sinif`) and every + /// human-facing surface see — an index is safe because the tuple field is + /// private and only [`GradeLevel::new`]/[`GradeLevel::anaokulu`] construct. + pub fn label(self) -> &'static str { + const LABELS: [&str; 13] = [ + "Anaokulu", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", + ]; + LABELS[self.0 as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_ladder_is_bounded() { + assert!(GradeLevel::new(MIN_GRADE_LEVEL).is_ok()); + assert!(GradeLevel::new(MAX_GRADE_LEVEL).is_ok()); + assert!(GradeLevel::new(-1).is_err()); + assert!(GradeLevel::new(MAX_GRADE_LEVEL + 1).is_err()); + } + + #[test] + fn anaokulu_is_the_floor_and_labels_are_stable() { + assert_eq!(GradeLevel::anaokulu().get(), 0); + assert_eq!(GradeLevel::anaokulu().label(), "Anaokulu"); + assert_eq!(GradeLevel::new(1).unwrap().label(), "1"); + assert_eq!(GradeLevel::new(12).unwrap().label(), "12"); + } +} diff --git a/src/domain/homework.rs b/src/domain/homework.rs index a15aee0..b3bc82b 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -87,6 +87,14 @@ impl HomeworkDescription { /// homework carries no roster, a student who enrolls later is covered /// automatically; a subset is a fixed snapshot of the students named at /// assign (or last PATCH) time. +/// +/// The `subject` tag names a topic of the homework's course — and, since the +/// course-template system, one the instance actually *teaches*: its resolved +/// subject set (override-or-inherit), validated service-side +/// ([`crate::service::subject::in_instance`] at tag time, +/// [`crate::service::offering_subject::ensure_resolved_member`] on create), +/// because the check needs the instance's override state and so cannot live +/// as a pure rule on this row. #[derive(Debug, Clone, sqlx::FromRow)] pub struct Homework { pub(crate) id: HomeworkId, diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 80d4c2b..098befe 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -25,6 +25,7 @@ pub mod course; pub mod course_membership; pub mod course_note; pub mod course_note_file; +pub mod course_offering; pub mod course_session; pub mod dietary_profile; pub mod enrollment; @@ -34,8 +35,10 @@ pub mod exam_answer; pub mod exam_attempt; pub mod exam_question; pub mod exam_result; +pub mod exam_weight; pub mod fee_plan; pub mod fee_plan_assignment; +pub mod grade; pub mod homework; pub mod homework_file; pub mod homework_result; @@ -50,6 +53,7 @@ pub mod message; pub mod monotonic_id; pub mod note; pub mod note_file; +pub mod offering_subject; pub mod parent_link; pub mod payment_ledger; pub mod person; @@ -75,6 +79,7 @@ pub mod term; pub mod text_fold; pub mod timestamp; pub mod user; +pub mod weekly_slot; pub mod work_entry; /// Fallback for lowercase-string enums whose `#[sqlx(type_name = "TEXT", diff --git a/src/domain/offering_subject.rs b/src/domain/offering_subject.rs new file mode 100644 index 0000000..e28f8fe --- /dev/null +++ b/src/domain/offering_subject.rs @@ -0,0 +1,82 @@ +//! The syllabus topic sets: which of a catalog course's subjects an offering +//! ([`crate::domain::course_offering::CourseOffering`]) selects for its grade, +//! and which one a class section ([`crate::domain::class_course::ClassCourse`]) +//! selects for itself. Both are pure membership junctions over `subject` — +//! there is no row type of their own, so this file carries the model's one +//! pure rule and the docs. +//! +//! The rule: a subject may be selected only for an offering of the course the +//! subject belongs to. "Lifted" from the course to the instance level, the +//! same gate guards the class-side selections, because an instance's course +//! is fixed at attach. +//! +//! Resolution is override-or-inherit, never merge, and is **flag-driven**: +//! [`ClassCourse::subjects_inherited`](crate::domain::class_course::ClassCourse::subjects_inherited) +//! `TRUE` = the offering's set applies, `FALSE` = the section's own +//! `class_course_subject` rows are authoritative **including when there are +//! none** (that is how a section clears its syllabus). The flag flips in the +//! same statement that writes or deletes a class-side row +//! ([`crate::db::offering_subject`]); the effective set is +//! [`crate::service::offering_subject::resolved_for_instance`]. + +use crate::domain::course::CourseId; +use crate::domain::subject::Subject; +use crate::error::ValidationError; + +/// The membership precondition: `subject` may be selected for a set whose +/// course is `offering_course` only when it belongs to that course. The same +/// 400 the bare-course tag check (`service::subject::in_course`) has always +/// answered — one condition, one error shape, now enforced at selection time +/// as well as tag time. +pub fn ensure_course_member( + subject: &Subject, + offering_course: &CourseId, +) -> Result<(), ValidationError> { + if subject.get_course() != offering_course { + return Err(ValidationError::Invalid { + field: "subject_id", + reason: "subject belongs to a different course", + }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::subject::{SubjectDescription, SubjectId, SubjectName}; + + fn a_subject(course: CourseId) -> Subject { + Subject { + id: SubjectId::generate(), + course, + name: SubjectName::try_new("Limits").unwrap(), + description: SubjectDescription::try_new("").unwrap(), + } + } + + /// The precondition refuses a subject of another course, naming the field + /// with the exact reason the tag-time check uses — drops the guard and + /// this fails on the `Ok`. + #[test] + fn a_foreign_course_subject_is_refused() { + let subject = a_subject(CourseId::from_key( + "019732e3-7b00-7000-8000-00000000dead", + )); + let offering_course = CourseId::from_key("019732e3-7b00-7000-8000-00000000beef"); + let refused = ensure_course_member(&subject, &offering_course).unwrap_err(); + assert_eq!( + refused.to_string(), + "subject_id: subject belongs to a different course" + ); + } + + /// A subject of the offering's own course passes — negates the guard's + /// "always refuse" mutation. + #[test] + fn an_own_course_subject_passes() { + let course = CourseId::from_key("019732e3-7b00-7000-8000-00000000dead"); + let subject = a_subject(course.clone()); + ensure_course_member(&subject, &course).unwrap(); + } +} diff --git a/src/domain/weekly_slot.rs b/src/domain/weekly_slot.rs new file mode 100644 index 0000000..f528ef1 --- /dev/null +++ b/src/domain/weekly_slot.rs @@ -0,0 +1,297 @@ +//! The weekly plan slot: one line of a course's timetable template — a +//! weekday and the time-of-day window one lesson hour lands in. +//! +//! Slots live on one of two owners: the grade-level offering +//! (`offering_slot`, the template) or the class×course instance +//! (`class_course_slot`, the per-class override). Which set a reader sees is +//! `class_course.weekly_plan_inherited`'s decision, applied by +//! [`crate::service::weekly_slot::resolved_for_instance`]: `TRUE` follows the +//! offering's rows, `FALSE` makes the section's own rows authoritative +//! *including when they are empty* — that is how a section clears its +//! timetable. Override-or-inherit, never merge. +//! +//! Two of one owner's slots may touch (one may start the minute another +//! ends) but never overlap on the same weekday; the exact duplicate is the +//! store's `UNIQUE (owner, weekday, starts_at)` key. The ordering a resolved +//! 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. +//! +//! 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::monotonic_id::next_uuid; +use crate::error::ValidationError; + +/// The identity of one slot row. A UUIDv7 minted by the process-wide +/// monotonic generator, like every other row id in the repo. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct WeeklySlotId(uuid::Uuid); + +impl WeeklySlotId { + pub fn generate() -> Self { + Self(next_uuid()) + } + + /// The inner uuid, for runtime-checked binds that cannot take the + /// newtype. Static `query!` binds take `self` directly. + pub fn uuid(&self) -> uuid::Uuid { + self.0 + } + + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. + pub fn from_key(key: &str) -> Self { + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) + } + + /// The bare uuid wire form. + pub fn key(&self) -> String { + self.0.to_string() + } +} + +/// An ISO weekday: `1` = Monday through `7` = Sunday. The same spell the +/// DDL's `CHECK (weekday BETWEEN 1 AND 7)` enforces at the store. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct Weekday(i16); + +impl Weekday { + /// The weekday `raw` names, or a validation error when it is off the + /// ISO scale — the `400` the add routes answer with. + pub fn new(raw: i16) -> Result { + if !(1..=7).contains(&raw) { + return Err(ValidationError::Invalid { + field: "weekday", + reason: "must be 1 (Monday) through 7 (Sunday)", + }); + } + Ok(Self(raw)) + } + + /// The integer the wire and the `weekday` column carry. + pub fn get(self) -> i16 { + self.0 + } +} + +/// A time of day as minutes past midnight — the wire form of the slot's +/// `TIME` columns (`540` = 09:00). The `TIME` cast is the statement's own; +/// this newtype range-checks what the statement binds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, sqlx::Type)] +#[sqlx(transparent)] +pub struct SlotMinute(i64); + +impl SlotMinute { + /// The minute `raw` names, or a validation error when it is not a minute + /// of a real day — the `400` the add routes answer with. + pub fn new(raw: i64) -> Result { + if !(MIN_SLOT_MINUTE..=MAX_SLOT_MINUTE).contains(&raw) { + return Err(ValidationError::Invalid { + field: "slot time", + reason: "must be minutes past midnight, 0 (00:00) through 1439 (23:59)", + }); + } + Ok(Self(raw)) + } + + /// The integer the wire carries. + pub fn get(self) -> i64 { + self.0 + } +} + +/// One weekly plan line: on `weekday`, from `starts_at` to `ends_at`. +/// +/// The list a resolver returns is ordered `weekday` first, then `starts_at`. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::FromRow)] +pub struct WeeklySlot { + pub(crate) id: WeeklySlotId, + pub(crate) weekday: Weekday, + pub(crate) starts_at: SlotMinute, + pub(crate) ends_at: SlotMinute, +} + +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. + pub fn new( + id: WeeklySlotId, + weekday: Weekday, + starts_at: SlotMinute, + ends_at: SlotMinute, + ) -> Result { + if starts_at.get() >= ends_at.get() { + return Err(ValidationError::Invalid { + field: "ends_at", + reason: "must be after starts_at — a slot needs a non-empty window", + }); + } + Ok(Self { + id, + weekday, + starts_at, + ends_at, + }) + } + + pub fn get_id(&self) -> &WeeklySlotId { + &self.id + } + + pub fn get_weekday(&self) -> Weekday { + self.weekday + } + + pub fn get_starts_at(&self) -> SlotMinute { + self.starts_at + } + + pub fn get_ends_at(&self) -> SlotMinute { + self.ends_at + } + + /// 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. + pub fn overlaps(&self, other: &WeeklySlot) -> bool { + self.weekday == other.weekday + && self.starts_at.get() < other.ends_at.get() + && other.starts_at.get() < self.ends_at.get() + } +} + +/// Why [`check_add`] refused a slot. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SlotAddError { + /// A slot of the same owner already overlaps the candidate on its + /// weekday. The exact duplicate overlaps too, so it answers here. + Overlap, + /// The owner's plan already holds [`MAX_WEEKLY_SLOTS`] slots. + Full, +} + +/// The add-time invariant, judged against the owner's current rows: overlap +/// first (it names the concrete collision the caller must move), then the +/// plan-size cap. A pure rule so the refusal order is one the tests can pin. +pub fn check_add(existing: &[WeeklySlot], candidate: &WeeklySlot) -> Result<(), SlotAddError> { + if existing.iter().any(|slot| slot.overlaps(candidate)) { + return Err(SlotAddError::Overlap); + } + if existing.len() >= MAX_WEEKLY_SLOTS { + return Err(SlotAddError::Full); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn day(raw: i16) -> Weekday { + Weekday::new(raw).unwrap() + } + + fn mins(raw: i64) -> SlotMinute { + SlotMinute::new(raw).unwrap() + } + + fn slot(weekday: i16, starts: i64, ends: i64) -> WeeklySlot { + WeeklySlot::new( + WeeklySlotId::generate(), + day(weekday), + mins(starts), + mins(ends), + ) + .unwrap() + } + + #[test] + fn weekdays_are_the_iso_scale() { + assert!(Weekday::new(1).is_ok()); + assert!(Weekday::new(7).is_ok()); + assert!(Weekday::new(0).is_err()); + assert!(Weekday::new(8).is_err()); + } + + #[test] + fn slot_minutes_are_one_real_day() { + assert!(SlotMinute::new(0).is_ok()); + assert!(SlotMinute::new(MAX_SLOT_MINUTE).is_ok()); + assert!(SlotMinute::new(-1).is_err()); + assert!(SlotMinute::new(MAX_SLOT_MINUTE + 1).is_err()); + } + + #[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()); + // A one-minute window stands. + assert!(WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(601)).is_ok()); + } + + #[test] + fn overlap_is_same_weekday_and_intersecting() { + let monday_morning = slot(1, 540, 600); + // Same window: an exact duplicate overlaps. + assert!(monday_morning.overlaps(&slot(1, 540, 600))); + // Partial and containing windows overlap. + assert!(monday_morning.overlaps(&slot(1, 570, 630))); + assert!(monday_morning.overlaps(&slot(1, 530, 610))); + assert!(monday_morning.overlaps(&slot(1, 530, 630))); + // Touching endpoints do not: one lesson may start when another ends. + assert!(!monday_morning.overlaps(&slot(1, 600, 660))); + assert!(!monday_morning.overlaps(&slot(1, 480, 540))); + // The same window on another weekday is a different line of the week. + assert!(!monday_morning.overlaps(&slot(2, 540, 600))); + } + + #[test] + fn check_add_refuses_overlap_before_the_cap() { + let existing: Vec = (0..MAX_WEEKLY_SLOTS) + .map(|i| { + slot( + ((i % 7) + 1) as i16, + 480 + (i as i64 / 7), + 481 + (i as i64 / 7), + ) + }) + .collect(); + let colliding = slot(1, 480, 482); + // Every plan below the cap still refuses the overlap first. + let short: Vec = existing[..MAX_WEEKLY_SLOTS - 1].to_vec(); + assert_eq!(check_add(&short, &colliding), Err(SlotAddError::Overlap)); + // A full plan refuses an overlap as an overlap, not as a full plan. + assert_eq!(check_add(&existing, &colliding), Err(SlotAddError::Overlap)); + } + + #[test] + fn check_add_refuses_a_full_plan_with_room_for_nothing_more() { + let existing: Vec = (0..MAX_WEEKLY_SLOTS) + .map(|i| { + slot( + ((i % 7) + 1) as i16, + 480 + (i as i64 / 7), + 481 + (i as i64 / 7), + ) + }) + .collect(); + // Touching, non-colliding, on a weekday with room: still refused — + // the cap, not the overlap, is the reason. (Sunday holds five of the + // forty, the last ending at 485; this one starts exactly there.) + let free_slot = slot(7, 485, 486); + assert_eq!(check_add(&existing, &free_slot), Err(SlotAddError::Full)); + // Below the cap the same candidate is accepted. + let short: Vec = existing[..MAX_WEEKLY_SLOTS - 1].to_vec(); + assert_eq!(check_add(&short, &free_slot), Ok(())); + } +} diff --git a/src/lib.rs b/src/lib.rs index 488ecbd..69a3256 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -67,6 +67,7 @@ use crate::web::module_gate::gate; (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), (name = "courses", description = "The course **catalog**: the school's reusable rows — kind `course` (a regular ders), `study` (etüt, a supervised study session) or `club` (kulüp) — with their curriculum subjects (`/courses/{id}/subjects`). A catalog row teaches nobody by itself: a ders is taught by attaching it to a şube, which mints an instance (`POST /classes/{id}/instances`), and everything a class actually runs — roster, teachers, exams, lessons, homework — belongs to that instance (`GET /instances/{id}`). An etüt or kulüp has no şube at all: it is joined school-wide (`POST /courses/{id}/members`, students only), and a `course`-kind ders refuses that door with a `400` — its students come through its instances. Catalog rights are the office's and the row's creator: edit, delete, its subjects and its member list all need the creator or manager+, and a row still taught anywhere (any instance, any member) cannot be deleted (`409`). `GET /courses/me` is what a caller is reached by, both tiers together; the instances themselves are `GET /instances/me`."), (name = "instances", description = "One catalog course **as one şube teaches it** — the instance, and the anchor everything academic hangs off. Attaching a course to a class (`POST /classes/{id}/instances`) mints one; two şubeler teaching the same course are two instances with their own roster, teachers, exams, lessons and homework. The row carries the instance's own policy: `ders_saati` (weekly lesson hours — the weight the instance takes in the year's karne average) and `counts_toward_karne`. Acting on an instance (`PATCH`, its rosters, its exams/sessions/homework, its roll-call) is open to manager+, to a teacher assigned to that instance (`POST /instances/{id}/teachers`, manager+) and to the şube's homeroom teacher — one rule, applied by every route here. `GET /instances/me` is a student's own list: the instances of the şubeler they are a live member of."), + (name = "offerings", description = "The grade-level course **templates** (`course_offering`): one offering per (course × grade level, `0` = anaokulu through `12`) carrying the title, description, default weekly hours (`default_ders_saati`, else 1) and default report-card policy (`default_counts_toward_karne`, else counted) that every şube at that grade teaches from. A şube's instance teaches **from** its offering and may override any content field — an unset field inherits down the chain offering → catalog course → constant, override-or-inherit, never merge. Attaching a course to a class at a grade with no offering yet mints an empty one automatically (so an untouched grade teaches exactly what the catalog row says); only a class-delivered ders (`kind = 'course'`) has offerings — a club or etüt is joined individually and has no grade. Reads are open to any signed-in session; writing (create, `PATCH`, delete) is manager+, and a template any instance still teaches from cannot be deleted (`409 offering_in_use`). The per-class overrides ride the instance (`PATCH /instances/{id}`, `POST /instances/{id}/reset`), not this group."), (name = "course-notes", description = "Notes a teacher attaches to a **catalog course** — announcements, recaps, anything worth pinning to the course rather than to one student — with file attachments, mirroring the personal `notes` stack. Writing (create, edit, delete, upload, delete a file) requires teacher+ and catalog rights over the course (its creator, or a manager/admin); reading (`GET /course-notes/{id}`, listing, downloading) is open to anyone the course reaches — a student enrolled in one of its instances, a member of it, its creator, or a manager/admin. `GET /course-notes` requires `?course=` and lists that course's notes only, newest first. At most 10 files per note, each at most the school's `max_file_bytes`. `GET /course-notes/{id}/rag` serves what the backend indexed for the AI features, and is derived data: deleting it suppresses nothing, and the next edit to the note or its files may regenerate it."), (name = "classes", description = "Class sections (şube): a named set of students the school moves as one, sitting in an academic year (`year`; a şube with no year takes no exam and is never rolled over). A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every instance the class carries, and attaching a course (`POST /classes/{id}/instances`) mints the class×course **instance** and enrolls the whole roster into it, the rows written being ordinary enrollments tagged with the şube that pumped them (a row with no such tag was placed by hand, and no sweep takes it back). A student already enrolled by hand keeps their own row. Removing a member is a **soft** leave: the stint is stamped `left_at` and the live-member counter comes down, but the row stays as the section's history — re-adding the same student is a fresh stint, so a pair may hold two rows, one live. `DELETE /classes/{id}/instances/{instance}` takes the whole instance with it — exams, homework, sessions, the roster it pumped, its teacher links — and unlinks the uploaded files those rows named. A homeroom teacher (`teacher_id`, sınıf öğretmeni) may act on every instance of their section; the class itself is the office's (manager+). Refusals carry a machine `code` beside the prose where two routes share one vocabulary: a member add is refused by a full roster (`class_at_roster_ceiling`) or by an instance list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both (`class_at_course_ceiling`, `class_roster_too_large`); `duplicate` is a refusal on either manual route; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet. Grade blueprints (`/classes/blueprints`) are the template side: a manager+ writes the courses every section of a grade takes, and the pump that stocks a section from it is idempotent and best-effort — the courses that did not fit come back in `skipped` with those codes, and `blueprint_deleted`/`class_deleted`/`course_deleted` report a row that vanished mid-pump."), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher). Roll call is also what feeds two badge counters (see `users`): the first mark taken for a lesson **at or after its own `starts_at`** credits its teacher's `lessons_held_total` once — a sheet opened early is never refused, it simply holds nothing until the bell — and a student marked `present` or `late` gains a `lessons_attended_total` a later correction gives back"), @@ -120,11 +121,41 @@ fn courses_router(state: &AppState) -> OpenApiRouter { ) } -/// `/instances` and the three foreign-module route pairs mounted inside it — +/// `/offerings` and the three foreign-module route pairs mounted inside it — +/// the same split as `/courses`: the grade-level template carries its own +/// subject selection (`Subjects`), exam weights (`Exams`) and weekly plan +/// (`Sessions`) beside the offering CRUD. Each child carries its own module's +/// gate *and*, through the outer one applied here, the course gate — so either +/// module being off refuses it. +fn offerings_router(state: &AppState) -> OpenApiRouter { + let children = gate( + web::offering_subjects::offering_routes(), + state, + Module::Subjects, + ) + .merge(gate( + web::exam_weights::offering_routes(), + state, + Module::Exams, + )) + .merge(gate( + web::weekly_plan::offering_routes(), + state, + Module::Sessions, + )); + gate( + web::offerings::routes().merge(children), + state, + Module::Courses, + ) +} + +/// `/instances` and the six foreign-module route pairs mounted inside it — /// the same split as `/courses`, one anchor down: the instance is what a class -/// section teaches, and what exams, sessions and homework hang off. Each child carries -/// its own module's gate *and*, through the outer one applied here, the course -/// gate (an instance is a course taught somewhere), so either module being off +/// section teaches, and what exams, sessions, homework, subject selection, +/// exam weights and the weekly plan hang off. Each child carries its own +/// module's gate *and*, through the outer one applied here, the course gate +/// (an instance is a course taught somewhere), so either module being off /// refuses it. fn instances_router(state: &AppState) -> OpenApiRouter { let children = gate(web::instances::exam_routes(), state, Module::Exams) @@ -137,6 +168,21 @@ fn instances_router(state: &AppState) -> OpenApiRouter { web::instances::homework_routes(), state, Module::Homework, + )) + .merge(gate( + web::offering_subjects::instance_routes(), + state, + Module::Subjects, + )) + .merge(gate( + web::exam_weights::instance_routes(), + state, + Module::Exams, + )) + .merge(gate( + web::weekly_plan::instance_routes(), + state, + Module::Sessions, )); gate( web::instances::routes().merge(children), @@ -193,6 +239,7 @@ pub fn build_router(state: AppState) -> Router { ) .nest("/courses", courses_router(&state)) .nest("/instances", instances_router(&state)) + .nest("/offerings", offerings_router(&state)) .nest("/academic-years", web::academic_years::routes()) .nest( "/course-notes", diff --git a/src/service/academic_year.rs b/src/service/academic_year.rs index fb3d2d5..12615c5 100644 --- a/src/service/academic_year.rs +++ b/src/service/academic_year.rs @@ -14,7 +14,6 @@ use crate::domain::academic_year::{ AcademicYear, AcademicYearId, AcademicYearName, GradePromotion, archived_error, rollover_target_not_empty, }; -use crate::domain::class_group::ClassGrade; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -215,24 +214,21 @@ pub async fn rollover( graduated: Vec::new(), }; for class in class_group::list_for_year(db, from).await? { - let Some(grade) = class.get_grade() else { - continue; - }; - let Some(mapped) = from_year.promotion_for(grade.as_str()) else { - // No promotion entry: this grade graduated. Reported once per + let grade = class.get_grade_level(); + let Some(next) = from_year.promotion_for(grade) else { + // No promotion entry: this rung graduated. Reported once per // label, however many class sections carry it. - let label = grade.as_str().to_string(); + let label = grade.label().to_string(); if !report.graduated.contains(&label) { report.graduated.push(label); } continue; }; - let next = ClassGrade::try_new(mapped)?; let planted = class_group::create( db, by, class.get_name().clone(), - Some(next), + next, Some(*target), class.get_teacher().copied(), ) @@ -258,11 +254,20 @@ pub async fn rollover( instance.get_course().key() ))); }; + // The section's own overrides ride along — a copy sets exactly + // what the source had set (its `None`s are the inherit state, and + // the fresh row is born NULL anyway). The *offering*, unlike these + // scalars, is deliberately NOT copied: `attach_sourced` resolved + // it against the new section's own `grade_level` (auto-creating + // that grade's template), so a rolled-up section teaches from its + // new grade's offering, never the source grade's. class_course::update( db, copied.get_id(), - Some(instance.get_ders_saati()), - Some(instance.counts_toward_karne()), + instance.get_title().cloned(), + instance.get_description().cloned(), + instance.get_ders_saati(), + instance.counts_toward_karne(), ) .await?; for teacher in class_course_teacher::list_for_instance(db, instance.get_id()).await? { diff --git a/src/service/class_blueprint.rs b/src/service/class_blueprint.rs index 9be17f9..b40b84e 100644 --- a/src/service/class_blueprint.rs +++ b/src/service/class_blueprint.rs @@ -35,7 +35,8 @@ use crate::db::class_pump::Attached; use crate::domain::class_blueprint::{ ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason, }; -use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId}; +use crate::domain::class_group::{ClassGroup, ClassGroupId}; +use crate::domain::grade::GradeLevel; use crate::domain::course::CourseId; use crate::domain::user::UserId; use crate::error::AppError; @@ -47,11 +48,11 @@ use crate::error::AppError; pub async fn create( db: &Database, creator: &UserId, - grade: ClassGrade, + grade_level: GradeLevel, courses: Vec, ) -> Result { let courses = ClassBlueprint::course_list(courses)?; - class_blueprint::create(db, creator, grade, courses).await + class_blueprint::create(db, creator, grade_level, courses).await } /// The row, for callers that only inspect it — the web layer's @@ -339,7 +340,7 @@ pub async fn pump( skipped: Vec::new(), }; let mut dead = Vec::new(); - for class in class_group::list_for_grade(db, &blueprint.grade).await? { + for class in class_group::list_for_grade(db, blueprint.grade_level).await? { pumped.matched += 1; if !apply_courses(db, blueprint, &class, by, &mut dead, &mut pumped.skipped).await? { break; @@ -378,7 +379,7 @@ pub async fn status( db: &Database, blueprint: &ClassBlueprint, ) -> Result, AppError> { - let sections = class_group::list_for_grade(db, &blueprint.grade).await?; + let sections = class_group::list_for_grade(db, blueprint.grade_level).await?; if sections.is_empty() { return Ok(Vec::new()); } @@ -415,14 +416,13 @@ mod tests { }; use crate::domain::class_group::{ClassGroup, ClassName}; - /// A section that a pump's own grade loop can actually find — [`a_class`] - /// carries no grade at all, so `list_for_grade` reaches none of them. + /// A section at the pump's own rung (9), so `list_for_grade` reaches it. async fn a_section(name: &str, db: &Database) -> ClassGroup { class_group::create( db, &fixture_user(db, "manager").await, ClassName::try_new(name).unwrap(), - Some(ClassBlueprint::grade_key("9").unwrap()), + GradeLevel::new(9).unwrap(), None, None, ) @@ -430,17 +430,12 @@ mod tests { .unwrap() } - /// A blueprint holding `courses`, at grade "9". + /// A blueprint holding `courses`, at rung 9. async fn a_blueprint(courses: Vec, db: &Database) -> ClassBlueprint { let manager = fixture_user(db, "manager").await; - create( - db, - &manager, - ClassBlueprint::grade_key("9").unwrap(), - courses, - ) - .await - .unwrap() + create(db, &manager, GradeLevel::new(9).unwrap(), courses) + .await + .unwrap() } /// Every skip names the record that actually failed. @@ -498,6 +493,7 @@ mod tests { // The class is deleted out from under the pump: the counter claim // matches nothing and the read that follows finds no row. let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; let course = a_course("algebra", &db).await; let class = class_group::read(&db, &a_class("9-A", &db).await) .await @@ -528,6 +524,7 @@ mod tests { // The class stands at its own ceiling: the same claim matches nothing, // but the row is there — and that is the one a manager can act on. let (db, _leases) = crate::database::init_test_db().await; + let manager = fixture_user(&db, "manager").await; let course = a_course("algebra", &db).await; let class = class_group::read(&db, &a_class("9-A", &db).await) .await diff --git a/src/service/class_course.rs b/src/service/class_course.rs index 2f2ced0..cb2bd98 100644 --- a/src/service/class_course.rs +++ b/src/service/class_course.rs @@ -9,9 +9,9 @@ use crate::database::Database; use crate::db::class_course; use crate::db::class_pump::{self, Axis}; use crate::domain::academic_year::AcademicYearId; -use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; +use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati, OverrideField}; use crate::domain::class_group::ClassGroupId; -use crate::domain::course::CourseId; +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ValidationError}; @@ -22,7 +22,10 @@ use crate::error::{AppError, ValidationError}; /// Students already in the course keep the rows they have — no second /// enrollment written, `source` untouched — and the attach is one /// `class_course` row per (class, course): the instance every exam, session, -/// homework and enrollment under this class's course now keys on. +/// homework and enrollment under this class's course now keys on. The row +/// teaches from its grade-level offering (auto-created empty by the pump); +/// only a class-delivered ders attaches — a club or etüt is a 400 naming the +/// course. pub async fn attach( db: &Database, class: &ClassGroupId, @@ -120,16 +123,101 @@ pub async fn read(db: &Database, id: &ClassCourseId) -> Result, + description: Option, staff: Option, counts: Option, ) -> Result { - class_course::update(db, id, staff, counts).await + class_course::update(db, id, title, description, staff, counts).await +} + +/// The instance's **effective** weekly hours and report-card policy: its own +/// override, else the offering's default, else the constants (one weekly +/// hour, counted toward the karne). Every read of the now-nullable +/// `ders_saati`/`counts_toward_karne` goes through here — a `NULL` on the +/// instance is *inherit*, never a value, and unwrapping it would present "not +/// decided" as a decision. +/// +/// One statement per call (the offering's two defaults off its row, which the +/// instance's `RESTRICT` foreign key keeps alive); the composition with the +/// full content chain (title, description, the set policies) is the Phase 3 +/// resolver's job. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct InstancePolicy { + pub ders_saati: DersSaati, + pub counts_toward_karne: bool, +} + +pub async fn resolve_policy( + db: &Database, + instance: &ClassCourse, +) -> Result { + let (default_hours, default_counts) = + crate::db::course_offering::defaults(db, instance.get_offering()) + .await? + .ok_or(AppError::NotFound)?; + Ok(InstancePolicy { + ders_saati: instance.get_ders_saati().or(default_hours).unwrap_or_else( + || { + DersSaati::try_new(crate::constant::MIN_DERS_SAATI) + .expect("the floor is a valid weekly-hours count") + }, + ), + counts_toward_karne: instance + .counts_toward_karne() + .or(default_counts) + .unwrap_or(true), + }) +} + +/// Clear the named overrides back to **inherit** — the reset behind `POST +/// /instances/{id}/reset`. The scalars go `NULL` (the offering's default, +/// then the catalog row or the constant, applies again); the three set flags +/// flip back to `TRUE` (the offering's set is authoritative again — deleting +/// the section's own set rows rides the child-table lanes' reset doors). +/// +/// An empty list is a 400: a reset naming nothing would otherwise read as a +/// success that did nothing. +pub async fn reset_overrides( + db: &Database, + id: &ClassCourseId, + fields: &[OverrideField], +) -> Result { + if fields.is_empty() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "fields", + reason: "name at least one override to reset", + })); + } + class_course::clear_overrides(db, id, fields).await +} + +/// Parse the reset route's field names. The set-valued policies are named by +/// their *set* (`subjects`, `exam_weights`, `weekly_plan`), not by the flag +/// column — resetting one flips the flag back to inherit. +pub fn parse_reset_field(name: &str) -> Result { + match name { + "title" => Ok(OverrideField::Title), + "description" => Ok(OverrideField::Description), + "ders_saati" => Ok(OverrideField::DersSaati), + "counts_toward_karne" => Ok(OverrideField::CountsTowardKarne), + "subjects" => Ok(OverrideField::Subjects), + "exam_weights" => Ok(OverrideField::ExamWeights), + "weekly_plan" => Ok(OverrideField::WeeklyPlan), + other => Err(ValidationError::Unknown { + field: "fields", + value: other.to_string(), + } + .into()), + } } /// The academic year this instance sits under, if any — the seam every @@ -261,6 +349,7 @@ pub async fn ensure_instance_teacher( #[cfg(test)] mod tests { use super::*; + use crate::constant::MIN_DERS_SAATI; use crate::db::class_group; use crate::db::class_member::tests::{ a_class, a_course, counter, course_exists, link_exists, rows, source_of, @@ -473,7 +562,9 @@ mod tests { ); } - /// PATCHing the instance writes only what the request carried. + /// PATCHing the instance writes only what the request carried, the reset + /// door clears a named override back to inherit, and the resolver layers + /// override → offering default → constant. #[tokio::test] async fn an_update_writes_only_the_fields_it_carried() { let (db, _leases) = crate::database::init_test_db().await; @@ -481,30 +572,78 @@ mod tests { let class = a_class("9-A", &db).await; let algebra = a_course("algebra", &db).await; let instance = attach(&db, &class, &algebra, &manager).await.unwrap(); + // A fresh instance carries no overrides: the resolver falls through + // the (empty, auto-created) offering to the constants. + let fresh = read(&db, instance.get_id()).await.unwrap().unwrap(); + assert_eq!(fresh.get_ders_saati(), None); + let fresh_policy = resolve_policy(&db, &fresh).await.unwrap(); + assert_eq!(fresh_policy.ders_saati.as_i64(), MIN_DERS_SAATI); + assert!(fresh_policy.counts_toward_karne); let updated = update( &db, instance.get_id(), + Some(CourseTitle::try_new("9-A Matematik").unwrap()), + None, Some(DersSaati::try_new(5).unwrap()), None, ) .await .unwrap(); - assert_eq!(updated.get_ders_saati().as_i64(), 5); - assert!( + assert_eq!( + updated.get_title().map(CourseTitle::as_str), + Some("9-A Matematik") + ); + assert_eq!(updated.get_ders_saati().map(DersSaati::as_i64), Some(5)); + assert_eq!( updated.counts_toward_karne(), + None, "the omitted field keeps its stored value" ); + // The effective hours follow the override, not the constant. + let policy = resolve_policy(&db, &updated).await.unwrap(); + assert_eq!(policy.ders_saati.as_i64(), 5); - let again = update(&db, instance.get_id(), None, Some(false)) - .await - .unwrap(); - assert!(!again.counts_toward_karne()); + let again = update( + &db, + instance.get_id(), + None, + None, + None, + Some(false), + ) + .await + .unwrap(); + assert_eq!(again.counts_toward_karne(), Some(false)); assert_eq!( - again.get_ders_saati().as_i64(), - 5, + again.get_ders_saati().map(DersSaati::as_i64), + Some(5), "…and the other direction holds too" ); + + // Reset: the named overrides go back to inherit, the unnamed (the + // title) stay. + let cleared = reset_overrides( + &db, + instance.get_id(), + &[OverrideField::DersSaati, OverrideField::CountsTowardKarne], + ) + .await + .unwrap(); + assert_eq!(cleared.get_ders_saati(), None); + assert_eq!(cleared.counts_toward_karne(), None); + assert_eq!( + cleared.get_title().map(CourseTitle::as_str), + Some("9-A Matematik"), + "the reset only touches the fields it names" + ); + let cleared_policy = resolve_policy(&db, &cleared).await.unwrap(); + assert_eq!(cleared_policy.ders_saati.as_i64(), MIN_DERS_SAATI); + assert!(cleared_policy.counts_toward_karne); + assert!( + reset_overrides(&db, instance.get_id(), &[]).await.is_err(), + "a reset naming nothing is a 400, not a no-op success" + ); } /// D10: the instance's own teacher, the section's homeroom teacher and a @@ -524,7 +663,7 @@ mod tests { &db, &manager, crate::domain::class_group::ClassName::try_new("9-A").unwrap(), - None, + crate::domain::grade::GradeLevel::new(9).unwrap(), None, Some(homeroom), ) diff --git a/src/service/class_group.rs b/src/service/class_group.rs index 4551666..54efbf8 100644 --- a/src/service/class_group.rs +++ b/src/service/class_group.rs @@ -5,7 +5,8 @@ use crate::database::Database; use crate::db::class_group; use crate::domain::academic_year::AcademicYearId; -use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; +use crate::domain::class_group::{ClassGroup, ClassGroupId, ClassName}; +use crate::domain::grade::GradeLevel; use crate::domain::user::UserId; use crate::error::AppError; @@ -25,11 +26,11 @@ pub async fn create( db: &Database, creator: &UserId, name: ClassName, - grade: Option, + grade_level: GradeLevel, year: Option, teacher: Option, ) -> Result { - class_group::create(db, creator, name, grade, year, teacher).await + class_group::create(db, creator, name, grade_level, year, teacher).await } /// The row, for callers that only inspect it — the web layer's @@ -38,15 +39,15 @@ pub async fn read(db: &Database, id: &ClassGroupId) -> Result class_group::read(db, id).await } -/// Every class, newest first — or one grade's, when `grade` narrows it: the -/// read behind the class index. +/// Every class, newest first — or one rung's, when `grade_level` narrows it: +/// the read behind the class index. pub async fn list_all( db: &Database, - grade: Option>, + grade_level: Option, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - class_group::list_all(db, grade, limit, offset).await + class_group::list_all(db, grade_level, limit, offset).await } /// The classes `ids` names, in no particular order — the join behind the two @@ -68,11 +69,11 @@ pub async fn update( db: &Database, class: ClassGroup, name: Option, - grade: Option>, + grade_level: Option, year: Option>, teacher: Option>, ) -> Result { - class_group::update(db, class, name, grade, year, teacher).await + class_group::update(db, class, name, grade_level, year, teacher).await } /// Delete the class and give its year reference back; `false` = refused, diff --git a/src/service/course_offering.rs b/src/service/course_offering.rs new file mode 100644 index 0000000..0a5bb60 --- /dev/null +++ b/src/service/course_offering.rs @@ -0,0 +1,95 @@ +//! Offering workflows: the one invariant the web layer cannot express alone — +//! only a **class-delivered** course (`kind = 'course'`) has grade-level +//! offerings, because only such a course is ever attached to a class section +//! ([`crate::domain::course::CourseKind::is_class_delivered`]). A club or an +//! etüt is joined individually, has no grade, and so has no template to +//! inherit from. +//! +//! Everything else (the duplicate template's `offering_exists`, the in-use +//! delete guard) is the store's own answer, mapped in +//! [`crate::db::course_offering`]. The manager+ gate lives in the web layer. + +use crate::database::Database; +use crate::db::{course, course_offering}; +use crate::domain::class_course::DersSaati; +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; +use crate::domain::grade::GradeLevel; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; + +/// Mint the grade-level template for a course. A course that is not +/// class-delivered is a 400 (there is no grade an offering could hang off); +/// a template that already exists is the db layer's 409 `offering_exists`. +#[allow(clippy::too_many_arguments)] // the create body, spelled field by field +pub async fn create( + db: &Database, + by: &UserId, + course_id: &CourseId, + grade: GradeLevel, + title: Option, + description: Option, + default_ders_saati: Option, + default_counts_toward_karne: Option, +) -> Result { + let course = course::read(db, course_id).await?.ok_or(AppError::NotFound)?; + if !course.get_kind().is_class_delivered() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "course", + reason: "only a ders has grade-level offerings — a club or etüt is joined individually, not attached", + })); + } + course_offering::create( + db, + course.get_id(), + grade, + title, + description, + default_ders_saati, + default_counts_toward_karne, + by, + ) + .await +} + +/// One offering by id, or `None` when the id names no row — the read behind +/// `GET /offerings/{id}`. +pub async fn read( + db: &Database, + id: &CourseOfferingId, +) -> Result, AppError> { + course_offering::read(db, id).await +} + +/// The offerings, optionally narrowed by course and/or grade ladder rung, +/// paged — the read behind `GET /offerings?course=&grade_level=`. +pub async fn list( + db: &Database, + course: Option<&CourseId>, + grade: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + course_offering::list(db, course, grade, limit, offset).await +} + +/// Field-scoped PATCH: absent keeps, `null` clears back to inherit, a value +/// sets the override. Shape flows straight through to +/// [`course_offering::update`]; a gone id is a 404 there. +pub async fn update( + db: &Database, + id: &CourseOfferingId, + title: Option>, + description: Option>, + default_ders_saati: Option>, + default_counts_toward_karne: Option>, +) -> Result { + course_offering::update(db, id, title, description, default_ders_saati, default_counts_toward_karne) + .await +} + +/// Delete the template. In use by any instance → 409 `offering_in_use`; a +/// gone id → 404. +pub async fn delete(db: &Database, id: &CourseOfferingId) -> Result<(), AppError> { + course_offering::delete(db, id).await +} diff --git a/src/service/exam.rs b/src/service/exam.rs index d95313e..ac2de48 100644 --- a/src/service/exam.rs +++ b/src/service/exam.rs @@ -547,7 +547,7 @@ mod tests { db, manager, ClassName::try_new(name).unwrap(), - None, + crate::domain::grade::GradeLevel::new(9).unwrap(), year.cloned(), None, ) diff --git a/src/service/exam_weight.rs b/src/service/exam_weight.rs new file mode 100644 index 0000000..729335c --- /dev/null +++ b/src/service/exam_weight.rs @@ -0,0 +1,404 @@ +//! Exam-weight overrides: the resolution chain and the write doors. +//! +//! **The chain** — [`resolve`] answers "what does an exam of this kind weigh +//! *in this section*": the section's own row (only while its +//! `exam_weights_inherited` flag is `FALSE`), else the grade-level template's +//! row, else the school `settings.exam_kinds` weight for that kind, else +//! [`crate::domain::exam_weight::FALLBACK_WEIGHT`] (1). The floor is what +//! keeps a *retired* kind — settings edits never rewrite history — counting +//! once, exactly as the pre-offering behaviour did. +//! +//! **Own set in force means authoritative, including when empty.** A section +//! with `exam_weights_inherited = FALSE` and no row for a kind resolves that +//! kind to 1 — *not* to the offering's or the settings' weight. That is how a +//! section zeroes out the template's weights without renaming the school's +//! vocabulary; the empty-own-set case is pinned by a test below. +//! +//! Every write validates the kind against `settings.exam_kinds` (the rows may +//! only name kinds the school runs — the routes answer 400 +//! `unknown_exam_kind`) and the weight against the same 1..=100 window the +//! settings enforce. The class-side writes flip the flag inside the statement +//! ([`crate::db::exam_weight`]); the reset restores it. + +use crate::database::Database; +use crate::db; +use crate::domain::class_course::{ClassCourse, ClassCourseId}; +use crate::domain::course_offering::CourseOfferingId; +use crate::domain::exam_weight::{ExamWeight, FALLBACK_WEIGHT}; +use crate::error::{AppError, ValidationError}; + +/// What an exam of `kind` weighs inside `instance`: the section's own row +/// while its own set is in force (a missing row is a 1, and the chain +/// *stops* there), else the offering's row, else the settings weight, else 1. +pub async fn resolve( + db: &Database, + instance: &ClassCourse, + kind: &str, +) -> Result { + if !instance.exam_weights_inherited() { + // The section's table is the whole answer — empty included. Falling + // through to the offering/settings here would silently re-attach the + // weights a section deliberately cleared. + return Ok(db::exam_weight::class_weight(db, instance.get_id(), kind) + .await? + .map(|row| row.get_weight()) + .unwrap_or(FALLBACK_WEIGHT)); + } + if let Some(row) = db::exam_weight::offering_weight(db, instance.get_offering(), kind).await? { + return Ok(row.get_weight()); + } + let school = super::settings::load(db).await?; + Ok(school.exam_kind_weight(kind).unwrap_or(FALLBACK_WEIGHT)) +} + +/// The section's **effective** weight map: the (inherited flag, one resolved +/// entry per kind). With the section's own set in force that map is exactly +/// its rows — even when that is nothing; while it inherits, every settings +/// kind (plus any kind an offering row adds) resolved off the offering → +/// settings → 1 chain. A client renders this verbatim; it never re-implements +/// the chain. +pub async fn resolved_for_class( + db: &Database, + instance: &ClassCourse, +) -> Result<(bool, Vec), AppError> { + if !instance.exam_weights_inherited() { + return Ok((false, db::exam_weight::list_for_class(db, instance.get_id()).await?)); + } + Ok((true, resolved_inherited(db, instance.get_offering()).await?)) +} + +/// The template's effective weight map: every settings kind (plus any kind its +/// rows add), each resolved off the offering's row → settings → 1. +pub async fn resolved_for_offering( + db: &Database, + offering: &CourseOfferingId, +) -> Result, AppError> { + resolved_inherited(db, offering).await +} + +/// The map an inheriting consumer sees: the settings vocabulary, extended by +/// whatever kinds the offering's own rows name (a retired kind with a stored +/// row keeps showing its stored weight), each resolved in memory off one batch +/// read. +async fn resolved_inherited( + db: &Database, + offering: &CourseOfferingId, +) -> Result, AppError> { + let school = super::settings::load(db).await?; + let rows = db::exam_weight::list_for_offering(db, offering).await?; + let weight_of = |kind: &str| { + rows.iter() + .find(|row| row.get_kind() == kind) + .map(ExamWeight::get_weight) + .or_else(|| school.exam_kind_weight(kind)) + .unwrap_or(FALLBACK_WEIGHT) + }; + let mut kinds: Vec = school + .get_exam_kinds() + .iter() + .map(|def| def.get_name().to_string()) + .collect(); + for row in &rows { + if !kinds.iter().any(|kind| kind == row.get_kind()) { + kinds.push(row.get_kind().to_string()); + } + } + kinds.sort(); + Ok(kinds + .into_iter() + .map(|kind| ExamWeight { + weight: weight_of(&kind), + kind, + }) + .collect()) +} + +/// The settings check behind every write: the row may only name a kind the +/// school runs. The refusal is a plain 400-shaped +/// [`ValidationError::Invalid`] on `field: "kind"` — the web layer re-renders +/// that shape as the coded `unknown_exam_kind` body. +async fn checked_weight(db: &Database, kind: &str, weight: i64) -> Result { + let school = super::settings::load(db).await?; + if !school.get_exam_kinds().iter().any(|def| def.get_name() == kind) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "kind", + reason: "unknown exam kind (the school's settings.exam_kinds is the vocabulary)", + })); + } + Ok(ExamWeight::try_new(kind, weight)?) +} + +/// Upsert one weight on the grade-level template. Manager+ is the route's +/// gate; a gone offering was the handler's 404 one instant earlier (the FK +/// backs the race). +pub async fn set_for_offering( + db: &Database, + offering: &CourseOfferingId, + kind: &str, + weight: i64, +) -> Result<(), AppError> { + let weight = checked_weight(db, kind, weight).await?; + db::exam_weight::upsert_for_offering(db, offering, kind, &weight).await +} + +/// Drop one weight row from the template; a pair with no row is a 404. +pub async fn remove_from_offering( + db: &Database, + offering: &CourseOfferingId, + kind: &str, +) -> Result<(), AppError> { + if !db::exam_weight::delete_from_offering(db, offering, kind).await? { + return Err(AppError::NotFound); + } + Ok(()) +} + +/// Upsert one weight on the section and take its set own — the flag flips in +/// the same statement, so the write is never half an override. A gone instance +/// is a 404. +pub async fn set_for_class( + db: &Database, + instance: &ClassCourseId, + kind: &str, + weight: i64, +) -> Result<(), AppError> { + let weight = checked_weight(db, kind, weight).await?; + db::exam_weight::upsert_for_class(db, instance, kind, &weight).await +} + +/// Drop one weight row from the section — still taking the set own (a section +/// that deletes its last row has *decided* on an empty set, and an empty own +/// set resolves 1). No row for the kind, or a gone instance, is a 404. +pub async fn remove_from_class( + db: &Database, + instance: &ClassCourseId, + kind: &str, +) -> Result<(), AppError> { + if !db::exam_weight::delete_from_class(db, instance, kind).await? { + return Err(AppError::NotFound); + } + Ok(()) +} + +/// Restore inheritance: delete every section weight row and set the flag back +/// to `TRUE`, in one statement. Idempotent; a gone instance is a 404. +pub async fn reset_class(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> { + db::exam_weight::reset_class(db, instance).await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::class_member::tests::{a_class, a_course}; + use crate::error::ValidationError; + + /// A manager account and one attached instance — the attach auto-mints + /// the grade-level offering the chain reads. The school's vocabulary is + /// seeded to what the chain tests assume: `final` weighs 3 in the + /// settings, `yazili` 1, and `oral` stays unknown so the refusal has a + /// name. + async fn an_instance(db: &Database) -> ClassCourse { + let mut params = crate::domain::settings::Settings::defaults().params(); + params.exam_kinds = vec![ + crate::domain::settings::ExamKindDef::try_new("final", 3).unwrap(), + crate::domain::settings::ExamKindDef::try_new("yazili", 1).unwrap(), + ]; + crate::db::settings::save(db, crate::domain::settings::Settings::try_new(params).unwrap()) + .await + .unwrap(); + let manager = crate::db::class_member::tests::fixture_user(db, "weights-manager").await; + let class = a_class("9-A", db).await; + let algebra = a_course("algebra-weights", db).await; + crate::service::class_course::attach(db, &class, &algebra, &manager) + .await + .unwrap() + } + + async fn offering_id(db: &Database, instance: &ClassCourse) -> CourseOfferingId { + crate::service::class_course::read(db, instance.get_id()) + .await + .unwrap() + .unwrap() + .get_offering() + .clone() + } + + /// The full chain on the default vocabulary (`final` weighs 3 in the + /// settings): settings → offering row → class row → reset, plus the + /// retired-kind floor. Each step *changes* the answer, so every + /// assertion can fail. + #[tokio::test] + async fn the_chain_walks_class_then_offering_then_settings_then_one() { + let (db, _leases) = crate::database::init_test_db().await; + let instance = an_instance(&db).await; + let offering = offering_id(&db, &instance).await; + + // Inheriting, nothing overridden anywhere: the settings weight. + assert_eq!(resolve(&db, &instance, "final").await.unwrap(), 3); + + // The template overrides the settings… + set_for_offering(&db, &offering, "final", 5).await.unwrap(); + assert_eq!(resolve(&db, &instance, "final").await.unwrap(), 5); + + // …and the section overrides the template. + set_for_class(&db, instance.get_id(), "final", 7).await.unwrap(); + let own7 = instance_of(&db, instance.get_id()).await; + assert!( + !own7.exam_weights_inherited(), + "the class-side write took the set own in the same statement" + ); + assert_eq!(resolve(&db, &own7, "final").await.unwrap(), 7); + + // Deleting the section's row takes the set own — and the chain + // STOPS at the class: 1, not the offering's 5, not the settings' 3. + // This is the empty-own-set contract: an own set in force is + // authoritative including when it is empty. + remove_from_class(&db, instance.get_id(), "final").await.unwrap(); + let own = instance_of(&db, instance.get_id()).await; + assert!(!own.exam_weights_inherited()); + assert!(db::exam_weight::list_for_class(&db, instance.get_id()) + .await + .unwrap() + .is_empty()); + assert_eq!( + resolve(&db, &own, "final").await.unwrap(), + FALLBACK_WEIGHT, + "an empty own set resolves 1 — the offering and settings weights stay out" + ); + // A kind the settings don't even list, under the same own set in + // force: 1 as well — the chain never left the class table. + assert_eq!( + resolve(&db, &own, "oral").await.unwrap(), + FALLBACK_WEIGHT, + "an unknown kind under an own set in force counts once" + ); + + // The reset restores inheritance: the offering's 5 applies again. + reset_class(&db, instance.get_id()).await.unwrap(); + let reset = instance_of(&db, instance.get_id()).await; + assert!(reset.exam_weights_inherited()); + assert_eq!(resolve(&db, &reset, "final").await.unwrap(), 5); + + // A kind the school does not list at all (no row anywhere) counts once. + assert_eq!(resolve(&db, &reset, "oral").await.unwrap(), FALLBACK_WEIGHT); + } + + /// While the section inherits, its effective map is the whole resolved + /// vocabulary; the moment its own set is in force, the map is exactly its + /// rows — nothing invented, nothing carried over. + #[tokio::test] + async fn the_resolved_map_switches_wholesale_with_the_flag() { + let (db, _leases) = crate::database::init_test_db().await; + let instance = an_instance(&db).await; + let offering = offering_id(&db, &instance).await; + set_for_offering(&db, &offering, "final", 5).await.unwrap(); + + let (inherited, map) = resolved_for_class(&db, &instance).await.unwrap(); + assert!(inherited); + let weight_of = |kind: &str| { + map.iter() + .find(|row| row.get_kind() == kind) + .map(ExamWeight::get_weight) + .unwrap_or_else(|| panic!("no `{kind}` in the resolved map")) + }; + assert_eq!(weight_of("final"), 5, "the offering row, not the settings 3"); + assert_eq!(weight_of("yazili"), 1, "the settings weight shines through"); + + set_for_class(&db, instance.get_id(), "yazili", 4).await.unwrap(); + let own = instance_of(&db, instance.get_id()).await; + let (inherited, map) = resolved_for_class(&db, &own).await.unwrap(); + assert!(!inherited); + assert_eq!(map.len(), 1, "the own set is the map — no inherited kinds"); + assert_eq!(map[0].get_kind(), "yazili"); + assert_eq!(map[0].get_weight(), 4); + } + + /// Writes refuse a kind the school does not run — before the weight is + /// even looked at (the settings vocabulary check is the first 400). + #[tokio::test] + async fn writes_refuse_an_unknown_kind_before_the_weight() { + let (db, _leases) = crate::database::init_test_db().await; + let instance = an_instance(&db).await; + let offering = offering_id(&db, &instance).await; + + for written in [ + set_for_offering(&db, &offering, "oral", 2).await, + set_for_class(&db, instance.get_id(), "oral", 2).await, + // Both wrong at once: the *kind* is what the error names. + set_for_class(&db, instance.get_id(), "oral", 500).await, + ] { + let err = written.unwrap_err(); + assert!( + matches!( + &err, + AppError::Validation(ValidationError::Invalid { field: "kind", .. }) + ), + "an unknown kind is refused on `kind`: {err:?}" + ); + } + + // A weight outside 1..=100 on a *known* kind is the bounds refusal. + let err = set_for_class(&db, instance.get_id(), "final", 500) + .await + .unwrap_err(); + assert!(matches!( + &err, + AppError::Validation(ValidationError::Invalid { field: "weight", .. }) + )); + } + + /// Deleting a row nobody wrote is a 404 and — per the flag-guarded + /// delete — flips nothing: a refused delete must not take the set own. + #[tokio::test] + async fn a_delete_with_no_row_is_a_404_that_moves_nothing() { + let (db, _leases) = crate::database::init_test_db().await; + let instance = an_instance(&db).await; + let offering = offering_id(&db, &instance).await; + + assert!(matches!( + remove_from_class(&db, instance.get_id(), "final").await, + Err(AppError::NotFound) + )); + assert!(matches!( + remove_from_offering(&db, &offering, "final").await, + Err(AppError::NotFound) + )); + let own = instance_of(&db, instance.get_id()).await; + assert!( + own.exam_weights_inherited(), + "the refused delete left inheritance in place" + ); + assert_eq!(resolve(&db, &own, "final").await.unwrap(), 3); + } + + /// The reset deletes every row and inherits again in one statement. + #[tokio::test] + async fn reset_drops_the_whole_own_set_and_inherits_again() { + let (db, _leases) = crate::database::init_test_db().await; + let instance = an_instance(&db).await; + set_for_class(&db, instance.get_id(), "yazili", 4).await.unwrap(); + set_for_class(&db, instance.get_id(), "final", 6).await.unwrap(); + + reset_class(&db, instance.get_id()).await.unwrap(); + let own = instance_of(&db, instance.get_id()).await; + assert!(own.exam_weights_inherited()); + assert!(db::exam_weight::list_for_class(&db, instance.get_id()) + .await + .unwrap() + .is_empty()); + // Settings weights apply again (yazili defaults to 1; final to 3). + assert_eq!(resolve(&db, &own, "final").await.unwrap(), 3); + + // A second reset is a no-op success, and a gone instance is a 404. + reset_class(&db, instance.get_id()).await.unwrap(); + let ghost = ClassCourseId::from_key("019732e3-7b00-7000-8000-00000000e1a1"); + assert!(matches!(reset_class(&db, &ghost).await, Err(AppError::NotFound))); + } + + async fn instance_of(db: &Database, id: &ClassCourseId) -> ClassCourse { + crate::service::class_course::read(db, id) + .await + .unwrap() + .unwrap() + } +} diff --git a/src/service/homework.rs b/src/service/homework.rs index 6c695e4..3a0cb20 100644 --- a/src/service/homework.rs +++ b/src/service/homework.rs @@ -35,6 +35,15 @@ pub async fn create( assigned: Option>, created_by: &UserId, ) -> Result { + // The subject tag is checked against the instance's *resolved* subject + // set — override-or-inherit — not merely against the catalog course. + // Service-side, so every caller (the route under `/instances` included) + // enforces the syllabus rule even though its own pre-flight only sees + // the course. + let instance = crate::service::class_course::read(db, class_course) + .await? + .ok_or(AppError::NotFound)?; + crate::service::offering_subject::ensure_resolved_member(db, &instance, subject).await?; homework::create( db, class_course, diff --git a/src/service/instance_resolve.rs b/src/service/instance_resolve.rs new file mode 100644 index 0000000..eb75465 --- /dev/null +++ b/src/service/instance_resolve.rs @@ -0,0 +1,185 @@ +//! The composed resolved view of one instance — the one call every +//! instance-scoped display rides. +//! +//! Wave 1/2 landed each axis's own resolver; this module composes them, so a +//! read surface never re-implements a fallback chain. The scalar content runs +//! instance → offering → catalog (`title`/`description`) or → constant +//! (`ders_saati` 1, `counts_toward_karne` TRUE); the set axes stay +//! flag-driven, exactly as their own resolvers rule — **override-or-inherit, +//! never merge**. +//! +//! Everything here is composition: [`resolve`] calls +//! [`crate::service::class_course::resolve_policy`], +//! [`crate::service::offering_subject::resolved_for_instance`], +//! [`crate::service::exam_weight::resolved_for_class`] and +//! [`crate::service::weekly_slot::resolved_for_instance`] and adds only the +//! title/description chain (whose two upper levels are a plain row read). +//! [`resolved_content`] is the batch twin of that chain for report surfaces +//! that already batch (karne, marks, attendance): two queries per batch, +//! never one per instance. + +use std::collections::HashMap; + +use crate::database::Database; +use crate::domain::class_course::{ClassCourse, DersSaati}; +use crate::domain::course::Course; +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; +use crate::domain::exam_weight::ExamWeight; +use crate::domain::subject::Subject; +use crate::domain::weekly_slot::WeeklySlot; +use crate::error::AppError; + +/// One instance's whole effective content: the resolved scalars plus *how* +/// each axis was sourced. A client renders this verbatim and never +/// re-implements the chain — the `*_overridden` flags tell an override from +/// an inherited value, and the three `*_inherited` flags tell whose set +/// (this section's own, possibly empty, or the offering template's) each +/// resolved set answers from. +#[derive(Debug, Clone)] +pub struct ResolvedInstance { + /// The display title: this section's override, else its offering's, else + /// the catalog course's. + pub title: String, + /// `true` when `title` is this section's own override. + pub title_overridden: bool, + /// The display description, same chain as [`Self::title`]. + pub description: String, + /// `true` when `description` is this section's own override. + pub description_overridden: bool, + /// The effective weekly hours: override, else offering default, else 1. + pub ders_saati: DersSaati, + /// `true` when the hours are this section's own override. + pub ders_saati_overridden: bool, + /// The effective report-card policy: override, else offering default, + /// else counted. + pub counts_toward_karne: bool, + /// `true` when the policy is this section's own override. + pub counts_toward_karne_overridden: bool, + /// `false` = the section's own subject table is authoritative, including + /// when empty; `true` = the offering's set applies. + pub subjects_inherited: bool, + /// The syllabus the section teaches, resolved override-or-inherit. + pub subjects: Vec, + /// The same switch for the section's exam-kind weights. + pub exam_weights_inherited: bool, + /// The section's effective weight map — every kind at its resolved + /// weight (own rows in force, else the offering → settings → 1 chain). + pub exam_weights: Vec, + /// The same switch for the section's weekly plan. + pub weekly_plan_inherited: bool, + /// The resolved plan: the offering's template week while inheriting, the + /// section's own rows (possibly empty) once it overrode. + pub weekly_plan: Vec, +} + +/// The title/description a batch of instances should display, keyed by +/// instance id key — the chain run once per batch: one offering read and one +/// catalog read for the whole set, then the instance's own override judged +/// in memory. An instance whose catalog row is unreachable renders an empty +/// string (the delete cascade makes that unreachable too; the karne lines +/// degrade rather than 500, the same as before this module existed). +pub async fn resolved_content( + db: &Database, + instances: &[&ClassCourse], +) -> Result, AppError> { + let mut offering_ids: Vec = Vec::new(); + let mut course_ids: Vec = Vec::new(); + for instance in instances { + if !offering_ids.contains(instance.get_offering()) { + offering_ids.push(instance.get_offering().clone()); + } + if !course_ids.contains(instance.get_course()) { + course_ids.push(instance.get_course().clone()); + } + } + let offerings = crate::db::course_offering::list_by_ids(db, &offering_ids).await?; + let courses = crate::db::course::list_by_ids(db, &course_ids).await?; + let offering_by_key: HashMap = offerings + .iter() + .map(|offering| (offering.get_id().key(), offering)) + .collect(); + let course_by_key: HashMap = courses + .iter() + .map(|course| (course.get_id().key(), course)) + .collect(); + + Ok(instances + .iter() + .map(|instance| { + let template = offering_by_key + .get(&instance.get_offering().key()) + .copied(); + let catalog = course_by_key.get(&instance.get_course().key()).copied(); + let title = instance + .get_title() + .or(template.and_then(|o| o.get_title())) + .or_else(|| catalog.map(|c| c.get_title())) + .map(|title| title.as_str().to_string()) + .unwrap_or_default(); + let description = instance + .get_description() + .or(template.and_then(|o| o.get_description())) + .or_else(|| catalog.map(|c| c.get_description())) + .map(|description| description.as_str().to_string()) + .unwrap_or_default(); + ( + instance.get_id().key().to_string(), + ResolvedContent { title, description }, + ) + }) + .collect()) +} + +/// The display strings of one instance: its resolved title and description. +pub struct ResolvedContent { + pub title: String, + pub description: String, +} + +/// Compose the whole resolved view of `instance` — the one call a read +/// surface pays instead of layering its own fallbacks. A gone offering or +/// catalog row is a `NotFound` (the `RESTRICT` foreign keys make that +/// unreachable; a missing row is never silently read as an empty template). +pub async fn resolve( + db: &Database, + instance: &ClassCourse, +) -> Result { + let offering = crate::db::course_offering::read(db, instance.get_offering()) + .await? + .ok_or(AppError::NotFound)?; + let course = crate::db::course::read(db, instance.get_course()) + .await? + .ok_or(AppError::NotFound)?; + let policy = crate::service::class_course::resolve_policy(db, instance).await?; + let subjects = + crate::service::offering_subject::resolved_for_instance(db, instance).await?; + let (exam_weights_inherited, exam_weights) = + crate::service::exam_weight::resolved_for_class(db, instance).await?; + let weekly_plan = crate::service::weekly_slot::resolved_for_instance(db, instance).await?; + + let title = instance + .get_title() + .or(offering.get_title()) + .unwrap_or_else(|| course.get_title()); + let description = instance + .get_description() + .or(offering.get_description()) + .unwrap_or_else(|| course.get_description()); + + Ok(ResolvedInstance { + title: title.as_str().to_string(), + title_overridden: instance.get_title().is_some(), + description: description.as_str().to_string(), + description_overridden: instance.get_description().is_some(), + ders_saati: policy.ders_saati, + ders_saati_overridden: instance.get_ders_saati().is_some(), + counts_toward_karne: policy.counts_toward_karne, + counts_toward_karne_overridden: instance.counts_toward_karne().is_some(), + subjects_inherited: instance.subjects_inherited(), + subjects, + exam_weights_inherited, + exam_weights, + weekly_plan_inherited: instance.weekly_plan_inherited(), + weekly_plan, + }) +} diff --git a/src/service/karne.rs b/src/service/karne.rs index c3911bc..8c81b49 100644 --- a/src/service/karne.rs +++ b/src/service/karne.rs @@ -6,8 +6,10 @@ //! average takes a label from the school's grade bands; and the term's own //! number is a single average over the instances, each weighted by its //! `ders_saati` (the report-card weight the section set on the instance). The -//! catalog's `course` row contributes only its title — the two class sections -//! teaching it are their own instances and their own report-card lines. +//! title a line shows is the instance's **resolved** one (override → offering +//! → catalog, via [`crate::service::instance_resolve`]) — two class sections +//! teaching the same catalog course are their own instances and their own +//! report-card lines. //! //! A line's marks are the exams *addressed to* its instance //! (`exam_audience`), not only the ones it owns: a shared exam announced to @@ -36,7 +38,8 @@ use crate::error::AppError; /// One instance's line on a report card: the average of the marks the student /// holds in it this term, its band label, and the `ders_saati` it weighs into -/// the year average with. `course` is the catalog course's title (what a +/// the year average with. `course` is the instance's **resolved** title — its +/// section's override, else its offering's, else the catalog course's (what a /// family reads); `class_course` is the instance itself, for anything that /// must act on the line. #[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)] @@ -150,14 +153,22 @@ async fn compute(db: &Database, user: &UserId, term: &Term) -> Result = - crate::db::class_course::list_for_class_ids(db, &class_ids) - .await? - .into_iter() - .filter(|instance| instance.counts_toward_karne()) - .collect(); + // The report-card-counting instances, each with its **resolved** policy: + // `counts_toward_karne` is nullable now (NULL = inherit the offering's + // default, else counted), so the filter and the weights both go through + // the resolver — a raw read would treat "not decided" as a decision. + let mut counted: Vec<( + crate::domain::class_course::ClassCourse, + crate::service::class_course::InstancePolicy, + )> = Vec::new(); + for instance in crate::db::class_course::list_for_class_ids(db, &class_ids).await? { + let policy = crate::service::class_course::resolve_policy(db, &instance).await?; + if policy.counts_toward_karne { + counted.push((instance, policy)); + } + } let instance_ids: Vec = - instances.iter().map(|i| i.get_id().clone()).collect(); + counted.iter().map(|(i, _)| i.get_id().clone()).collect(); // The term's exams inside those instances, plus this student's marks on // them. An exam another term owns is not this report card's to weigh. @@ -178,24 +189,20 @@ async fn compute(db: &Database, user: &UserId, term: &Term) -> Result = - instances.iter().map(|i| i.get_course().clone()).collect(); - let courses = crate::db::course::list_by_ids(db, &course_ids).await?; - let titles: HashMap = courses - .iter() - .map(|course| { - ( - course.get_id().key(), - course.get_title().as_str().to_string(), - ) - }) - .collect(); + // Titles for the lines: the sections' **resolved** titles (override → + // offering → catalog), batched — one offering read + one catalog read + // for the whole report. + let line_refs: Vec<&crate::domain::class_course::ClassCourse> = + counted.iter().map(|(i, _)| i).collect(); + let titles = crate::service::instance_resolve::resolved_content(db, &line_refs).await?; - let mut lines = Vec::with_capacity(instances.len()); + let mut lines = Vec::with_capacity(counted.len()); let mut weighted: Vec<(f64, i64)> = Vec::new(); - for instance in &instances { + for (instance, policy) in &counted { let mut pairs: Vec<(i64, i64)> = Vec::new(); + // The section's weight chain answer per kind, computed once — every + // mark of a kind weighs the same inside one line. + let mut line_weights: HashMap = HashMap::new(); for (line, result) in &results { // Every mark the read attributed to another instance stays out of // this line; one line's marks are exactly those addressed under it. @@ -207,24 +214,35 @@ async fn compute(db: &Database, user: &UserId, term: &Term) -> Result *weight, + None => { + let weight = + crate::service::exam_weight::resolve(db, instance, kind).await?; + line_weights.insert(kind.to_string(), weight); + weight + } + }; pairs.push((result.get_mark().as_i64(), weight)); } let average = weighted_average(&pairs); if let Some(average) = average { - weighted.push((average, instance.get_ders_saati().as_i64())); + weighted.push((average, policy.ders_saati.as_i64())); } lines.push(KarneInstance { class_course: instance.get_id().key(), + // The resolved display title: the section's override, else its + // offering's, else the catalog's — never the bare catalog row. course: titles - .get(instance.get_course().key().as_str()) - .cloned() + .get(instance.get_id().key().as_str()) + .map(|content| content.title.clone()) .unwrap_or_default(), - ders_saati: instance.get_ders_saati().as_i64(), + ders_saati: policy.ders_saati.as_i64(), band: average.and_then(|average| school.grade_label(average).map(str::to_string)), average, }); @@ -321,7 +339,7 @@ mod tests { }; // The owner sits both exams; the addressed instance only the shared - // one. Both kinds are `yazili`, whose default weight is 1. + // one. Both kinds (`yazili`, `sozlu`) weigh 1 in the default settings. let owner = line(&fixture.owner); assert_eq!( owner.average, @@ -350,4 +368,45 @@ mod tests { "75 clears the floor" ); } + + /// A class-level weight moves the average: with the owner section's own + /// set in force (`yazili` = 2), its ortak mark counts double — + /// (85×2 + 45×1) / 3 — while the sibling section, still inheriting, keeps + /// the plain settings weight and its plain mean. Read off the settings + /// singleton both lines would have stayed at 65 and 85. + #[tokio::test] + async fn a_class_level_weight_changes_the_karne_average() { + let (db, _leases) = crate::database::init_test_db().await; + let fixture = crate::db::exam_result::tests::an_ortak_exam_karne(&db).await; + + let owner = crate::service::class_course::read(&db, &fixture.owner) + .await + .unwrap() + .unwrap(); + crate::service::exam_weight::set_for_class(&db, owner.get_id(), "yazili", 2) + .await + .unwrap(); + + let report = build(&db, &fixture.student, &fixture.term).await.unwrap(); + let line = |instance: &crate::domain::class_course::ClassCourseId| { + report + .instances + .iter() + .find(|line| line.class_course == instance.key()) + .unwrap_or_else(|| panic!("no line for {}", instance.key())) + }; + + assert_eq!( + line(&fixture.owner).average, + Some((2.0 * crate::db::exam_result::tests::ORTAK_MARK as f64 + + crate::db::exam_result::tests::OWNER_MARK as f64) + / 3.0), + "the ortak mark counts double under the section's own weight" + ); + assert_eq!( + line(&fixture.addressed).average, + Some(crate::db::exam_result::tests::ORTAK_MARK as f64), + "the sibling still inherits — a class weight never leaks across sections" + ); + } } diff --git a/src/service/mod.rs b/src/service/mod.rs index aac82fb..5c7be73 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -20,6 +20,7 @@ pub mod class_member; pub mod course; pub mod course_note; pub mod course_note_file; +pub mod course_offering; pub mod course_session; pub mod dietary_profile; pub mod enrollment; @@ -29,6 +30,7 @@ pub mod exam_answer; pub mod exam_attempt; pub mod exam_question; pub mod exam_result; +pub mod exam_weight; pub mod fee_plan; pub mod fee_plan_assignment; pub mod homework; @@ -36,6 +38,7 @@ pub mod homework_file; pub mod homework_result; pub mod homework_submission; pub mod instance; +pub mod instance_resolve; pub mod karne; pub mod meal_attendance; pub mod meal_booking; @@ -44,6 +47,7 @@ pub mod menu; pub mod message; pub mod note; pub mod note_file; +pub mod offering_subject; pub mod parent_link; pub mod payment_ledger; pub mod person; @@ -66,4 +70,5 @@ pub mod solution_image; pub mod subject; pub mod term; pub mod user; +pub mod weekly_slot; pub mod work_entry; diff --git a/src/service/offering_subject.rs b/src/service/offering_subject.rs new file mode 100644 index 0000000..eae7599 --- /dev/null +++ b/src/service/offering_subject.rs @@ -0,0 +1,470 @@ +//! Syllabus selection workflows: the offering's topic set (a manager curates +//! the grade's template) and the section's own override of it, plus the two +//! resolvers the read surfaces and the tag-validation rewire ride on. The SQL +//! lives in [`crate::db::offering_subject`]; the one pure rule — a selection +//! names a subject of the offering's own course — in +//! [`crate::domain::offering_subject`]. +//! +//! Resolution is override-or-inherit, never merge, and flag-driven: +//! `subjects_inherited` TRUE → the offering's set, FALSE → the section's own +//! rows **even when that set is empty**. Every class-side write door here +//! flips the flag in the same statement as its row change (the CTEs in the +//! db module), so the flag can never describe a stale set; this module never +//! writes `class_course` itself. + +use crate::database::Database; +use crate::domain::class_course::ClassCourse; +use crate::domain::course::CourseId; +use crate::domain::course_offering::CourseOfferingId; +use crate::domain::offering_subject::ensure_course_member; +use crate::domain::subject::{Subject, SubjectId}; +use crate::error::{AppError, ValidationError}; +use crate::{db, service}; + +/// The topics the grade-level template selects, name-then-id order — the +/// inheritance side of [`resolved_for_instance`]. +pub async fn resolved_for_offering( + db: &Database, + offering: &CourseOfferingId, +) -> Result, AppError> { + db::offering_subject::list_for_offering(db, offering).await +} + +/// The topics this section teaches, resolved override-or-inherit: its own +/// rows while `subjects_inherited` is FALSE (including an empty set — a +/// section may clear its syllabus), otherwise the offering's set. +pub async fn resolved_for_instance( + db: &Database, + instance: &ClassCourse, +) -> Result, AppError> { + if instance.subjects_inherited() { + resolved_for_offering(db, instance.get_offering()).await + } else { + db::offering_subject::list_for_class_course(db, instance.get_id()).await + } +} + +/// A 400 unless `subject` sits in what the section *teaches* — the resolved +/// set, not the bare course. This is the half of the tag check the +/// exam-question and homework writers now pay in addition to +/// [`service::subject::in_course`](crate::service::subject::in_course): +/// a subject of the right course can still be off the syllabus. +pub async fn ensure_resolved_member( + db: &Database, + instance: &ClassCourse, + subject: &SubjectId, +) -> Result<(), AppError> { + match db::offering_subject::resolves_for_class_course(db, instance.get_id(), subject).await? { + Some(true) => Ok(()), + Some(false) => Err(ValidationError::Invalid { + field: "subject_id", + reason: "subject is not in this section's subject set", + } + .into()), + // The section vanished between the handler's read and this probe; + // that is a 404, not a validation miss. + None => Err(AppError::NotFound), + } +} + +/// The request's subject as a validated selection candidate: it exists, and +/// it belongs to `course` — the exact two 400s the tag-time check answers, +/// reused so a refused selection and a refused tag read identically. +async fn subject_of_course( + db: &Database, + key: &str, + course: &CourseId, +) -> Result { + let subject = db::subject::read(db, &SubjectId::from_key(key)) + .await? + .ok_or(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + })?; + ensure_course_member(&subject, course)?; + Ok(subject) +} + +/// Select a topic for the offering. Manager-only at the route. Answers the +/// subject and whether this call added it — re-adding a selection is a no-op +/// success (`added` = false). +pub async fn add_to_offering( + db: &Database, + offering: &CourseOfferingId, + subject_key: &str, +) -> Result<(Subject, bool), AppError> { + let offering = service::course_offering::read(db, offering) + .await? + .ok_or(AppError::NotFound)?; + let subject = subject_of_course(db, subject_key, offering.get_course()).await?; + let added = db::offering_subject::add_for_offering(db, offering.get_id(), subject.get_id()) + .await?; + Ok((subject, added)) +} + +/// Drop a topic from the offering's selection. A subject the offering never +/// selected is a 404. +pub async fn remove_from_offering( + db: &Database, + offering: &CourseOfferingId, + subject_key: &str, +) -> Result<(), AppError> { + let offering = service::course_offering::read(db, offering) + .await? + .ok_or(AppError::NotFound)?; + let dropped = + db::offering_subject::remove_for_offering(db, offering.get_id(), &SubjectId::from_key(subject_key)) + .await?; + if !dropped { + return Err(AppError::NotFound); + } + Ok(()) +} + +/// Select a topic for the section's own set — the override: the CTE in the +/// db module flips `subjects_inherited` to FALSE in the same statement, so +/// from this call on the section's own table (not the offering's) is +/// authoritative. Idempotent: re-adding is a no-op success (`added` = false). +pub async fn add_to_instance( + db: &Database, + instance: &ClassCourse, + subject_key: &str, +) -> Result<(Subject, bool), AppError> { + let subject = subject_of_course(db, subject_key, instance.get_course()).await?; + let (live, added) = + db::offering_subject::add_for_class_course(db, instance.get_id(), subject.get_id()) + .await?; + if !live { + // The section was detached between the handler's gate and this write. + return Err(AppError::NotFound); + } + Ok((subject, added)) +} + +/// Drop a topic from the section's own set (flagging the set as its own in +/// the same statement, when a row actually went). A subject the section +/// never selected is a 404 — including while inheriting, where it must not +/// silently start an override. +pub async fn remove_from_instance( + db: &Database, + instance: &ClassCourse, + subject_key: &str, +) -> Result<(), AppError> { + let (live, dropped) = db::offering_subject::remove_for_class_course( + db, + instance.get_id(), + &SubjectId::from_key(subject_key), + ) + .await?; + if !live || !dropped { + return Err(AppError::NotFound); + } + Ok(()) +} + +/// The section's reset door: sweep its own rows and restore inheritance — +/// the flag goes back to TRUE in the same statement that sweeps. Answers the +/// number of rows the sweep removed (0 is a fine answer: clearing an empty +/// own set is exactly the request that must re-inherit). +pub async fn reset_instance(db: &Database, instance: &ClassCourse) -> Result { + let (swept, live) = db::offering_subject::reset_for_class_course(db, instance.get_id()).await?; + if !live { + return Err(AppError::NotFound); + } + Ok(swept) +} + +/// Parse a path segment as a subject key — the nil-uuid trick the repo's +/// other id keys use: a malformed segment matches no row and reads as a 404. +/// Kept next to the doors so callers need no domain imports for it. +pub fn subject_key(key: &str) -> SubjectId { + SubjectId::from_key(key) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::init_test_db; + use crate::db::course::a_test_instance; + use crate::db::subject as subject_rows; + use crate::domain::subject::{SubjectDescription, SubjectName}; + + async fn a_topic(db: &Database, course: &CourseId, name: &str) -> Subject { + subject_rows::create( + db, + course, + SubjectName::try_new(name).unwrap(), + SubjectDescription::try_new("").unwrap(), + ) + .await + .unwrap() + } + + /// A live instance row for a freshly attached course: inheriting by + /// default, offering auto-minted for the same course. + async fn an_instance(db: &Database) -> (ClassCourse, CourseId) { + let (instance, course) = a_test_instance(db).await; + let row = service::class_course::read(db, &instance) + .await + .unwrap() + .unwrap(); + (row, course) + } + + fn names(subjects: &[Subject]) -> Vec<&str> { + subjects + .iter() + .map(|s| s.get_name().as_str()) + .collect::>() + } + + /// Inheritance: with the flag at its attach-time TRUE and no own rows, + /// the section resolves to exactly the offering's set, in name order — + /// Alpha before Zeta although Zeta was created first, so dropping the + /// ORDER BY fails this. + #[tokio::test] + async fn an_inheriting_section_resolves_the_offerings_set_in_name_order() { + let (db, _leases) = init_test_db().await; + let (instance, course) = an_instance(&db).await; + let zeta = a_topic(&db, &course, "Zeta").await; + let alpha = a_topic(&db, &course, "Alpha").await; + for subject in [&zeta, &alpha] { + db::offering_subject::add_for_offering( + &db, + instance.get_offering(), + subject.get_id(), + ) + .await + .unwrap(); + } + + assert!(instance.subjects_inherited()); + let resolved = resolved_for_instance(&db, &instance).await.unwrap(); + assert_eq!(names(&resolved), vec!["Alpha", "Zeta"]); + // The offering-side resolver agrees — one chain, two doors. + let offering = resolved_for_offering(&db, instance.get_offering()) + .await + .unwrap(); + assert_eq!(names(&offering), vec!["Alpha", "Zeta"]); + } + + /// Own-set-wins, including when empty: one add flips the flag and the + /// section resolves to its own table; after removing the only own row the + /// flag is still FALSE and the resolved set is *empty* — the offering's + /// topics must NOT bleed back in, or "clear the syllabus" would be + /// impossible. + #[tokio::test] + async fn an_owned_set_wins_even_when_it_is_empty() { + let (db, _leases) = init_test_db().await; + let (instance, course) = an_instance(&db).await; + let offering_topic = a_topic(&db, &course, "Offering-only").await; + db::offering_subject::add_for_offering( + &db, + instance.get_offering(), + offering_topic.get_id(), + ) + .await + .unwrap(); + let own = a_topic(&db, &course, "Own").await; + + let (_, added) = add_to_instance(&db, &instance, &own.get_id().key()) + .await + .unwrap(); + assert!(added); + + let owned = service::class_course::read(&db, instance.get_id()) + .await + .unwrap() + .unwrap(); + assert!(!owned.subjects_inherited(), "the add must flip the flag"); + assert_eq!( + names(&resolved_for_instance(&db, &owned).await.unwrap()), + vec!["Own"] + ); + + remove_from_instance(&db, &owned, &own.get_id().key()) + .await + .unwrap(); + let cleared = service::class_course::read(&db, instance.get_id()) + .await + .unwrap() + .unwrap(); + assert!( + !cleared.subjects_inherited(), + "a plain row delete must not restore inheritance" + ); + assert!(resolved_for_instance(&db, &cleared).await.unwrap().is_empty()); + } + + /// The membership precondition at both doors: a subject of *another* + /// course is a 400 with the tag-check's exact reason, writes no row, and + /// leaves the flag alone. Break `ensure_course_member` (or wire a door + /// past it) and the asserts on the error and the row counts fail. + #[tokio::test] + async fn a_foreign_course_subject_is_refused_at_both_doors() { + let (db, _leases) = init_test_db().await; + let (instance, _course) = an_instance(&db).await; + let (foreign_instance, foreign_course) = an_instance(&db).await; + let stranger = a_topic(&db, &foreign_course, "Stranger").await; + + for door in [ + add_to_offering(&db, instance.get_offering(), &stranger.get_id().key()).await, + add_to_instance(&db, &instance, &stranger.get_id().key()).await, + ] { + let err = door.unwrap_err(); + assert!( + matches!(err, AppError::Validation(_)), + "expected the 400 validation refusal, got {err:?}" + ); + assert_eq!( + err.to_string(), + "subject_id: subject belongs to a different course" + ); + } + + // Nothing landed anywhere, and the section still inherits. + assert!(resolved_for_offering(&db, instance.get_offering()) + .await + .unwrap() + .is_empty()); + assert!(resolved_for_offering(&db, foreign_instance.get_offering()) + .await + .unwrap() + .is_empty()); + assert!(db::offering_subject::list_for_class_course(&db, instance.get_id()) + .await + .unwrap() + .is_empty()); + assert!(instance.subjects_inherited()); + } + + /// The reset door: after an own selection, reset sweeps the rows and + /// flips the flag back to TRUE in the same statement — the offering's set + /// applies again, and a second reset stays green (idempotent). + #[tokio::test] + async fn a_reset_restores_inheritance() { + let (db, _leases) = init_test_db().await; + let (instance, course) = an_instance(&db).await; + let offering_topic = a_topic(&db, &course, "Template").await; + db::offering_subject::add_for_offering( + &db, + instance.get_offering(), + offering_topic.get_id(), + ) + .await + .unwrap(); + let own = a_topic(&db, &course, "Own").await; + add_to_instance(&db, &instance, &own.get_id().key()) + .await + .unwrap(); + + let swept = reset_instance(&db, &instance).await.unwrap(); + assert_eq!(swept, 1, "the one own row must be gone"); + + let restored = service::class_course::read(&db, instance.get_id()) + .await + .unwrap() + .unwrap(); + assert!(restored.subjects_inherited()); + assert_eq!( + names(&resolved_for_instance(&db, &restored).await.unwrap()), + vec!["Template"] + ); + + // Resetting a section that now holds nothing is still a clean 200-ish + // success: the door is about the flag as much as the rows. + assert_eq!(reset_instance(&db, &restored).await.unwrap(), 0); + } + + /// Idempotent add: the second POST of the same selection succeeds without + /// a second row — and the flag stays FALSE across both. A duplicate row + /// (or a 409 on the repeat) fails the count/asserts. + #[tokio::test] + async fn re_adding_a_selection_is_a_no_op_success() { + let (db, _leases) = init_test_db().await; + let (instance, course) = an_instance(&db).await; + let topic = a_topic(&db, &course, "Twice").await; + + let (first_subject, first_added) = + add_to_instance(&db, &instance, &topic.get_id().key()).await.unwrap(); + assert!(first_added); + let (_, second_added) = + add_to_instance(&db, &instance, &topic.get_id().key()).await.unwrap(); + assert!(!second_added, "the repeat must be a no-op, not a second row"); + + assert_eq!(first_subject.get_id(), topic.get_id()); + let own = db::offering_subject::list_for_class_course(&db, instance.get_id()) + .await + .unwrap(); + assert_eq!(names(&own), vec!["Twice"]); + + // The offering door idempts the same way. + let (_, offering_again) = + add_to_offering(&db, instance.get_offering(), &topic.get_id().key()) + .await + .unwrap(); + assert!(offering_again); + let (_, offering_repeat) = + add_to_offering(&db, instance.get_offering(), &topic.get_id().key()) + .await + .unwrap(); + assert!(!offering_repeat); + assert_eq!( + names( + &resolved_for_offering(&db, instance.get_offering()) + .await + .unwrap() + ), + vec!["Twice"] + ); + } + + /// The rewire's core: a same-course subject OFF the resolved set is + /// refused by the tag gate, and accepted once the section selects it — + /// while the plain course check (`service::subject::in_course`) would + /// pass both. Whatever makes `ensure_resolved_member` a bare-course + /// check again fails one of the two asserts. + #[tokio::test] + async fn the_tag_gate_checks_the_resolved_set_not_the_bare_course() { + let (db, _leases) = init_test_db().await; + let (instance, course) = an_instance(&db).await; + let selected = a_topic(&db, &course, "Selected").await; + let unselected = a_topic(&db, &course, "Unselected").await; + db::offering_subject::add_for_offering( + &db, + instance.get_offering(), + selected.get_id(), + ) + .await + .unwrap(); + + // Inheriting: the offering's set is the syllabus. + ensure_resolved_member(&db, &instance, selected.get_id()) + .await + .unwrap(); + let err = ensure_resolved_member(&db, &instance, unselected.get_id()) + .await + .unwrap_err(); + assert_eq!( + err.to_string(), + "subject_id: subject is not in this section's subject set" + ); + + // Same subject, once the section owns it: accepted. The owned set is + // authoritative *instead of* the offering's, so `selected` — in the + // course, on the offering — is now OFF the syllabus. + add_to_instance(&db, &instance, &unselected.get_id().key()) + .await + .unwrap(); + ensure_resolved_member(&db, &instance, unselected.get_id()) + .await + .unwrap(); + let err = ensure_resolved_member(&db, &instance, selected.get_id()) + .await + .unwrap_err(); + assert_eq!( + err.to_string(), + "subject_id: subject is not in this section's subject set" + ); + } +} diff --git a/src/service/rag_scope.rs b/src/service/rag_scope.rs index 6eabaac..759045a 100644 --- a/src/service/rag_scope.rs +++ b/src/service/rag_scope.rs @@ -132,17 +132,24 @@ pub async fn for_user( let classes = crate::db::class_group::list_by_ids(db, &class_ids).await?; let courses = crate::db::course::list_by_ids(db, &course_ids).await?; - // Grade labels, keyed by class section. A class with no grade at all (a - // club-shaped section, and the shape a fixture class carries) simply - // contributes no entry, so its instances scope the subject across every - // grade — the documented meaning of an absent `sinif`. + // Display labels, keyed by class section. Every section carries a ladder + // rung now, so every class-keyed instance pairs with one; only the + // school-wide club/study memberships ride in with no grade at all (the + // documented meaning of an absent `sinif`). let grades: HashMap = classes .iter() - .filter_map(|class| { - class - .get_grade() - .map(|grade| (class.get_id().key(), grade.as_str().to_owned())) - }) + .map(|class| (class.get_id().key(), class.get_grade_level().label().to_owned())) + .collect(); + // The instances' **resolved** titles (override → offering → catalog): the + // section's own grade content is what a scope pair names. Batched — one + // offering read + one catalog read for the whole scope. The club/study + // memberships below keep the catalog title: a school-wide course has no + // offering, so the catalog row is the only label there is. + let instance_refs: Vec<&ClassCourse> = instances.iter().collect(); + let resolved = crate::service::instance_resolve::resolved_content(db, &instance_refs).await?; + let ders_by_instance: HashMap = resolved + .into_iter() + .map(|(key, content)| (key, content.title)) .collect(); let titles: HashMap = courses .iter() @@ -152,10 +159,10 @@ pub async fn for_user( let mut pairs: Vec = Vec::new(); let mut seen: HashSet<(Option, String)> = HashSet::new(); for instance in &instances { - // A course row the batch read did not answer is unreachable — the + // A title the batch read did not answer is unreachable — the // instance's key is a foreign key — so the skip is a guard against a // dangling read, not a rule: a title-less pair could not be routed. - let Some(ders) = titles.get(&instance.get_course().key()) else { + let Some(ders) = ders_by_instance.get(instance.get_id().key().as_str()) else { continue; }; push_pair( @@ -203,7 +210,8 @@ fn push_pair( #[cfg(test)] mod tests { use super::*; - use crate::domain::class_group::{ClassGrade, ClassGroupId, ClassName}; + use crate::domain::class_group::{ClassGroupId, ClassName}; + use crate::domain::grade::GradeLevel; use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; use crate::domain::user::Username; @@ -230,15 +238,15 @@ mod tests { .unwrap() } - /// A class section carrying a grade label — the half of every instance - /// pair, since `a_class` deliberately has none. + /// A class section at a chosen rung — the half of every instance pair + /// that scopes by grade. async fn graded_class(db: &Database, name: &str, grade: &str) -> ClassGroupId { let office = crate::db::class_member::tests::fixture_user(db, "ragscope-office").await; crate::service::class_group::create( db, &office, ClassName::try_new(name).unwrap(), - Some(ClassGrade::try_new(grade).unwrap()), + GradeLevel::new(grade.parse().unwrap()).unwrap(), None, None, ) diff --git a/src/service/subject.rs b/src/service/subject.rs index e2e5e68..67ff7ac 100644 --- a/src/service/subject.rs +++ b/src/service/subject.rs @@ -1,10 +1,14 @@ -//! Subject workflows: the two id resolvers every question/homework tag goes +//! Subject workflows: the id resolvers every question/homework tag goes //! through — the same-course rule for curriculum content, existence-only for //! the bank's cross-course origin metadata — over the row writes in -//! [`crate::db::subject`]. +//! [`crate::db::subject`]. Since the course-template system, the tag gate for +//! instance-scoped content is [`in_instance`]: the same-course rule *plus* +//! the section's resolved subject set (override-or-inherit), because a +//! section teaches a selection of the course, not the whole course. use crate::database::Database; use crate::db::subject; +use crate::domain::class_course::ClassCourse; use crate::domain::course::CourseId; use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; use crate::error::{AppError, ValidationError}; @@ -53,9 +57,12 @@ pub async fn delete(db: &Database, target: Subject) -> Result } /// Turn a request-supplied subject id into a validated reference, provided the -/// subject belongs to `course` — a question may only be tagged with a subject -/// of its own exam's course. Unknown or foreign subjects are a `400` naming -/// the field. Shared by the question create/update handlers. +/// subject belongs to `course`. The *course half* of the instance tag gate — +/// a question may only be tagged with a subject of its own exam's course. +/// Instance-scoped writers use [`in_instance`], which adds the section's +/// resolved subject set on top; this fn stays for the callers that have only +/// the course at hand. Unknown or foreign subjects are a `400` naming the +/// field. Shared by the question create/update handlers. pub async fn in_course(db: &Database, id: &str, course: &CourseId) -> Result { let subject = subject::read(db, &SubjectId::from_key(id)) @@ -73,6 +80,25 @@ pub async fn in_course(db: &Database, id: &str, course: &CourseId) -> Result Result { + let subject_id = in_course(db, id, instance.get_course()).await?; + crate::service::offering_subject::ensure_resolved_member(db, instance, &subject_id).await?; + Ok(subject_id) +} + /// Turn a request-supplied subject id into a validated reference, checking only /// that the subject exists — no course tie. For the question bank, whose subject /// is cross-course origin metadata: the same-course rule applies at instantiate diff --git a/src/service/weekly_slot.rs b/src/service/weekly_slot.rs new file mode 100644 index 0000000..fba4529 --- /dev/null +++ b/src/service/weekly_slot.rs @@ -0,0 +1,479 @@ +//! Weekly-plan workflows: the two resolution arms (the flag decides whose +//! rows a reader sees), the guarded adds (overlap and cap, judged inside the +//! owner's row lock so two racers cannot both clear the pre-check), and the +//! override doors (add/remove/reset on the section's own set, each flipping +//! `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. + +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::weekly_slot::{ + SlotAddError, SlotMinute, Weekday, WeeklySlot, WeeklySlotId, check_add, +}; +use crate::error::AppError; + +/// The weekly plan a read should present for `instance`: the offering's +/// slots while the section follows the template +/// (`weekly_plan_inherited`), its own rows once it overrode — **including +/// when that own set is empty**, which is how a section clears its +/// timetable. Weekday first, then start time; the empty plan is a valid +/// answer, never an error. +pub async fn resolved_for_instance( + db: &Database, + instance: &ClassCourse, +) -> Result, AppError> { + if instance.weekly_plan_inherited() { + resolved_for_offering(db, instance.get_offering()).await + } else { + resolved_own(db, instance.get_id()).await + } +} + +/// The offering's template week — the arm `resolved_for_instance` follows +/// while the section inherits, and the direct read the offering-side route +/// serves. Weekday first, then start time. +pub async fn resolved_for_offering( + db: &Database, + offering_id: &CourseOfferingId, +) -> Result, AppError> { + slot_db::list_for_offering(db, offering_id).await +} + +/// The section's own rows, flag-independent — the resolver's override arm. +async fn resolved_own( + db: &Database, + instance: &ClassCourseId, +) -> Result, AppError> { + slot_db::list_for_class(db, instance).await +} + +/// Add one slot to the offering's template week. Manager-gated at the route; +/// 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. +pub async fn add_for_offering( + db: &Database, + offering: &CourseOfferingId, + weekday: Weekday, + starts_at: SlotMinute, + ends_at: SlotMinute, +) -> Result { + let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at)?; + let owner = offering.clone(); + tx_with_retry(db, false, async move |tx| { + // The row lock serializes the pre-check and the insert: under READ + // COMMITTED a rival's uncommitted slot would otherwise be invisible. + slot_db::lock_offering_tx(tx, &owner).await?; + let existing = slot_db::list_for_offering_on(&mut *tx, &owner).await?; + check_add(&existing, &slot).map_err(slot_add_conflict)?; + slot_db::add_for_offering_tx(tx, &slot, &owner).await + }) + .await +} + +/// Add one slot to the section's own week — the override door. Writing any +/// row flips `weekly_plan_inherited` to `FALSE` in the same statement, so the +/// section's own set becomes authoritative from this write on. Same refusals +/// as [`add_for_offering`], plus 404 when the instance is gone. +pub async fn add_for_class( + db: &Database, + instance: &ClassCourseId, + weekday: Weekday, + starts_at: SlotMinute, + ends_at: SlotMinute, +) -> Result { + let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at)?; + let owner = instance.clone(); + tx_with_retry(db, false, async move |tx| { + slot_db::lock_class_tx(tx, &owner).await?; + let existing = slot_db::list_for_class_on(&mut *tx, &owner).await?; + check_add(&existing, &slot).map_err(slot_add_conflict)?; + slot_db::add_for_class_tx(tx, &slot, &owner).await + }) + .await +} + +/// Drop one slot of the offering's template week. A slot of another offering +/// (or an already-gone id) is a 404. +pub async fn remove_for_offering( + db: &Database, + offering: &CourseOfferingId, + slot: &WeeklySlotId, +) -> Result<(), AppError> { + slot_db::remove_for_offering(db, offering, slot).await +} + +/// Drop one slot of the section's own week — the override door. The flag +/// flips to `FALSE` in the same statement as the delete, so dropping the +/// last row leaves the section with an authoritative *empty* plan rather +/// than quietly re-inheriting. A 404 (unknown id, or another instance's +/// slot) leaves the flag untouched. +pub async fn remove_for_class( + db: &Database, + instance: &ClassCourseId, + slot: &WeeklySlotId, +) -> Result<(), AppError> { + slot_db::remove_for_class(db, instance, slot).await +} + +/// Reset the section's weekly plan to inherit: delete its own slots and flip +/// the flag back to `TRUE` in one statement. After this +/// [`resolved_for_instance`] serves the offering's rows again. Idempotent for +/// a section that never overrode; 404 when the instance is gone. +pub async fn reset_for_class(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> { + slot_db::reset_for_class(db, instance).await +} + +/// Map the pure add-time refusals onto the wire's coded 409s. +fn slot_add_conflict(error: SlotAddError) -> AppError { + match error { + SlotAddError::Overlap => AppError::ConflictCoded { + code: "slot_overlap", + message: "another slot already occupies an intersecting time on this weekday".into(), + }, + SlotAddError::Full => AppError::ConflictCoded { + code: "slot_cap", + message: format!( + "this weekly plan already holds the maximum of {} slots", + crate::constant::MAX_WEEKLY_SLOTS + ), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::class_member::tests::{a_class, a_course, fixture_user}; + + /// The instance row, re-read from the store — the flag assertions judge + /// the stored column, not a return value. + async fn instance_row(db: &Database, id: &ClassCourseId) -> ClassCourse { + crate::service::class_course::read(db, id) + .await + .unwrap() + .unwrap() + } + + fn day(raw: i16) -> Weekday { + Weekday::new(raw).unwrap() + } + + fn mins(raw: i64) -> SlotMinute { + SlotMinute::new(raw).unwrap() + } + + /// An attached instance: its auto-minted offering id is the template the + /// inheritance arm reads. + async fn an_instance(db: &Database, name: &str) -> ClassCourse { + let manager = fixture_user(db, "manager").await; + let class = a_class(name, db).await; + let course = a_course("Matematik", db).await; + crate::service::class_course::attach(db, &class, &course, &manager) + .await + .unwrap() + } + + fn coded(result: &Result) -> String { + match result { + Err(AppError::ConflictCoded { code, .. }) => code.to_string(), + other => panic!("expected a coded 409, got {other:?}"), + } + } + + /// While the section inherits, its resolved plan is the offering's — + /// weekday first, then start time, whatever order the slots were added + /// in. The flag stays TRUE; nothing on the section's side was written. + #[tokio::test] + async fn an_inheriting_section_resolves_the_offerings_slots_in_order() { + let (db, _leases) = crate::database::init_test_db().await; + 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)) + .await + .unwrap(); + add_for_offering(&db, &offering, day(1), mins(600), mins(660)) + .await + .unwrap(); + add_for_offering(&db, &offering, day(1), mins(480), mins(540)) + .await + .unwrap(); + + assert!( + instance_row(&db, instance.get_id()) + .await + .weekly_plan_inherited() + ); + let resolved = resolved_for_instance(&db, &instance).await.unwrap(); + let starts: Vec = resolved.iter().map(|s| s.get_starts_at().get()).collect(); + let weekdays: Vec = resolved.iter().map(|s| s.get_weekday().get()).collect(); + assert_eq!(weekdays, vec![1, 1, 2], "weekday orders first"); + assert_eq!(starts, vec![480, 600, 600], "start time breaks the tie"); + } + + /// The override arm: once the section wrote a slot of its own, its own + /// set is authoritative — and **stays** authoritative when empty, which + /// is exactly how a section clears its timetable instead of silently + /// re-inheriting the template. + #[tokio::test] + async fn an_own_set_wins_including_when_it_is_empty() { + 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)) + .await + .unwrap(); + + add_for_class(&db, instance.get_id(), day(3), mins(540), mins(600)) + .await + .unwrap(); + // The write flipped the flag: re-read so the resolver follows the + // override arm instead of the stale inheriting snapshot. + let instance = instance_row(&db, instance.get_id()).await; + assert!(!instance.weekly_plan_inherited()); + let resolved = resolved_for_instance(&db, &instance).await.unwrap(); + assert_eq!(resolved.len(), 1, "the own row, not the offering's"); + + // Dropping the last own row empties the authoritative set; the + // offering's slot stays hidden behind the still-FALSE flag. + let own_id = resolved[0].get_id().clone(); + remove_for_class(&db, instance.get_id(), &own_id) + .await + .unwrap(); + assert!( + !instance_row(&db, instance.get_id()) + .await + .weekly_plan_inherited() + ); + assert!( + resolved_for_instance(&db, &instance) + .await + .unwrap() + .is_empty() + ); + } + + /// Intersecting windows on one weekday are refused — partial, exact + /// duplicate, and containment — while touching endpoints and other + /// weekdays pass. Malformed bodies are 400s. + #[tokio::test] + 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)) + .await + .unwrap(); + + for (starts, ends, why) in [ + (540, 600, "the exact duplicate"), + (570, 630, "the partial overlap"), + (530, 610, "the containing window"), + (530, 630, "the wider window"), + ] { + let attempt = + add_for_class(&db, instance.get_id(), day(1), mins(starts), mins(ends)).await; + assert_eq!( + coded(&attempt), + "slot_overlap", + "{why} must answer 409 slot_overlap" + ); + } + + // Touching endpoints and a different weekday are not overlaps. + add_for_class(&db, instance.get_id(), day(1), mins(600), mins(660)) + .await + .unwrap(); + add_for_class(&db, instance.get_id(), day(2), mins(540), mins(600)) + .await + .unwrap(); + assert_eq!( + slot_db::list_for_class(&db, instance.get_id()) + .await + .unwrap() + .len(), + 3 + ); + + // Malformed bodies are validation 400s, before any owner query runs. + 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; + 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; + assert!( + matches!(inverted, Err(AppError::Validation(_))), + "{inverted:?}" + ); + } + + /// The cap bounds one owner's plan; the refusal names the cap, and the + /// stored set never exceeds the bound. + #[tokio::test] + async fn the_slot_cap_holds() { + let (db, _leases) = crate::database::init_test_db().await; + let instance = an_instance(&db, "5-D").await; + + // Forty non-overlapping one-minute windows: weekday (i%7)+1, minute + // 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), + ) + .await + .unwrap(); + } + assert_eq!( + slot_db::list_for_class(&db, instance.get_id()) + .await + .unwrap() + .len(), + crate::constant::MAX_WEEKLY_SLOTS + ); + + // 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; + assert_eq!(coded(&one_more), "slot_cap"); + assert_eq!( + slot_db::list_for_class(&db, instance.get_id()) + .await + .unwrap() + .len(), + crate::constant::MAX_WEEKLY_SLOTS + ); + } + + /// The reset door: the own slots go, the flag returns to TRUE, and the + /// offering's rows are what the section resolves again. + #[tokio::test] + async fn reset_restores_inheritance() { + 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)) + .await + .unwrap(); + add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540)) + .await + .unwrap(); + assert!( + !instance_row(&db, instance.get_id()) + .await + .weekly_plan_inherited() + ); + + reset_for_class(&db, instance.get_id()).await.unwrap(); + let after = instance_row(&db, instance.get_id()).await; + assert!(after.weekly_plan_inherited()); + let resolved = resolved_for_instance(&db, &after).await.unwrap(); + assert_eq!(resolved.len(), 1, "the offering's slot serves again"); + assert_eq!(resolved[0].get_weekday(), day(1)); + + // Idempotent: resetting an inheriting section is a no-op success. + reset_for_class(&db, instance.get_id()).await.unwrap(); + assert!( + instance_row(&db, instance.get_id()) + .await + .weekly_plan_inherited() + ); + } + + /// Removing an unknown slot — or another instance's slot — is a 404 that + /// leaves both sections alone. An own removal keeps the rest of the set. + #[tokio::test] + async fn removing_a_slot_scopes_to_its_owner() { + let (db, _leases) = crate::database::init_test_db().await; + 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)) + .await + .unwrap(); + add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540)) + .await + .unwrap(); + let own = slot_db::list_for_class(&db, instance.get_id()) + .await + .unwrap(); + + // Another section's instance id is a 404, and the flag/id stand. + let stranger = remove_for_class(&db, other.get_id(), own[0].get_id()).await; + assert!(matches!(stranger, Err(AppError::NotFound)), "{stranger:?}"); + // An unknown slot id is a 404 too. + let missing = remove_for_class(&db, instance.get_id(), &WeeklySlotId::generate()).await; + assert!(matches!(missing, Err(AppError::NotFound)), "{missing:?}"); + assert_eq!( + slot_db::list_for_class(&db, instance.get_id()) + .await + .unwrap() + .len(), + 2 + ); + + remove_for_class(&db, instance.get_id(), own[0].get_id()) + .await + .unwrap(); + let rest = slot_db::list_for_class(&db, instance.get_id()) + .await + .unwrap(); + assert_eq!(rest.len(), 1); + assert_eq!(rest[0].get_weekday(), day(2)); + assert!( + !instance_row(&db, instance.get_id()) + .await + .weekly_plan_inherited() + ); + } + + /// The offering-side doors mirror the class side minus the flag: overlap + /// refused, remove scoped to the offering, resolve ordering holds. + #[tokio::test] + async fn the_offering_side_adds_removes_and_resolves() { + let (db, _leases) = crate::database::init_test_db().await; + 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)) + .await + .unwrap(); + let clash = add_for_offering(&db, &offering, day(1), mins(570), mins(630)).await; + assert_eq!(coded(&clash), "slot_overlap"); + + let slots = slot_db::list_for_offering(&db, &offering).await.unwrap(); + assert_eq!(slots.len(), 1); + let unknown = remove_for_offering(&db, &offering, &WeeklySlotId::generate()).await; + assert!(matches!(unknown, Err(AppError::NotFound)), "{unknown:?}"); + + // Another offering's slot id is not deletable through this one. + let other_offering = an_instance(&db, "5-I").await.get_offering().clone(); + let foreign = remove_for_offering(&db, &other_offering, slots[0].get_id()).await; + assert!(matches!(foreign, Err(AppError::NotFound)), "{foreign:?}"); + + remove_for_offering(&db, &offering, slots[0].get_id()) + .await + .unwrap(); + assert!( + resolved_for_offering(&db, &offering) + .await + .unwrap() + .is_empty() + ); + } +} diff --git a/src/web/academic_years.rs b/src/web/academic_years.rs index a9a42e9..e427b56 100644 --- a/src/web/academic_years.rs +++ b/src/web/academic_years.rs @@ -24,6 +24,7 @@ use utoipa_axum::routes; use crate::domain::academic_year::{ AcademicYear, AcademicYearId, AcademicYearName, GradePromotion, }; +use crate::domain::grade::GradeLevel; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service; @@ -68,18 +69,22 @@ struct UpdateYear { grade_promotions: Option>, } -/// One grade-promotion pair off the wire. +/// One grade-promotion pair off the wire: two rungs on the grade ladder +/// (`0` = anaokulu, `1..=12` the school years). #[derive(Deserialize, Serialize, ToSchema)] struct PromotionBody { - #[schema(max_length = 20, example = "5")] - from_grade: String, - #[schema(max_length = 20, example = "6")] - to_grade: String, + #[schema(minimum = 0, maximum = 12, example = 5)] + from_grade: i16, + #[schema(minimum = 0, maximum = 12, example = 6)] + to_grade: i16, } impl PromotionBody { fn parse(&self) -> Result { - Ok(GradePromotion::try_new(&self.from_grade, &self.to_grade)?) + Ok(GradePromotion::new( + GradeLevel::new(self.from_grade)?, + GradeLevel::new(self.to_grade)?, + )) } } @@ -119,8 +124,8 @@ impl YearResponse { .get_grade_promotions() .iter() .map(|promo| PromotionBody { - from_grade: promo.get_from_grade().to_string(), - to_grade: promo.get_to_grade().to_string(), + from_grade: promo.get_from_grade().get(), + to_grade: promo.get_to_grade().get(), }) .collect(), class_count: year.get_class_count(), @@ -140,9 +145,9 @@ struct RolloverResponse { classes: usize, #[schema(example = 312)] students: usize, - /// The grade labels that stayed behind (graduation), in the order they - /// were met. - #[schema(example = json!(["8", "12"]))] + /// The labels of the rungs that stayed behind (graduation), in the order + /// they were met — `"Anaokulu"` at the floor, the year number elsewhere. + #[schema(example = json!(["11", "12"]))] graduated: Vec, } diff --git a/src/web/attendance.rs b/src/web/attendance.rs index b33ded9..eba74b6 100644 --- a/src/web/attendance.rs +++ b/src/web/attendance.rs @@ -223,6 +223,12 @@ async fn build_report( let course_by_key: HashMap = courses.iter().map(|c| (c.get_id().key(), c)).collect(); let people = person_map(courses.iter().flat_map(course_people), db).await?; + // The per-instance blocks display the sections' **resolved** + // titles/descriptions (override → offering → catalog), batched — the + // `/courses` catalog list is the deliberate exception that keeps the + // catalog row's own values, because that surface IS the catalog. + let instance_refs: Vec<&ClassCourse> = instances.iter().collect(); + let content = crate::service::instance_resolve::resolved_content(db, &instance_refs).await?; let mut blocks = Vec::with_capacity(instance_ids.len()); let mut visible_rows: Vec<&SessionAttendance> = Vec::with_capacity(sessions.len()); @@ -242,9 +248,17 @@ async fn build_report( }; let rows = &by_instance[instance_id.key().as_str()]; visible_rows.extend(rows.iter().copied()); + // The instance-scoped display: resolved title/description over the + // catalog row's (which stays the id/kind/counters source). + let resolved = content + .get(instance.get_id().key().as_str()) + .expect("resolved_content covers every instance it is given"); + let mut course = CourseResponse::new(course, &people); + course.title = resolved.title.clone(); + course.description = resolved.description.clone(); blocks.push(CourseAttendance { instance: instance.get_id().key(), - course: CourseResponse::new(course, &people), + course, counts: StatusCounts::tally(rows.iter().map(|r| r.get_status())), }); } diff --git a/src/web/classes.rs b/src/web/classes.rs index 9d6dfc0..8b48594 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -19,7 +19,8 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId, Pumped, Skip}; use crate::domain::class_course::{ClassCourse, ClassCourseId}; -use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; +use crate::domain::class_group::{ClassGroup, ClassGroupId, ClassName}; +use crate::domain::grade::GradeLevel; use crate::domain::class_member::ClassMember; use crate::domain::course::CourseId; use crate::domain::role::Role; @@ -64,10 +65,11 @@ pub fn routes() -> OpenApiRouter { struct CreateClass { #[schema(max_length = 200, example = "9-A")] name: String, - /// The school's own label for the year this class sits in ("9", "10-A", - /// "kindergarten"). Free text; omit (or send `""`) for a class with no grade. - #[schema(max_length = 20, example = "9")] - grade: Option, + /// The class's rung on the shared grade ladder — an integer, `0` = + /// anaokulu, `1..=12` the school years. Required: every section sits at a + /// grade; it is school-wide club/study courses that belong to none. + #[schema(minimum = 0, maximum = 12, example = 9)] + grade_level: i16, /// The academic year this class sits in (`GET /academic-years`). Optional; /// a class with no year takes no exam and is never rolled over. year: Option, @@ -81,11 +83,11 @@ struct CreateClass { struct UpdateClass { #[schema(max_length = 200)] name: Option, - /// Omit to keep the current grade, send `null` (or `""`) to clear it, or - /// send a label to (re)set it. - #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option, max_length = 20)] - grade: Option>, + /// Omit to keep the current grade, or send a ladder rung (an integer, + /// `0`..=12) to (re)set it. The grade is required on every class, so it + /// cannot be cleared. + #[schema(value_type = Option, minimum = 0, maximum = 12)] + grade_level: Option, /// Omit to keep the current academic year, send `null` to unlink, or send /// a year id to (re)assign. #[serde(default, deserialize_with = "set_or_clear")] @@ -124,9 +126,9 @@ struct ClassResponse { creator: Option, #[schema(example = "9-A")] name: String, - /// The school's own free-text grade label; `null` when the class has none. - #[schema(example = "9")] - grade: Option, + /// The class's rung on the grade ladder (`0` = anaokulu). + #[schema(example = 9)] + grade_level: i16, /// The academic year this class sits in (`GET /academic-years`); `null` /// when unassigned. year: Option, @@ -150,7 +152,7 @@ impl ClassResponse { id: class.get_id().key().to_string(), creator: with_creator.then(|| PersonRef::resolve(people, class.get_creator())), name: class.get_name().as_str().to_string(), - grade: class.get_grade().map(|g| g.as_str().to_string()), + grade_level: class.get_grade_level().get(), year: class.get_year().map(|year| year.key().to_string()), teacher: class .get_teacher() @@ -168,7 +170,7 @@ struct CreateClassResponse { /// The courses the template could not put on this section, empty when it /// took them all (and always empty when no template covered its grade). skipped: Vec, - /// The grade label of the blueprint that stocked this section, or `null` + /// The ladder rung of the blueprint that stocked this section, or `null` /// when none did. `null` with an empty `skipped` is what tells "no template /// covers this grade" apart from "the template applied cleanly" — the /// distinction `matched` makes on the grade-wide pumps. @@ -179,7 +181,7 @@ struct CreateClassResponse { /// remedy is the same either way — `POST /classes/{id}/blueprint`, which is /// idempotent and `404`s when there is genuinely no template. #[schema(example = "9")] - stocked_from: Option, + stocked_from: Option, } /// Every person a [`ClassResponse`] names: its homeroom teacher, plus its @@ -234,10 +236,14 @@ impl ClassMemberResponse { struct ClassCourseResponse { id: String, class: String, - /// The catalog course the class takes (`GET /courses/{id}`) — its title - /// lives there; what this class actually teaches is the row this response - /// describes. + /// The catalog course the class takes (`GET /courses/{id}`). course: String, + /// The **resolved** display title of this instance: its own override, + /// else its offering's, else the catalog course's — what every + /// instance-scoped surface shows. + title: String, + /// The resolved description, the same chain as `title`. + description: String, /// Who attached it. attached_by: PersonRef, /// Weekly lesson hours; the instance's weight in the year's report-card average. @@ -254,24 +260,35 @@ struct ClassCourseResponse { } impl ClassCourseResponse { - fn new( + /// The weekly hours and report-card policy shown here are the *resolved* + /// ones (instance override, else its offering's default, else the + /// catalog/constants) — the instance row itself may inherit both. So are + /// the title and description: `content` is the + /// [`crate::service::instance_resolve::resolved_content`] entry for this + /// instance, batched by the caller so a page stays two queries. + async fn new( + db: &Database, link: &ClassCourse, + content: &crate::service::instance_resolve::ResolvedContent, teachers: &[UserId], people: &std::collections::HashMap, - ) -> Self { - Self { + ) -> Result { + let policy = crate::service::class_course::resolve_policy(db, link).await?; + Ok(Self { id: link.get_id().key().to_string(), class: link.get_class().key().to_string(), course: link.get_course().key().to_string(), + title: content.title.clone(), + description: content.description.clone(), attached_by: PersonRef::resolve(people, link.get_attached_by()), - ders_saati: link.get_ders_saati().as_i64(), - counts_toward_karne: link.counts_toward_karne(), + ders_saati: policy.ders_saati.as_i64(), + counts_toward_karne: policy.counts_toward_karne, enrollment_count: link.get_enrollment_count(), teachers: teachers .iter() .map(|teacher| PersonRef::resolve(people, teacher)) .collect(), - } + }) } } @@ -283,17 +300,8 @@ async fn class_or_404(id: &str, db: &Database) -> Result { .ok_or(AppError::NotFound) } -/// An empty grade is *no* grade: the column is nullable, so a client that omits -/// it and one that sends `""` must land on the same stored row. -fn grade_or_none(text: Option<&str>) -> Result, AppError> { - match text { - None | Some("") => Ok(None), - Some(text) => Ok(Some(ClassGrade::try_new(text)?)), - } -} - /// The homeroom teacher a request names, as the row itself — an empty string is -/// *no* teacher, exactly like `grade`, so omitting the field and clearing it +/// *no* teacher, exactly like `year`, so omitting the field and clearing it /// with `""` land on the same stored row. The named account must exist and hold /// teacher-or-higher: a class's homeroom teacher is staff, and the check is the /// same shape `add_member` uses for a non-student. The `User` comes back so the @@ -361,12 +369,12 @@ async fn classes_page( } /// Create a class. Requires manager+ — a class is school structure, not a -/// teacher's own room. `grade` is a free-text label for the year ("9", "10-A"), -/// `year` links the academic year (which is what binds the class to a report +/// teacher's own room. `grade_level` is the class's rung on the grade ladder +/// (`0` = anaokulu, `1..=12`), `year` links the academic year (which is what binds the class to a report /// card and to the rollover), `teacher_id` names the homeroom teacher (a /// teacher+ account); all optional. /// -/// If a blueprint covers the new class's grade, the class is **stocked from it +/// If a blueprint covers the new class's rung, the class is **stocked from it /// at once** — the same best-effort pump `POST /classes/{id}/blueprint` runs, so /// a course that does not fit comes back in `skipped` and the class is created /// either way. `stocked_from` names the template that did it, and is `null` when @@ -379,7 +387,7 @@ async fn classes_page( request_body = CreateClass, responses( (status = 201, description = "Class created, stocked from its grade's blueprint when one covers it", body = CreateClassResponse), - (status = 400, description = "Invalid name or grade, an unknown academic year, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), + (status = 400, description = "Invalid name or grade_level, an unknown academic year, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 409, description = "The named homeroom teacher was demoted below teacher while the request ran (the class was rolled back, nothing was created), or the named academic year is archived — past years are read-only", body = ErrorResponse), @@ -392,7 +400,7 @@ async fn create_class( Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let name = ClassName::try_new(&req.name)?; - let grade = grade_or_none(req.grade.as_deref())?; + let grade_level = GradeLevel::new(req.grade_level)?; // Pre-flight only: `ClassGroup::create` claims a reference on the year // before it writes the link, and a year deleted in between fails that claim // with this very error — so an unknown id reads the same whichever side wins. @@ -402,7 +410,7 @@ async fn create_class( &st.db, user.get_id(), name, - grade, + grade_level, year, teacher.as_ref().map(|t| *t.get_id()), ) @@ -453,10 +461,9 @@ async fn create_class( )) } -/// Stock a freshly created class from its grade's blueprint, if one covers it: -/// the template's grade label and the pairs it could not place, or `None` when -/// the class has no grade, no blueprint holds that grade, or the stocking could -/// not be carried out. +/// Stock a freshly created class from its rung's blueprint, if one covers it: +/// the template's ladder rung and the pairs it could not place, or `None` when +/// no blueprint holds that rung or the stocking could not be carried out. /// /// Swallowing that last case is the deliberate one. Every other pump here may /// fail its whole request, because the caller can name what it asked for again — @@ -470,35 +477,32 @@ async fn stock_from_blueprint( class: &ClassGroup, by: &UserId, db: &Database, -) -> Option<(String, Vec)> { - let grade = class.get_grade()?; - let blueprint = class_blueprint::read(db, &ClassBlueprintId::for_grade(grade)) - .await - .ok()??; +) -> Option<(i16, Vec)> { + let blueprint = class_blueprint::read( + db, + &ClassBlueprintId::for_grade(&class.get_grade_level()), + ) + .await + .ok()??; let skipped = class_blueprint::apply_to(db, &blueprint, class, by) .await .ok()?; - Some((blueprint.get_grade().as_str().to_string(), skipped)) + Some((blueprint.get_grade_level().get(), skipped)) } /// Filter for the class index. #[derive(Deserialize, IntoParams)] struct ClassFilter { - /// Narrow to the sections carrying this exact grade label — the same - /// spelling a blueprint is keyed by, matched verbatim (no trimming, no case - /// folding: a filter that normalized would disagree with the pump it exists - /// to debug). `?grade=` (empty) asks for the sections carrying *no* grade, - /// exactly as an empty `grade` on a write means no grade. Omit for every - /// class. - #[param(example = "9")] - grade: Option, + /// Narrow to the sections carrying this exact ladder rung — the same + /// equality a blueprint is keyed by. Omit for every class. + #[param(example = 9)] + grade_level: Option, } -/// List every class, newest first. Requires teacher+. `?grade=` narrows to one -/// grade label, matched exactly as written — the label a blueprint is keyed by, -/// so this is the read that shows which sections a `POST /classes/blueprints` -/// pump covered (and `?grade=` on its own lists the sections with no grade at -/// all). An unknown label is an empty page, not a `404`. Paged via +/// List every class, newest first. Requires teacher+. `?grade_level=` narrows +/// to one ladder rung — the same equality a blueprint is keyed by, so this is +/// the read that shows which sections a `POST /classes/blueprints` pump +/// covered. An unknown rung is an empty page, not a `404`. Paged via /// `?limit=&offset=` (omit `limit` for the full list); returns a /// `{items, total, limit, offset}` envelope whose `total` counts every class /// under the same filter, not just this page. @@ -510,7 +514,7 @@ struct ClassFilter { params(ClassFilter, PageParams), responses( (status = 200, description = "A page of classes (the full list when unpaged)", body = Page), - (status = 400, description = "Invalid grade, limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid grade_level, limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), ), @@ -522,15 +526,13 @@ async fn list_classes( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - // The same newtype the write paths validate against, so an over-long label - // is the same `400` here as on a create. `grade_or_none` folds `""` into - // "no grade"; the outer `Option` is what keeps *omitted* apart from it. - let grade = filter - .grade - .as_deref() - .map(|grade| grade_or_none(Some(grade))) + // The same newtype the write paths validate against, so an off-ladder + // rung is the same `400` here as on a create or a PATCH. + let grade_level = filter + .grade_level + .map(GradeLevel::new) .transpose()?; - let (classes, total) = class_group::list_all(&st.db, grade, limit, offset).await?; + let (classes, total) = class_group::list_all(&st.db, grade_level, limit, offset).await?; // Join people onto the page alone — the lookup shrinks with the window. let people = person_map( classes.iter().flat_map(|class| class_people(class, true)), @@ -579,7 +581,7 @@ async fn get_class( request_body = UpdateClass, responses( (status = 200, description = "Updated class", body = ClassResponse), - (status = 400, description = "Invalid name or grade, an unknown academic year, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), + (status = 400, description = "Invalid name or grade_level, an unknown academic year, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), @@ -603,10 +605,7 @@ async fn update_class( // omitted field stays `None` so the save never re-sends this snapshot's // value over a concurrent PATCH of that field. let name = req.name.as_deref().map(ClassName::try_new).transpose()?; - let grade = match req.grade { - Some(ref update) => Some(grade_or_none(update.as_deref())?), - None => None, - }; + let grade_level = req.grade_level.map(GradeLevel::new).transpose()?; let year = match req.year { // Explicit `null` clears the link; a value must name a real year. Some(update) => Some(academic_year::resolve(&st.db, update.as_deref()).await?), @@ -625,7 +624,7 @@ async fn update_class( &st.db, class, name, - grade, + grade_level, year, teacher.map(|teacher| teacher.map(|teacher| *teacher.get_id())), ) @@ -948,9 +947,16 @@ async fn attach_course( let link = class_course::attach(&st.db, class.get_id(), course.get_id(), user.get_id()).await?; let people = PersonRef::map_of(&[&user]); + let content = { + let refs = [&link]; + crate::service::instance_resolve::resolved_content(&st.db, &refs).await? + }; + let resolved = content + .get(link.get_id().key().as_str()) + .expect("resolved_content covers every instance it is given"); Ok(( StatusCode::CREATED, - Json(ClassCourseResponse::new(&link, &[], &people)), + Json(ClassCourseResponse::new(&st.db, &link, resolved, &[], &people).await?), )) } @@ -992,10 +998,17 @@ async fn list_class_courses( &st.db, ) .await?; - let items = with_teachers - .iter() - .map(|(row, teachers)| ClassCourseResponse::new(row, teachers, &people)) - .collect(); + // The page's resolved titles/descriptions in one batch (one offering + // read + one catalog read), never per-row fallback reads. + let refs: Vec<&ClassCourse> = with_teachers.iter().map(|(row, _)| row).collect(); + let content = crate::service::instance_resolve::resolved_content(&st.db, &refs).await?; + let mut items = Vec::with_capacity(with_teachers.len()); + for (row, teachers) in &with_teachers { + let resolved = content + .get(row.get_id().key().as_str()) + .expect("resolved_content covers every instance it is given"); + items.push(ClassCourseResponse::new(&st.db, row, resolved, teachers, &people).await?); + } Ok(Json(Page::new(items, total, limit, offset))) } @@ -1078,11 +1091,10 @@ async fn detach_course( #[derive(Deserialize, ToSchema)] struct CreateBlueprint { - /// The grade label this template stocks — the same free text a class - /// carries in `grade` ("9", "10-A"). It is the blueprint's own id, so it - /// must be non-empty and free of `/ \ ? # %`. - #[schema(max_length = 20, example = "9")] - grade: String, + /// The ladder rung this template stocks — 0 = anaokulu, 1..=12 school + /// years. It is the blueprint's own id, so a rung off the ladder is a 400. + #[schema(minimum = 0, maximum = 12, example = 9)] + grade_level: i16, /// The courses every class section at that grade takes. course_ids: Vec, } @@ -1097,9 +1109,9 @@ struct UpdateBlueprint { #[derive(Serialize, ToSchema)] struct BlueprintResponse { - /// The grade label, which is also the blueprint's id in every path here. - #[schema(example = "9")] - grade: String, + /// The ladder rung, which is also the blueprint's id in every path here. + #[schema(example = 9)] + grade_level: i16, /// The course ids this grade's sections take. courses: Vec, /// Who wrote the template. @@ -1112,7 +1124,7 @@ impl BlueprintResponse { people: &std::collections::HashMap, ) -> Self { Self { - grade: blueprint.get_grade().as_str().to_string(), + grade_level: blueprint.get_grade_level().get(), courses: blueprint .get_courses() .iter() @@ -1181,11 +1193,9 @@ impl SkipResponse { struct BlueprintPumpResponse { blueprint: BlueprintResponse, /// How many class sections this pump reached. **`0` means no section - /// carries this grade label** — the template was saved and stocked - /// nothing. A grade is free text and matched exactly, so `"9 "`, `"9-A"` - /// and `"9"` are three different grades: check the label against the one - /// the sections actually carry, since an empty `skipped` alone reads the - /// same whether every section took the list or none was found. + /// carries this rung** — the template was saved and stocked nothing: + /// an empty `skipped` alone reads the same whether every section took + /// the list or none was found. /// /// The sections *reached*, not the ones the grade holds: a /// `blueprint_deleted` skip ends the run, and this then counts the ones @@ -1213,8 +1223,8 @@ struct SectionStatusResponse { #[derive(Serialize, ToSchema)] struct BlueprintStatusResponse { - #[schema(example = "9")] - grade: String, + #[schema(example = 9)] + grade_level: i16, /// The template every section below is measured against. courses: Vec, /// How many sections carry this grade label — the same count a pump @@ -1250,11 +1260,11 @@ async fn resolve_courses(ids: &[String], db: &Database) -> Result, Ok(courses) } -/// The blueprint a path grade names, or a 404. -async fn blueprint_or_404(grade: &str, db: &Database) -> Result { - class_blueprint::read(db, &ClassBlueprintId::from_key(grade)) - .await? - .ok_or(AppError::NotFound) +/// The blueprint `id` names, or a 404. Path handlers parse their segment +/// with `ClassBlueprintId::from_key`, which lands a non-numeric key on an id +/// that matches no row — a `404`, never a decode panic. +async fn blueprint_or_404(id: &ClassBlueprintId, db: &Database) -> Result { + class_blueprint::read(db, id).await?.ok_or(AppError::NotFound) } async fn blueprint_body( @@ -1289,7 +1299,7 @@ async fn blueprint_body( request_body = CreateBlueprint, responses( (status = 201, description = "Blueprint created, with the number of sections it reached and the classes it could not stock", body = BlueprintPumpResponse), - (status = 400, description = "Invalid or unaddressable grade, too many courses, or a course that does not exist", body = ErrorResponse), + (status = 400, description = "A grade_level off the ladder, too many courses, or a course that does not exist", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 409, description = "A blueprint already exists for that grade", body = ErrorResponse), @@ -1301,9 +1311,9 @@ async fn create_blueprint( RequireManager(user): RequireManager, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { - let grade = ClassBlueprint::grade_key(&req.grade)?; + let grade_level = GradeLevel::new(req.grade_level)?; let courses = resolve_courses(&req.course_ids, &st.db).await?; - let mut blueprint = class_blueprint::create(&st.db, user.get_id(), grade, courses).await?; + let mut blueprint = class_blueprint::create(&st.db, user.get_id(), grade_level, courses).await?; let pumped = class_blueprint::pump(&st.db, &mut blueprint, user.get_id()).await?; let body = blueprint_body(&blueprint, &pumped, &st.db).await?; Ok((StatusCode::CREATED, Json(body))) @@ -1349,7 +1359,7 @@ async fn list_blueprints( path = "/blueprints/{grade}", tag = "classes", security(("session_cookie" = [])), - params(("grade" = String, Path, description = "Grade label")), + params(("grade" = String, Path, description = "Grade level (0 = anaokulu, 1..=12 school years)")), responses( (status = 200, description = "The blueprint", body = BlueprintResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), @@ -1362,7 +1372,7 @@ async fn get_blueprint( RequireManager(_user): RequireManager, Path(grade): Path, ) -> Result, AppError> { - let blueprint = blueprint_or_404(&grade, &st.db).await?; + let blueprint = blueprint_or_404(&ClassBlueprintId::from_key(&grade), &st.db).await?; let people = person_map([*blueprint.get_creator()], &st.db).await?; Ok(Json(BlueprintResponse::new(&blueprint, &people))) } @@ -1387,7 +1397,7 @@ async fn get_blueprint( path = "/blueprints/{grade}", tag = "classes", security(("session_cookie" = [])), - params(("grade" = String, Path, description = "Grade label")), + params(("grade" = String, Path, description = "Grade level (0 = anaokulu, 1..=12 school years)")), request_body = UpdateBlueprint, responses( (status = 200, description = "Updated blueprint, with the number of sections it reached and the classes it could not stock", body = BlueprintPumpResponse), @@ -1405,7 +1415,7 @@ async fn update_blueprint( Path(grade): Path, Json(req): Json, ) -> Result, AppError> { - let blueprint = blueprint_or_404(&grade, &st.db).await?; + let blueprint = blueprint_or_404(&ClassBlueprintId::from_key(&grade), &st.db).await?; let courses = resolve_courses(&req.course_ids, &st.db).await?; // The dropped templates cascade: every sourced instance they leave behind // is detached, and its subtree's files are gone from the database and the @@ -1430,7 +1440,7 @@ async fn update_blueprint( path = "/blueprints/{grade}", tag = "classes", security(("session_cookie" = [])), - params(("grade" = String, Path, description = "Grade label")), + params(("grade" = String, Path, description = "Grade level (0 = anaokulu, 1..=12 school years)")), responses( (status = 204, description = "Deleted"), (status = 401, description = "Not authenticated", body = ErrorResponse), @@ -1444,7 +1454,7 @@ async fn delete_blueprint( RequireManager(_user): RequireManager, Path(grade): Path, ) -> Result { - let blueprint = blueprint_or_404(&grade, &st.db).await?; + let blueprint = blueprint_or_404(&ClassBlueprintId::from_key(&grade), &st.db).await?; // Deleting a blueprint detaches every sourced instance it started, subtree // and all — the returned keys are the only record of the files those rows // named, so they are unlinked here (the same contract the instance-detach @@ -1477,7 +1487,7 @@ async fn delete_blueprint( path = "/blueprints/{grade}/status", tag = "classes", security(("session_cookie" = [])), - params(("grade" = String, Path, description = "Grade label")), + params(("grade" = String, Path, description = "Grade level (0 = anaokulu, 1..=12 school years)")), responses( (status = 200, description = "Every section at the grade, with the template courses it is missing", body = BlueprintStatusResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), @@ -1490,10 +1500,10 @@ async fn blueprint_status( RequireManager(_user): RequireManager, Path(grade): Path, ) -> Result, AppError> { - let blueprint = blueprint_or_404(&grade, &st.db).await?; + let blueprint = blueprint_or_404(&ClassBlueprintId::from_key(&grade), &st.db).await?; let sections = class_blueprint::status(&st.db, &blueprint).await?; Ok(Json(BlueprintStatusResponse { - grade: blueprint.get_grade().as_str().to_string(), + grade_level: blueprint.get_grade_level().get(), courses: blueprint .get_courses() .iter() @@ -1543,8 +1553,8 @@ async fn apply_blueprint( Path(id): Path, ) -> Result, AppError> { let class = class_or_404(&id, &st.db).await?; - let grade = class.get_grade().ok_or(AppError::NotFound)?; - let blueprint = blueprint_or_404(grade.as_str(), &st.db).await?; + let blueprint = + blueprint_or_404(&ClassBlueprintId::for_grade(&class.get_grade_level()), &st.db).await?; // The pump writes both ends, so both are guarded — the class, whose year // every instance it mints will belong to, and every course the template // names. A course the template names that is already gone is the pump's own @@ -1561,20 +1571,15 @@ async fn apply_blueprint( mod tests { use super::*; - /// The nullable-grade rule both write paths share: absent and `""` are the - /// same *no grade*, so a PATCH clearing with `""` cannot store a blank - /// label a create could never make. + /// The one validation both write paths share: the rung must sit on the + /// ladder, and the wire type is the integer itself — no `"9"`/`"10-A"` + /// string ever crosses the boundary. #[test] - fn an_empty_grade_is_no_grade() { - assert!(grade_or_none(None).unwrap().is_none()); - assert!(grade_or_none(Some("")).unwrap().is_none()); - assert_eq!( - grade_or_none(Some("9")) - .unwrap() - .map(|g| g.as_str().to_string()), - Some("9".to_string()) - ); - assert!(grade_or_none(Some(&"x".repeat(1000))).is_err()); + fn a_grade_level_is_a_ladder_rung() { + assert!(GradeLevel::new(0).is_ok()); + assert!(GradeLevel::new(12).is_ok()); + assert!(GradeLevel::new(-1).is_err()); + assert!(GradeLevel::new(13).is_err()); } /// The same nullable rule on the homeroom teacher, plus the bar it holds: diff --git a/src/web/courses.rs b/src/web/courses.rs index 5450b1d..8975ffe 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -220,6 +220,11 @@ async fn list_courses( let window = paginate(&courses, limit, offset); // Join creators onto the page alone — the lookup shrinks with the window. let people = person_map(window.iter().flat_map(course_people), &st.db).await?; + // Deliberate exception to the instance-resolved display rule: this + // surface IS the ders catalog, so it shows each row's own catalog + // title/description. The grade templates (`/offerings`) and the + // per-class instances (`/instances`) resolve from it — they never edit + // it. let items = window .iter() .map(|course| CourseResponse::new(course, &people)) diff --git a/src/web/exam_weights.rs b/src/web/exam_weights.rs new file mode 100644 index 0000000..332d43b --- /dev/null +++ b/src/web/exam_weights.rs @@ -0,0 +1,368 @@ +//! The exam-weight override routes: per-kind weights on the grade-level +//! template (`/offerings/{id}/exam-weights`, manager+) and on the class +//! section (`/instances/{id}/exam-weights`, the D10 instance gate), plus the +//! section's reset. +//! +//! Every `GET` returns the **resolved** map — the effective weight of every +//! kind under that level, computed here — so a client renders it verbatim and +//! never re-implements the class → offering → settings → 1 chain. The +//! instance map carries the `inherited` flag: while it is `true` the map is +//! the offering's resolved set; while `false` it is exactly the section's own +//! rows, empty included (an own set in force is authoritative even when +//! empty). +//! +//! A write naming a kind the school does not run is the one refusal here with +//! a machine code — 400 `unknown_exam_kind` — because a client can branch on +//! "fix the kind" vs "fix the weight"; it is rendered by this module (the +//! service's `ValidationError::Invalid { field: "kind" }` re-wrapped), since +//! the coded-body vocabulary lives with the route that publishes it. + +use axum::Json; +use axum::extract::Path; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::database::Database; +use crate::domain::class_course::{ClassCourse, ClassCourseId}; +use crate::domain::course_offering::CourseOfferingId; +use crate::domain::exam_weight::ExamWeight; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; +use crate::state::AppState; +use crate::web::instances::can_view_instance; +use crate::web::tenant_state::State; + +use super::{CurrentUser, RequireManager, RequireTeacher}; + +/// Mounted under `/offerings` — the template's weight routes. +pub fn offering_routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(get_offering_weights, patch_offering_weight)) + .routes(routes!(delete_offering_weight)) +} + +/// Mounted inside `/instances` — the section's weight routes and reset. +pub fn instance_routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(get_instance_weights, patch_instance_weight)) + .routes(routes!(delete_instance_weight)) + .routes(routes!(reset_instance_weights)) +} + +#[derive(Deserialize, ToSchema)] +struct PatchExamWeight { + /// The exam kind exactly as the school spells it in `GET /settings` + /// (`settings.exam_kinds`). Anything else is a 400 `unknown_exam_kind`. + #[schema(example = "midterm")] + kind: String, + /// The weight this kind carries under the level being edited: 1..=100. + #[schema(minimum = 1, maximum = 100, example = 3)] + weight: i64, +} + +/// One resolved entry: the kind and the weight an exam of it carries *here* +/// after the whole fallback chain. +#[derive(Serialize, ToSchema)] +pub struct ExamWeightEntry { + #[schema(example = "midterm")] + pub kind: String, + pub weight: i64, +} + +impl ExamWeightEntry { + pub(crate) fn of(row: &ExamWeight) -> Self { + Self { + kind: row.get_kind().to_string(), + weight: row.get_weight(), + } + } +} + +/// The template's resolved weight map. +#[derive(Serialize, ToSchema)] +pub struct OfferingExamWeightsResponse { + /// Every kind the school runs (plus any kind a stored row adds), each at + /// its effective weight: the offering's own row, else the settings + /// weight, else 1. + pub weights: Vec, +} + +/// The section's resolved weight map, with the override switch. +#[derive(Serialize, ToSchema)] +pub struct InstanceExamWeightsResponse { + /// `true` = the section follows its offering's set (the map below is the + /// offering's, resolved); `false` = the section's own table is + /// authoritative and the map is exactly its rows — including when that is + /// none, which is how a section zeroes the template's weights. + pub inherited: bool, + pub weights: Vec, +} + +async fn offering_or_404(key: &str, db: &Database) -> Result { + let id = CourseOfferingId::from_key(key); + if service::course_offering::read(db, &id).await?.is_none() { + return Err(AppError::NotFound); + } + Ok(id) +} + +/// The instance row the write gates judge — a missing id is a 404 before any +/// body is read. +async fn instance_or_404(key: &str, db: &Database) -> Result { + service::class_course::read(db, &ClassCourseId::from_key(key)) + .await? + .ok_or(AppError::NotFound) +} + +/// Re-renders the service's kind refusal as the coded 400 this route +/// documents; every other error keeps its own wire shape. +fn kind_refusal(err: AppError, kind: &str) -> Response { + if let AppError::Validation(ValidationError::Invalid { field: "kind", .. }) = &err { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ + "error": format!("kind: `{kind}` is not a known exam kind"), + "code": "unknown_exam_kind", + })), + ) + .into_response(); + } + err.into_response() +} + +// ---- the template's weights -------------------------------------------------- + +/// The grade-level template's resolved exam-kind weights. Any signed-in +/// session. +#[utoipa::path( + get, + path = "/{id}/exam-weights", + tag = "offerings", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Offering id")), + responses( + (status = 200, description = "The offering's resolved weights", body = OfferingExamWeightsResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Offering not found", body = ErrorResponse), + ), +)] +async fn get_offering_weights( + State(st): State, + CurrentUser(_user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let offering = offering_or_404(&id, &st.db).await?; + let weights = service::exam_weight::resolved_for_offering(&st.db, &offering).await?; + Ok(Json(OfferingExamWeightsResponse { + weights: weights.iter().map(ExamWeightEntry::of).collect(), + })) +} + +/// Set (or rewrite) one kind's weight on the template. Manager+. The kind must +/// be one the school runs — a 400 carrying the machine code +/// `unknown_exam_kind` otherwise; the weight must sit in 1..=100. Sections +/// that still inherit the template pick the change up immediately. +#[utoipa::path( + patch, + path = "/{id}/exam-weights", + tag = "offerings", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Offering id")), + request_body = PatchExamWeight, + responses( + (status = 200, description = "The offering's resolved weights after the write", body = OfferingExamWeightsResponse), + (status = 400, description = "A weight outside 1..=100, or a kind the school does not run (body carries the machine code `unknown_exam_kind`)", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Offering not found", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn patch_offering_weight( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, + Json(req): Json, +) -> Result { + let offering = offering_or_404(&id, &st.db).await?; + if let Err(err) = + service::exam_weight::set_for_offering(&st.db, &offering, &req.kind, req.weight).await + { + return Ok(kind_refusal(err, &req.kind)); + } + let weights = service::exam_weight::resolved_for_offering(&st.db, &offering).await?; + Ok(Json(OfferingExamWeightsResponse { + weights: weights.iter().map(ExamWeightEntry::of).collect(), + }) + .into_response()) +} + +/// Drop one kind's weight row from the template; the settings weight applies +/// again. A kind with no row is a 404. +#[utoipa::path( + delete, + path = "/{id}/exam-weights/{kind}", + tag = "offerings", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Offering id"), + ("kind" = String, Path, description = "Exam kind"), + ), + responses( + (status = 204, description = "Row deleted — the settings weight applies again"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Offering not found, or it carries no weight row for this kind", body = ErrorResponse), + ), +)] +async fn delete_offering_weight( + State(st): State, + RequireManager(_user): RequireManager, + Path((id, kind)): Path<(String, String)>, +) -> Result { + let offering = offering_or_404(&id, &st.db).await?; + service::exam_weight::remove_from_offering(&st.db, &offering, &kind).await?; + Ok(StatusCode::NO_CONTENT) +} + +// ---- the section's weights --------------------------------------------------- + +/// The section's resolved exam-kind weights and its override switch. Visible +/// to the same eyes as the rest of the instance's reads. +#[utoipa::path( + get, + path = "/{id}/exam-weights", + tag = "instances", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Instance id")), + responses( + (status = 200, description = "The section's resolved weights, with the inherited flag", body = InstanceExamWeightsResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance not found", body = ErrorResponse), + ), +)] +async fn get_instance_weights( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let instance = instance_or_404(&id, &st.db).await?; + if !can_view_instance(&st.db, instance.get_id(), &user).await? { + return Err(AppError::Forbidden( + "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its weights", + )); + } + let (inherited, weights) = service::exam_weight::resolved_for_class(&st.db, &instance).await?; + Ok(Json(InstanceExamWeightsResponse { + inherited, + weights: weights.iter().map(ExamWeightEntry::of).collect(), + })) +} + +/// Set (or rewrite) one kind's weight on the section — and take its weight set +/// own: the flag flips in the same statement, so from here on the section's +/// own rows (these included) are the whole map, even where they are absent. +/// Requires teacher+ and a right over the instance (D10). +#[utoipa::path( + patch, + path = "/{id}/exam-weights", + tag = "instances", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Instance id")), + request_body = PatchExamWeight, + responses( + (status = 200, description = "The section's resolved weights after the write (`inherited` now `false`)", body = InstanceExamWeightsResponse), + (status = 400, description = "A weight outside 1..=100, or a kind the school does not run (body carries the machine code `unknown_exam_kind`)", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance not found", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn patch_instance_weight( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result { + let instance = instance_or_404(&id, &st.db).await?; + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; + if let Err(err) = + service::exam_weight::set_for_class(&st.db, instance.get_id(), &req.kind, req.weight).await + { + return Ok(kind_refusal(err, &req.kind)); + } + // The write flipped the flag, so the map is computed off the fresh row, + // never the one the gate read. + let fresh = service::class_course::read(&st.db, instance.get_id()) + .await? + .ok_or(AppError::NotFound)?; + let (inherited, weights) = service::exam_weight::resolved_for_class(&st.db, &fresh).await?; + Ok(Json(InstanceExamWeightsResponse { + inherited, + weights: weights.iter().map(ExamWeightEntry::of).collect(), + }) + .into_response()) +} + +/// Drop one kind's weight row from the section. Deleting still takes the set +/// own — removing the last row *decides* on an empty set (every kind then +/// weighs 1 here) rather than falling back. A kind with no row is a 404 that +/// changes nothing. +#[utoipa::path( + delete, + path = "/{id}/exam-weights/{kind}", + tag = "instances", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Instance id"), + ("kind" = String, Path, description = "Exam kind"), + ), + responses( + (status = 204, description = "Row deleted — the section's own set stays authoritative without it"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance not found, or it carries no weight row for this kind", body = ErrorResponse), + ), +)] +async fn delete_instance_weight( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, kind)): Path<(String, String)>, +) -> Result { + let instance = instance_or_404(&id, &st.db).await?; + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; + service::exam_weight::remove_from_class(&st.db, instance.get_id(), &kind).await?; + Ok(StatusCode::NO_CONTENT) +} + +/// The reset: drop every section weight row and follow the offering's set +/// (then the settings, then 1) again. Idempotent. +#[utoipa::path( + delete, + path = "/{id}/exam-weights", + tag = "instances", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Instance id")), + responses( + (status = 204, description = "Rows deleted — inheritance restored"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance not found", body = ErrorResponse), + ), +)] +async fn reset_instance_weights( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let instance = instance_or_404(&id, &st.db).await?; + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; + service::exam_weight::reset_class(&st.db, instance.get_id()).await?; + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index d5f1e49..d7f4d6e 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -12,8 +12,10 @@ use crate::service::exam_question; #[derive(Deserialize, ToSchema)] pub(crate) struct CreateQuestion { - /// The subject this question belongs to — one of the subjects of the exam - /// instance's catalog course (`GET /courses/{id}/subjects`). Required. + /// The subject this question belongs to — one of the subjects the exam + /// instance actually teaches: its resolved subject set + /// (`GET /instances/{id}/subjects`), always a subject of the instance's + /// catalog course. Required. #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] subject_id: String, /// The question itself. @@ -139,9 +141,11 @@ impl QuestionResponse { } /// Add a question to an exam. Requires teacher+ and management rights over the -/// exam's instance. `subject_id` must name one of the subjects of that -/// instance's catalog course (`GET /courses/{id}/subjects`) — every question -/// belongs to a subject. +/// exam's instance. `subject_id` must name one of the subjects the instance +/// actually *teaches* — its resolved subject set (the offering's selection, +/// or the section's own while it overrides; `GET /instances/{id}/subjects`) — +/// and in every case a subject of the instance's catalog course. Every +/// question belongs to a subject. /// `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` /// questions carry neither. Locked once attempts exist. #[utoipa::path( @@ -153,7 +157,7 @@ impl QuestionResponse { request_body = CreateQuestion, responses( (status = 201, description = "Question created", body = QuestionResponse), - (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), + (status = 400, description = "Invalid text, kind, points, choices, or correct — or a subject that is unknown, from another course, or outside the instance's resolved subject set", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), @@ -184,7 +188,7 @@ pub(crate) async fn create_question( exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; let subject = - service::subject::in_course(&st.db, &req.subject_id, instance.get_course()).await?; + service::subject::in_instance(&st.db, &req.subject_id, &instance).await?; let text = QuestionText::try_new(&req.text)?; let points = QuestionPoints::try_new(req.points)?; // No stored choices to match against on create, so every option is new and @@ -294,7 +298,7 @@ pub(crate) async fn question_page( request_body = UpdateQuestion, responses( (status = 200, description = "Updated question", body = QuestionResponse), - (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), + (status = 400, description = "Invalid text, kind, points, choices, or correct — or a subject that is unknown, from another course, or outside the instance's resolved subject set", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), @@ -323,10 +327,8 @@ pub(crate) async fn update_question( exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; - let subject = match req.subject_id { - Some(ref subject_id) => { - service::subject::in_course(&st.db, subject_id, instance.get_course()).await? - } + let subject = match &req.subject_id { + Some(subject_id) => service::subject::in_instance(&st.db, subject_id, &instance).await?, None => *question.get_subject(), }; let text = match req.text { @@ -462,7 +464,7 @@ pub(crate) struct InstantiateFromBank { request_body = InstantiateFromBank, responses( (status = 201, description = "Question created from the template", body = QuestionResponse), - (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), + (status = 400, description = "A subject that is unknown, from another course, or outside the instance's resolved subject set", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), (status = 404, description = "No such exam, or no bank template the caller may see", body = ErrorResponse), @@ -489,18 +491,20 @@ pub(crate) async fn question_from_bank( // No lease — same reasoning as `create_question`. The freeze gate rides in // the insert's transaction. exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; - let subject = - service::subject::in_course(&st.db, &req.subject_id, instance.get_course()).await?; - let template = bank_question::read(&st.db, &BankQuestionId::from_key(&bid)) .await? .ok_or(AppError::NotFound)?; // A template the caller may not see is a 404, exactly as it is on the bank's // own routes — instantiating is a read of `correct`, and a 403 here would - // confirm that someone else's private template exists under that id. + // confirm that someone else's private template exists under that id. The + // read precedes the subject gate, so an invisible template never leaks + // existence through a body-validation 400. if !crate::web::bank_questions::can_see(&template, &user) { return Err(AppError::NotFound); } + let subject = + service::subject::in_instance(&st.db, &req.subject_id, &instance).await?; + let question = exam_question::create_from_bank( &st.db, exam.get_id(), diff --git a/src/web/homework.rs b/src/web/homework.rs index 6604233..4f38038 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -279,8 +279,10 @@ struct UpdateHomework { /// Edit a homework's title, description, due date, subject, or assigned subset. /// Requires teacher+ and management rights over its instance. Omitted fields /// keep their value; a newly set `due_at` is re-checked against now and a new -/// `subject_id` re-checked against the instance's course. Narrowing `assigned` -/// is refused (409) while it would orphan an existing submission or result. +/// `subject_id` re-checked against the instance's resolved subject set (the +/// offering's selection, or the section's own while it overrides). Narrowing +/// `assigned` is refused (409) while it would orphan an existing submission or +/// result. #[utoipa::path( patch, path = "/{id}", @@ -290,7 +292,7 @@ struct UpdateHomework { request_body = UpdateHomework, responses( (status = 200, description = "Updated homework", body = HomeworkResponse), - (status = 400, description = "Invalid title, description, due date, subject (unknown or from another course), or assigned list", body = ErrorResponse), + (status = 400, description = "Invalid title, description, due date, subject (unknown, from another course, or outside the instance's resolved subject set), or assigned list", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), @@ -336,7 +338,7 @@ async fn update_homework( check_not_past("due_at", due_at)?; let subject = match &req.subject_id { Some(subject_id) => Some( - crate::service::subject::in_course(&st.db, subject_id, instance.get_course()).await?, + crate::service::subject::in_instance(&st.db, subject_id, &instance).await?, ), None => None, }; diff --git a/src/web/instances.rs b/src/web/instances.rs index 2a89890..0ed8c68 100644 --- a/src/web/instances.rs +++ b/src/web/instances.rs @@ -3,9 +3,12 @@ //! //! Everything a class actually runs hangs off this row: its roster, its //! teachers, its exams, its lessons and its homework. Two sections teaching the -//! same course are two instances and share none of it. The weekly hours -//! (`ders_saati`) and the report-card policy (`counts_toward_karne`) are the -//! instance's own, so two sections may legitimately differ. +//! same course are two instances and share none of it. Each instance points at +//! its grade-level **offering** template and may override the content fields +//! (`title`, `description`, `ders_saati`, `counts_toward_karne`) — a `PATCH` +//! sets an override, `POST /{id}/reset` clears back to inherit, and what a +//! read presents is the resolved value (override → offering default → +//! constant), never the raw `NULL`. //! //! The catalog CRUD stays in [`super::courses`]; the exam, session and //! homework sub-routers live *here* now (they used to hang off `/courses/{id}`) @@ -25,6 +28,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; +use crate::domain::course::{CourseDescription, CourseTitle}; use crate::domain::course_session::SessionTopic; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ @@ -39,16 +43,20 @@ use crate::service; use crate::service::instance::{can_manage_instance, visible_instances}; use crate::state::AppState; +use super::exam_weights::ExamWeightEntry; use super::homework::{description_or_none, resolve_assigned}; +use super::weekly_plan::WeeklySlotDto; use super::{ CurrentUser, ExamResponse, HomeworkResponse, Page, PageParams, PersonRef, RequireManager, - RequireTeacher, SessionResponse, check_not_past, check_time_range, paginate, person_map, + RequireTeacher, SessionResponse, SubjectResponse, check_not_past, check_time_range, paginate, + person_map, }; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() .routes(routes!(my_instances)) .routes(routes!(get_instance, update_instance)) + .routes(routes!(reset_instance)) .routes(routes!(assign_teacher)) .routes(routes!(unassign_teacher)) .routes(routes!(enroll, list_roster)) @@ -74,15 +82,33 @@ pub fn homework_routes() -> OpenApiRouter { #[derive(Deserialize, ToSchema)] struct UpdateInstance { - /// Weekly lesson hours: the instance's weight in the year's report-card average. - /// Omit to keep the stored value; at least 1 and at most 40. + /// The section's own title override. Omit to keep the stored value; a + /// PATCH **sets**, it never clears — clearing back to inherit is the + /// reset door's (`POST /instances/{id}/reset`). + #[schema(max_length = 200, example = "9-A Matematik")] + title: Option, + /// The section's own description override. Omit to keep; never clears. + #[schema(max_length = 2_000)] + description: Option, + /// The section's own weekly-hours override: the weight it takes in the + /// year's report-card average while it is set. Omit to keep the stored + /// value (`null` to clear is the reset door's); at least 1 and at most 40. #[schema(minimum = 1, maximum = 40, example = 5)] ders_saati: Option, - /// Whether this instance's marks count into the report card. Omit to keep the - /// stored value. + /// The section's own report-card policy override. Omit to keep; never + /// clears. counts_toward_karne: Option, } +#[derive(Deserialize, ToSchema)] +struct ResetInstanceOverrides { + /// The overrides to clear back to **inherit**: `title`, `description`, + /// `ders_saati`, `counts_toward_karne` — and, flipping the section's own + /// table back to non-authoritative (the offering's set applies again), + /// `subjects`, `exam_weights`, `weekly_plan`. Unknown names are a 400. + fields: Vec, +} + #[derive(Deserialize, ToSchema)] struct AssignTeacher { /// The staff member to put in charge of this instance. Must hold the @@ -185,8 +211,14 @@ struct CreateSessionInCourse { ends_at: Option, } -/// Public shape of one instance: the course as this section teaches it, with the -/// policy that is the instance's own. +/// Public shape of one instance: the course as this section teaches it. Every +/// content field is the **resolved** view the instance resolver composes — +/// scalar chains run override → offering → catalog/constant, the set axes are +/// flag-driven — so a client renders this verbatim and renders a per-class +/// edit screen from this one call: `*_overridden` tells its own override from +/// an inherited value, `*_inherited` tells whose set is authoritative. The +/// raw template values (nullable, unset = inherit) live one level up, on +/// `GET /offerings/{id}`. #[derive(Serialize, ToSchema)] pub struct InstanceResponse { #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] @@ -196,11 +228,51 @@ pub struct InstanceResponse { /// The catalog course being taught (`GET /courses/{id}`) — its title lives /// there, shared by every instance of it. pub course: String, - /// Weekly lesson hours; the instance's weight in the year's report-card average. + /// The grade-level offering template this section teaches from + /// (`GET /offerings/{id}`) — the thing its unset fields inherit from. + pub offering: String, + /// The section's **resolved** title: its own override, else its + /// offering's, else the catalog course's. + pub title: String, + /// `true` when `title` is this section's own override rather than + /// inherited from the offering or the catalog. + pub title_overridden: bool, + /// The section's **resolved** description, the same chain as `title`. + pub description: String, + /// `true` when `description` is this section's own override. + pub description_overridden: bool, + /// The section's **effective** weekly hours: its own override, else the + /// offering's default, else 1 — the weight it takes in the year's + /// report-card average. #[schema(example = 5)] pub ders_saati: i64, - /// Whether this instance's marks count toward the report card. + /// `true` when the hours are this section's own override. + pub ders_saati_overridden: bool, + /// The effective report-card policy: own override, else the offering's + /// default, else counted. pub counts_toward_karne: bool, + /// `true` when the policy is this section's own override. + pub counts_toward_karne_overridden: bool, + /// `false` = this section's own subject table is authoritative, including + /// when empty; `true` = the offering's subject set applies. + pub subjects_inherited: bool, + /// The section's **resolved** syllabus — the same set + /// `GET /{id}/subjects` serves, name-then-id order. + pub subjects: Vec, + /// `true` = the section follows its offering's weight map; `false` = its + /// own table is authoritative, empty included. + pub exam_weights_inherited: bool, + /// The section's **resolved** weight map: every kind at its effective + /// weight (override → offering → settings → 1). + pub exam_weights: Vec, + /// The same switch for the section's weekly plan. + pub weekly_plan_inherited: bool, + /// The section's **resolved** weekly plan: its own `class_course_slot` + /// rows when the flag above is `false` — including when that set is + /// empty — the offering's `offering_slot` template week when `true`. + /// Weekday first, then start time. Template data a timetable renders; + /// nothing generates dated `course_session` rows from it. + pub weekly_plan: Vec, /// How many students are enrolled right now. #[schema(example = 28)] pub enrollment_count: i64, @@ -210,23 +282,44 @@ pub struct InstanceResponse { } impl InstanceResponse { - fn new( + async fn new( + db: &Database, instance: &ClassCourse, teachers: &[UserId], people: &HashMap, - ) -> Self { - Self { + ) -> Result { + // One composed resolver call: title, description, the policy pair and + // the three set axes — never a fallback chain re-implemented here. + let resolved = service::instance_resolve::resolve(db, instance).await?; + Ok(Self { id: instance.get_id().key().to_string(), class: instance.get_class().key().to_string(), course: instance.get_course().key().to_string(), - ders_saati: instance.get_ders_saati().as_i64(), - counts_toward_karne: instance.counts_toward_karne(), + offering: instance.get_offering().key(), + title: resolved.title, + title_overridden: resolved.title_overridden, + description: resolved.description, + description_overridden: resolved.description_overridden, + ders_saati: resolved.ders_saati.as_i64(), + ders_saati_overridden: resolved.ders_saati_overridden, + counts_toward_karne: resolved.counts_toward_karne, + counts_toward_karne_overridden: resolved.counts_toward_karne_overridden, + subjects_inherited: resolved.subjects_inherited, + subjects: resolved.subjects.iter().map(SubjectResponse::new).collect(), + exam_weights_inherited: resolved.exam_weights_inherited, + exam_weights: resolved + .exam_weights + .iter() + .map(ExamWeightEntry::of) + .collect(), + weekly_plan_inherited: resolved.weekly_plan_inherited, + weekly_plan: resolved.weekly_plan.iter().map(WeeklySlotDto::new).collect(), enrollment_count: instance.get_enrollment_count(), teachers: teachers .iter() .map(|teacher| PersonRef::resolve(people, teacher)) .collect(), - } + }) } } @@ -344,10 +437,10 @@ async fn my_instances( .collect(); let with_teachers = crate::db::class_course_teacher::into_instances(&st.db, window).await?; let people = instance_people(&with_teachers, &st.db).await?; - let items = with_teachers - .iter() - .map(|(instance, teachers)| InstanceResponse::new(instance, teachers, &people)) - .collect(); + let mut items = Vec::with_capacity(with_teachers.len()); + for (instance, teachers) in &with_teachers { + items.push(InstanceResponse::new(&st.db, instance, teachers, &people).await?); + } Ok(Json(Page::new(items, total, limit, offset))) } @@ -380,12 +473,13 @@ async fn get_instance( let teachers = crate::db::class_course_teacher::list_for_instance(&st.db, instance.get_id()).await?; let people = person_map(teachers.iter().cloned(), &st.db).await?; - Ok(Json(InstanceResponse::new(&instance, &teachers, &people))) + Ok(Json(InstanceResponse::new(&st.db, &instance, &teachers, &people).await?)) } -/// Update one instance's own policy. Requires teacher+ and a right over this -/// instance: manager+, one of its assigned teachers, or its section's homeroom -/// teacher. Omitted fields keep their value; both are non-clearable. +/// Update one instance's own policy overrides. Requires teacher+ and a right +/// over this instance: manager+, one of its assigned teachers, or its +/// section's homeroom teacher. Omitted fields keep their value; a PATCH +/// **sets**, it never clears — `POST /{id}/reset` is the clear door. #[utoipa::path( patch, path = "/{id}", @@ -395,7 +489,7 @@ async fn get_instance( request_body = UpdateInstance, responses( (status = 200, description = "Updated instance", body = InstanceResponse), - (status = 400, description = "Invalid ders_saati", body = ErrorResponse), + (status = 400, description = "Invalid title, description, or ders_saati", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), @@ -413,14 +507,73 @@ async fn update_instance( service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; service::class_course::require_open(&st.db, instance.get_id()).await?; + let title = match &req.title { + Some(title) => Some(CourseTitle::try_new(title)?), + None => None, + }; + let description = match &req.description { + Some(description) => Some(CourseDescription::try_new(description)?), + None => None, + }; let staff = req.ders_saati.map(DersSaati::try_new).transpose()?; + let updated = service::class_course::update( + &st.db, + instance.get_id(), + title, + description, + staff, + req.counts_toward_karne, + ) + .await?; + let teachers = + crate::db::class_course_teacher::list_for_instance(&st.db, updated.get_id()).await?; + let people = person_map(teachers.iter().cloned(), &st.db).await?; + Ok(Json(InstanceResponse::new(&st.db, &updated, &teachers, &people).await?)) +} + +/// Clear the named overrides back to inherit — the door a PATCH never is. +/// Same gate as the PATCH: teacher+ with a right over this instance, and a +/// live (non-archived) year. Resetting a set policy (`subjects`, +/// `exam_weights`, `weekly_plan`) flips the section's flag back to +/// *inherited*; deleting the section's own rows under it rides the child +/// tables' own reset doors. +#[utoipa::path( + post, + path = "/{id}/reset", + tag = "instances", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Instance id")), + request_body = ResetInstanceOverrides, + responses( + (status = 200, description = "The overrides cleared; the instance now inherits the named fields", body = InstanceResponse), + (status = 400, description = "A field name is unknown, or the list is empty", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn reset_instance( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; + service::class_course::require_open(&st.db, instance.get_id()).await?; + + let mut fields = Vec::with_capacity(req.fields.len()); + for name in &req.fields { + fields.push(service::class_course::parse_reset_field(name)?); + } let updated = - service::class_course::update(&st.db, instance.get_id(), staff, req.counts_toward_karne) - .await?; + service::class_course::reset_overrides(&st.db, instance.get_id(), &fields).await?; let teachers = crate::db::class_course_teacher::list_for_instance(&st.db, updated.get_id()).await?; let people = person_map(teachers.iter().cloned(), &st.db).await?; - Ok(Json(InstanceResponse::new(&updated, &teachers, &people))) + Ok(Json(InstanceResponse::new(&st.db, &updated, &teachers, &people).await?)) } /// Assign a teacher to this instance (idempotent). Manager+ only — staffing is @@ -461,7 +614,7 @@ async fn assign_teacher( let teachers = crate::db::class_course_teacher::list_for_instance(&st.db, instance.get_id()).await?; let people = person_map(teachers.iter().cloned(), &st.db).await?; - Ok(Json(InstanceResponse::new(&instance, &teachers, &people))) + Ok(Json(InstanceResponse::new(&st.db, &instance, &teachers, &people).await?)) } /// Unassign a teacher from this instance. Manager+ only. The instance, its @@ -1033,7 +1186,7 @@ mod tests { &db, &office, ClassName::try_new("5-A").unwrap(), - None, + crate::domain::grade::GradeLevel::new(5).unwrap(), None, Some(teacher), ) @@ -1132,7 +1285,7 @@ mod tests { &db, &office, ClassName::try_new("5-A").unwrap(), - None, + crate::domain::grade::GradeLevel::new(5).unwrap(), None, Some(teacher), ) diff --git a/src/web/limits.rs b/src/web/limits.rs index 0eb98a1..22c9a01 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -181,8 +181,11 @@ struct CourseLimits { max_session_topic_len: usize, max_term_name_len: usize, max_class_name_len: usize, - /// A class's optional free-text grade label ("9", "10-A"). - max_class_grade_len: usize, + /// The valid `grade_level` range on a class and a blueprint: `0` is + /// anaokulu, `1..=12` the school years. Every class carries one — there + /// is no "no grade" any more. + min_grade_level: i16, + max_grade_level: i16, /// Students one class may hold. Removing one frees a place. max_class_members: i64, /// Instances one class may carry. Detaching one frees a place. @@ -194,6 +197,17 @@ struct CourseLimits { max_academic_year_name_len: usize, } +/// The weekly plan: one offering's (or one section's) timetable template. +#[derive(Serialize, ToSchema)] +struct WeeklyPlanLimits { + /// Inclusive bounds for a slot's `starts_at`/`ends_at` minutes past + /// midnight (`540` = 09:00). + min_slot_minute: i64, + max_slot_minute: i64, + /// Slots one weekly plan may hold. + max_weekly_slots: i64, +} + /// Exams, their questions, answers, and marks. #[derive(Serialize, ToSchema)] struct ExamLimits { @@ -515,6 +529,9 @@ struct LimitsResponse { message: MessageLimits, event: EventLimits, course: CourseLimits, + /// The weekly plan's timetable bounds (`/offerings/{id}/weekly-plan` and + /// the instance override doors). + weekly_plan: WeeklyPlanLimits, exam: ExamLimits, homework: HomeworkLimits, question_pool: QuestionPoolLimits, @@ -602,13 +619,19 @@ impl LimitsResponse { max_session_topic_len: MAX_SESSION_TOPIC_LEN, max_term_name_len: MAX_TERM_NAME_LEN, max_class_name_len: MAX_CLASS_NAME_LEN, - max_class_grade_len: MAX_CLASS_GRADE_LEN, + min_grade_level: MIN_GRADE_LEVEL, + max_grade_level: MAX_GRADE_LEVEL, max_class_members: MAX_CLASS_MEMBERS, max_class_courses: MAX_CLASS_COURSES, min_ders_saati: MIN_DERS_SAATI, max_ders_saati: MAX_DERS_SAATI, max_academic_year_name_len: MAX_ACADEMIC_YEAR_NAME_LEN, }, + weekly_plan: WeeklyPlanLimits { + min_slot_minute: MIN_SLOT_MINUTE, + max_slot_minute: MAX_SLOT_MINUTE, + max_weekly_slots: MAX_WEEKLY_SLOTS as i64, + }, exam: ExamLimits { max_title_len: MAX_EXAM_TITLE_LEN, max_description_len: MAX_EXAM_DESCRIPTION_LEN, diff --git a/src/web/marks.rs b/src/web/marks.rs index 438c8c1..1a1a4ad 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -125,10 +125,12 @@ async fn enrolled_instances(user: &UserId, db: &Database) -> Result, @@ -145,8 +147,9 @@ async fn build_report( instances = kept; } - // One settings read weighs and labels the whole report, and one batch read - // resolves every block's catalog row (its title and kind). + // One settings read grades (bands/labels) the whole report — the weights + // ride each section's own chain now — and one batch read resolves every + // block's catalog row (its title and kind). let school = service::settings::load(db).await?; let course_ids: Vec = instances.iter().map(|i| i.get_course().clone()).collect(); @@ -156,10 +159,19 @@ async fn build_report( .map(|course| (course.get_id().key(), course)) .collect(); let people = person_map(courses.iter().flat_map(course_people), db).await?; + // The blocks display the sections' **resolved** titles/descriptions + // (override → offering → catalog), batched — the `/courses` catalog list + // is the deliberate exception that keeps the catalog row's own values, + // because that surface IS the catalog. + let instance_refs: Vec<&ClassCourse> = instances.iter().collect(); + let content = service::instance_resolve::resolved_content(db, &instance_refs).await?; let mut blocks = Vec::with_capacity(instances.len()); let mut seen: HashSet = HashSet::new(); for instance in &instances { + // The section's weight chain answer per kind, computed once — every + // mark of a kind weighs the same inside one block. + let mut line_weights: HashMap = HashMap::new(); let exams = crate::service::exam::list_for_class_course(db, instance.get_id()).await?; let by_exam: HashMap = exams.iter().map(|e| (e.get_id().key(), e)).collect(); let results = @@ -174,11 +186,19 @@ async fn build_report( let Some(exam) = by_exam.get(result.get_exam().key().as_str()) else { continue; }; - // The kind's current settings weight; an exam keeps a retired - // kind, and its marks then count once. - let weight = school - .exam_kind_weight(exam.get_kind().as_str()) - .unwrap_or(1); + // The kind's weight *in this section*: the section's own + // override, else the offering's, else the settings weight, else 1 + // — a retired kind keeps counting once, an own set in force is + // the whole answer, empty included. + let kind = exam.get_kind().as_str(); + let weight = match line_weights.get(kind) { + Some(weight) => *weight, + None => { + let weight = service::exam_weight::resolve(db, instance, kind).await?; + line_weights.insert(kind.to_string(), weight); + weight + } + }; entries.push(MarkEntry { exam: exam.get_id().key().to_string(), title: exam.get_title().as_str().to_string(), @@ -200,9 +220,17 @@ async fn build_report( }; seen.insert(instance.get_id().key()); let average = weighted_average(&pairs); + // The instance-scoped display: resolved title/description over the + // catalog row's (which stays the id/kind/counters source). + let resolved = content + .get(instance.get_id().key().as_str()) + .expect("resolved_content covers every instance it is given"); + let mut course = CourseResponse::new(course, &people); + course.title = resolved.title.clone(); + course.description = resolved.description.clone(); blocks.push(CourseMarks { instance: instance.get_id().key(), - course: CourseResponse::new(course, &people), + course, average, average_grade: average.and_then(|a| school.grade_label(a).map(str::to_string)), results: entries, diff --git a/src/web/mod.rs b/src/web/mod.rs index c5072e0..ff9c2c3 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -18,6 +18,7 @@ pub mod course_notes; pub mod courses; pub mod etag; pub mod events; +pub mod exam_weights; pub mod exam_ws; pub mod exams; pub mod homework; @@ -30,6 +31,8 @@ pub mod messages; pub mod module_gate; pub mod modules; pub mod notes; +pub mod offering_subjects; +pub mod offerings; pub mod payments; pub mod podcast; pub mod pomodoro; @@ -42,6 +45,7 @@ pub mod settings; pub mod subjects; pub mod terms; pub mod users; +pub mod weekly_plan; pub mod work; pub mod tenant_state; @@ -526,7 +530,7 @@ mod tests { db, &office, ClassName::try_new("9-A").unwrap(), - None, + crate::domain::grade::GradeLevel::new(9).unwrap(), None, Some(*teacher.get_id()), ) diff --git a/src/web/offering_subjects.rs b/src/web/offering_subjects.rs new file mode 100644 index 0000000..805964c --- /dev/null +++ b/src/web/offering_subjects.rs @@ -0,0 +1,317 @@ +//! Syllabus topic selection on the course-template system: the topics an +//! offering ([`crate::domain::course_offering::CourseOffering`]) selects for +//! its grade, and the per-section override +//! ([`crate::domain::class_course::ClassCourse`]). The override rule is +//! override-or-inherit, never merge, and it is **flag-driven**: +//! `subjects_inherited` `TRUE` follows the offering's set, `FALSE` makes the +//! section's own table authoritative *including when it is empty* — the +//! section-level deletes and the reset door flip it in the same statement as +//! the row change ([`crate::db::offering_subject`]). +//! +//! This module exports two routers: [`offering_routes`] (mounted under +//! `/offerings` by the offerings router) and [`instance_routes`] (mounted +//! inside `/instances` like the exam/session/homework children). Reads are +//! open to any signed-in session; offering writes are the office's +//! (`manager`+); instance writes pay the D10 gate every other +//! instance-scoped write pays (`service::class_course::ensure_instance_teacher`) +//! and refuse on an archived year. +//! +//! Selection always names a subject of the offering's own course — a foreign +//! topic is the same 400 the question/homework tag check answers. + +use axum::Json; +use axum::extract::Path; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::database::Database; +use crate::domain::class_course::{ClassCourse, ClassCourseId}; +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; +use crate::domain::user::User; +use crate::error::{AppError, ErrorResponse}; +use crate::service; +use crate::state::AppState; +use crate::web::dto::SubjectResponse; +use crate::web::tenant_state::State; + +use super::{CurrentUser, RequireManager, RequireTeacher}; + +/// The offering-side half: mounted under `/offerings`. +pub fn offering_routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(list_offering_subjects, add_offering_subject)) + .routes(routes!(remove_offering_subject)) +} + +/// The instance-side half: mounted inside `/instances`, next to the exam, +/// session and homework children. The two `DELETE`s stay in separate +/// `routes!` calls — one call may register each HTTP method only once. +pub fn instance_routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(list_instance_subjects, add_instance_subject)) + .routes(routes!(remove_instance_subject)) + .routes(routes!(reset_instance_subjects)) +} + +#[derive(Deserialize, ToSchema)] +struct AddSubject { + /// The subject id to select (`GET /courses/{id}/subjects`). Must belong + /// to the offering's own course — a foreign topic is a 400. + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] + subject: String, +} + +/// The topics one section teaches, resolved override-or-inherit — plus the +/// switch, so a client can tell "the template's set" from "its own (possibly +/// empty) set". +#[derive(Serialize, ToSchema)] +struct ResolvedSubjects { + /// The resolved set, by subject name then id. + subjects: Vec, + /// `true` = the section follows its offering's set; `false` = its own + /// selection is authoritative, even when the list above is empty. + subjects_inherited: bool, +} + +async fn offering_or_404(key: &str, db: &Database) -> Result { + service::course_offering::read(db, &CourseOfferingId::from_key(key)) + .await? + .ok_or(AppError::NotFound) +} + +async fn instance_or_404(key: &str, db: &Database) -> Result { + service::class_course::read(db, &ClassCourseId::from_key(key)) + .await? + .ok_or(AppError::NotFound) +} + +/// The instance-side write gate: D10 (manager+, this instance's teachers, its +/// şube's homeroom teacher) over a live year — the same pair every other +/// instance-scoped write pays. +async fn gated_instance(key: &str, user: &User, db: &Database) -> Result { + let instance = instance_or_404(key, db).await?; + service::class_course::ensure_instance_teacher(db, user, instance.get_id()).await?; + service::class_course::require_open(db, instance.get_id()).await?; + Ok(instance) +} + +/// The offering's selected topics — the set every inheriting section at that +/// grade teaches — by subject name then id. Any signed-in session. +#[utoipa::path( + get, + path = "/{id}/subjects", + tag = "offerings", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Offering id")), + responses( + (status = 200, description = "The offering's selected subjects", body = [SubjectResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Offering not found", body = ErrorResponse), + ), +)] +async fn list_offering_subjects( + State(st): State, + CurrentUser(_user): CurrentUser, + Path(id): Path, +) -> Result>, AppError> { + let offering = offering_or_404(&id, &st.db).await?; + let subjects = service::offering_subject::resolved_for_offering(&st.db, offering.get_id()) + .await?; + Ok(Json(subjects.iter().map(SubjectResponse::new).collect())) +} + +/// Select a topic for the offering. Manager+. Re-selecting an already +/// selected topic is a no-op success (`200`, not a second row). +#[utoipa::path( + post, + path = "/{id}/subjects", + tag = "offerings", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Offering id")), + request_body = AddSubject, + responses( + (status = 201, description = "Subject selected", body = SubjectResponse), + (status = 200, description = "Already selected — no-op success", body = SubjectResponse), + (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Offering not found", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: `subject` is missing or malformed"), + ), +)] +async fn add_offering_subject( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let offering = offering_or_404(&id, &st.db).await?; + let (subject, added) = + service::offering_subject::add_to_offering(&st.db, offering.get_id(), &req.subject) + .await?; + let code = if added { + StatusCode::CREATED + } else { + StatusCode::OK + }; + Ok((code, Json(SubjectResponse::new(&subject)))) +} + +/// Drop a topic from the offering's selection. Manager+. Dropping a topic the +/// offering never selected is a 404. +#[utoipa::path( + delete, + path = "/{id}/subjects/{subject}", + tag = "offerings", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Offering id"), + ("subject" = String, Path, description = "Subject id"), + ), + responses( + (status = 204, description = "Dropped"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Offering not found, or subject not selected", body = ErrorResponse), + ), +)] +async fn remove_offering_subject( + State(st): State, + RequireManager(_user): RequireManager, + Path((id, subject)): Path<(String, String)>, +) -> Result { + let offering = offering_or_404(&id, &st.db).await?; + service::offering_subject::remove_from_offering(&st.db, offering.get_id(), &subject).await?; + Ok(StatusCode::NO_CONTENT) +} + +/// The topics this section teaches, resolved override-or-inherit, with the +/// switch: `subjects_inherited: false` means the listed set (even when +/// empty) is the section's own and the offering's is ignored. Any signed-in +/// session. +#[utoipa::path( + get, + path = "/{id}/subjects", + tag = "instances", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Instance (class×course) id")), + responses( + (status = 200, description = "The resolved subject set and whether it is inherited", body = ResolvedSubjects), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Instance not found", body = ErrorResponse), + ), +)] +async fn list_instance_subjects( + State(st): State, + CurrentUser(_user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let instance = instance_or_404(&id, &st.db).await?; + let subjects = service::offering_subject::resolved_for_instance(&st.db, &instance).await?; + Ok(Json(ResolvedSubjects { + subjects: subjects.iter().map(SubjectResponse::new).collect(), + subjects_inherited: instance.subjects_inherited(), + })) +} + +/// Select a topic for this section's own set — the override. The switch +/// flips to "own" in the same write, so the section's table (not the +/// offering's set) becomes authoritative from this call on. Re-selecting an +/// already selected topic is a no-op success. D10 gate; refuses on an +/// archived year. +#[utoipa::path( + post, + path = "/{id}/subjects", + tag = "instances", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Instance (class×course) id")), + request_body = AddSubject, + responses( + (status = 201, description = "Subject selected — the section now owns its set", body = SubjectResponse), + (status = 200, description = "Already selected — no-op success", body = SubjectResponse), + (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance not found", body = ErrorResponse), + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: `subject` is missing or malformed"), + ), +)] +async fn add_instance_subject( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let instance = gated_instance(&id, &user, &st.db).await?; + let (subject, added) = + service::offering_subject::add_to_instance(&st.db, &instance, &req.subject).await?; + let code = if added { + StatusCode::CREATED + } else { + StatusCode::OK + }; + Ok((code, Json(SubjectResponse::new(&subject)))) +} + +/// Drop one topic from this section's own set (keeping the set its own — +/// clearing the syllabus needs the reset below, or deleting the last rows +/// one by one). Dropping a topic the section never selected is a 404 and +/// flips nothing. D10 gate; refuses on an archived year. +#[utoipa::path( + delete, + path = "/{id}/subjects/{subject}", + tag = "instances", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Instance (class×course) id"), + ("subject" = String, Path, description = "Subject id"), + ), + responses( + (status = 204, description = "Dropped — the section keeps its own set"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance not found, or subject not in the section's own set", body = ErrorResponse), + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), + ), +)] +async fn remove_instance_subject( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, subject)): Path<(String, String)>, +) -> Result { + let instance = gated_instance(&id, &user, &st.db).await?; + service::offering_subject::remove_from_instance(&st.db, &instance, &subject).await?; + Ok(StatusCode::NO_CONTENT) +} + +/// Restore inheritance: sweep the section's own rows and flip +/// `subjects_inherited` back to TRUE in the same statement — the offering's +/// set applies again. A section whose own set was already empty resets +/// cleanly. D10 gate; refuses on an archived year. +#[utoipa::path( + delete, + path = "/{id}/subjects", + tag = "instances", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Instance (class×course) id")), + responses( + (status = 204, description = "Own set swept — the offering's set applies again"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance not found", body = ErrorResponse), + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), + ), +)] +async fn reset_instance_subjects( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let instance = gated_instance(&id, &user, &st.db).await?; + service::offering_subject::reset_instance(&st.db, &instance).await?; + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/web/offerings.rs b/src/web/offerings.rs new file mode 100644 index 0000000..90f1bf8 --- /dev/null +++ b/src/web/offerings.rs @@ -0,0 +1,376 @@ +//! The course **offerings**: the grade-level templates (`course_offering`) +//! every class×course instance inherits from — one row per +//! (course × grade_level) carrying the title, description and the +//! weekly-hours / report-card defaults for that grade, with the per-class +//! overrides living on the instances themselves +//! ([`crate::web::instances`]). +//! +//! Reads are open to any signed-in session; writes are the office's +//! (`manager`+), the same bar as the catalog itself. Every write door keeps +//! the override-or-inherit rule visible: a `PATCH` field sent as `null` +//! clears back to inherit, and the delete refuses with `offering_in_use` +//! while any instance still teaches from the template. + +use std::collections::HashMap; + +use axum::Json; +use axum::extract::{Path, Query}; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::{IntoParams, ToSchema}; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::database::Database; +use crate::domain::class_course::DersSaati; +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; +use crate::domain::grade::GradeLevel; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; +use crate::state::AppState; +use crate::web::tenant_state::State; + +use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, person_map, set_or_clear}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(create_offering, list_offerings)) + .routes(routes!(get_offering, update_offering, delete_offering)) +} + +#[derive(Deserialize, ToSchema)] +struct CreateOffering { + /// The catalog course this template teaches from (`POST /courses`). + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] + course: String, + /// The ladder rung: `0` is anaokulu, `1..=12` the school years. + #[schema(minimum = 0, maximum = 12, example = 9)] + grade_level: i16, + /// The grade's own title; omit to inherit the catalog course's. + #[schema(max_length = 200)] + title: Option, + /// The grade's own description; omit to inherit the catalog's. + #[schema(max_length = 2_000)] + description: Option, + /// The grade's default weekly hours; omit for the constant 1. + #[schema(minimum = 1, maximum = 40, example = 5)] + default_ders_saati: Option, + /// The grade's default report-card policy; omit for counted (`true`). + default_counts_toward_karne: Option, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateOffering { + /// Omit to keep; send `null` to clear (inherit the catalog course's + /// title); send a value to set the grade's own. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option, max_length = 200)] + title: Option>, + /// Omit to keep; `null` to clear (inherit the catalog's); a value to set. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option, max_length = 2_000)] + description: Option>, + /// Omit to keep; `null` to clear (inherit the constant 1); 1..=40 to set. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option, minimum = 1, maximum = 40)] + default_ders_saati: Option>, + /// Omit to keep; `null` to clear (inherit counted); a value to set. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + default_counts_toward_karne: Option>, +} + +/// The list filters, both optional and combinable. +#[derive(Deserialize, IntoParams)] +struct OfferingFilter { + /// Only this course's offerings. + #[param(example = "019732e3-7b00-7000-8000-00000000dead")] + course: Option, + /// Only this ladder rung (`0` = anaokulu). + #[param(minimum = 0, maximum = 12)] + grade_level: Option, +} + +impl OfferingFilter { + /// Validate + canonicalize: a malformed course key is a 400, not an empty + /// page — the caller asked for something, the key just does not name it. + fn resolve(&self) -> Result<(Option, Option), AppError> { + let course = match &self.course { + Some(key) => { + let id = CourseId::from_key(key); + if id.uuid().is_nil() { + return Err(ValidationError::Invalid { + field: "course", + reason: "must be a hyphenated uuid", + } + .into()); + } + Some(id) + } + None => None, + }; + let grade = self.grade_level.map(GradeLevel::new).transpose()?; + Ok((course, grade)) + } +} + +/// Public shape of one offering: the grade-level template, with `null` +/// meaning *inherit* on every content field. These are the **raw template +/// values** — this row IS the grade's template, so a manager reads and edits +/// exactly what is stored here. The per-instance **resolved** view (override +/// → offering → catalog/constant, no nulls, with the source flags) is what +/// `GET /instances/{id}` serves. +#[derive(Serialize, ToSchema)] +pub struct OfferingResponse { + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] + pub id: String, + /// The catalog course taught from this template (`GET /courses/{id}`). + pub course: String, + /// The ladder rung: `0` = anaokulu, `1..=12` the school years. + pub grade_level: i16, + /// The grade's own title; `null` = the catalog course's title. + pub title: Option, + /// The grade's own description; `null` = the catalog course's. + pub description: Option, + /// The grade's default weekly hours; `null` = the constant 1. + pub default_ders_saati: Option, + /// The grade's default report-card policy; `null` = counted (`true`). + pub default_counts_toward_karne: Option, + /// Who minted the template (deliberately, or by first attaching the + /// course to a class at this grade). + pub created_by: PersonRef, + /// Mint instant, UTC unix-milliseconds. + pub created_at: i64, + /// Last content edit, UTC unix-milliseconds. + pub updated_at: i64, +} + +impl OfferingResponse { + fn new(offering: &CourseOffering, people: &HashMap) -> Self { + Self { + id: offering.get_id().key(), + course: offering.get_course().key(), + grade_level: offering.get_grade_level().get(), + title: offering.get_title().map(|t| t.as_str().to_string()), + description: offering.get_description().map(|d| d.as_str().to_string()), + default_ders_saati: offering.get_default_ders_saati().map(DersSaati::as_i64), + default_counts_toward_karne: offering.get_default_counts_toward_karne(), + created_by: PersonRef::resolve(people, offering.get_created_by()), + created_at: offering.get_created_at().as_millis(), + updated_at: offering.get_updated_at().as_millis(), + } + } +} + +async fn offering_or_404(key: &str, db: &Database) -> Result { + service::course_offering::read(db, &CourseOfferingId::from_key(key)) + .await? + .ok_or(AppError::NotFound) +} + +/// Create the grade-level template for a course. Manager+. A course that is +/// not a class-delivered ders has no grade axis and is refused (a club or +/// etüt is joined individually, never attached); a template that already +/// exists for the (course, grade) pair is a 409 `offering_exists`. +#[utoipa::path( + post, + path = "/", + tag = "offerings", + security(("session_cookie" = [])), + request_body = CreateOffering, + responses( + (status = 201, description = "Offering created", body = OfferingResponse), + (status = 400, description = "Invalid fields, or the course is not a class-delivered ders (kind `course`)", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + (status = 409, description = "The course already has an offering for this grade — the body carries the machine code `offering_exists`", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn create_offering( + State(st): State, + RequireManager(user): RequireManager, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let course = CourseId::from_key(&req.course); + if course.uuid().is_nil() { + return Err(ValidationError::Invalid { + field: "course", + reason: "must be a hyphenated uuid", + } + .into()); + } + let grade = GradeLevel::new(req.grade_level)?; + let title = match &req.title { + Some(title) => Some(CourseTitle::try_new(title)?), + None => None, + }; + let description = match &req.description { + Some(description) => Some(CourseDescription::try_new(description)?), + None => None, + }; + let staff = req.default_ders_saati.map(DersSaati::try_new).transpose()?; + let offering = service::course_offering::create( + &st.db, + user.get_id(), + &course, + grade, + title, + description, + staff, + req.default_counts_toward_karne, + ) + .await?; + let people = PersonRef::map_of(&[&user]); + Ok((StatusCode::CREATED, Json(OfferingResponse::new(&offering, &people)))) +} + +/// List the offerings, paged via `?limit=&offset=` (omit `limit` for all of +/// them); optionally narrowed by `?course=` and/or `?grade_level=`. Returns a +/// `{items, total, limit, offset}` envelope. +#[utoipa::path( + get, + path = "/", + tag = "offerings", + security(("session_cookie" = [])), + params(PageParams, OfferingFilter), + responses( + (status = 200, description = "A page of offerings (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit, offset, course key, or grade_level", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn list_offerings( + State(st): State, + CurrentUser(_user): CurrentUser, + Query(page): Query, + Query(filter): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let (course, grade) = filter.resolve()?; + let (rows, total) = + service::course_offering::list(&st.db, course.as_ref(), grade, limit, offset).await?; + let people = person_map(rows.iter().map(|o| *o.get_created_by()), &st.db).await?; + let items = rows + .iter() + .map(|offering| OfferingResponse::new(offering, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Fetch one offering by id. Any signed-in session. The body is the raw +/// template row (nullable = inherit) — not the per-instance resolved view +/// `GET /instances/{id}` serves. +#[utoipa::path( + get, + path = "/{id}", + tag = "offerings", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Offering id")), + responses( + (status = 200, description = "The offering's raw template values (null = inherit); the per-class resolved view lives on GET /instances/{id}", body = OfferingResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn get_offering( + State(st): State, + CurrentUser(_user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let offering = offering_or_404(&id, &st.db).await?; + let people = person_map(std::iter::once(*offering.get_created_by()), &st.db).await?; + Ok(Json(OfferingResponse::new(&offering, &people))) +} + +/// Field-scoped edit. Manager+. Omitted fields keep their value; an explicit +/// `null` clears the override back to inherit (the catalog course's title or +/// description, the constant 1 weekly hour, counted toward the karne); a +/// value sets the grade's own. Instances that carry no override of their own +/// follow the change immediately — that is what inherit means. +#[utoipa::path( + patch, + path = "/{id}", + tag = "offerings", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Offering id")), + request_body = UpdateOffering, + responses( + (status = 200, description = "Updated offering", body = OfferingResponse), + (status = 400, description = "Invalid field values", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type"), + ), +)] +async fn update_offering( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + // Tri-state per field: absent = keep, null = clear to inherit, value = set. + let title = match req.title { + None => None, + Some(inner) => Some(match inner { + None => None, + Some(text) => Some(CourseTitle::try_new(&text)?), + }), + }; + let description = match req.description { + None => None, + Some(inner) => Some(match inner { + None => None, + Some(text) => Some(CourseDescription::try_new(&text)?), + }), + }; + let staff = match req.default_ders_saati { + None => None, + Some(inner) => Some(match inner { + None => None, + Some(hours) => Some(DersSaati::try_new(hours)?), + }), + }; + let offering = service::course_offering::update( + &st.db, + &CourseOfferingId::from_key(&id), + title, + description, + staff, + req.default_counts_toward_karne, + ) + .await?; + let people = person_map(std::iter::once(*offering.get_created_by()), &st.db).await?; + Ok(Json(OfferingResponse::new(&offering, &people))) +} + +/// Delete the template. Manager+. Refused with 409 `offering_in_use` while +/// any class×course instance still teaches from it — detach the course from +/// those classes first. Deleting a template no section uses erases only the +/// grade's overrides; the instances keep existing (their next attach +/// re-mints an empty template). +#[utoipa::path( + delete, + path = "/{id}", + tag = "offerings", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Offering id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "An instance still teaches from this offering — the body carries the machine code `offering_in_use`", body = ErrorResponse), + ), +)] +async fn delete_offering( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, +) -> Result { + service::course_offering::delete(&st.db, &CourseOfferingId::from_key(&id)).await?; + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/web/users.rs b/src/web/users.rs index 44955f9..2e06e55 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -1008,8 +1008,9 @@ struct ProfileClassRef { id: String, #[schema(example = "9-A")] name: String, - #[schema(example = "9")] - grade: Option, + /// The class's rung on the grade ladder (`0` = anaokulu). + #[schema(example = 9)] + grade_level: i16, } /// A course as a profile shows it — a label, nothing more. @@ -1207,13 +1208,17 @@ async fn profile_of( .map(|class| ProfileClassRef { id: class.get_id().key().to_string(), name: class.get_name().as_str().to_string(), - grade: class.get_grade().map(|grade| grade.as_str().to_string()), + grade_level: class.get_grade_level().get(), }) .collect(), courses: courses .iter() .map(|course| ProfileCourseRef { id: course.get_id().key().to_string(), + // Catalog-tier surface, like `GET /courses`: a profile lists + // the person's courses by their catalog identity (a person + // may sit two sections of one ders), so the catalog title is + // the deliberate exception to the instance-resolved display. title: course.get_title().as_str().to_string(), kind: course.get_kind().as_str().to_string(), }) diff --git a/src/web/weekly_plan.rs b/src/web/weekly_plan.rs new file mode 100644 index 0000000..493f363 --- /dev/null +++ b/src/web/weekly_plan.rs @@ -0,0 +1,371 @@ +//! The weekly plan surface: the timetable template's routes on both owners — +//! the grade-level offering (`/offerings/{id}/weekly-plan`, the office's +//! door) and the class×course instance (`/instances/{id}/weekly-plan`, the +//! D10 door), split into the two mount functions the router composes +//! (`offering_routes` under `/offerings`, `instance_routes` inside +//! `/instances`) so each carries its own module's gate. +//! +//! A slot is one weekday plus a minutes-past-midnight window (`1` = Monday +//! through `7` = Sunday, `540` = 09:00). Two slots of one owner may touch but +//! never overlap (409 `slot_overlap`); a plan holds at most +//! [`crate::constant::MAX_WEEKLY_SLOTS`] slots (409 `slot_cap`). +//! Writing any instance-side row flips `weekly_plan_inherited` to `false` in +//! the same statement, and `DELETE /instances/{id}/weekly-plan` (no slot id) +//! is the reset back to inherit — the resolved reads never merge the two +//! sets. +//! +//! **No scheduler.** Nothing generates dated `course_session` rows from a +//! weekly plan — `course_session` stays the per-lesson occurrence, written by +//! its own routes. These routes serve template + override + resolution only. + +use axum::Json; +use axum::extract::Path; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::database::Database; +use crate::domain::class_course::{ClassCourse, ClassCourseId}; +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; +use crate::domain::weekly_slot::{SlotMinute, Weekday, WeeklySlot, WeeklySlotId}; +use crate::error::{AppError, ErrorResponse}; +use crate::service; +use crate::state::AppState; +use crate::web::tenant_state::State; + +use super::instances::can_view_instance; +use super::{CurrentUser, RequireManager, RequireTeacher}; + +/// The route set mounted under `/offerings` (relative paths): the template +/// week's reads and the office's writes. +pub fn offering_routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(list_offering_weekly_plan, add_offering_slot)) + .routes(routes!(remove_offering_slot)) +} + +/// The instance-side half: mounted inside `/instances` — the section's +/// resolved plan, its override writes, and the reset. The two `DELETE`s stay +/// in separate `routes!` calls — one call may register each HTTP method only +/// once. +pub fn instance_routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(list_instance_weekly_plan, add_instance_slot)) + .routes(routes!(remove_instance_slot)) + .routes(routes!(reset_instance_weekly_plan)) +} + +/// A weekly plan line the caller sent: the ISO weekday and the two +/// minutes-past-midnight bounds of the lesson window. +#[derive(Deserialize, ToSchema)] +struct CreateSlot { + /// `1` = Monday through `7` = Sunday. + weekday: i16, + /// Minutes past midnight (`540` = 09:00) — the window opens here. + starts_at: i64, + /// Minutes past midnight — strictly after `starts_at`. + ends_at: i64, +} + +/// Public shape of one weekly plan slot. Times stay the minutes-past-midnight +/// form the request sent; `weekday` stays the integer (`1` = Monday). +#[derive(Serialize, ToSchema)] +pub struct WeeklySlotDto { + pub id: String, + /// `1` = Monday through `7` = Sunday. + pub weekday: i16, + /// Minutes past midnight — the window opens here. + pub starts_at: i64, + /// Minutes past midnight, strictly after `starts_at`. + pub ends_at: i64, +} + +impl WeeklySlotDto { + pub fn new(slot: &WeeklySlot) -> Self { + Self { + id: slot.get_id().key(), + weekday: slot.get_weekday().get(), + starts_at: slot.get_starts_at().get(), + ends_at: slot.get_ends_at().get(), + } + } +} + +/// The section's **resolved** weekly plan: whose rows are authoritative and +/// what they are — the offering's template week while +/// `weekly_plan_inherited` stands, the section's own rows (possibly empty) +/// once it overrode. Ordered weekday first, then start time. +#[derive(Serialize, ToSchema)] +pub struct InstanceWeeklyPlan { + pub weekly_plan: Vec, + /// `true` = the offering's template week is authoritative; `false` = the + /// section's own rows below, including when that list is empty. + pub weekly_plan_inherited: bool, +} + +async fn offering_or_404(key: &str, db: &Database) -> Result { + service::course_offering::read(db, &CourseOfferingId::from_key(key)) + .await? + .ok_or(AppError::NotFound) +} + +/// The instance a path id names, or a 404 — the read arm mirrors +/// [`super::instances`]'s. +async fn instance_or_404(key: &str, db: &Database) -> Result { + service::class_course::read(db, &ClassCourseId::from_key(key)) + .await? + .ok_or(AppError::NotFound) +} + +/// The body's slot, range-checked before anything is written: weekday and +/// minute bounds here, the non-empty window inside the domain `WeeklySlot`. +fn parse_slot( + req: &CreateSlot, +) -> Result<(Weekday, SlotMinute, SlotMinute), crate::error::ValidationError> { + Ok(( + Weekday::new(req.weekday)?, + SlotMinute::new(req.starts_at)?, + SlotMinute::new(req.ends_at)?, + )) +} + +/// List the offering's template week — weekday first, then start time. Any +/// signed-in session, the same visibility as the offering read itself. +#[utoipa::path( + get, + path = "/{id}/weekly-plan", + tag = "offerings", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Offering id")), + responses( + (status = 200, description = "The template week, ordered weekday then start time", body = [WeeklySlotDto]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Offering not found", body = ErrorResponse), + ), +)] +async fn list_offering_weekly_plan( + State(st): State, + CurrentUser(_user): CurrentUser, + Path(id): Path, +) -> Result>, AppError> { + let offering = offering_or_404(&id, &st.db).await?; + let slots = service::weekly_slot::resolved_for_offering(&st.db, offering.get_id()).await?; + Ok(Json(slots.iter().map(WeeklySlotDto::new).collect())) +} + +/// Add one slot to the offering's template week. Manager+. Refused with 409 +/// `slot_overlap` when a template slot already occupies an intersecting +/// window on that weekday (an exact duplicate overlaps too), 409 `slot_cap` +/// when the week already holds the maximum. +#[utoipa::path( + post, + path = "/{id}/weekly-plan", + tag = "offerings", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Offering id")), + request_body = CreateSlot, + responses( + (status = 201, description = "Slot added", body = WeeklySlotDto), + (status = 400, description = "Invalid weekday or minutes, or an empty window", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Offering not found", body = ErrorResponse), + (status = 409, description = "Another slot of this week overlaps the window (`slot_overlap`), or the plan is at the slot cap (`slot_cap`)", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn add_offering_slot( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let offering = offering_or_404(&id, &st.db).await?; + let (weekday, starts_at, ends_at) = parse_slot(&req)?; + let slot = service::weekly_slot::add_for_offering( + &st.db, + offering.get_id(), + weekday, + starts_at, + ends_at, + ) + .await?; + Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot)))) +} + +/// Drop one slot of the offering's template week. Manager+. A slot of another +/// offering, or one already gone, is a 404. +#[utoipa::path( + delete, + path = "/{id}/weekly-plan/{slot}", + tag = "offerings", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Offering id"), + ("slot" = String, Path, description = "Slot id"), + ), + responses( + (status = 204, description = "Slot removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Offering or slot not found", body = ErrorResponse), + ), +)] +async fn remove_offering_slot( + State(st): State, + RequireManager(_user): RequireManager, + Path((id, slot)): Path<(String, String)>, +) -> Result { + let offering = offering_or_404(&id, &st.db).await?; + service::weekly_slot::remove_for_offering( + &st.db, + offering.get_id(), + &WeeklySlotId::from_key(&slot), + ) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +/// The section's resolved weekly plan plus whose rows it is. Visible to the +/// same eyes as the instance read: enrolled students, its teachers, its +/// şube's homeroom teacher, and managers/admins. +#[utoipa::path( + get, + path = "/{id}/weekly-plan", + tag = "instances", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Instance id")), + responses( + (status = 200, description = "The resolved plan and the flag that picked it", body = InstanceWeeklyPlan), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled, and not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance not found", body = ErrorResponse), + ), +)] +async fn list_instance_weekly_plan( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let instance = instance_or_404(&id, &st.db).await?; + if !can_view_instance(&st.db, instance.get_id(), &user).await? { + return Err(AppError::Forbidden( + "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view it", + )); + } + let weekly_plan = service::weekly_slot::resolved_for_instance(&st.db, &instance).await?; + Ok(Json(InstanceWeeklyPlan { + weekly_plan: weekly_plan.iter().map(WeeklySlotDto::new).collect(), + weekly_plan_inherited: instance.weekly_plan_inherited(), + })) +} + +/// Add one slot to the section's own week. Requires teacher+ and a right over +/// the instance; the write flips `weekly_plan_inherited` to `false` in the +/// same statement, so from here the section's own rows — not the offering's +/// template — are what every read resolves. Same overlap and cap refusals as +/// the offering side. +#[utoipa::path( + post, + path = "/{id}/weekly-plan", + tag = "instances", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Instance id")), + request_body = CreateSlot, + responses( + (status = 201, description = "Slot added; the section now overrides the template", body = WeeklySlotDto), + (status = 400, description = "Invalid weekday or minutes, or an empty window", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance not found", body = ErrorResponse), + (status = 409, description = "This instance's academic year is archived; another slot of this week overlaps the window (`slot_overlap`); or the plan is at the slot cap (`slot_cap`)", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn add_instance_slot( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let instance = instance_or_404(&id, &st.db).await?; + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; + 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?; + Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot)))) +} + +/// Drop one slot of the section's own week. Requires teacher+ and a right +/// over the instance. The flag flip to `false` rides the delete in the same +/// statement — dropping the last own row leaves the section with an +/// authoritative *empty* plan, not a quiet return to the template +/// (`DELETE /{id}/weekly-plan` is the way back to inherit). A slot of another +/// instance, or one already gone, is a 404 that leaves the flag untouched. +#[utoipa::path( + delete, + path = "/{id}/weekly-plan/{slot}", + tag = "instances", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Instance id"), + ("slot" = String, Path, description = "Slot id"), + ), + responses( + (status = 204, description = "Slot removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance or slot not found", body = ErrorResponse), + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), + ), +)] +async fn remove_instance_slot( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, slot)): Path<(String, String)>, +) -> Result { + let instance = instance_or_404(&id, &st.db).await?; + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; + service::class_course::require_open(&st.db, instance.get_id()).await?; + service::weekly_slot::remove_for_class( + &st.db, + instance.get_id(), + &WeeklySlotId::from_key(&slot), + ) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +/// Reset the section's weekly plan to inherit — delete every slot of its own +/// week and flip `weekly_plan_inherited` back to `true` in one statement, so +/// the offering's template week is what every read resolves again. +/// Idempotent for a section that never overrode. +#[utoipa::path( + delete, + path = "/{id}/weekly-plan", + tag = "instances", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Instance id")), + responses( + (status = 204, description = "The section's own week is gone; the offering's template is authoritative again"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), + (status = 404, description = "Instance not found", body = ErrorResponse), + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), + ), +)] +async fn reset_instance_weekly_plan( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let instance = instance_or_404(&id, &st.db).await?; + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; + service::class_course::require_open(&st.db, instance.get_id()).await?; + service::weekly_slot::reset_for_class(&st.db, instance.get_id()).await?; + Ok(StatusCode::NO_CONTENT) +} diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 413b109..121d2d7 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -3672,8 +3672,10 @@ async fn a_manager_study_request_carries_the_school_wide_scope_pairs() { .as_array() .expect("scope_pairs is an array"); assert_eq!(pairs.len(), 2, "manager receives every school pair"); - assert!(pairs.contains(&json!([null, "Matematik"]))); - assert!(pairs.contains(&json!([null, "Fizik"]))); + // Every şube sits at a ladder rung now, so the pairs name the rung label, + // not a null grade. + assert!(pairs.contains(&json!(["9", "Matematik"]))); + assert!(pairs.contains(&json!(["9", "Fizik"]))); } /// A connected worker that does not carry the capability is not a worker for diff --git a/tests/board_invite.rs b/tests/board_invite.rs index 6fb9f07..870e899 100644 --- a/tests/board_invite.rs +++ b/tests/board_invite.rs @@ -66,7 +66,7 @@ async fn a_class(app: &axum::Router, manager: &str, name: &str, members: &[&str] "POST", "/classes", Some(manager), - Some(json!({ "name": name })), + Some(json!({ "name": name, "grade_level": 9 })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 9d3b431..dd9381f 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -517,7 +517,43 @@ pub async fn create_subject(app: &Router, cookie: &str, course: &str, name: &str ) .await; assert_eq!(res.status, StatusCode::CREATED, "create subject {name}"); - id_of(&res.body) + let subject = id_of(&res.body); + + // The subject-tag gates (homework, exam questions) read the section's + // resolved syllabus, so a topic a suite creates is only usable once the + // offering selects it. When the course has been attached somewhere, the + // offering exists — select the fresh topic there (idempotent; a + // non-manager cookie cannot curate the offering and skips this, which + // the tag gates then surface as their own 400). + let res = send( + app, + "GET", + &format!("/offerings?course={course}"), + Some(cookie), + None, + ) + .await; + if res.status == StatusCode::OK + && let Some(offering) = res.body["items"][0]["id"].as_str() + { + let res = send( + app, + "POST", + &format!("/offerings/{offering}/subjects"), + Some(cookie), + Some(json!({ "subject": subject })), + ) + .await; + // A non-manager cookie cannot curate the offering; the tag gates + // then answer their own 400 and the caller selects another way + // (see `create_homework`'s instance-door retry). + assert!( + matches!(res.status, StatusCode::CREATED | StatusCode::OK | StatusCode::FORBIDDEN), + "select subject {name} on offering {offering}: {}", + res.body + ); + } + subject } // ---- the academic fixture --------------------------------------------------- @@ -595,10 +631,14 @@ pub async fn create_term(app: &Router, staff: &str, year: &str, name: &str) -> S } /// Create a class (şube) as `staff` (asserts 201); returns its id. `body` -/// carries everything but the name: `year`, `teacher_id`, `grade`. +/// carries everything but the name: `year`, `teacher_id`, `grade_level` +/// (defaulting to rung 9 when the caller does not name one). pub async fn create_class(app: &Router, staff: &str, name: &str, body: Value) -> String { let mut body = body; body["name"] = json!(name); + if body.get("grade_level").is_none() { + body["grade_level"] = json!(9); + } let res = send(app, "POST", "/classes", Some(staff), Some(body)).await; assert_eq!( res.status, @@ -749,6 +789,75 @@ pub async fn create_exam_with(app: &Router, cookie: &str, instance: &str, body: .await } +/// One homework-create send with the subject-gate retry: a `subject_id` the +/// section's resolved syllabus does not carry is refused, and the writer — +/// who holds a right over the instance (the very gate the homework write +/// passed) — takes the topic onto the section's own set through the instance +/// door and retries once. Every other refusal comes back untouched. +async fn send_homework_create( + app: &Router, + cookie: &str, + instance: &str, + body: Value, +) -> Res { + let res = send( + app, + "POST", + &format!("/instances/{instance}/homework"), + Some(cookie), + Some(body.clone()), + ) + .await; + if res.status == StatusCode::BAD_REQUEST + && res.body["error"] + .as_str() + .is_some_and(|e| e.contains("subject is not in this section's subject set")) + { + let subject = body["subject_id"].as_str().expect("subject_id").to_string(); + let res = send( + app, + "POST", + &format!("/instances/{instance}/subjects"), + Some(cookie), + Some(json!({ "subject": subject })), + ) + .await; + assert!( + matches!(res.status, StatusCode::CREATED | StatusCode::OK), + "select subject {subject} on instance {instance}: {}", + res.body + ); + return send( + app, + "POST", + &format!("/instances/{instance}/homework"), + Some(cookie), + Some(body), + ) + .await; + } + res +} + +/// Take `subject` onto the section's own syllabus through the instance door — +/// the D10 gate, the same right the question and homework writers hold. +/// Idempotent: a subject already in the set re-answers 200. +pub async fn select_instance_subject(app: &Router, cookie: &str, instance: &str, subject: &str) { + let res = send( + app, + "POST", + &format!("/instances/{instance}/subjects"), + Some(cookie), + Some(json!({ "subject": subject })), + ) + .await; + assert!( + matches!(res.status, StatusCode::CREATED | StatusCode::OK), + "select subject {subject} on instance {instance}: {}", + res.body + ); +} + /// Create a homework inside `instance` as `cookie` (asserts 201); returns its /// id. Tagged with `subject` (required — every homework carries one of its /// course's subjects) and due at `due_at` (unix-millis; must not lie past the @@ -762,12 +871,11 @@ pub async fn create_homework( title: &str, due_at: i64, ) -> String { - let res = send( + let res = send_homework_create( app, - "POST", - &format!("/instances/{instance}/homework"), - Some(cookie), - Some(json!({ "title": title, "subject_id": subject, "due_at": due_at })), + cookie, + instance, + json!({ "title": title, "subject_id": subject, "due_at": due_at }), ) .await; assert_eq!( @@ -780,16 +888,11 @@ pub async fn create_homework( } /// Create a homework inside `instance` from a full JSON body (no assertion) — -/// for exercising the `assigned` subset and the validation rejects. +/// for exercising the `assigned` subset and the validation rejects. The +/// subject-gate retry applies here too; every other refusal comes back as +/// the server answered it. pub async fn create_homework_with(app: &Router, cookie: &str, instance: &str, body: Value) -> Res { - send( - app, - "POST", - &format!("/instances/{instance}/homework"), - Some(cookie), - Some(body), - ) - .await + send_homework_create(app, cookie, instance, body).await } /// Create a lesson session inside `instance` as `cookie` (asserts 201); returns diff --git a/tests/e2e.rs b/tests/e2e.rs index 461f3e1..b5b93ca 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -674,7 +674,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { // a plain teacher run the instance's roster and write its exams. let class: Value = manager .post(format!("{base}/classes")) - .json(&json!({ "name": "9-A", "year": year, "teacher_id": teacher_id })) + .json(&json!({ "name": "9-A", "grade_level": 9, "year": year, "teacher_id": teacher_id })) .send() .await .unwrap() @@ -693,6 +693,26 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { .unwrap(); let instance_id = instance["id"].as_str().unwrap().to_string(); + // The attach auto-minted the grade-level offering with an empty syllabus; + // the manager selects the fresh topic onto it, because a question may + // only name a subject the section teaches. + let offering: Value = manager + .get(format!("{base}/instances/{instance_id}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let offering_id = offering["offering"].as_str().unwrap().to_string(); + let res = manager + .post(format!("{base}/offerings/{offering_id}/subjects")) + .json(&json!({ "subject": subject_id })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let res = teacher .post(format!("{base}/instances/{instance_id}/enrollments")) .json(&json!({ "user_id": student_id })) @@ -3288,7 +3308,7 @@ async fn a_class_seats_its_roster_and_gives_the_seat_back() { ); let res = manager .post(format!("{base}/classes")) - .json(&json!({ "name": "9-A", "grade": "9", "teacher_id": teacher_id })) + .json(&json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id })) .send() .await .unwrap(); @@ -3541,7 +3561,7 @@ async fn a_manager_archived_year_refuses_every_write_and_answers_every_read() { // instance is what every one of the writes below hangs off. let res = mudur .post(format!("{base}/classes")) - .json(&json!({ "name": "9-A", "grade": "9", "year": year_id })) + .json(&json!({ "name": "9-A", "grade_level": 9, "year": year_id })) .send() .await .unwrap(); @@ -3560,6 +3580,28 @@ async fn a_manager_archived_year_refuses_every_write_and_answers_every_read() { assert_eq!(res.status(), StatusCode::CREATED); let instance_id = json_of(res).await["id"].as_str().unwrap().to_string(); + // The attach auto-minted the grade-level offering with an empty syllabus; + // select the fresh topic onto it so the question and the homework below + // may tag it. + let offering_id = json_of( + mudur + .get(format!("{base}/instances/{instance_id}")) + .send() + .await + .unwrap(), + ) + .await["offering"] + .as_str() + .unwrap() + .to_string(); + let res = mudur + .post(format!("{base}/offerings/{offering_id}/subjects")) + .json(&json!({ "subject": subject_id })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let exam: Value = json_of( mudur .post(format!("{base}/instances/{instance_id}/exams")) @@ -4162,7 +4204,7 @@ async fn a_course_taught_by_two_subeler_is_two_instances_end_to_end() { // --- two şubeler, one catalog course ------------------------------------ let res = mudur .post(format!("{base}/classes")) - .json(&json!({ "name": "5-A", "grade": "5", "year": year, "teacher_id": hoca_id })) + .json(&json!({ "name": "5-A", "grade_level": 5, "year": year, "teacher_id": hoca_id })) .send() .await .unwrap(); @@ -4170,7 +4212,7 @@ async fn a_course_taught_by_two_subeler_is_two_instances_end_to_end() { let five_a = id_of(&res.json::().await.unwrap()["class"]); let res = mudur .post(format!("{base}/classes")) - .json(&json!({ "name": "5-B", "grade": "5", "year": year })) + .json(&json!({ "name": "5-B", "grade_level": 5, "year": year })) .send() .await .unwrap(); diff --git a/tests/integration.rs b/tests/integration.rs index 3877835..4cb37eb 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -8,8 +8,8 @@ use axum::http::{Request, StatusCode}; use common::{ add_member, app_and_db, app_and_tenants, attach_instance, create_class, create_course, create_exam, create_exam_with, create_homework, create_session, create_subject, create_term, - create_year, enroll, ensure_year, id_of, login, login_as, me_id, mem_app, send, set_role, - taught_under, unenroll, upload_course_note_file, + create_year, enroll, ensure_year, id_of, login, login_as, me_id, mem_app, select_instance_subject, + send, set_role, taught, taught_under, unenroll, upload_course_note_file, }; use hezarfen_backend::build_router; use hezarfen_backend::constant::{ @@ -4671,6 +4671,8 @@ async fn subject_reference_counts_track_every_writer() { let t = taught_under(&app, &mudur, &teacher, "physics").await; let from = create_subject(&app, &teacher, &t.course, "optics").await; let to = create_subject(&app, &teacher, &t.course, "waves").await; + select_instance_subject(&app, &teacher, &t.instance, &from).await; + select_instance_subject(&app, &teacher, &t.instance, &to).await; let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "yazili").await; let due = Timestamp::now().as_millis() + 86_400_000; @@ -9093,6 +9095,8 @@ async fn subject_delete_blocks_while_questions_reference_it() { let t = taught_under(&app, &mudur, &teacher, "history").await; let tagged = create_subject(&app, &teacher, &t.course, "antiquity").await; let spare = create_subject(&app, &teacher, &t.course, "middle ages").await; + select_instance_subject(&app, &teacher, &t.instance, &tagged).await; + select_instance_subject(&app, &teacher, &t.instance, &spare).await; let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; let question_body = create_question_body( &app, @@ -9189,7 +9193,7 @@ async fn create_question( id_of(&create_question_body(app, cookie, exam, subject, body).await) } -/// Like [`create_question`], but hands back the whole response: choice ids are +/// Like [`create_question_body`], but hands back the whole response: choice ids are /// minted by the server, so a test that answers a question — or pictures one of /// its options — has to read them off the response rather than count positions. async fn create_question_body( @@ -9205,9 +9209,33 @@ async fn create_question_body( "POST", &format!("/exams/{exam}/questions"), Some(cookie), - Some(body), + Some(body.clone()), ) .await; + // The subject-tag gate reads the section's resolved syllabus: a topic the + // offering never selected is refused. The writer holds a right over the + // instance (the very gate the question write passed), so take the topic + // onto the section's own set through the instance door and retry once. + let res = if res.status == StatusCode::BAD_REQUEST + && res.body["error"] + .as_str() + .is_some_and(|e| e.contains("subject is not in this section's subject set")) + { + let exam_row = send(app, "GET", &format!("/exams/{exam}"), Some(cookie), None).await; + assert_eq!(exam_row.status, StatusCode::OK, "{}", exam_row.body); + let instance = exam_row.body["class_course"].as_str().expect("class_course"); + select_instance_subject(app, cookie, instance, subject).await; + send( + app, + "POST", + &format!("/exams/{exam}/questions"), + Some(cookie), + Some(body), + ) + .await + } else { + res + }; assert_eq!( res.status, StatusCode::CREATED, @@ -9266,6 +9294,7 @@ async fn question_crud_validation_and_rbac() { scheduling_kinds(&app, &mudur).await; let t = taught_under(&app, &mudur, &teacher, "logic").await; let subject = create_subject(&app, &teacher, &t.course, "propositions").await; + select_instance_subject(&app, &teacher, &t.instance, &subject).await; let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; // A choice question echoes its full authoring view, correct included. @@ -9470,6 +9499,7 @@ async fn question_crud_validation_and_rbac() { // Re-tagging stays inside the course: another of its subjects is fine, a // foreign course's subject is a 400. let second_subject = create_subject(&app, &teacher, &t.course, "predicates").await; + select_instance_subject(&app, &teacher, &t.instance, &second_subject).await; let res = send( &app, "PATCH", @@ -15759,6 +15789,7 @@ async fn hw_world(app: &axum::Router, db: &hezarfen_backend::database::Database) let veli_id = me_id(app, &veli).await; let t = taught_under(app, &mudur, &teacher, "math").await; let subject = create_subject(app, &teacher, &t.course, "algebra").await; + select_instance_subject(app, &teacher, &t.instance, &subject).await; // The students sit in the şube: the pump enrolls them into the instance. add_member(app, &mudur, &t.class, &ali_id).await; add_member(app, &mudur, &t.class, &veli_id).await; @@ -16092,6 +16123,7 @@ async fn homework_patch_rechecks_and_blocks_orphaning() { .await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); let algebra2 = create_subject(&app, &w.teacher, &w.course, "algebra II").await; + select_instance_subject(&app, &w.teacher, &w.instance, &algebra2).await; let res = send( &app, "PATCH", @@ -17172,6 +17204,7 @@ async fn homework_blocks_subject_delete_until_retagged() { // Re-tagging frees the old subject and guards the new one. let second = create_subject(&app, &w.teacher, &w.course, "geometry").await; + select_instance_subject(&app, &w.teacher, &w.instance, &second).await; let res = send( &app, "PATCH", @@ -19837,6 +19870,7 @@ async fn bank_question_create_get_list_and_instantiate() { let mudur = login_as(&app, &db, "algebra_m", "manager").await; let t = taught_under(&app, &mudur, &teacher, "algebra").await; let subject = create_subject(&app, &teacher, &t.course, "linear").await; + select_instance_subject(&app, &teacher, &t.instance, &subject).await; // Create a template — subject is origin metadata, not held to a course. let res = send( @@ -19936,6 +19970,7 @@ async fn bank_question_list_pages_filters_and_names() { let mudur = login_as(&app, &db, "algebra_m", "manager").await; let t = taught_under(&app, &mudur, &teacher, "algebra").await; let subject = create_subject(&app, &teacher, &t.course, "linear").await; + select_instance_subject(&app, &teacher, &t.instance, &subject).await; let other_subject = create_subject(&app, &teacher, &t.course, "quadratic").await; // 120 templates — more than the clients' `limit=100`. @@ -20413,6 +20448,7 @@ async fn bank_private_template_is_invisible_until_published() { scheduling_kinds(&app, &mudur).await; let t = taught_under(&app, &mudur, &owner, "bio").await; let subject = create_subject(&app, &owner, &t.course, "cells").await; + select_instance_subject(&app, &owner, &t.instance, &subject).await; // Two templates; only the second is ever published. let res = send( @@ -20463,6 +20499,7 @@ async fn bank_private_template_is_invisible_until_published() { // The other teacher's own exam, to attempt an instantiate from. let t2 = taught_under(&app, &mudur, &other, "bio2").await; let subject2 = create_subject(&app, &other, &t2.course, "cells2").await; + select_instance_subject(&app, &other, &t2.instance, &subject2).await; let exam2 = create_exam(&app, &other, &t2.instance, &t2.term, "quiz", "final").await; let owner_id = me_id(&app, &owner).await; @@ -20740,6 +20777,7 @@ async fn bank_instantiate_copies_images() { scheduling_kinds(&app, &mudur).await; let t = taught_under(&app, &mudur, &teacher, "geo1").await; let subject = create_subject(&app, &teacher, &t.course, "maps1").await; + select_instance_subject(&app, &teacher, &t.instance, &subject).await; // A choice template with an illustration and one option picture. let res = send( @@ -21042,6 +21080,7 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() { scheduling_kinds(&app, &mudur).await; let t = taught_under(&app, &mudur, &teacher, "geo2").await; let subject = create_subject(&app, &teacher, &t.course, "maps2").await; + select_instance_subject(&app, &teacher, &t.instance, &subject).await; // Two images so the copy loop has multiple steps. let res = send( @@ -21411,6 +21450,7 @@ async fn bank_provenance_both_directions() { scheduling_kinds(&app, &mudur).await; let t = taught_under(&app, &mudur, &teacher, "bprov_c").await; let subject = create_subject(&app, &teacher, &t.course, "bprov_s").await; + select_instance_subject(&app, &teacher, &t.instance, &subject).await; // Bank -> exam: from_bank is the template id, banked_as stays null. let res = send( @@ -21921,6 +21961,7 @@ async fn bank_list_counts_the_copies_made_from_each_template() { scheduling_kinds(&app, &mudur).await; let t = taught_under(&app, &mudur, &teacher, "buse_c").await; let subject = create_subject(&app, &teacher, &t.course, "buse_s").await; + select_instance_subject(&app, &teacher, &t.instance, &subject).await; let template = |text: &'static str| { send( @@ -22042,6 +22083,7 @@ async fn refreshing_a_question_recopies_its_template() { scheduling_kinds(&app, &mudur).await; let t = taught_under(&app, &mudur, &teacher, "bref_c").await; let subject = create_subject(&app, &teacher, &t.course, "bref_s").await; + select_instance_subject(&app, &teacher, &t.instance, &subject).await; // A template with an illustration and a picture on its first option. let res = send( @@ -26993,7 +27035,7 @@ async fn a_class_pumps_enrollments_and_guards_each_axis_separately() { "POST", "/classes", Some(&teacher), - Some(json!({"name": "9-A"})), + Some(json!({"name": "9-A", "grade_level": 9})), ) .await; assert_eq!( @@ -27006,13 +27048,13 @@ async fn a_class_pumps_enrollments_and_guards_each_axis_separately() { "POST", "/classes", Some(&manager), - Some(json!({"name": "9-A", "grade": ""})), + Some(json!({"name": "9-A", "grade_level": 9})), ) .await; assert_eq!(res.status, StatusCode::CREATED); - assert!( - res.body["class"]["grade"].is_null(), - "an empty grade is no grade" + assert_eq!( + res.body["class"]["grade_level"], 9, + "the class carries the rung it was created at" ); let class = id_of(&res.body["class"]); assert_eq!( @@ -27206,7 +27248,7 @@ async fn class_reads_are_staff_only_and_a_manager_manages_every_course() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A" })), + Some(json!({ "name": "9-A", "grade_level": 9 })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); @@ -27309,7 +27351,7 @@ async fn a_demotion_sweeps_the_class_membership_and_what_it_pumped() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A" })), + Some(json!({ "name": "9-A", "grade_level": 9 })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); @@ -27467,7 +27509,7 @@ async fn a_year_a_class_points_at_refuses_to_delete() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A", "year": year })), + Some(json!({ "name": "9-A", "grade_level": 9, "year": year })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); @@ -27552,7 +27594,7 @@ async fn an_attach_that_cannot_seat_the_whole_class_seats_none_of_it() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A" })), + Some(json!({ "name": "9-A", "grade_level": 9 })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); @@ -30269,7 +30311,7 @@ const CORE_PREFIXES: [(&str, &str); 14] = [ /// A module may own more than one prefix: `courses` also answers under /// `/instances` (the instance anchor), and `chatbot` — the whole `ai` package — /// also answers under `/rag`, `/insights` and `/podcast`. -const MODULE_PREFIXES: [(Module, &str); 25] = [ +const MODULE_PREFIXES: [(Module, &str); 26] = [ (Module::Chatbot, "/chatbot"), (Module::Chatbot, "/rag"), (Module::Chatbot, "/insights"), @@ -30280,6 +30322,7 @@ const MODULE_PREFIXES: [(Module, &str); 25] = [ (Module::Appointments, "/appointments"), (Module::Courses, "/courses"), (Module::Courses, "/instances"), + (Module::Courses, "/offerings"), (Module::CourseNotes, "/course-notes"), (Module::Classes, "/classes"), (Module::Sessions, "/sessions"), @@ -30895,3 +30938,433 @@ async fn the_insight_run_ledger_is_manager_only() { let res = send(&app, "GET", "/insights/runs", Some(&teacher), None).await; assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); } + +// --- course template: the six template/instance children are wired -------- + +/// The six foreign-module route pairs wave 2 mounted — subject selection, +/// exam weights and the weekly plan under both `/offerings` and +/// `/instances` — all answer through the built router with one manager +/// session. A missed merge or a double prefix would 404 here; the module +/// gates stay out of the way because the school runs every module. +#[tokio::test] +async fn offering_and_instance_template_children_answer_through_the_router() { + let (app, db) = app_and_db().await; + let mudur = login_as(&app, &db, "mudur_template", "manager").await; + + // One class-delivered ders attached to one şube: the attach auto-mints + // the grade-level offering the section inherits from, and the instance + // read names it. + let t = taught(&app, &mudur, "resim").await; + let read = send( + &app, + "GET", + &format!("/instances/{}", t.instance), + Some(&mudur), + None, + ) + .await; + assert_eq!(read.status, StatusCode::OK, "{}", read.body); + let offering = read.body["offering"] + .as_str() + .expect("instance carries its offering") + .to_string(); + + // The catalog POST itself: a second grade level of the same ders is a + // fresh template — 201, not a 404 from a double-prefixed mount. + let created = send( + &app, + "POST", + "/offerings", + Some(&mudur), + Some(json!({ "course": t.course, "grade_level": 0 })), + ) + .await; + assert_eq!(created.status, StatusCode::CREATED, "{}", created.body); + + for (path, why) in [ + ( + format!("/offerings/{offering}/subjects"), + "offering subjects", + ), + ( + format!("/offerings/{offering}/exam-weights"), + "offering exam weights", + ), + ( + format!("/offerings/{offering}/weekly-plan"), + "offering weekly plan", + ), + ( + format!("/instances/{}/subjects", t.instance), + "instance subjects", + ), + ( + format!("/instances/{}/exam-weights", t.instance), + "instance exam weights", + ), + ( + format!("/instances/{}/weekly-plan", t.instance), + "instance weekly plan", + ), + ] { + let res = send(&app, "GET", &path, Some(&mudur), None).await; + assert_eq!(res.status, StatusCode::OK, "{why}: {}", res.body); + } +} + +// --- course template: the user's per-class scenario, end to end ------------- + +/// The user's scenario (2026-09-23): a 9th-grade and a 12th-grade section both +/// teach Biology — same catalog course, two instances — and each resolves to +/// the template of its own grade, with per-class overrides deviating exactly +/// one axis at a time (override-or-inherit, never merge). Driven over the HTTP +/// surface only: +/// +/// (a) both instances share the course id but resolve to different offerings; +/// (b) the grade-9 offering's template (title suffix, description, hours, a +/// topic, a weight, a slot) shows on the grade-9 instance and nowhere on +/// grade 12; +/// (c) a `ders_saati` override on one instance deviates exactly that axis; +/// (d) an own-but-empty subject set beats the offering's set; +/// (e) the reset doors restore inheritance (a scalar, and the set axes); +/// (f) a topic of the grade-9 template tags a question there and is refused +/// in the grade-12 instance; +/// (g) the marks and karne reports show each section its own resolved title. +#[tokio::test] +async fn course_template_resolution_is_per_class_end_to_end() { + let (app, db) = app_and_db().await; + let staff = login_as(&app, &db, "mudur_scenario", "manager").await; + + // One ders, two topics, two şubeler at different rungs of the ladder. + let course = create_course(&app, &staff, "Biyoloji").await; + let s1 = create_subject(&app, &staff, &course, "Hücre").await; + let s2 = create_subject(&app, &staff, &course, "Genetik").await; + let year = ensure_year(&app, &staff).await; + let term = create_term(&app, &staff, &year, "1. Dönem").await; + let class_a = create_class( + &app, + &staff, + "9-A", + json!({ "year": year, "grade_level": 9 }), + ) + .await; + let class_b = create_class( + &app, + &staff, + "12-B", + json!({ "year": year, "grade_level": 12 }), + ) + .await; + let inst_a = attach_instance(&app, &staff, &class_a, &course).await; + let inst_b = attach_instance(&app, &staff, &class_b, &course).await; + let read_instance = |uri: String| { + let app = app.clone(); + let staff = staff.clone(); + async move { send(&app, "GET", &uri, Some(&staff), None).await } + }; + + // (a) Same ders, two instances — and each teaches from its own grade's + // template: shared course id, distinct offering ids, both scalars still + // inheriting the catalog/constant floor. + let a = read_instance(format!("/instances/{inst_a}")).await; + let b = read_instance(format!("/instances/{inst_b}")).await; + assert_eq!(a.status, StatusCode::OK, "{}", a.body); + assert_eq!(b.status, StatusCode::OK, "{}", b.body); + assert_eq!(a.body["course"], course, "(a) same catalog course"); + assert_eq!(b.body["course"], course, "(a) same catalog course"); + let offering_a = a.body["offering"].as_str().expect("(a) offering id"); + let offering_b = b.body["offering"].as_str().expect("(a) offering id"); + assert_ne!(offering_a, offering_b, "(a) each grade has its own template"); + assert_eq!(a.body["title"], "Biyoloji", "(a) pre-template title inherits"); + assert_eq!(a.body["title_overridden"], false); + assert_eq!(b.body["ders_saati"], 1, "(a) the constant floor, not a value"); + assert_eq!(b.body["ders_saati_overridden"], false); + + // (b) Fill the grade-9 template; the grade-12 one stays empty. + let patched = send( + &app, + "PATCH", + &format!("/offerings/{offering_a}"), + Some(&staff), + Some(json!({ + "title": "Biyoloji (9. sınıf)", + "description": "9. sınıf müfredatı", + "default_ders_saati": 4 + })), + ) + .await; + assert_eq!(patched.status, StatusCode::OK, "{}", patched.body); + for (offering, subject) in [(offering_a, &s1), (offering_b, &s2)] { + let res = send( + &app, + "POST", + &format!("/offerings/{offering}/subjects"), + Some(&staff), + Some(json!({ "subject": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + } + let weighted = send( + &app, + "PATCH", + &format!("/offerings/{offering_a}/exam-weights"), + Some(&staff), + Some(json!({ "kind": "yazili", "weight": 3 })), + ) + .await; + assert_eq!(weighted.status, StatusCode::OK, "{}", weighted.body); + let slotted = send( + &app, + "POST", + &format!("/offerings/{offering_a}/weekly-plan"), + Some(&staff), + Some(json!({ "weekday": 1, "starts_at": 540, "ends_at": 570 })), + ) + .await; + assert_eq!(slotted.status, StatusCode::CREATED, "{}", slotted.body); + + let a = read_instance(format!("/instances/{inst_a}")).await; + assert_eq!(a.body["title"], "Biyoloji (9. sınıf)", "(b) grade-9 title"); + assert_eq!(a.body["title_overridden"], false, "(b) inherited, not owned"); + assert_eq!(a.body["description"], "9. sınıf müfredatı"); + assert_eq!(a.body["ders_saati"], 4, "(b) the grade-9 default"); + assert_eq!(a.body["subjects_inherited"], true); + assert_eq!(a.body["subjects"][0]["id"], s1, "(b) the grade-9 syllabus"); + let a_weights = a.body["exam_weights"] + .as_array() + .expect("(b) resolved weight map"); + let a_yazili = a_weights + .iter() + .find(|w| w["kind"] == "yazili") + .expect("(b) settings kinds are always mapped"); + assert_eq!(a_yazili["weight"], 3, "(b) the template's weight"); + assert_eq!(a.body["weekly_plan"][0]["weekday"], 1, "(b) template week"); + + let b = read_instance(format!("/instances/{inst_b}")).await; + assert_eq!(b.body["title"], "Biyoloji", "(b) grade 12 stays on the catalog"); + assert_eq!(b.body["ders_saati"], 1, "(b) the empty template inherits all"); + assert_eq!(b.body["subjects"][0]["id"], s2, "(b) grade 12's own template"); + assert!( + !b.body["subjects"] + .as_array() + .expect("(b) subjects array") + .iter() + .any(|s| s["id"] == s1), + "(b) no bleed of the grade-9 topic into grade 12" + ); + let b_weights = b.body["exam_weights"] + .as_array() + .expect("(b) resolved weight map"); + let b_yazili = b_weights + .iter() + .find(|w| w["kind"] == "yazili") + .expect("(b) settings kinds are always mapped"); + assert_eq!(b_yazili["weight"], 1, "(b) grade 12 keeps the settings weight"); + assert_eq!( + b.body["weekly_plan"] + .as_array() + .expect("(b) weekly plan array") + .len(), + 0, + "(b) the empty grade-12 template week" + ); + + // (c) Override exactly one axis on the grade-9 section: its hours move, + // everything else keeps flowing from the template, and grade 12 is + // untouched. + let patched = send( + &app, + "PATCH", + &format!("/instances/{inst_a}"), + Some(&staff), + Some(json!({ "ders_saati": 6 })), + ) + .await; + assert_eq!(patched.status, StatusCode::OK, "{}", patched.body); + let a = read_instance(format!("/instances/{inst_a}")).await; + assert_eq!(a.body["ders_saati"], 6, "(c) the override wins"); + assert_eq!(a.body["ders_saati_overridden"], true, "(c) flagged as owned"); + assert_eq!( + a.body["title"], "Biyoloji (9. sınıf)", + "(c) no merge: the title still inherits" + ); + assert_eq!(a.body["title_overridden"], false, "(c) still not owned"); + assert_eq!( + a.body["subjects_inherited"], true, + "(c) the set axis is untouched" + ); + let b = read_instance(format!("/instances/{inst_b}")).await; + assert_eq!(b.body["ders_saati"], 1, "(c) grade 12 unaffected"); + + // (f) Topic tagging while grade 9 still inherits: its template's topic is + // accepted there, refused next door. + let exam_a = create_exam(&app, &staff, &inst_a, &term, "A sınavı", "yazili").await; + let exam_b = create_exam(&app, &staff, &inst_b, &term, "B sınavı", "yazili").await; + let tagged = send( + &app, + "POST", + &format!("/exams/{exam_a}/questions"), + Some(&staff), + Some(json!({ "subject_id": s1, "text": "Mitokondri?", "kind": "text", "points": 10 })), + ) + .await; + assert_eq!(tagged.status, StatusCode::CREATED, "(f) {}", tagged.body); + let refused = send( + &app, + "POST", + &format!("/exams/{exam_b}/questions"), + Some(&staff), + Some(json!({ "subject_id": s1, "text": "Mitokondri?", "kind": "text", "points": 10 })), + ) + .await; + assert_eq!(refused.status, StatusCode::BAD_REQUEST, "(f) {}", refused.body); + let own = send( + &app, + "POST", + &format!("/exams/{exam_b}/questions"), + Some(&staff), + Some(json!({ "subject_id": s2, "text": "DNA?", "kind": "text", "points": 10 })), + ) + .await; + assert_eq!( + own.status, + StatusCode::CREATED, + "(f) the refusal is syllabus scope, not course scope: {}", + own.body + ); + + // (d) An own set that is EMPTY wins: take a topic onto the section and + // drop it — the flag stays "own", the resolved set is empty, and the + // sibling still sees its own template's topic. + let took = send( + &app, + "POST", + &format!("/instances/{inst_a}/subjects"), + Some(&staff), + Some(json!({ "subject": s1 })), + ) + .await; + assert_eq!(took.status, StatusCode::CREATED, "(d) {}", took.body); + let dropped = send( + &app, + "DELETE", + &format!("/instances/{inst_a}/subjects/{s1}"), + Some(&staff), + None, + ) + .await; + assert_eq!(dropped.status, StatusCode::NO_CONTENT, "(d) {}", dropped.body); + let a = read_instance(format!("/instances/{inst_a}")).await; + assert_eq!(a.body["subjects_inherited"], false, "(d) the set is its own"); + assert_eq!( + a.body["subjects"] + .as_array() + .expect("(d) subjects array") + .len(), + 0, + "(d) empty own set beats the template's" + ); + let b = read_instance(format!("/instances/{inst_b}")).await; + assert_eq!( + b.body["subjects"][0]["id"], s2, + "(d) the sibling still inherits its template" + ); + + // (e) The reset doors restore inheritance: the scalar goes back to the + // offering's default, the weekly plan back to the template week, and the + // subjects flag back to the template's set. + let reset = send( + &app, + "POST", + &format!("/instances/{inst_a}/reset"), + Some(&staff), + Some(json!({ "fields": ["ders_saati"] })), + ) + .await; + assert_eq!(reset.status, StatusCode::OK, "(e) {}", reset.body); + assert_eq!(reset.body["ders_saati"], 4, "(e) the offering default again"); + assert_eq!(reset.body["ders_saati_overridden"], false, "(e) inheriting"); + + let own_slot = send( + &app, + "POST", + &format!("/instances/{inst_a}/weekly-plan"), + Some(&staff), + Some(json!({ "weekday": 2, "starts_at": 600, "ends_at": 630 })), + ) + .await; + assert_eq!(own_slot.status, StatusCode::CREATED, "(e) {}", own_slot.body); + let a = read_instance(format!("/instances/{inst_a}")).await; + assert_eq!(a.body["weekly_plan_inherited"], false, "(e) own week wins"); + assert_eq!(a.body["weekly_plan"][0]["weekday"], 2); + let plan_reset = send( + &app, + "DELETE", + &format!("/instances/{inst_a}/weekly-plan"), + Some(&staff), + None, + ) + .await; + assert_eq!(plan_reset.status, StatusCode::NO_CONTENT, "(e)"); + let a = read_instance(format!("/instances/{inst_a}")).await; + assert_eq!(a.body["weekly_plan_inherited"], true, "(e) inheriting again"); + assert_eq!( + a.body["weekly_plan"][0]["weekday"], 1, + "(e) the template week again" + ); + + let subjects_reset = send( + &app, + "POST", + &format!("/instances/{inst_a}/reset"), + Some(&staff), + Some(json!({ "fields": ["subjects"] })), + ) + .await; + assert_eq!(subjects_reset.status, StatusCode::OK, "(e)"); + let a = read_instance(format!("/instances/{inst_a}")).await; + assert_eq!(a.body["subjects_inherited"], true, "(e) the flag is back"); + assert_eq!(a.body["subjects"][0]["id"], s1, "(e) the template set again"); + + // (g) The batched report reads show each section its own resolved title. + let ogrenci = login(&app, "scenario_ogrenci").await; + let student_id = me_id(&app, &ogrenci).await; + add_member(&app, &staff, &class_a, &student_id).await; + add_member(&app, &staff, &class_b, &student_id).await; + + let marks = send(&app, "GET", &format!("/marks/{student_id}"), Some(&staff), None).await; + assert_eq!(marks.status, StatusCode::OK, "(g) {}", marks.body); + let blocks = marks.body["courses"].as_array().expect("(g) marks blocks"); + assert_eq!(blocks.len(), 2, "(g) one block per section: {}", marks.body); + for block in blocks { + let expected = if block["instance"] == inst_a { + "Biyoloji (9. sınıf)" + } else { + "Biyoloji" + }; + assert_eq!(block["course"]["title"], expected, "(g) {}", marks.body); + } + + let karne = send( + &app, + "GET", + &format!("/marks/karne/{student_id}?term={term}"), + Some(&staff), + None, + ) + .await; + assert_eq!(karne.status, StatusCode::OK, "(g) {}", karne.body); + let lines = karne.body["instances"] + .as_array() + .expect("(g) karne lines"); + assert_eq!(lines.len(), 2, "(g) one line per section: {}", karne.body); + for line in lines { + let expected = if line["class_course"] == inst_a { + "Biyoloji (9. sınıf)" + } else { + "Biyoloji" + }; + assert_eq!(line["course"], expected, "(g) {}", karne.body); + } +} diff --git a/tests/pagination.rs b/tests/pagination.rs index 46114bd..8684666 100644 --- a/tests/pagination.rs +++ b/tests/pagination.rs @@ -594,7 +594,7 @@ async fn class_lists_are_paged() { "POST", "/classes", Some(&manager), - Some(json!({ "name": format!("9-{n}") })), + Some(json!({ "name": format!("9-{n}"), "grade_level": 9 })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); diff --git a/tests/partial_patch_terms.rs b/tests/partial_patch_terms.rs index f2b5648..a3cebf0 100644 --- a/tests/partial_patch_terms.rs +++ b/tests/partial_patch_terms.rs @@ -209,7 +209,7 @@ async fn an_archived_term_is_frozen_for_writes_and_open_for_reads() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A", "year": year })), + Some(json!({ "name": "9-A", "year": year, "grade_level": 9 })), ) .await; assert_eq!( diff --git a/tests/persistence.rs b/tests/persistence.rs index 4517b1e..a465545 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -9,7 +9,9 @@ mod common; use axum::Router; use axum::http::StatusCode; -use common::{create_subject, enroll, login_as, me_id, send, set_role, taught_under}; +use common::{ + create_subject, enroll, login_as, me_id, select_instance_subject, send, set_role, taught_under, +}; use hezarfen_backend::database::Database; use hezarfen_backend::module::ModuleSet; use hezarfen_backend::rate_limit::RateLimitConfig; @@ -314,6 +316,9 @@ async fn attempt_history_survives_remigration() { let mudur = login_as(&app, &db, "mudur", "manager").await; let t = taught_under(&app, &mudur, &teacher, "biology").await; let subject = create_subject(&app, &teacher, &t.course, "cells").await; + // The tag check reads the resolved syllabus — the topic rides the + // section's own set before any question may carry it. + select_instance_subject(&app, &teacher, &t.instance, &subject).await; enroll(&app, &teacher, &t.instance, &student_id).await; let res = send( &app, diff --git a/tests/regress_blueprints.rs b/tests/regress_blueprints.rs index adf8f9b..88094ff 100644 --- a/tests/regress_blueprints.rs +++ b/tests/regress_blueprints.rs @@ -19,7 +19,7 @@ use common::{ upload_file_at, }; use hezarfen_backend::database::Database; -use hezarfen_backend::domain::class_blueprint::ClassBlueprint; +use hezarfen_backend::domain::grade::GradeLevel; use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::monotonic_id::next_uuid; use hezarfen_backend::domain::timestamp::Timestamp; @@ -76,22 +76,24 @@ async fn source_of(class: &str, course: &str, db: &Database) -> Option uuid::Uuid { - sqlx::query_scalar::<_, uuid::Uuid>("SELECT id FROM class_blueprint WHERE grade = $1") - .bind(grade) +async fn blueprint_id(grade_level: i16, db: &Database) -> uuid::Uuid { + sqlx::query_scalar::<_, uuid::Uuid>( + "SELECT id FROM class_blueprint WHERE grade_level = $1", + ) + .bind(grade_level) .fetch_one(db) .await .unwrap() } /// Does that grade's template still name that course, in the store? -async fn templated(grade: &str, course: &str, db: &Database) -> bool { +async fn templated(grade_level: i16, course: &str, db: &Database) -> bool { sqlx::query_scalar::<_, i64>( "SELECT count(*) FROM blueprint_course bc \ JOIN class_blueprint b ON b.id = bc.blueprint \ - WHERE b.grade = $1 AND bc.course = $2", + WHERE b.grade_level = $1 AND bc.course = $2", ) - .bind(grade) + .bind(grade_level) .bind(CourseId::from_key(course)) .fetch_one(db) .await @@ -115,13 +117,18 @@ async fn held(app: &axum::Router, cookie: &str, grade: &str) -> Vec { } /// Create a class section as `cookie`; returns its id. -async fn create_class(app: &axum::Router, cookie: &str, name: &str, grade: &str) -> String { +async fn create_class( + app: &axum::Router, + cookie: &str, + name: &str, + grade_level: i16, +) -> String { let res = send( app, "POST", "/classes", Some(cookie), - Some(json!({ "name": name, "grade": grade })), + Some(json!({ "name": name, "grade_level": grade_level })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "create class {name}"); @@ -210,11 +217,11 @@ async fn a_blueprint_is_created_read_updated_and_deleted() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); - assert_eq!(made.body["blueprint"]["grade"], "9"); + assert_eq!(made.body["blueprint"]["grade_level"], 9); assert_eq!(made.body["blueprint"]["courses"][0], algebra.as_str()); assert!(skips(&made).is_empty(), "no class exists to skip"); @@ -225,7 +232,7 @@ async fn a_blueprint_is_created_read_updated_and_deleted() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [] })), + Some(json!({ "grade_level": 9, "course_ids": [] })), ) .await; assert_eq!(again.status, StatusCode::CONFLICT, "{:?}", again.body); @@ -270,20 +277,20 @@ async fn a_blueprint_is_created_read_updated_and_deleted() { let gone = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await; assert_eq!(gone.status, StatusCode::NOT_FOUND); - // An unaddressable grade is a 400, not a record nobody can ever read back. - for bad in ["", "9/A"] { + // An off-ladder rung is a 400, not a record nobody can ever read back. + for bad in [-1, 13, 99] { let refused = send( &app, "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": bad, "course_ids": [] })), + Some(json!({ "grade_level": bad, "course_ids": [] })), ) .await; assert_eq!( refused.status, StatusCode::BAD_REQUEST, - "grade {bad:?}: {:?}", + "grade_level {bad}: {:?}", refused.body ); } @@ -302,12 +309,12 @@ async fn a_fresh_class_takes_its_grades_blueprint() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone(), physics.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED); - let class = create_class(&app, &manager, "9-A", "9").await; + let class = create_class(&app, &manager, "9-A", 9).await; let student = student_in(&app, &db, &class, &manager, "ali").await; let applied = send( @@ -325,7 +332,7 @@ async fn a_fresh_class_takes_its_grades_blueprint() { assert!(attached(&class, course, &db).await); assert_eq!( source_of(&class, course, &db).await, - Some(blueprint_id("9", &db).await), + Some(blueprint_id(9, &db).await), "the blueprint must own what it attached" ); let instance = instance_of(&class, course, &db).await; @@ -361,7 +368,7 @@ async fn a_fresh_class_takes_its_grades_blueprint() { assert_eq!(rows("SELECT count(*) FROM class_course", &db).await, 2); // A class whose grade no blueprint covers is a 404, not an empty success. - let other = create_class(&app, &manager, "10-A", "10").await; + let other = create_class(&app, &manager, "10-A", 10).await; let none = send( &app, "POST", @@ -388,7 +395,7 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone(), physics.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); @@ -398,12 +405,12 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A", "grade": "9" })), + Some(json!({ "name": "9-A", "grade_level": 9 })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); assert_eq!( - res.body["stocked_from"], "9", + res.body["stocked_from"], 9, "the create must name the template that stocked it: {:?}", res.body ); @@ -419,7 +426,7 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { assert!(attached(&class, course, &db).await, "{course} is attached"); assert_eq!( source_of(&class, course, &db).await, - Some(blueprint_id("9", &db).await), + Some(blueprint_id(9, &db).await), "the blueprint must own what a create attached, exactly as a pump does" ); } @@ -451,8 +458,9 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { // A grade no template covers, and a class with no grade at all: `null`, // which is the one thing an empty `skipped` could never say. for body in [ - json!({ "name": "10-A", "grade": "10" }), - json!({ "name": "satranç", "grade": "" }), + json!({ "name": "10-A", "grade_level": 10 }), + // A club-shaped section sits at the ladder's floor, like any class. + json!({ "name": "satranç", "grade_level": 0 }), ] { let res = send(&app, "POST", "/classes", Some(&manager), Some(body)).await; assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); @@ -497,7 +505,7 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone(), physics.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); @@ -522,7 +530,7 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { .unwrap(); tx.commit().await.unwrap(); assert!( - templated("9", &physics, &db).await, + templated(9, &physics, &db).await, "the id is still listed" ); @@ -531,7 +539,7 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A", "grade": "9" })), + Some(json!({ "name": "9-A", "grade_level": 9 })), ) .await; assert_eq!( @@ -540,7 +548,7 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { "a pair that will not fit may not cost the class: {:?}", res.body ); - assert_eq!(res.body["stocked_from"], "9"); + assert_eq!(res.body["stocked_from"], 9); assert_eq!(skips(&res).len(), 1, "{:?}", res.body); assert_eq!(skips(&res)[0]["reason"], "course_deleted"); assert_eq!(skips(&res)[0]["course"], physics.as_str()); @@ -584,9 +592,9 @@ async fn an_edit_retro_pumps_every_class_at_the_grade() { let (app, db) = app_and_db().await; let manager = login_as(&app, &db, "mgr", "manager").await; let algebra = create_course(&app, &manager, "algebra").await; - let a = create_class(&app, &manager, "9-A", "9").await; - let b = create_class(&app, &manager, "9-B", "9").await; - let ten = create_class(&app, &manager, "10-A", "10").await; + let a = create_class(&app, &manager, "9-A", 9).await; + let b = create_class(&app, &manager, "9-B", 9).await; + let ten = create_class(&app, &manager, "10-A", 10).await; let ali = student_in(&app, &db, &a, &manager, "ali").await; student_in(&app, &db, &ten, &manager, "veli").await; @@ -596,7 +604,7 @@ async fn an_edit_retro_pumps_every_class_at_the_grade() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [] })), + Some(json!({ "grade_level": 9, "course_ids": [] })), ) .await; assert_eq!(made.status, StatusCode::CREATED); @@ -658,7 +666,7 @@ async fn a_duplicate_attach_answers_its_machine_code() { let (app, db) = app_and_db().await; let manager = login_as(&app, &db, "mgr", "manager").await; let roomy = create_course(&app, &manager, "algebra").await; - let class = create_class(&app, &manager, "9-A", "9").await; + let class = create_class(&app, &manager, "9-A", 9).await; student_in(&app, &db, &class, &manager, "ali").await; let attached = send( @@ -701,8 +709,8 @@ async fn a_removal_spares_a_hand_attached_course() { let (app, db) = app_and_db().await; let manager = login_as(&app, &db, "mgr", "manager").await; let algebra = create_course(&app, &manager, "algebra").await; - let pumped = create_class(&app, &manager, "9-A", "9").await; - let byhand = create_class(&app, &manager, "9-B", "9").await; + let pumped = create_class(&app, &manager, "9-A", 9).await; + let byhand = create_class(&app, &manager, "9-B", 9).await; let ali = student_in(&app, &db, &pumped, &manager, "ali").await; student_in(&app, &db, &byhand, &manager, "veli").await; @@ -727,7 +735,7 @@ async fn a_removal_spares_a_hand_attached_course() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED); @@ -739,7 +747,7 @@ async fn a_removal_spares_a_hand_attached_course() { ); assert_eq!( source_of(&pumped, &algebra, &db).await, - Some(blueprint_id("9", &db).await), + Some(blueprint_id(9, &db).await), ); // Drop it from the template. @@ -799,7 +807,7 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() { let (app, db) = app_and_db().await; let manager = login_as(&app, &db, "mgr", "manager").await; let algebra = create_course(&app, &manager, "algebra").await; - let class = create_class(&app, &manager, "9-A", "9").await; + let class = create_class(&app, &manager, "9-A", 9).await; student_in(&app, &db, &class, &manager, "ali").await; let attached_by_hand = send( &app, @@ -836,7 +844,7 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); @@ -896,7 +904,7 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); @@ -905,13 +913,13 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() { // is stocked by its own create, and one that existed already was stocked by // the template's. Moving it there afterwards is neither — a grade change is // deliberately a blueprint no-op. - let class = create_class(&app, &manager, "9-A", "10").await; + let class = create_class(&app, &manager, "9-A", 10).await; let moved = send( &app, "PATCH", &format!("/classes/{class}"), Some(&manager), - Some(json!({ "grade": "9" })), + Some(json!({ "grade_level": 9 })), ) .await; assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body); @@ -923,19 +931,35 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() { // the strand consists of. Capture the uuid before the delete: the grade // label is UNIQUE, not the FK. let manager_id = UserId::from_key(&me_id(&app, &manager).await); - let stranded = blueprint_id("9", &db).await; + let stranded = blueprint_id(9, &db).await; let mut tx = db.begin().await.unwrap(); sqlx::query("SET LOCAL session_replication_role = replica") .execute(&mut *tx) .await .unwrap(); - sqlx::query("DELETE FROM class_blueprint WHERE grade = '9'") + sqlx::query("DELETE FROM class_blueprint WHERE grade_level = 9") .execute(&mut *tx) .await .unwrap(); + // The strand names an offering too (the column is NOT NULL): the pump run + // above already minted one for (algebra, 9) — reuse it, minting a twin + // only if none survived, exactly like `ensure_tx` would. + let offering: (uuid::Uuid,) = sqlx::query_as( + "INSERT INTO course_offering (id, course, grade_level, created_by, created_at, updated_at) \ + VALUES ($1, $2, 9, $3, $4, $4) \ + ON CONFLICT (course, grade_level) DO UPDATE SET updated_at = EXCLUDED.updated_at \ + RETURNING id", + ) + .bind(next_uuid()) + .bind(CourseId::from_key(&algebra)) + .bind(manager_id) + .bind(Timestamp::now().as_millis()) + .fetch_one(&mut *tx) + .await + .unwrap(); sqlx::query( - "INSERT INTO class_course (id, class, course, attached_by, attached_at, source) \ - VALUES ($1, $2, $3, $4, $5, $6)", + "INSERT INTO class_course (id, class, course, attached_by, attached_at, source, offering) \ + VALUES ($1, $2, $3, $4, $5, $6, $7)", ) .bind(next_uuid()) .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id")) @@ -943,6 +967,7 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() { .bind(manager_id) .bind(Timestamp::now().as_millis()) .bind(stranded) + .bind(offering.0) .execute(&mut *tx) .await .unwrap(); @@ -990,30 +1015,30 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() { ); } -/// The silent miss `matched` exists for: a grade label is free text and matched -/// exactly, so a template keyed `"9 "` reaches none of the sections keyed `"9"` +/// The silent miss `matched` exists for: sections are matched by their ladder +/// rung, so a template keyed at a rung no section carries reaches none of them /// — and it says so with an empty `skipped`, which is the same body a template /// that stocked every section returns. /// -/// Both halves are asserted from the same section, one label apart, because the +/// Both halves are asserted from the same section, one rung apart, because the /// count only means anything against the case that *does* reach it: a `matched` -/// wired to the course list would claim 1 on the typo, and one wired to the -/// skip count would answer 0 on the label that works. +/// wired to the course list would claim 1 on the empty rung, and one wired to +/// the skip count would answer 0 on the rung that works. #[tokio::test] -async fn a_grade_label_nothing_carries_reports_matched_zero() { +async fn a_rung_nothing_carries_reports_matched_zero() { let (app, db) = app_and_db().await; let manager = login_as(&app, &db, "mgr", "manager").await; let algebra = create_course(&app, &manager, "algebra").await; // The section exists first, so a template that finds it stocks it on // create. - let class = create_class(&app, &manager, "9-A", "9").await; + let class = create_class(&app, &manager, "9-A", 9).await; let typo = send( &app, "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9 ", "course_ids": [algebra.clone()] })), + Some(json!({ "grade_level": 11, "course_ids": [algebra.clone()] })), ) .await; assert_eq!(typo.status, StatusCode::CREATED, "{:?}", typo.body); @@ -1024,12 +1049,12 @@ async fn a_grade_label_nothing_carries_reports_matched_zero() { ); assert_eq!( typo.body["matched"], 0, - "no section carries \"9 \", and that must not read as success: {:?}", + "no section sits at 11, and that must not read as success: {:?}", typo.body ); assert!( !attached(&class, &algebra, &db).await, - "a trailing space really is a different grade" + "a rung above the section's really is a different grade" ); let right = send( @@ -1037,7 +1062,7 @@ async fn a_grade_label_nothing_carries_reports_matched_zero() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), ) .await; assert_eq!(right.status, StatusCode::CREATED, "{:?}", right.body); @@ -1074,7 +1099,7 @@ async fn a_status_read_names_the_course_a_section_is_short() { let algebra = create_course(&app, &manager, "algebra").await; // The section starts at grade 10, where nothing stocks it, so the template // below is never what attached anything to it. - let short = create_class(&app, &manager, "9-A", "10").await; + let short = create_class(&app, &manager, "9-A", 10).await; // No template covers the grade yet, and that is a 404 rather than an empty // report — there is nothing to be out of sync with. @@ -1093,7 +1118,7 @@ async fn a_status_read_names_the_course_a_section_is_short() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); @@ -1101,7 +1126,7 @@ async fn a_status_read_names_the_course_a_section_is_short() { assert_eq!(made.body["matched"], 0, "no section carries the label yet"); // A section created at the grade is stocked by its own create, in sync. - let full = create_class(&app, &manager, "9-B", "9").await; + let full = create_class(&app, &manager, "9-B", 9).await; assert!(attached(&full, &algebra, &db).await); // The other section reaches the grade by a rename, which is deliberately @@ -1111,7 +1136,7 @@ async fn a_status_read_names_the_course_a_section_is_short() { "PATCH", &format!("/classes/{short}"), Some(&manager), - Some(json!({ "grade": "9" })), + Some(json!({ "grade_level": 9 })), ) .await; assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body); @@ -1126,7 +1151,7 @@ async fn a_status_read_names_the_course_a_section_is_short() { ) .await; assert_eq!(drifted.status, StatusCode::OK, "{:?}", drifted.body); - assert_eq!(drifted.body["grade"], "9"); + assert_eq!(drifted.body["grade_level"], 9); assert_eq!(drifted.body["matched"], 2, "both sections carry the label"); assert_eq!( missing(&drifted, &short), @@ -1213,14 +1238,14 @@ async fn deleting_a_course_takes_it_out_of_every_blueprint() { // a section that lets its link go is what lets the course be deleted at // all (the guard reads the course's own instance counter, so one still // teaching it is a 409). - let class = create_class(&app, &manager, "9-A", "9").await; + let class = create_class(&app, &manager, "9-A", 9).await; let made = send( &app, "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone(), history.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone(), history.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); @@ -1268,11 +1293,11 @@ async fn deleting_a_course_takes_it_out_of_every_blueprint() { assert_eq!(deleted.status, StatusCode::NO_CONTENT, "{:?}", deleted.body); assert!( - !templated("9", &history, &db).await, + !templated(9, &history, &db).await, "the deleted course is out of the template" ); assert!( - templated("9", &algebra, &db).await, + templated(9, &algebra, &db).await, "…and nothing else is — the sweep names one course" ); assert!( @@ -1336,7 +1361,7 @@ async fn a_grade_with_no_sections_still_loses_its_deleted_course() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "11", "course_ids": [algebra.clone()] })), + Some(json!({ "grade_level": 11, "course_ids": [algebra.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); @@ -1353,7 +1378,7 @@ async fn a_grade_with_no_sections_still_loses_its_deleted_course() { assert_eq!(deleted.status, StatusCode::NO_CONTENT, "{:?}", deleted.body); assert!( - !templated("11", &algebra, &db).await, + !templated(11, &algebra, &db).await, "no section to walk, and the id is gone anyway" ); assert!( @@ -1396,7 +1421,7 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() { let manager = login_as(&app, &db, "mgr", "manager").await; let algebra = create_course(&app, &manager, "algebra").await; let history = create_course(&app, &manager, "history").await; - let class = create_class(&app, &manager, "9-A", "9").await; + let class = create_class(&app, &manager, "9-A", 9).await; let ali = student_in(&app, &db, &class, &manager, "ali").await; let made = send( @@ -1404,7 +1429,7 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone(), history.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone(), history.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); @@ -1415,7 +1440,7 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() { sqlx::query( "DELETE FROM blueprint_course \ WHERE course = $1 \ - AND blueprint = (SELECT id FROM class_blueprint WHERE grade = '9')", + AND blueprint = (SELECT id FROM class_blueprint WHERE grade_level = 9)", ) .bind(CourseId::from_key(&history)) .execute(&db) @@ -1506,7 +1531,7 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() { let manager = login_as(&app, &db, "mgr", "manager").await; let algebra = create_course(&app, &manager, "algebra").await; let history = create_course(&app, &manager, "history").await; - let class = create_class(&app, &manager, "9-A", "9").await; + let class = create_class(&app, &manager, "9-A", 9).await; let mut conn = db.acquire().await.expect("acquire for the trigger"); sqlx::raw_sql(sqlx::AssertSqlSafe(format!( @@ -1527,7 +1552,7 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); @@ -1610,7 +1635,7 @@ async fn a_template_write_refuses_a_course_that_is_gone() { let refused = class_blueprint::create( &db, &by, - ClassBlueprint::grade_key("9").unwrap(), + GradeLevel::new(9).unwrap(), vec![ghost.clone()], ) .await; @@ -1627,7 +1652,7 @@ async fn a_template_write_refuses_a_course_that_is_gone() { let blueprint = class_blueprint::create( &db, &by, - ClassBlueprint::grade_key("9").unwrap(), + GradeLevel::new(9).unwrap(), vec![algebra.clone()], ) .await @@ -1670,15 +1695,15 @@ async fn a_blueprint_removal_unlinks_the_swept_instances_blob_bytes() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); let class = - common::create_class(&app, &manager, "9-A", json!({ "grade": "9", "year": year })).await; + common::create_class(&app, &manager, "9-A", json!({ "grade_level": 9, "year": year })).await; assert_eq!( source_of(&class, &algebra, &db).await, - Some(blueprint_id("9", &db).await), + Some(blueprint_id(9, &db).await), "the create must stock the section from the template" ); let instance = instance_of(&class, &algebra, &db).await; diff --git a/tests/regress_classes.rs b/tests/regress_classes.rs index 3fdcdeb..454e786 100644 --- a/tests/regress_classes.rs +++ b/tests/regress_classes.rs @@ -13,6 +13,7 @@ use common::{ use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use hezarfen_backend::database::Database; use hezarfen_backend::domain::class_group::ClassName; +use hezarfen_backend::domain::grade::GradeLevel; use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; @@ -108,7 +109,7 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() { &db, &manager, ClassName::try_new("9-A").unwrap(), - None, + GradeLevel::new(9).unwrap(), None, None, ) @@ -155,7 +156,7 @@ async fn a_stale_link_detaches_and_frees_its_class() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A" })), + Some(json!({ "name": "9-A", "grade_level": 9 })), ) .await; assert_eq!(res.status, StatusCode::CREATED); @@ -237,7 +238,7 @@ async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A" })), + Some(json!({ "name": "9-A", "grade_level": 9 })), ) .await; res.body["class"]["id"].as_str().unwrap().to_string() @@ -365,7 +366,7 @@ async fn a_hand_enroll_takes_the_row_off_the_class() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A" })), + Some(json!({ "name": "9-A", "grade_level": 9 })), ) .await; res.body["class"]["id"].as_str().unwrap().to_string() @@ -472,7 +473,7 @@ async fn a_role_change_sweeps_memberships_and_enrollments_together() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A" })), + Some(json!({ "name": "9-A", "grade_level": 9 })), ) .await; res.body["class"]["id"].as_str().unwrap().to_string() @@ -573,7 +574,7 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() { &db, &manager, ClassName::try_new("9-A").unwrap(), - None, + GradeLevel::new(9).unwrap(), None, None, ) @@ -654,7 +655,7 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() { &db, &manager, ClassName::try_new("9-A").unwrap(), - None, + GradeLevel::new(9).unwrap(), None, None, ) @@ -708,7 +709,7 @@ async fn a_class_refuses_the_member_past_its_ceiling() { &db, &manager, ClassName::try_new("9-A").unwrap(), - None, + GradeLevel::new(9).unwrap(), None, None, ) @@ -778,7 +779,7 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() { &db, &manager, ClassName::try_new("9-A").unwrap(), - None, + GradeLevel::new(9).unwrap(), None, None, ) @@ -839,7 +840,7 @@ async fn a_class_over_the_course_ceiling_takes_no_member() { &db, &manager, ClassName::try_new("9-B").unwrap(), - None, + GradeLevel::new(9).unwrap(), None, None, ) @@ -881,7 +882,10 @@ async fn a_class_over_the_course_ceiling_takes_no_member() { /// `{class, skipped, stocked_from}` since a create stocks from its grade's /// blueprint, and the tests below are about the class itself. The two outer /// fields have their own tests (`regress_blueprints`). -async fn create_class(app: &axum::Router, cookie: &str, body: serde_json::Value) -> Res { +async fn create_class(app: &axum::Router, cookie: &str, mut body: serde_json::Value) -> Res { + if body.get("grade_level").is_none() { + body["grade_level"] = serde_json::json!(9); + } let mut res = send(app, "POST", "/classes", Some(cookie), Some(body)).await; assert_eq!(res.status, StatusCode::CREATED, "create class"); res.body = res.body["class"].clone(); @@ -912,7 +916,7 @@ async fn the_homeroom_teacher_round_trips_through_create_and_patch() { let created = create_class( &app, &manager, - json!({ "name": "9-A", "teacher_id": teacher_id }), + json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id }), ) .await; let class = created.body["id"].as_str().unwrap().to_string(); @@ -933,7 +937,7 @@ async fn the_homeroom_teacher_round_trips_through_create_and_patch() { "PATCH", &format!("/classes/{class}"), Some(&manager), - Some(json!({ "name": "9-B" })), + Some(json!({ "name": "9-B", "grade_level": 9 })), ) .await; assert_eq!(renamed.status, StatusCode::OK); @@ -1000,7 +1004,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A", "teacher_id": bad })), + Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": bad })), ) .await; assert_eq!(refused.status, StatusCode::BAD_REQUEST, "create with {bad}"); @@ -1011,7 +1015,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() { "a refused create may write no class" ); - let class = create_class(&app, &manager, json!({ "name": "9-A" })) + let class = create_class(&app, &manager, json!({ "name": "9-A", "grade_level": 9 })) .await .body["id"] .as_str() @@ -1023,7 +1027,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() { "PATCH", &format!("/classes/{class}"), Some(&manager), - Some(json!({ "name": "9-B", "teacher_id": bad })), + Some(json!({ "name": "9-B", "grade_level": 9, "teacher_id": bad })), ) .await; assert_eq!(refused.status, StatusCode::BAD_REQUEST, "patch with {bad}"); @@ -1255,7 +1259,7 @@ async fn only_staff_and_a_linked_parent_read_another_users_classes() { let class = create_class( &app, &admin, - json!({ "name": "9-A", "teacher_id": teacher_id }), + json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id }), ) .await .body["id"] @@ -1476,7 +1480,7 @@ async fn a_create_whose_teacher_is_demoted_mid_write_rolls_back_whole() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A", "teacher_id": teacher_id, "year": year })), + Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id, "year": year })), ) .await; @@ -1539,7 +1543,7 @@ async fn a_rolled_back_create_at_a_blueprinted_grade_leaves_nothing_behind() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [course] })), + Some(json!({ "grade_level": 9, "course_ids": [course] })), ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); @@ -1550,7 +1554,7 @@ async fn a_rolled_back_create_at_a_blueprinted_grade_leaves_nothing_behind() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A", "grade": "9", "teacher_id": teacher_id })), + Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id })), ) .await; @@ -1580,7 +1584,7 @@ async fn a_patch_whose_teacher_is_demoted_mid_write_undoes_the_column() { let manager = login_as(&app, &db, "manager", "manager").await; let teacher = login_as(&app, &db, "teacher", "teacher").await; let teacher_id = me_id(&app, &teacher).await; - let class = create_class(&app, &manager, json!({ "name": "9-A" })) + let class = create_class(&app, &manager, json!({ "name": "9-A", "grade_level": 9 })) .await .body["id"] .as_str() @@ -1701,7 +1705,7 @@ async fn a_rollback_the_guard_refuses_is_a_500_not_a_lying_409() { "POST", "/classes", Some(&manager), - Some(json!({ "name": "9-A", "teacher_id": teacher_id })), + Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id })), ) .await; @@ -1737,23 +1741,25 @@ fn names(res: &Res) -> Vec { .collect() } -/// `?grade=` is the read a manager holding a blueprint's skip list needs: which -/// sections carry the label the pump keyed on. It is the *query's* `WHERE`, so -/// `total` counts the filtered set and a window walks that set alone — drop the -/// predicate and every assertion below sees the unfiltered four instead. +/// `?grade_level=` is the read a manager holding a blueprint's skip list +/// needs: which sections carry the rung the pump keyed on. It is the *query's* +/// `WHERE`, so `total` counts the filtered set and a window walks that set +/// alone — drop the predicate and every assertion below sees the unfiltered +/// four instead. #[tokio::test] async fn the_class_index_filters_by_grade() { let (app, db) = app_and_db().await; let manager = login_as(&app, &db, "mgr", "manager").await; - for (name, grade) in [ - ("9-A", "9"), - ("9-B", "9"), - ("10-A", "10"), - // A club-shaped section: created with no grade at all, so its row - // carries no `grade` key. - ("satranc", ""), + for (name, grade_level) in [ + ("9-A", 9), + ("9-B", 9), + ("10-A", 10), + // A club-shaped section: created at the ladder's floor, like every + // class — it just never shares a rung with an ordinary section here. + ("satranc", 0), ] { - create_class(&app, &manager, json!({ "name": name, "grade": grade })).await; + create_class(&app, &manager, json!({ "name": name, "grade_level": grade_level })) + .await; } let list = async |query: &str| -> Res { let res = send( @@ -1778,14 +1784,16 @@ async fn the_class_index_filters_by_grade() { assert_eq!(total(&res.body), 4); assert_eq!(names(&res).len(), 4); - // One label, matched exactly: both sections at it, and a `total` that + // One rung, matched exactly: both sections at it, and a `total` that // counts only them. - let res = list("?grade=9").await; + let res = list("?grade_level=9").await; assert_eq!(total(&res.body), 2, "total counts the filtered set"); assert_eq!(names(&res), ["9-B", "9-A"], "newest first, 9 only"); - // "9" is not a prefix match, a fold, or a trim. - assert_eq!(names(&list("?grade=10").await), ["10-A"]); - for miss in ["?grade=11", "?grade=%209", "?grade=9-A"] { + assert_eq!(names(&list("?grade_level=10").await), ["10-A"]); + // Rungs nobody carries are empty pages, not errors — the integers leave + // no spelling games to play (an unparseable value like `anaokulu` never + // reaches the handler: the query decoder refuses it with a `400`). + for miss in ["?grade_level=11", "?grade_level=12"] { let res = list(miss).await; assert_eq!(total(&res.body), 0, "GET /classes{miss} total"); assert!( @@ -1794,22 +1802,22 @@ async fn the_class_index_filters_by_grade() { ); } - // Empty `?grade=` is *no* grade, the same reading `grade_or_none` gives a - // write — the sections a blueprint can never cover. - let res = list("?grade=").await; + // The floor is a rung like any other: it filters, it does not mean + // "no grade" — no such class exists any more. + let res = list("?grade_level=0").await; assert_eq!((total(&res.body), names(&res)), (1, vec!["satranc".into()])); // Filter and window compose: the window is cut from the filtered set, and // `total` stays that set's size on every page of it. - let first = list("?grade=9&limit=1&offset=0").await; + let first = list("?grade_level=9&limit=1&offset=0").await; assert_eq!(total(&first.body), 2); assert_eq!(names(&first), ["9-B"]); assert_eq!(first.body["limit"], 1); - let second = list("?grade=9&limit=1&offset=1").await; + let second = list("?grade_level=9&limit=1&offset=1").await; assert_eq!(total(&second.body), 2); assert_eq!(names(&second), ["9-A"], "consecutive pages are disjoint"); assert_eq!(second.body["offset"], 1); - let past = list("?grade=9&limit=1&offset=9").await; + let past = list("?grade_level=9&limit=1&offset=9").await; assert!(names(&past).is_empty(), "past the end is an empty page"); assert_eq!( total(&past.body), @@ -1817,12 +1825,12 @@ async fn the_class_index_filters_by_grade() { "…with the filtered total still honest" ); - // A label the write paths would refuse is refused here too, rather than + // A rung the write paths would refuse is refused here too, rather than // reading as "no such grade". let res = send( &app, "GET", - &format!("/classes?grade={}", "9".repeat(21)), + "/classes?grade_level=13", Some(&manager), None, ) @@ -1862,7 +1870,7 @@ async fn a_member_exit_never_hands_a_row_to_a_class_that_is_gone() { &db, &manager, ClassName::try_new(name).unwrap(), - None, + GradeLevel::new(9).unwrap(), None, None, ) @@ -1947,7 +1955,7 @@ async fn an_archived_year_freezes_every_class_write_and_no_read() { let class = create_class( &app, &manager, - json!({ "name": "9-A", "grade": "9", "year": year }), + json!({ "name": "9-A", "grade_level": 9, "year": year }), ) .await; let class = common::id_of(&class.body); @@ -1978,7 +1986,7 @@ async fn an_archived_year_freezes_every_class_write_and_no_read() { "POST", "/classes/blueprints", Some(&manager), - Some(json!({ "grade": "9", "course_ids": [dated] })), + Some(json!({ "grade_level": 9, "course_ids": [dated] })), ) .await; assert_eq!(blueprint.status, StatusCode::CREATED, "blueprint"); @@ -1998,7 +2006,7 @@ async fn an_archived_year_freezes_every_class_write_and_no_read() { ( "PATCH", format!("/classes/{class}"), - Some(json!({ "name": "9-B" })), + Some(json!({ "name": "9-B", "grade_level": 9 })), ), ( "POST", @@ -2082,7 +2090,7 @@ async fn an_archived_year_freezes_every_class_write_and_no_read() { "PATCH", &format!("/classes/{class}"), Some(&manager), - Some(json!({ "name": "9-B" })), + Some(json!({ "name": "9-B", "grade_level": 9 })), ) .await; assert_eq!(patched.status, StatusCode::OK, "thawed: {:?}", patched.body); @@ -2110,14 +2118,14 @@ async fn two_subeler_teaching_one_course_are_two_instances() { let a = create_class( &app, &manager, - json!({ "name": "5-A", "grade": "5", "year": year }), + json!({ "name": "5-A", "grade_level": 5, "year": year }), ) .await; let a = common::id_of(&a.body); let b = create_class( &app, &manager, - json!({ "name": "5-B", "grade": "5", "year": year }), + json!({ "name": "5-B", "grade_level": 5, "year": year }), ) .await; let b = common::id_of(&b.body); diff --git a/tests/regress_course_child_orphans.rs b/tests/regress_course_child_orphans.rs index 17e663b..0dba13f 100644 --- a/tests/regress_course_child_orphans.rs +++ b/tests/regress_course_child_orphans.rs @@ -38,6 +38,7 @@ use hezarfen_backend::db::{ use hezarfen_backend::domain::academic_year::AcademicYearName; use hezarfen_backend::domain::class_course::ClassCourseId; use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName}; +use hezarfen_backend::domain::grade::GradeLevel; use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; use hezarfen_backend::domain::course_note::{CourseNoteContent, CourseNoteTitle}; use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; @@ -155,7 +156,7 @@ async fn fixture(db: &Database) -> Fixture { db, &teacher, ClassName::try_new("9-A").unwrap(), - None, + GradeLevel::new(9).unwrap(), Some(year), None, ) diff --git a/tests/regress_event_class_audience.rs b/tests/regress_event_class_audience.rs index eefa9b4..0a8a7f2 100644 --- a/tests/regress_event_class_audience.rs +++ b/tests/regress_event_class_audience.rs @@ -20,7 +20,7 @@ async fn create_class(app: &Router, cookie: &str, name: &str) -> String { "POST", "/classes", Some(cookie), - Some(json!({"name": name})), + Some(json!({"name": name, "grade_level": 9})), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); diff --git a/tests/regress_profile.rs b/tests/regress_profile.rs index bf7e244..b079f45 100644 --- a/tests/regress_profile.rs +++ b/tests/regress_profile.rs @@ -932,7 +932,7 @@ async fn section() -> Section { let student = login(&app, "kid").await; let student_id = me_id(&app, &student).await; - let class = create_class(&app, &manager, "9-A", "9").await; + let class = create_class(&app, &manager, "9-A", 9).await; add_member(&app, &manager, &class, &student_id).await; link_student(&app, &admin, &parent_id, &student_id).await; @@ -947,13 +947,13 @@ async fn section() -> Section { } } -async fn create_class(app: &Router, manager: &str, name: &str, grade: &str) -> String { +async fn create_class(app: &Router, manager: &str, name: &str, grade_level: i16) -> String { let res = send( app, "POST", "/classes", Some(manager), - Some(json!({ "name": name, "grade": grade })), + Some(json!({ "name": name, "grade_level": grade_level })), ) .await; assert_eq!( @@ -1072,7 +1072,7 @@ async fn teacher_parent_manager_and_the_owner_still_read_the_class_block() { let mine = send(&s.app, "GET", "/users/me/profile", Some(&s.student), None).await; assert_eq!(mine.status, StatusCode::OK, "{}", mine.body); assert_eq!(mine.body["classes"][0]["name"], "9-A"); - assert_eq!(mine.body["classes"][0]["grade"], "9"); + assert_eq!(mine.body["classes"][0]["grade_level"], 9); } /// `stats.classes` is the owner's true total, deliberately *not* the length of diff --git a/tests/regress_review.rs b/tests/regress_review.rs index fc930a1..28f5792 100644 --- a/tests/regress_review.rs +++ b/tests/regress_review.rs @@ -21,7 +21,7 @@ mod common; use axum::http::StatusCode; use common::{ app_and_db, create_exam_with, create_subject, enroll, id_of, login, login_as, me_id, send, - taught_under, ABSENT_ID, + select_instance_subject, taught_under, ABSENT_ID, }; use serde_json::json; @@ -38,6 +38,10 @@ async fn review_hides_the_key_of_a_bank_question_live_under_another_sitting() { let t = taught_under(&app, &mudur, &teacher, "maths").await; let subject = create_subject(&app, &teacher, &t.course, "arithmetic").await; + // The section only tags questions with topics it actually *teaches* — + // the resolved set, not the bare course — so the fixture takes the topic + // onto this section first. + select_instance_subject(&app, &teacher, &t.instance, &subject).await; enroll(&app, &teacher, &t.instance, &student_id).await; // One template, instantiated into both exams below. @@ -226,6 +230,9 @@ async fn review_hides_a_question_banked_out_of_it_and_live_elsewhere() { let t = taught_under(&app, &mudur, &teacher, "physics").await; let subject = create_subject(&app, &teacher, &t.course, "optics").await; + // Same as above: the tag check reads the resolved syllabus, so the + // fixture teaches the topic before tagging with it. + select_instance_subject(&app, &teacher, &t.instance, &subject).await; enroll(&app, &teacher, &t.instance, &student_id).await; let exam = async |title: &str, review: bool| { @@ -397,6 +404,7 @@ async fn a_retake_in_progress_closes_the_students_own_review_reads() { let t = taught_under(&app, &mudur, &teacher, "biology").await; let subject = create_subject(&app, &teacher, &t.course, "cells").await; + select_instance_subject(&app, &teacher, &t.instance, &subject).await; enroll(&app, &teacher, &t.instance, &student_id).await; let res = create_exam_with( &app, @@ -494,6 +502,7 @@ async fn review_stays_shut_while_another_sitting_is_still_available() { let t = taught_under(&app, &mudur, &teacher, "chemistry").await; let subject = create_subject(&app, &teacher, &t.course, "bonds").await; + select_instance_subject(&app, &teacher, &t.instance, &subject).await; enroll(&app, &teacher, &t.instance, &student_id).await; // Unlimited sittings: no amount of finishing exhausts them. let res = create_exam_with( diff --git a/tests/regress_role_sweep.rs b/tests/regress_role_sweep.rs index fbdd95f..c1622bc 100644 --- a/tests/regress_role_sweep.rs +++ b/tests/regress_role_sweep.rs @@ -24,6 +24,7 @@ use hezarfen_backend::database::Database; use hezarfen_backend::db::enrollment; use hezarfen_backend::domain::class_course::ClassCourseId; use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName}; +use hezarfen_backend::domain::grade::GradeLevel; use hezarfen_backend::domain::event::EventId; use hezarfen_backend::domain::role::Role; use hezarfen_backend::domain::timestamp::Timestamp; @@ -385,7 +386,7 @@ async fn a_class_named(name: &str, db: &Database) -> ClassGroupId { db, &manager, ClassName::try_new(name).unwrap(), - None, + GradeLevel::new(9).unwrap(), None, None, ) diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 21e8dd0..1026b8a 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -422,15 +422,27 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { ), ( "CreateClass", - "grade", - "maxLength", - MAX_CLASS_GRADE_LEN as i64, + "grade_level", + "minimum", + MIN_GRADE_LEVEL as i64, + ), + ( + "CreateClass", + "grade_level", + "maximum", + MAX_GRADE_LEVEL as i64, ), ( "CreateBlueprint", - "grade", - "maxLength", - MAX_CLASS_GRADE_LEN as i64, + "grade_level", + "minimum", + MIN_GRADE_LEVEL as i64, + ), + ( + "CreateBlueprint", + "grade_level", + "maximum", + MAX_GRADE_LEVEL as i64, ), ( "UpdateClass", @@ -440,9 +452,15 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { ), ( "UpdateClass", - "grade", - "maxLength", - MAX_CLASS_GRADE_LEN as i64, + "grade_level", + "minimum", + MIN_GRADE_LEVEL as i64, + ), + ( + "UpdateClass", + "grade_level", + "maximum", + MAX_GRADE_LEVEL as i64, ), ( "CreateExamInCourse", @@ -735,6 +753,18 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { ), ("ExamKindDto", "weight", "minimum", MIN_EXAM_KIND_WEIGHT), ("ExamKindDto", "weight", "maximum", MAX_EXAM_KIND_WEIGHT), + ( + "PatchExamWeight", + "weight", + "minimum", + MIN_EXAM_KIND_WEIGHT, + ), + ( + "PatchExamWeight", + "weight", + "maximum", + MAX_EXAM_KIND_WEIGHT, + ), ("GradeBandDto", "min", "minimum", MIN_MARK), ("GradeBandDto", "min", "maximum", MAX_MARK), ( @@ -1121,8 +1151,8 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { ), // --- academic years and the class×course instance (the K12 anchor) --- // A year is named like a term ("2026-2027"), so it shares the term - // name's bound; its two grade labels are şube grades, bounded like - // `CreateClass.grade`. + // name's bound; its two grade fields are şube rungs on the grade + // ladder, bounded like `CreateClass.grade_level`. ( "CreateYear", "name", @@ -1138,19 +1168,61 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { ( "PromotionBody", "from_grade", - "maxLength", - MAX_CLASS_GRADE_LEN as i64, + "minimum", + MIN_GRADE_LEVEL as i64, + ), + ( + "PromotionBody", + "from_grade", + "maximum", + MAX_GRADE_LEVEL as i64, ), ( "PromotionBody", "to_grade", - "maxLength", - MAX_CLASS_GRADE_LEN as i64, + "minimum", + MIN_GRADE_LEVEL as i64, + ), + ( + "PromotionBody", + "to_grade", + "maximum", + MAX_GRADE_LEVEL as i64, ), // The instance's weekly hours: the karne weight, bounded so one // 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 offering spine (course × grade_level templates) and the + // per-class instance overrides: same bounds as the catalog course + // they inherit from. + ("CreateOffering", "grade_level", "minimum", MIN_GRADE_LEVEL as i64), + ("CreateOffering", "grade_level", "maximum", MAX_GRADE_LEVEL as i64), + ("CreateOffering", "title", "maxLength", MAX_COURSE_TITLE_LEN as i64), + ( + "CreateOffering", + "description", + "maxLength", + MAX_COURSE_DESCRIPTION_LEN as i64, + ), + ("CreateOffering", "default_ders_saati", "minimum", MIN_DERS_SAATI), + ("CreateOffering", "default_ders_saati", "maximum", MAX_DERS_SAATI), + ("UpdateOffering", "title", "maxLength", MAX_COURSE_TITLE_LEN as i64), + ( + "UpdateOffering", + "description", + "maxLength", + MAX_COURSE_DESCRIPTION_LEN as i64, + ), + ("UpdateOffering", "default_ders_saati", "minimum", MIN_DERS_SAATI), + ("UpdateOffering", "default_ders_saati", "maximum", MAX_DERS_SAATI), + ("UpdateInstance", "title", "maxLength", MAX_COURSE_TITLE_LEN as i64), + ( + "UpdateInstance", + "description", + "maxLength", + MAX_COURSE_DESCRIPTION_LEN as i64, + ), ] }