Grade-ladder course templates with per-class overrides
Browse files at this commit450bc8c32802abea05546130b0aee876bc779e98Parent: d20043a- feat
- grade-ladder course templates with per-class overrides
141 changed files +10247 -1491
- .sqlx/query-0d43379f5a5659b67aac90cf445d4cec5a553470ca82ed9abe7d8c96426f89e8.json +195 -0
- .sqlx/query-104be5e218ca66359da27921b718bdd2080d1028cac51b4d02c2da17c8801164.json +35 -0
- .sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.json +0 -16
- .sqlx/query-14cec436a7e98559a57cb1d7774f9fe07682ffe64656eb896e5dbdea552e8b68.json +140 -0
- .sqlx/query-c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224.json → .sqlx/query-18985d632ae94316c8d8264120ba6f399e9e872828bbc54476e5e4530e4ff3c1.json +3 -3
- .sqlx/query-1b758d64428adc0646ba71730da548c092d1b2f3e0a04f88c804af7418806ccb.json +131 -0
- .sqlx/query-1e414f1562d1ce9ffecbefc3a59a8ef1e9b997124fbd33f132b1f13de461bc82.json +28 -0
- .sqlx/query-1e86c1b69c7cd6921d5eb58a699fef8aaaa1dccc39fa5013ef8c63cd921eab13.json +15 -0
- .sqlx/query-2075dc47197914af259df4c078864ff391ff866bf6d31b7be0d46b79a3ac8105.json +30 -0
- .sqlx/query-20f46ea5136009f0e249054393e9b0e620016bea2e6948b77bfa5de11cec9a31.json +31 -0
- .sqlx/query-226d8fedbdfff68ad589198c3b5d74d83bc6c46ca3f091a8414971b90b962f4d.json +29 -0
- .sqlx/query-241dacf040e632e2f52a4d880204dd78b17477cef8b90dd3bc4a86f802e6ceeb.json +28 -0
- .sqlx/query-25314c9439acdb33cc922ecfbb01a44966ab7ed9ef418dd84fe2015c37660ff0.json +18 -0
- .sqlx/query-fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee.json → .sqlx/query-300ce2f167cc68e369e3c160d8f92c856cf4cf7ca6e66506edce327c303c16fc.json +7 -7
- .sqlx/query-34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806.json → .sqlx/query-33bbec94bbb7505d5fa5a5f410dc24808b8cd035c6b6701f307b822c6e0f849a.json +6 -6
- .sqlx/query-3a49e0572c8418cd692b7bda75b8ea1bfd4efce1a726282cfb739be6451a0714.json +14 -0
- .sqlx/query-3e9f95bb451cba4b6329f8b668746675840688b5154d1068cf160c27939ea9fb.json +36 -0
- .sqlx/query-43080d91adcc0a8157749588483288588f6d126cb4b3258c7470ee3b7bbc041a.json +16 -0
- .sqlx/query-438ec451416f46f1acf945aa928b5d5e4c1009828660062c0c8a90c31f871bd2.json +24 -0
- .sqlx/query-45c0a9450aa19fa07de87083711413eae6d9a3ab48889a56ece629279f2c156e.json +28 -0
- .sqlx/query-b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681.json → .sqlx/query-493f0cef9fc99fe448ea60cff7490d06dce0779211543a72b1f6f769d9f00ed8.json +6 -6
- .sqlx/query-53ee62a6c31f6ef2484ff5eabf8a67ee265f58c23aeab000e821aa10277500d4.json +198 -0
- .sqlx/query-551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b.json +0 -121
- .sqlx/query-56a731baf00b6a3d69e425c7ae42d449430f363319ce19ab195f2429eb9a5c55.json +139 -0
- .sqlx/query-57ddd7816e29e63fb63429671883aa1520d57597b73bd54ff9a22fb3efb596d3.json +132 -0
- .sqlx/query-5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f.json +0 -119
- .sqlx/query-63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.json +0 -119
- .sqlx/query-6423c5c6d3d4fd79ca2dbe114a576ac6ba2b766dcd148e2a69cbe89ea9af3e8d.json +64 -0
- .sqlx/query-704e608a4d2d4c1e7f7c074fc50aa93dbea4b41fb0aca74bdc7eea4c67516b61.json +30 -0
- .sqlx/query-72e1bd0ea654b5fedc586273f41ac084feae1400c53631f766fbcb8ef5bd280a.json +29 -0
- .sqlx/query-744c8ef425e5e4fe9af88506e0210dcb368c1a315ee6809f8f34e837b7eae57f.json +191 -0
- .sqlx/query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.json → .sqlx/query-7a23cb18cccbbda676484bfcedcb3953c2f44a93f7c597debe56eb6b21ce7fcf.json +3 -3
- .sqlx/query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.json → .sqlx/query-7bb873764f075c33eb5e71d0941255cf0a3cf01b761da187bd50deec4523d60f.json +3 -3
- .sqlx/query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.json → .sqlx/query-80ca84ff3ec8a4ede6d8f9a9ccaedfe02ba5c16d2b9a46646d5649fc1f9fd4fd.json +6 -6
- .sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.json +58 -0
- .sqlx/query-b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59.json → .sqlx/query-85cd8f96075296070428fcbe59a136252078a07cc4b7807788e08b171c8cdf9a.json +7 -7
- .sqlx/query-b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5.json → .sqlx/query-860e57dee5cc91e6477ac1e7650ae4031a4b0a06e9b4e2710b9943252462d7dc.json +6 -6
- .sqlx/query-8613f11afd0f7a09653c3bde7a25b6c98f1aa548e5adf13260939390db5aab0f.json +15 -0
- .sqlx/query-90313888df75e74f326c9731c88340ede5fb34c70b0b0d837a378fe6b92afc94.json +28 -0
- .sqlx/query-92a2fd1dbde98ae6cb59dd691c4efee61e93775bc39519714dc122790a448285.json +15 -0
- .sqlx/query-9f90a0a4125b00161e377a19a73020cd6fd3ea903470e9b153d02352b12118cc.json +191 -0
- .sqlx/query-0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4.json → .sqlx/query-a3db9a0caa7b47888741c892b1bdee2772a3590e71d0e0a23fcecb8dba228e81.json +3 -3
- .sqlx/query-a63cae3c38fc5ab52786505d1944169bab3769effe0dccbed8587f89d788a1f2.json +88 -0
- .sqlx/query-cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7.json → .sqlx/query-a7aed9e7c0d53a5e944ad27f13c7dcc078b9ce93ba209d3b2ca1d16382b62f45.json +3 -2
- .sqlx/query-a8ca6711e03ab03d9d6526c95853c5b62ea7b6ac7f3046b6fd1c784cb5979618.json +36 -0
- .sqlx/query-a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3.json +0 -119
- .sqlx/query-a91d1a048aed0671318c7c2faf3537a93f34014875f1df15279d500f0c2927e7.json +15 -0
- .sqlx/query-ab7ce121deae040653c2886cda93146a6c02d1d932da63f364a78a56dee79eed.json +28 -0
- .sqlx/query-ad70c205e5c81bbb3fb230215a00fbb18af95e8b1bb437b87bd31e38fb804bdc.json +64 -0
- .sqlx/query-b026b654310663a018f93884e2a015ab473efa48671c58ff10f33ed8b89dc803.json +28 -0
- .sqlx/query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.json → .sqlx/query-b3e310ca3331217df9d486461ce82cb568bbcfcb88386270920f3eb6579a526e.json +6 -6
- .sqlx/query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.json +54 -0
- .sqlx/query-bd186c14f1a5c0dc4b4f7fb543ebd4484136dd6aa75069f987075137e1b99b00.json +16 -0
- .sqlx/query-d692aa84085905ea3e70d4a94b5e81ff85548c6aeb096ee914d5349bf525137a.json +131 -0
- .sqlx/query-d863a8f429da502da7981c356a262f553ea0b23b4fd1569241119aac0f8d62cc.json +36 -0
- .sqlx/query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.json +58 -0
- .sqlx/query-e0876982733c62617ab8446239526f4da6f49846a4e7ee948a173ef54aafed1a.json +191 -0
- .sqlx/query-e17820680b6881ea134fe37906611bc25d774d21850be124025fda552104867b.json +35 -0
- .sqlx/query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.json +54 -0
- .sqlx/query-e6c03c7c747131bd9060a3f8a8eff1cf34e8727b6c3ac7222620b87b0dc1eeb1.json +23 -0
- .sqlx/query-5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b.json → .sqlx/query-e8784821e75fe4ab681ff91695d953af6c4abd32821251f7804ef02c4e637cf8.json +3 -3
- .sqlx/query-eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e.json +0 -88
- .sqlx/query-b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f.json → .sqlx/query-f0638db11ad696e78ee6a72951c1983881eafa5fafeb80813293bd778717080f.json +6 -6
- .sqlx/query-f085293284bed3226150271a91561f7c1d3953b66c413aa1b0f0349fa350f8ab.json +35 -0
- .sqlx/query-f46c1dcb86e2a1a7a542afaed21054de776315e010bfd709f5408df7259ed02b.json +31 -0
- README.md +55 -15
- src/constant.rs +25 -5
- src/db/class_blueprint.rs +29 -29
- src/db/class_course.rs +143 -42
- src/db/class_group.rs +39 -42
- src/db/class_member.rs +4 -3
- src/db/class_pump.rs +95 -28
- src/db/course.rs +2 -2
- src/db/course_offering.rs +429 -0
- src/db/course_session.rs +1 -1
- src/db/event.rs +1 -1
- src/db/exam.rs +1 -1
- src/db/exam_result.rs +7 -6
- src/db/exam_weight.rs +239 -0
- src/db/mod.rs +4 -0
- src/db/offering_subject.rs +244 -0
- src/db/weekly_slot.rs +275 -0
- src/domain/academic_year.rs +35 -34
- src/domain/class_blueprint.rs +51 -61
- src/domain/class_course.rs +108 -14
- src/domain/class_group.rs +16 -27
- src/domain/course_offering.rs +120 -0
- src/domain/exam_question.rs +4 -2
- src/domain/exam_weight.rs +81 -0
- src/domain/grade.rs +89 -0
- src/domain/homework.rs +8 -0
- src/domain/mod.rs +5 -0
- src/domain/offering_subject.rs +82 -0
- src/domain/weekly_slot.rs +297 -0
- src/lib.rs +51 -4
- src/service/academic_year.rs +16 -11
- src/service/class_blueprint.rs +14 -17
- src/service/class_course.rs +156 -17
- src/service/class_group.rs +10 -9
- src/service/course_offering.rs +95 -0
- src/service/exam.rs +1 -1
- src/service/exam_weight.rs +404 -0
- src/service/homework.rs +9 -0
- src/service/instance_resolve.rs +185 -0
- src/service/karne.rs +94 -35
- src/service/mod.rs +5 -0
- src/service/offering_subject.rs +470 -0
- src/service/rag_scope.rs +23 -15
- src/service/subject.rs +31 -5
- src/service/weekly_slot.rs +479 -0
- src/web/academic_years.rs +16 -11
- src/web/attendance.rs +15 -1
- src/web/classes.rs +137 -132
- src/web/courses.rs +5 -0
- src/web/exam_weights.rs +368 -0
- src/web/exams/questions.rs +21 -17
- src/web/homework.rs +6 -4
- src/web/instances.rs +186 -33
- src/web/limits.rs +26 -3
- src/web/marks.rs +40 -12
- src/web/mod.rs +5 -1
- src/web/offering_subjects.rs +317 -0
- src/web/offerings.rs +376 -0
- src/web/users.rs +8 -3
- src/web/weekly_plan.rs +371 -0
- tests/ai_bridge.rs +4 -2
- tests/board_invite.rs +1 -1
- tests/common/mod.rs +119 -16
- tests/e2e.rs +47 -5
- tests/integration.rs +487 -14
- tests/pagination.rs +1 -1
- tests/partial_patch_terms.rs +1 -1
- tests/persistence.rs +6 -1
- tests/regress_blueprints.rs +105 -80
- tests/regress_classes.rs +62 -54
- tests/regress_course_child_orphans.rs +2 -1
- tests/regress_event_class_audience.rs +1 -1
- tests/regress_profile.rs +4 -4
- tests/regress_review.rs +10 -1
- tests/regress_role_sweep.rs +2 -1
- tests/spec_bounds.rs +87 -15
.sqlx/query-0d43379f5a5659b67aac90cf445d4cec5a553470ca82ed9abe7d8c96426f89e8.jsonadded+195 -0
| @@ -0,0 +1,195 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassCourseId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "class: ClassGroupId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "class_course", | ||
| 24 | + "name": "class" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "course: CourseId", | ||
| 31 | + "type_info": "Uuid", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "class_course", | ||
| 35 | + "name": "course" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "offering: CourseOfferingId", | ||
| 42 | + "type_info": "Uuid", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "class_course", | ||
| 46 | + "name": "offering" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "attached_by: UserId", | ||
| 53 | + "type_info": "Uuid", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "class_course", | ||
| 57 | + "name": "attached_by" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "source?: ClassBlueprintId", | ||
| 64 | + "type_info": "Int2", | ||
| 65 | + "origin": { | ||
| 66 | + "Table": { | ||
| 67 | + "table": "class_blueprint", | ||
| 68 | + "name": "grade_level" | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | + }, | ||
| 72 | + { | ||
| 73 | + "ordinal": 6, | ||
| 74 | + "name": "title?: CourseTitle", | ||
| 75 | + "type_info": "Text", | ||
| 76 | + "origin": { | ||
| 77 | + "Table": { | ||
| 78 | + "table": "class_course", | ||
| 79 | + "name": "title" | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + }, | ||
| 83 | + { | ||
| 84 | + "ordinal": 7, | ||
| 85 | + "name": "description?: CourseDescription", | ||
| 86 | + "type_info": "Text", | ||
| 87 | + "origin": { | ||
| 88 | + "Table": { | ||
| 89 | + "table": "class_course", | ||
| 90 | + "name": "description" | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + }, | ||
| 94 | + { | ||
| 95 | + "ordinal": 8, | ||
| 96 | + "name": "ders_saati?: DersSaati", | ||
| 97 | + "type_info": "Int8", | ||
| 98 | + "origin": "Expression" | ||
| 99 | + }, | ||
| 100 | + { | ||
| 101 | + "ordinal": 9, | ||
| 102 | + "name": "counts_toward_karne", | ||
| 103 | + "type_info": "Bool", | ||
| 104 | + "origin": { | ||
| 105 | + "Table": { | ||
| 106 | + "table": "class_course", | ||
| 107 | + "name": "counts_toward_karne" | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + }, | ||
| 111 | + { | ||
| 112 | + "ordinal": 10, | ||
| 113 | + "name": "subjects_inherited", | ||
| 114 | + "type_info": "Bool", | ||
| 115 | + "origin": { | ||
| 116 | + "Table": { | ||
| 117 | + "table": "class_course", | ||
| 118 | + "name": "subjects_inherited" | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + }, | ||
| 122 | + { | ||
| 123 | + "ordinal": 11, | ||
| 124 | + "name": "exam_weights_inherited", | ||
| 125 | + "type_info": "Bool", | ||
| 126 | + "origin": { | ||
| 127 | + "Table": { | ||
| 128 | + "table": "class_course", | ||
| 129 | + "name": "exam_weights_inherited" | ||
| 130 | + } | ||
| 131 | + } | ||
| 132 | + }, | ||
| 133 | + { | ||
| 134 | + "ordinal": 12, | ||
| 135 | + "name": "weekly_plan_inherited", | ||
| 136 | + "type_info": "Bool", | ||
| 137 | + "origin": { | ||
| 138 | + "Table": { | ||
| 139 | + "table": "class_course", | ||
| 140 | + "name": "weekly_plan_inherited" | ||
| 141 | + } | ||
| 142 | + } | ||
| 143 | + }, | ||
| 144 | + { | ||
| 145 | + "ordinal": 13, | ||
| 146 | + "name": "enrollment_count", | ||
| 147 | + "type_info": "Int8", | ||
| 148 | + "origin": { | ||
| 149 | + "Table": { | ||
| 150 | + "table": "class_course", | ||
| 151 | + "name": "enrollment_count" | ||
| 152 | + } | ||
| 153 | + } | ||
| 154 | + }, | ||
| 155 | + { | ||
| 156 | + "ordinal": 14, | ||
| 157 | + "name": "attached_at: Timestamp", | ||
| 158 | + "type_info": "Int8", | ||
| 159 | + "origin": { | ||
| 160 | + "Table": { | ||
| 161 | + "table": "class_course", | ||
| 162 | + "name": "attached_at" | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + } | ||
| 166 | + ], | ||
| 167 | + "parameters": { | ||
| 168 | + "Left": [ | ||
| 169 | + "Uuid", | ||
| 170 | + "Text", | ||
| 171 | + "Text", | ||
| 172 | + "Int8", | ||
| 173 | + "Bool" | ||
| 174 | + ] | ||
| 175 | + }, | ||
| 176 | + "nullable": [ | ||
| 177 | + false, | ||
| 178 | + false, | ||
| 179 | + false, | ||
| 180 | + false, | ||
| 181 | + false, | ||
| 182 | + true, | ||
| 183 | + true, | ||
| 184 | + true, | ||
| 185 | + null, | ||
| 186 | + true, | ||
| 187 | + false, | ||
| 188 | + false, | ||
| 189 | + false, | ||
| 190 | + false, | ||
| 191 | + false | ||
| 192 | + ] | ||
| 193 | + }, | ||
| 194 | + "hash": "0d43379f5a5659b67aac90cf445d4cec5a553470ca82ed9abe7d8c96426f89e8" | ||
| 195 | +} | ||
.sqlx/query-104be5e218ca66359da27921b718bdd2080d1028cac51b4d02c2da17c8801164.jsonadded+35 -0
| @@ -0,0 +1,35 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT default_ders_saati::bigint AS \"default_ders_saati?: DersSaati\",\n default_counts_toward_karne\n FROM course_offering WHERE id = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "default_ders_saati?: DersSaati", | ||
| 9 | + "type_info": "Int8", | ||
| 10 | + "origin": "Expression" | ||
| 11 | + }, | ||
| 12 | + { | ||
| 13 | + "ordinal": 1, | ||
| 14 | + "name": "default_counts_toward_karne", | ||
| 15 | + "type_info": "Bool", | ||
| 16 | + "origin": { | ||
| 17 | + "Table": { | ||
| 18 | + "table": "course_offering", | ||
| 19 | + "name": "default_counts_toward_karne" | ||
| 20 | + } | ||
| 21 | + } | ||
| 22 | + } | ||
| 23 | + ], | ||
| 24 | + "parameters": { | ||
| 25 | + "Left": [ | ||
| 26 | + "Uuid" | ||
| 27 | + ] | ||
| 28 | + }, | ||
| 29 | + "nullable": [ | ||
| 30 | + null, | ||
| 31 | + true | ||
| 32 | + ] | ||
| 33 | + }, | ||
| 34 | + "hash": "104be5e218ca66359da27921b718bdd2080d1028cac51b4d02c2da17c8801164" | ||
| 35 | +} | ||
.sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.jsondeleted+0 -16
| @@ -1,16 +0,0 @@ | |||
| 1 | -{ | ||
| 2 | - "db_name": "PostgreSQL", | ||
| 3 | - "query": "INSERT INTO class_blueprint (id, grade, creator)\n VALUES ($1, $2, $3)", | ||
| 4 | - "describe": { | ||
| 5 | - "columns": [], | ||
| 6 | - "parameters": { | ||
| 7 | - "Left": [ | ||
| 8 | - "Uuid", | ||
| 9 | - "Text", | ||
| 10 | - "Uuid" | ||
| 11 | - ] | ||
| 12 | - }, | ||
| 13 | - "nullable": [] | ||
| 14 | - }, | ||
| 15 | - "hash": "13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730" | ||
| 16 | -} | ||
.sqlx/query-14cec436a7e98559a57cb1d7774f9fe07682ffe64656eb896e5dbdea552e8b68.jsonadded+140 -0
| @@ -0,0 +1,140 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: CourseOfferingId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "course_offering", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "course: CourseId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "course_offering", | ||
| 24 | + "name": "course" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "grade_level: GradeLevel", | ||
| 31 | + "type_info": "Int2", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "course_offering", | ||
| 35 | + "name": "grade_level" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "title?: CourseTitle", | ||
| 42 | + "type_info": "Text", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "course_offering", | ||
| 46 | + "name": "title" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "description?: CourseDescription", | ||
| 53 | + "type_info": "Text", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "course_offering", | ||
| 57 | + "name": "description" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "default_ders_saati?: DersSaati", | ||
| 64 | + "type_info": "Int8", | ||
| 65 | + "origin": "Expression" | ||
| 66 | + }, | ||
| 67 | + { | ||
| 68 | + "ordinal": 6, | ||
| 69 | + "name": "default_counts_toward_karne", | ||
| 70 | + "type_info": "Bool", | ||
| 71 | + "origin": { | ||
| 72 | + "Table": { | ||
| 73 | + "table": "course_offering", | ||
| 74 | + "name": "default_counts_toward_karne" | ||
| 75 | + } | ||
| 76 | + } | ||
| 77 | + }, | ||
| 78 | + { | ||
| 79 | + "ordinal": 7, | ||
| 80 | + "name": "created_by: UserId", | ||
| 81 | + "type_info": "Uuid", | ||
| 82 | + "origin": { | ||
| 83 | + "Table": { | ||
| 84 | + "table": "course_offering", | ||
| 85 | + "name": "created_by" | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + }, | ||
| 89 | + { | ||
| 90 | + "ordinal": 8, | ||
| 91 | + "name": "created_at: Timestamp", | ||
| 92 | + "type_info": "Int8", | ||
| 93 | + "origin": { | ||
| 94 | + "Table": { | ||
| 95 | + "table": "course_offering", | ||
| 96 | + "name": "created_at" | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + }, | ||
| 100 | + { | ||
| 101 | + "ordinal": 9, | ||
| 102 | + "name": "updated_at: Timestamp", | ||
| 103 | + "type_info": "Int8", | ||
| 104 | + "origin": { | ||
| 105 | + "Table": { | ||
| 106 | + "table": "course_offering", | ||
| 107 | + "name": "updated_at" | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | + ], | ||
| 112 | + "parameters": { | ||
| 113 | + "Left": [ | ||
| 114 | + "Uuid", | ||
| 115 | + "Bool", | ||
| 116 | + "Text", | ||
| 117 | + "Bool", | ||
| 118 | + "Text", | ||
| 119 | + "Bool", | ||
| 120 | + "Int8", | ||
| 121 | + "Bool", | ||
| 122 | + "Bool", | ||
| 123 | + "Int8" | ||
| 124 | + ] | ||
| 125 | + }, | ||
| 126 | + "nullable": [ | ||
| 127 | + false, | ||
| 128 | + false, | ||
| 129 | + false, | ||
| 130 | + true, | ||
| 131 | + true, | ||
| 132 | + null, | ||
| 133 | + true, | ||
| 134 | + false, | ||
| 135 | + false, | ||
| 136 | + false | ||
| 137 | + ] | ||
| 138 | + }, | ||
| 139 | + "hash": "14cec436a7e98559a57cb1d7774f9fe07682ffe64656eb896e5dbdea552e8b68" | ||
| 140 | +} | ||
.sqlx/query-c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224.json → .sqlx/query-18985d632ae94316c8d8264120ba6f399e9e872828bbc54476e5e4530e4ff3c1.jsonrenamed+3 -3
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "SELECT id FROM class_blueprint WHERE grade = $1 FOR KEY SHARE", | 3 | + "query": "SELECT id FROM class_blueprint WHERE grade_level = $1 FOR KEY SHARE", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -17,12 +17,12 @@ | |||
| 17 | ], | 17 | ], |
| 18 | "parameters": { | 18 | "parameters": { |
| 19 | "Left": [ | 19 | "Left": [ |
| 20 | - "Text" | 20 | + "Int2" |
| 21 | ] | 21 | ] |
| 22 | }, | 22 | }, |
| 23 | "nullable": [ | 23 | "nullable": [ |
| 24 | false | 24 | false |
| 25 | ] | 25 | ] |
| 26 | }, | 26 | }, |
| 27 | - "hash": "c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224" | 27 | + "hash": "18985d632ae94316c8d8264120ba6f399e9e872828bbc54476e5e4530e4ff3c1" |
| 28 | } | 28 | } |
.sqlx/query-1b758d64428adc0646ba71730da548c092d1b2f3e0a04f88c804af7418806ccb.jsonadded+131 -0
| @@ -0,0 +1,131 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: CourseOfferingId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "course_offering", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "course: CourseId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "course_offering", | ||
| 24 | + "name": "course" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "grade_level: GradeLevel", | ||
| 31 | + "type_info": "Int2", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "course_offering", | ||
| 35 | + "name": "grade_level" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "title?: CourseTitle", | ||
| 42 | + "type_info": "Text", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "course_offering", | ||
| 46 | + "name": "title" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "description?: CourseDescription", | ||
| 53 | + "type_info": "Text", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "course_offering", | ||
| 57 | + "name": "description" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "default_ders_saati?: DersSaati", | ||
| 64 | + "type_info": "Int8", | ||
| 65 | + "origin": "Expression" | ||
| 66 | + }, | ||
| 67 | + { | ||
| 68 | + "ordinal": 6, | ||
| 69 | + "name": "default_counts_toward_karne", | ||
| 70 | + "type_info": "Bool", | ||
| 71 | + "origin": { | ||
| 72 | + "Table": { | ||
| 73 | + "table": "course_offering", | ||
| 74 | + "name": "default_counts_toward_karne" | ||
| 75 | + } | ||
| 76 | + } | ||
| 77 | + }, | ||
| 78 | + { | ||
| 79 | + "ordinal": 7, | ||
| 80 | + "name": "created_by: UserId", | ||
| 81 | + "type_info": "Uuid", | ||
| 82 | + "origin": { | ||
| 83 | + "Table": { | ||
| 84 | + "table": "course_offering", | ||
| 85 | + "name": "created_by" | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + }, | ||
| 89 | + { | ||
| 90 | + "ordinal": 8, | ||
| 91 | + "name": "created_at: Timestamp", | ||
| 92 | + "type_info": "Int8", | ||
| 93 | + "origin": { | ||
| 94 | + "Table": { | ||
| 95 | + "table": "course_offering", | ||
| 96 | + "name": "created_at" | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + }, | ||
| 100 | + { | ||
| 101 | + "ordinal": 9, | ||
| 102 | + "name": "updated_at: Timestamp", | ||
| 103 | + "type_info": "Int8", | ||
| 104 | + "origin": { | ||
| 105 | + "Table": { | ||
| 106 | + "table": "course_offering", | ||
| 107 | + "name": "updated_at" | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | + ], | ||
| 112 | + "parameters": { | ||
| 113 | + "Left": [ | ||
| 114 | + "Uuid" | ||
| 115 | + ] | ||
| 116 | + }, | ||
| 117 | + "nullable": [ | ||
| 118 | + false, | ||
| 119 | + false, | ||
| 120 | + false, | ||
| 121 | + true, | ||
| 122 | + true, | ||
| 123 | + null, | ||
| 124 | + true, | ||
| 125 | + false, | ||
| 126 | + false, | ||
| 127 | + false | ||
| 128 | + ] | ||
| 129 | + }, | ||
| 130 | + "hash": "1b758d64428adc0646ba71730da548c092d1b2f3e0a04f88c804af7418806ccb" | ||
| 131 | +} | ||
.sqlx/query-1e414f1562d1ce9ffecbefc3a59a8ef1e9b997124fbd33f132b1f13de461bc82.jsonadded+28 -0
| @@ -0,0 +1,28 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassCourseId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "parameters": { | ||
| 19 | + "Left": [ | ||
| 20 | + "Uuid" | ||
| 21 | + ] | ||
| 22 | + }, | ||
| 23 | + "nullable": [ | ||
| 24 | + false | ||
| 25 | + ] | ||
| 26 | + }, | ||
| 27 | + "hash": "1e414f1562d1ce9ffecbefc3a59a8ef1e9b997124fbd33f132b1f13de461bc82" | ||
| 28 | +} | ||
.sqlx/query-1e86c1b69c7cd6921d5eb58a699fef8aaaa1dccc39fa5013ef8c63cd921eab13.jsonadded+15 -0
| @@ -0,0 +1,15 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "DELETE FROM offering_exam_weight WHERE offering = $1 AND kind = $2", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid", | ||
| 9 | + "Text" | ||
| 10 | + ] | ||
| 11 | + }, | ||
| 12 | + "nullable": [] | ||
| 13 | + }, | ||
| 14 | + "hash": "1e86c1b69c7cd6921d5eb58a699fef8aaaa1dccc39fa5013ef8c63cd921eab13" | ||
| 15 | +} | ||
.sqlx/query-2075dc47197914af259df4c078864ff391ff866bf6d31b7be0d46b79a3ac8105.jsonadded+30 -0
| @@ -0,0 +1,30 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassCourseId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "parameters": { | ||
| 19 | + "Left": [ | ||
| 20 | + "Uuid", | ||
| 21 | + "Text", | ||
| 22 | + "Int8" | ||
| 23 | + ] | ||
| 24 | + }, | ||
| 25 | + "nullable": [ | ||
| 26 | + false | ||
| 27 | + ] | ||
| 28 | + }, | ||
| 29 | + "hash": "2075dc47197914af259df4c078864ff391ff866bf6d31b7be0d46b79a3ac8105" | ||
| 30 | +} | ||
.sqlx/query-20f46ea5136009f0e249054393e9b0e620016bea2e6948b77bfa5de11cec9a31.jsonadded+31 -0
| @@ -0,0 +1,31 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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!\"", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "live!", | ||
| 9 | + "type_info": "Bool", | ||
| 10 | + "origin": "Expression" | ||
| 11 | + }, | ||
| 12 | + { | ||
| 13 | + "ordinal": 1, | ||
| 14 | + "name": "dropped!", | ||
| 15 | + "type_info": "Bool", | ||
| 16 | + "origin": "Expression" | ||
| 17 | + } | ||
| 18 | + ], | ||
| 19 | + "parameters": { | ||
| 20 | + "Left": [ | ||
| 21 | + "Uuid", | ||
| 22 | + "Uuid" | ||
| 23 | + ] | ||
| 24 | + }, | ||
| 25 | + "nullable": [ | ||
| 26 | + null, | ||
| 27 | + null | ||
| 28 | + ] | ||
| 29 | + }, | ||
| 30 | + "hash": "20f46ea5136009f0e249054393e9b0e620016bea2e6948b77bfa5de11cec9a31" | ||
| 31 | +} | ||
.sqlx/query-226d8fedbdfff68ad589198c3b5d74d83bc6c46ca3f091a8414971b90b962f4d.jsonadded+29 -0
| @@ -0,0 +1,29 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT id AS \"id: CourseOfferingId\" FROM course_offering\n WHERE course = $1 AND grade_level = $2", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: CourseOfferingId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "course_offering", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "parameters": { | ||
| 19 | + "Left": [ | ||
| 20 | + "Uuid", | ||
| 21 | + "Int2" | ||
| 22 | + ] | ||
| 23 | + }, | ||
| 24 | + "nullable": [ | ||
| 25 | + false | ||
| 26 | + ] | ||
| 27 | + }, | ||
| 28 | + "hash": "226d8fedbdfff68ad589198c3b5d74d83bc6c46ca3f091a8414971b90b962f4d" | ||
| 29 | +} | ||
.sqlx/query-241dacf040e632e2f52a4d880204dd78b17477cef8b90dd3bc4a86f802e6ceeb.jsonadded+28 -0
| @@ -0,0 +1,28 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT id AS \"id: ClassCourseId\" FROM class_course WHERE id = $1\n FOR NO KEY UPDATE", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassCourseId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "parameters": { | ||
| 19 | + "Left": [ | ||
| 20 | + "Uuid" | ||
| 21 | + ] | ||
| 22 | + }, | ||
| 23 | + "nullable": [ | ||
| 24 | + false | ||
| 25 | + ] | ||
| 26 | + }, | ||
| 27 | + "hash": "241dacf040e632e2f52a4d880204dd78b17477cef8b90dd3bc4a86f802e6ceeb" | ||
| 28 | +} | ||
.sqlx/query-25314c9439acdb33cc922ecfbb01a44966ab7ed9ef418dd84fe2015c37660ff0.jsonadded+18 -0
| @@ -0,0 +1,18 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid", | ||
| 9 | + "Uuid", | ||
| 10 | + "Int2", | ||
| 11 | + "Uuid", | ||
| 12 | + "Int8" | ||
| 13 | + ] | ||
| 14 | + }, | ||
| 15 | + "nullable": [] | ||
| 16 | + }, | ||
| 17 | + "hash": "25314c9439acdb33cc922ecfbb01a44966ab7ed9ef418dd84fe2015c37660ff0" | ||
| 18 | +} | ||
.sqlx/query-fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee.json → .sqlx/query-300ce2f167cc68e369e3c160d8f92c856cf4cf7ca6e66506edce327c303c16fc.jsonrenamed+7 -7
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "INSERT INTO class_group (id, creator, name, grade, year, teacher)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"", | 3 | + "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\"", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -38,12 +38,12 @@ | |||
| 38 | }, | 38 | }, |
| 39 | { | 39 | { |
| 40 | "ordinal": 3, | 40 | "ordinal": 3, |
| 41 | - "name": "grade: ClassGrade", | 41 | + "name": "grade_level: GradeLevel", |
| 42 | - "type_info": "Text", | 42 | + "type_info": "Int2", |
| 43 | "origin": { | 43 | "origin": { |
| 44 | "Table": { | 44 | "Table": { |
| 45 | "table": "class_group", | 45 | "table": "class_group", |
| 46 | - "name": "grade" | 46 | + "name": "grade_level" |
| 47 | } | 47 | } |
| 48 | } | 48 | } |
| 49 | }, | 49 | }, |
| @@ -75,7 +75,7 @@ | |||
| 75 | "Uuid", | 75 | "Uuid", |
| 76 | "Uuid", | 76 | "Uuid", |
| 77 | "Text", | 77 | "Text", |
| 78 | - "Text", | 78 | + "Int2", |
| 79 | "Uuid", | 79 | "Uuid", |
| 80 | "Uuid" | 80 | "Uuid" |
| 81 | ] | 81 | ] |
| @@ -84,10 +84,10 @@ | |||
| 84 | false, | 84 | false, |
| 85 | false, | 85 | false, |
| 86 | false, | 86 | false, |
| 87 | - true, | 87 | + false, |
| 88 | true, | 88 | true, |
| 89 | true | 89 | true |
| 90 | ] | 90 | ] |
| 91 | }, | 91 | }, |
| 92 | - "hash": "fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee" | 92 | + "hash": "300ce2f167cc68e369e3c160d8f92c856cf4cf7ca6e66506edce327c303c16fc" |
| 93 | } | 93 | } |
.sqlx/query-34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806.json → .sqlx/query-33bbec94bbb7505d5fa5a5f410dc24808b8cd035c6b6701f307b822c6e0f849a.jsonrenamed+6 -6
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = ANY($1)", | 3 | + "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)", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -38,12 +38,12 @@ | |||
| 38 | }, | 38 | }, |
| 39 | { | 39 | { |
| 40 | "ordinal": 3, | 40 | "ordinal": 3, |
| 41 | - "name": "grade: ClassGrade", | 41 | + "name": "grade_level: GradeLevel", |
| 42 | - "type_info": "Text", | 42 | + "type_info": "Int2", |
| 43 | "origin": { | 43 | "origin": { |
| 44 | "Table": { | 44 | "Table": { |
| 45 | "table": "class_group", | 45 | "table": "class_group", |
| 46 | - "name": "grade" | 46 | + "name": "grade_level" |
| 47 | } | 47 | } |
| 48 | } | 48 | } |
| 49 | }, | 49 | }, |
| @@ -79,10 +79,10 @@ | |||
| 79 | false, | 79 | false, |
| 80 | false, | 80 | false, |
| 81 | false, | 81 | false, |
| 82 | - true, | 82 | + false, |
| 83 | true, | 83 | true, |
| 84 | true | 84 | true |
| 85 | ] | 85 | ] |
| 86 | }, | 86 | }, |
| 87 | - "hash": "34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806" | 87 | + "hash": "33bbec94bbb7505d5fa5a5f410dc24808b8cd035c6b6701f307b822c6e0f849a" |
| 88 | } | 88 | } |
.sqlx/query-3a49e0572c8418cd692b7bda75b8ea1bfd4efce1a726282cfb739be6451a0714.jsonadded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "DELETE FROM course_offering\n WHERE id = $1\n AND NOT EXISTS (SELECT 1 FROM class_course cc WHERE cc.offering = $1)", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid" | ||
| 9 | + ] | ||
| 10 | + }, | ||
| 11 | + "nullable": [] | ||
| 12 | + }, | ||
| 13 | + "hash": "3a49e0572c8418cd692b7bda75b8ea1bfd4efce1a726282cfb739be6451a0714" | ||
| 14 | +} | ||
.sqlx/query-3e9f95bb451cba4b6329f8b668746675840688b5154d1068cf160c27939ea9fb.jsonadded+36 -0
| @@ -0,0 +1,36 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "inherited: bool", | ||
| 9 | + "type_info": "Bool", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "exam_weights_inherited" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "removed!: i64", | ||
| 20 | + "type_info": "Int8", | ||
| 21 | + "origin": "Expression" | ||
| 22 | + } | ||
| 23 | + ], | ||
| 24 | + "parameters": { | ||
| 25 | + "Left": [ | ||
| 26 | + "Uuid", | ||
| 27 | + "Text" | ||
| 28 | + ] | ||
| 29 | + }, | ||
| 30 | + "nullable": [ | ||
| 31 | + false, | ||
| 32 | + null | ||
| 33 | + ] | ||
| 34 | + }, | ||
| 35 | + "hash": "3e9f95bb451cba4b6329f8b668746675840688b5154d1068cf160c27939ea9fb" | ||
| 36 | +} | ||
.sqlx/query-43080d91adcc0a8157749588483288588f6d126cb4b3258c7470ee3b7bbc041a.jsonadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "INSERT INTO class_blueprint (id, grade_level, creator)\n VALUES ($1, $2, $3)", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid", | ||
| 9 | + "Int2", | ||
| 10 | + "Uuid" | ||
| 11 | + ] | ||
| 12 | + }, | ||
| 13 | + "nullable": [] | ||
| 14 | + }, | ||
| 15 | + "hash": "43080d91adcc0a8157749588483288588f6d126cb4b3258c7470ee3b7bbc041a" | ||
| 16 | +} | ||
.sqlx/query-438ec451416f46f1acf945aa928b5d5e4c1009828660062c0c8a90c31f871bd2.jsonadded+24 -0
| @@ -0,0 +1,24 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "member!", | ||
| 9 | + "type_info": "Bool", | ||
| 10 | + "origin": "Expression" | ||
| 11 | + } | ||
| 12 | + ], | ||
| 13 | + "parameters": { | ||
| 14 | + "Left": [ | ||
| 15 | + "Uuid", | ||
| 16 | + "Uuid" | ||
| 17 | + ] | ||
| 18 | + }, | ||
| 19 | + "nullable": [ | ||
| 20 | + null | ||
| 21 | + ] | ||
| 22 | + }, | ||
| 23 | + "hash": "438ec451416f46f1acf945aa928b5d5e4c1009828660062c0c8a90c31f871bd2" | ||
| 24 | +} | ||
.sqlx/query-45c0a9450aa19fa07de87083711413eae6d9a3ab48889a56ece629279f2c156e.jsonadded+28 -0
| @@ -0,0 +1,28 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassCourseId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "parameters": { | ||
| 19 | + "Left": [ | ||
| 20 | + "Uuid" | ||
| 21 | + ] | ||
| 22 | + }, | ||
| 23 | + "nullable": [ | ||
| 24 | + false | ||
| 25 | + ] | ||
| 26 | + }, | ||
| 27 | + "hash": "45c0a9450aa19fa07de87083711413eae6d9a3ab48889a56ece629279f2c156e" | ||
| 28 | +} | ||
.sqlx/query-b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681.json → .sqlx/query-493f0cef9fc99fe448ea60cff7490d06dce0779211543a72b1f6f769d9f00ed8.jsonrenamed+6 -6
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE teacher = $1 ORDER BY id DESC", | 3 | + "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", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -38,12 +38,12 @@ | |||
| 38 | }, | 38 | }, |
| 39 | { | 39 | { |
| 40 | "ordinal": 3, | 40 | "ordinal": 3, |
| 41 | - "name": "grade: ClassGrade", | 41 | + "name": "grade_level: GradeLevel", |
| 42 | - "type_info": "Text", | 42 | + "type_info": "Int2", |
| 43 | "origin": { | 43 | "origin": { |
| 44 | "Table": { | 44 | "Table": { |
| 45 | "table": "class_group", | 45 | "table": "class_group", |
| 46 | - "name": "grade" | 46 | + "name": "grade_level" |
| 47 | } | 47 | } |
| 48 | } | 48 | } |
| 49 | }, | 49 | }, |
| @@ -79,10 +79,10 @@ | |||
| 79 | false, | 79 | false, |
| 80 | false, | 80 | false, |
| 81 | false, | 81 | false, |
| 82 | - true, | 82 | + false, |
| 83 | true, | 83 | true, |
| 84 | true | 84 | true |
| 85 | ] | 85 | ] |
| 86 | }, | 86 | }, |
| 87 | - "hash": "b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681" | 87 | + "hash": "493f0cef9fc99fe448ea60cff7490d06dce0779211543a72b1f6f769d9f00ed8" |
| 88 | } | 88 | } |
.sqlx/query-53ee62a6c31f6ef2484ff5eabf8a67ee265f58c23aeab000e821aa10277500d4.jsonadded+198 -0
| @@ -0,0 +1,198 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassCourseId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "class: ClassGroupId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "class_course", | ||
| 24 | + "name": "class" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "course: CourseId", | ||
| 31 | + "type_info": "Uuid", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "class_course", | ||
| 35 | + "name": "course" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "offering: CourseOfferingId", | ||
| 42 | + "type_info": "Uuid", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "class_course", | ||
| 46 | + "name": "offering" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "attached_by: UserId", | ||
| 53 | + "type_info": "Uuid", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "class_course", | ||
| 57 | + "name": "attached_by" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "source?: ClassBlueprintId", | ||
| 64 | + "type_info": "Int2", | ||
| 65 | + "origin": { | ||
| 66 | + "Table": { | ||
| 67 | + "table": "class_blueprint", | ||
| 68 | + "name": "grade_level" | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | + }, | ||
| 72 | + { | ||
| 73 | + "ordinal": 6, | ||
| 74 | + "name": "title?: CourseTitle", | ||
| 75 | + "type_info": "Text", | ||
| 76 | + "origin": { | ||
| 77 | + "Table": { | ||
| 78 | + "table": "class_course", | ||
| 79 | + "name": "title" | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + }, | ||
| 83 | + { | ||
| 84 | + "ordinal": 7, | ||
| 85 | + "name": "description?: CourseDescription", | ||
| 86 | + "type_info": "Text", | ||
| 87 | + "origin": { | ||
| 88 | + "Table": { | ||
| 89 | + "table": "class_course", | ||
| 90 | + "name": "description" | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + }, | ||
| 94 | + { | ||
| 95 | + "ordinal": 8, | ||
| 96 | + "name": "ders_saati?: DersSaati", | ||
| 97 | + "type_info": "Int8", | ||
| 98 | + "origin": "Expression" | ||
| 99 | + }, | ||
| 100 | + { | ||
| 101 | + "ordinal": 9, | ||
| 102 | + "name": "counts_toward_karne", | ||
| 103 | + "type_info": "Bool", | ||
| 104 | + "origin": { | ||
| 105 | + "Table": { | ||
| 106 | + "table": "class_course", | ||
| 107 | + "name": "counts_toward_karne" | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + }, | ||
| 111 | + { | ||
| 112 | + "ordinal": 10, | ||
| 113 | + "name": "subjects_inherited", | ||
| 114 | + "type_info": "Bool", | ||
| 115 | + "origin": { | ||
| 116 | + "Table": { | ||
| 117 | + "table": "class_course", | ||
| 118 | + "name": "subjects_inherited" | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + }, | ||
| 122 | + { | ||
| 123 | + "ordinal": 11, | ||
| 124 | + "name": "exam_weights_inherited", | ||
| 125 | + "type_info": "Bool", | ||
| 126 | + "origin": { | ||
| 127 | + "Table": { | ||
| 128 | + "table": "class_course", | ||
| 129 | + "name": "exam_weights_inherited" | ||
| 130 | + } | ||
| 131 | + } | ||
| 132 | + }, | ||
| 133 | + { | ||
| 134 | + "ordinal": 12, | ||
| 135 | + "name": "weekly_plan_inherited", | ||
| 136 | + "type_info": "Bool", | ||
| 137 | + "origin": { | ||
| 138 | + "Table": { | ||
| 139 | + "table": "class_course", | ||
| 140 | + "name": "weekly_plan_inherited" | ||
| 141 | + } | ||
| 142 | + } | ||
| 143 | + }, | ||
| 144 | + { | ||
| 145 | + "ordinal": 13, | ||
| 146 | + "name": "enrollment_count", | ||
| 147 | + "type_info": "Int8", | ||
| 148 | + "origin": { | ||
| 149 | + "Table": { | ||
| 150 | + "table": "class_course", | ||
| 151 | + "name": "enrollment_count" | ||
| 152 | + } | ||
| 153 | + } | ||
| 154 | + }, | ||
| 155 | + { | ||
| 156 | + "ordinal": 14, | ||
| 157 | + "name": "attached_at: Timestamp", | ||
| 158 | + "type_info": "Int8", | ||
| 159 | + "origin": { | ||
| 160 | + "Table": { | ||
| 161 | + "table": "class_course", | ||
| 162 | + "name": "attached_at" | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + } | ||
| 166 | + ], | ||
| 167 | + "parameters": { | ||
| 168 | + "Left": [ | ||
| 169 | + "Uuid", | ||
| 170 | + "Bool", | ||
| 171 | + "Bool", | ||
| 172 | + "Bool", | ||
| 173 | + "Bool", | ||
| 174 | + "Bool", | ||
| 175 | + "Bool", | ||
| 176 | + "Bool" | ||
| 177 | + ] | ||
| 178 | + }, | ||
| 179 | + "nullable": [ | ||
| 180 | + false, | ||
| 181 | + false, | ||
| 182 | + false, | ||
| 183 | + false, | ||
| 184 | + false, | ||
| 185 | + true, | ||
| 186 | + true, | ||
| 187 | + true, | ||
| 188 | + null, | ||
| 189 | + true, | ||
| 190 | + false, | ||
| 191 | + false, | ||
| 192 | + false, | ||
| 193 | + false, | ||
| 194 | + false | ||
| 195 | + ] | ||
| 196 | + }, | ||
| 197 | + "hash": "53ee62a6c31f6ef2484ff5eabf8a67ee265f58c23aeab000e821aa10277500d4" | ||
| 198 | +} | ||
.sqlx/query-551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b.jsondeleted+0 -121
| @@ -1,121 +0,0 @@ | |||
| 1 | -{ | ||
| 2 | - "db_name": "PostgreSQL", | ||
| 3 | - "query": "WITH updated AS (\n UPDATE class_course\n SET ders_saati = COALESCE($2::bigint, ders_saati::bigint)::smallint,\n counts_toward_karne = COALESCE($3, counts_toward_karne)\n WHERE id = $1\n RETURNING *)\n SELECT u.id AS \"id: ClassCourseId\", u.class AS \"class: ClassGroupId\",\n u.course AS \"course: CourseId\", u.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n u.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n u.counts_toward_karne, u.enrollment_count,\n u.attached_at AS \"attached_at: Timestamp\"\n FROM updated u\n LEFT JOIN class_blueprint b ON b.id = u.source", | ||
| 4 | - "describe": { | ||
| 5 | - "columns": [ | ||
| 6 | - { | ||
| 7 | - "ordinal": 0, | ||
| 8 | - "name": "id: ClassCourseId", | ||
| 9 | - "type_info": "Uuid", | ||
| 10 | - "origin": { | ||
| 11 | - "Table": { | ||
| 12 | - "table": "class_course", | ||
| 13 | - "name": "id" | ||
| 14 | - } | ||
| 15 | - } | ||
| 16 | - }, | ||
| 17 | - { | ||
| 18 | - "ordinal": 1, | ||
| 19 | - "name": "class: ClassGroupId", | ||
| 20 | - "type_info": "Uuid", | ||
| 21 | - "origin": { | ||
| 22 | - "Table": { | ||
| 23 | - "table": "class_course", | ||
| 24 | - "name": "class" | ||
| 25 | - } | ||
| 26 | - } | ||
| 27 | - }, | ||
| 28 | - { | ||
| 29 | - "ordinal": 2, | ||
| 30 | - "name": "course: CourseId", | ||
| 31 | - "type_info": "Uuid", | ||
| 32 | - "origin": { | ||
| 33 | - "Table": { | ||
| 34 | - "table": "class_course", | ||
| 35 | - "name": "course" | ||
| 36 | - } | ||
| 37 | - } | ||
| 38 | - }, | ||
| 39 | - { | ||
| 40 | - "ordinal": 3, | ||
| 41 | - "name": "attached_by: UserId", | ||
| 42 | - "type_info": "Uuid", | ||
| 43 | - "origin": { | ||
| 44 | - "Table": { | ||
| 45 | - "table": "class_course", | ||
| 46 | - "name": "attached_by" | ||
| 47 | - } | ||
| 48 | - } | ||
| 49 | - }, | ||
| 50 | - { | ||
| 51 | - "ordinal": 4, | ||
| 52 | - "name": "source?: ClassBlueprintId", | ||
| 53 | - "type_info": "Text", | ||
| 54 | - "origin": { | ||
| 55 | - "Table": { | ||
| 56 | - "table": "class_blueprint", | ||
| 57 | - "name": "grade" | ||
| 58 | - } | ||
| 59 | - } | ||
| 60 | - }, | ||
| 61 | - { | ||
| 62 | - "ordinal": 5, | ||
| 63 | - "name": "ders_saati!: DersSaati", | ||
| 64 | - "type_info": "Int8", | ||
| 65 | - "origin": "Expression" | ||
| 66 | - }, | ||
| 67 | - { | ||
| 68 | - "ordinal": 6, | ||
| 69 | - "name": "counts_toward_karne", | ||
| 70 | - "type_info": "Bool", | ||
| 71 | - "origin": { | ||
| 72 | - "Table": { | ||
| 73 | - "table": "class_course", | ||
| 74 | - "name": "counts_toward_karne" | ||
| 75 | - } | ||
| 76 | - } | ||
| 77 | - }, | ||
| 78 | - { | ||
| 79 | - "ordinal": 7, | ||
| 80 | - "name": "enrollment_count", | ||
| 81 | - "type_info": "Int8", | ||
| 82 | - "origin": { | ||
| 83 | - "Table": { | ||
| 84 | - "table": "class_course", | ||
| 85 | - "name": "enrollment_count" | ||
| 86 | - } | ||
| 87 | - } | ||
| 88 | - }, | ||
| 89 | - { | ||
| 90 | - "ordinal": 8, | ||
| 91 | - "name": "attached_at: Timestamp", | ||
| 92 | - "type_info": "Int8", | ||
| 93 | - "origin": { | ||
| 94 | - "Table": { | ||
| 95 | - "table": "class_course", | ||
| 96 | - "name": "attached_at" | ||
| 97 | - } | ||
| 98 | - } | ||
| 99 | - } | ||
| 100 | - ], | ||
| 101 | - "parameters": { | ||
| 102 | - "Left": [ | ||
| 103 | - "Uuid", | ||
| 104 | - "Int8", | ||
| 105 | - "Bool" | ||
| 106 | - ] | ||
| 107 | - }, | ||
| 108 | - "nullable": [ | ||
| 109 | - false, | ||
| 110 | - false, | ||
| 111 | - false, | ||
| 112 | - false, | ||
| 113 | - true, | ||
| 114 | - null, | ||
| 115 | - false, | ||
| 116 | - false, | ||
| 117 | - false | ||
| 118 | - ] | ||
| 119 | - }, | ||
| 120 | - "hash": "551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b" | ||
| 121 | -} | ||
.sqlx/query-56a731baf00b6a3d69e425c7ae42d449430f363319ce19ab195f2429eb9a5c55.jsonadded+139 -0
| @@ -0,0 +1,139 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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\"", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: CourseOfferingId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "course_offering", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "course: CourseId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "course_offering", | ||
| 24 | + "name": "course" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "grade_level: GradeLevel", | ||
| 31 | + "type_info": "Int2", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "course_offering", | ||
| 35 | + "name": "grade_level" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "title?: CourseTitle", | ||
| 42 | + "type_info": "Text", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "course_offering", | ||
| 46 | + "name": "title" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "description?: CourseDescription", | ||
| 53 | + "type_info": "Text", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "course_offering", | ||
| 57 | + "name": "description" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "default_ders_saati?: DersSaati", | ||
| 64 | + "type_info": "Int8", | ||
| 65 | + "origin": "Expression" | ||
| 66 | + }, | ||
| 67 | + { | ||
| 68 | + "ordinal": 6, | ||
| 69 | + "name": "default_counts_toward_karne", | ||
| 70 | + "type_info": "Bool", | ||
| 71 | + "origin": { | ||
| 72 | + "Table": { | ||
| 73 | + "table": "course_offering", | ||
| 74 | + "name": "default_counts_toward_karne" | ||
| 75 | + } | ||
| 76 | + } | ||
| 77 | + }, | ||
| 78 | + { | ||
| 79 | + "ordinal": 7, | ||
| 80 | + "name": "created_by: UserId", | ||
| 81 | + "type_info": "Uuid", | ||
| 82 | + "origin": { | ||
| 83 | + "Table": { | ||
| 84 | + "table": "course_offering", | ||
| 85 | + "name": "created_by" | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + }, | ||
| 89 | + { | ||
| 90 | + "ordinal": 8, | ||
| 91 | + "name": "created_at: Timestamp", | ||
| 92 | + "type_info": "Int8", | ||
| 93 | + "origin": { | ||
| 94 | + "Table": { | ||
| 95 | + "table": "course_offering", | ||
| 96 | + "name": "created_at" | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + }, | ||
| 100 | + { | ||
| 101 | + "ordinal": 9, | ||
| 102 | + "name": "updated_at: Timestamp", | ||
| 103 | + "type_info": "Int8", | ||
| 104 | + "origin": { | ||
| 105 | + "Table": { | ||
| 106 | + "table": "course_offering", | ||
| 107 | + "name": "updated_at" | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | + ], | ||
| 112 | + "parameters": { | ||
| 113 | + "Left": [ | ||
| 114 | + "Uuid", | ||
| 115 | + "Uuid", | ||
| 116 | + "Int2", | ||
| 117 | + "Text", | ||
| 118 | + "Text", | ||
| 119 | + "Int8", | ||
| 120 | + "Bool", | ||
| 121 | + "Uuid", | ||
| 122 | + "Int8" | ||
| 123 | + ] | ||
| 124 | + }, | ||
| 125 | + "nullable": [ | ||
| 126 | + false, | ||
| 127 | + false, | ||
| 128 | + false, | ||
| 129 | + true, | ||
| 130 | + true, | ||
| 131 | + null, | ||
| 132 | + true, | ||
| 133 | + false, | ||
| 134 | + false, | ||
| 135 | + false | ||
| 136 | + ] | ||
| 137 | + }, | ||
| 138 | + "hash": "56a731baf00b6a3d69e425c7ae42d449430f363319ce19ab195f2429eb9a5c55" | ||
| 139 | +} | ||
.sqlx/query-57ddd7816e29e63fb63429671883aa1520d57597b73bd54ff9a22fb3efb596d3.jsonadded+132 -0
| @@ -0,0 +1,132 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: CourseOfferingId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "course_offering", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "course: CourseId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "course_offering", | ||
| 24 | + "name": "course" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "grade_level: GradeLevel", | ||
| 31 | + "type_info": "Int2", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "course_offering", | ||
| 35 | + "name": "grade_level" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "title?: CourseTitle", | ||
| 42 | + "type_info": "Text", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "course_offering", | ||
| 46 | + "name": "title" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "description?: CourseDescription", | ||
| 53 | + "type_info": "Text", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "course_offering", | ||
| 57 | + "name": "description" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "default_ders_saati?: DersSaati", | ||
| 64 | + "type_info": "Int8", | ||
| 65 | + "origin": "Expression" | ||
| 66 | + }, | ||
| 67 | + { | ||
| 68 | + "ordinal": 6, | ||
| 69 | + "name": "default_counts_toward_karne", | ||
| 70 | + "type_info": "Bool", | ||
| 71 | + "origin": { | ||
| 72 | + "Table": { | ||
| 73 | + "table": "course_offering", | ||
| 74 | + "name": "default_counts_toward_karne" | ||
| 75 | + } | ||
| 76 | + } | ||
| 77 | + }, | ||
| 78 | + { | ||
| 79 | + "ordinal": 7, | ||
| 80 | + "name": "created_by: UserId", | ||
| 81 | + "type_info": "Uuid", | ||
| 82 | + "origin": { | ||
| 83 | + "Table": { | ||
| 84 | + "table": "course_offering", | ||
| 85 | + "name": "created_by" | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + }, | ||
| 89 | + { | ||
| 90 | + "ordinal": 8, | ||
| 91 | + "name": "created_at: Timestamp", | ||
| 92 | + "type_info": "Int8", | ||
| 93 | + "origin": { | ||
| 94 | + "Table": { | ||
| 95 | + "table": "course_offering", | ||
| 96 | + "name": "created_at" | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + }, | ||
| 100 | + { | ||
| 101 | + "ordinal": 9, | ||
| 102 | + "name": "updated_at: Timestamp", | ||
| 103 | + "type_info": "Int8", | ||
| 104 | + "origin": { | ||
| 105 | + "Table": { | ||
| 106 | + "table": "course_offering", | ||
| 107 | + "name": "updated_at" | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | + ], | ||
| 112 | + "parameters": { | ||
| 113 | + "Left": [ | ||
| 114 | + "Uuid", | ||
| 115 | + "Int2" | ||
| 116 | + ] | ||
| 117 | + }, | ||
| 118 | + "nullable": [ | ||
| 119 | + false, | ||
| 120 | + false, | ||
| 121 | + false, | ||
| 122 | + true, | ||
| 123 | + true, | ||
| 124 | + null, | ||
| 125 | + true, | ||
| 126 | + false, | ||
| 127 | + false, | ||
| 128 | + false | ||
| 129 | + ] | ||
| 130 | + }, | ||
| 131 | + "hash": "57ddd7816e29e63fb63429671883aa1520d57597b73bd54ff9a22fb3efb596d3" | ||
| 132 | +} | ||
.sqlx/query-5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f.jsondeleted+0 -119
| @@ -1,119 +0,0 @@ | |||
| 1 | -{ | ||
| 2 | - "db_name": "PostgreSQL", | ||
| 3 | - "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.id = ANY($1)\n ORDER BY cc.attached_at DESC, cc.id DESC", | ||
| 4 | - "describe": { | ||
| 5 | - "columns": [ | ||
| 6 | - { | ||
| 7 | - "ordinal": 0, | ||
| 8 | - "name": "id: ClassCourseId", | ||
| 9 | - "type_info": "Uuid", | ||
| 10 | - "origin": { | ||
| 11 | - "Table": { | ||
| 12 | - "table": "class_course", | ||
| 13 | - "name": "id" | ||
| 14 | - } | ||
| 15 | - } | ||
| 16 | - }, | ||
| 17 | - { | ||
| 18 | - "ordinal": 1, | ||
| 19 | - "name": "class: ClassGroupId", | ||
| 20 | - "type_info": "Uuid", | ||
| 21 | - "origin": { | ||
| 22 | - "Table": { | ||
| 23 | - "table": "class_course", | ||
| 24 | - "name": "class" | ||
| 25 | - } | ||
| 26 | - } | ||
| 27 | - }, | ||
| 28 | - { | ||
| 29 | - "ordinal": 2, | ||
| 30 | - "name": "course: CourseId", | ||
| 31 | - "type_info": "Uuid", | ||
| 32 | - "origin": { | ||
| 33 | - "Table": { | ||
| 34 | - "table": "class_course", | ||
| 35 | - "name": "course" | ||
| 36 | - } | ||
| 37 | - } | ||
| 38 | - }, | ||
| 39 | - { | ||
| 40 | - "ordinal": 3, | ||
| 41 | - "name": "attached_by: UserId", | ||
| 42 | - "type_info": "Uuid", | ||
| 43 | - "origin": { | ||
| 44 | - "Table": { | ||
| 45 | - "table": "class_course", | ||
| 46 | - "name": "attached_by" | ||
| 47 | - } | ||
| 48 | - } | ||
| 49 | - }, | ||
| 50 | - { | ||
| 51 | - "ordinal": 4, | ||
| 52 | - "name": "source?: ClassBlueprintId", | ||
| 53 | - "type_info": "Text", | ||
| 54 | - "origin": { | ||
| 55 | - "Table": { | ||
| 56 | - "table": "class_blueprint", | ||
| 57 | - "name": "grade" | ||
| 58 | - } | ||
| 59 | - } | ||
| 60 | - }, | ||
| 61 | - { | ||
| 62 | - "ordinal": 5, | ||
| 63 | - "name": "ders_saati!: DersSaati", | ||
| 64 | - "type_info": "Int8", | ||
| 65 | - "origin": "Expression" | ||
| 66 | - }, | ||
| 67 | - { | ||
| 68 | - "ordinal": 6, | ||
| 69 | - "name": "counts_toward_karne", | ||
| 70 | - "type_info": "Bool", | ||
| 71 | - "origin": { | ||
| 72 | - "Table": { | ||
| 73 | - "table": "class_course", | ||
| 74 | - "name": "counts_toward_karne" | ||
| 75 | - } | ||
| 76 | - } | ||
| 77 | - }, | ||
| 78 | - { | ||
| 79 | - "ordinal": 7, | ||
| 80 | - "name": "enrollment_count", | ||
| 81 | - "type_info": "Int8", | ||
| 82 | - "origin": { | ||
| 83 | - "Table": { | ||
| 84 | - "table": "class_course", | ||
| 85 | - "name": "enrollment_count" | ||
| 86 | - } | ||
| 87 | - } | ||
| 88 | - }, | ||
| 89 | - { | ||
| 90 | - "ordinal": 8, | ||
| 91 | - "name": "attached_at: Timestamp", | ||
| 92 | - "type_info": "Int8", | ||
| 93 | - "origin": { | ||
| 94 | - "Table": { | ||
| 95 | - "table": "class_course", | ||
| 96 | - "name": "attached_at" | ||
| 97 | - } | ||
| 98 | - } | ||
| 99 | - } | ||
| 100 | - ], | ||
| 101 | - "parameters": { | ||
| 102 | - "Left": [ | ||
| 103 | - "UuidArray" | ||
| 104 | - ] | ||
| 105 | - }, | ||
| 106 | - "nullable": [ | ||
| 107 | - false, | ||
| 108 | - false, | ||
| 109 | - false, | ||
| 110 | - false, | ||
| 111 | - false, | ||
| 112 | - null, | ||
| 113 | - false, | ||
| 114 | - false, | ||
| 115 | - false | ||
| 116 | - ] | ||
| 117 | - }, | ||
| 118 | - "hash": "5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f" | ||
| 119 | -} | ||
.sqlx/query-63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.jsondeleted+0 -119
| @@ -1,119 +0,0 @@ | |||
| 1 | -{ | ||
| 2 | - "db_name": "PostgreSQL", | ||
| 3 | - "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.class = ANY($1)\n ORDER BY cc.attached_at DESC, cc.id DESC", | ||
| 4 | - "describe": { | ||
| 5 | - "columns": [ | ||
| 6 | - { | ||
| 7 | - "ordinal": 0, | ||
| 8 | - "name": "id: ClassCourseId", | ||
| 9 | - "type_info": "Uuid", | ||
| 10 | - "origin": { | ||
| 11 | - "Table": { | ||
| 12 | - "table": "class_course", | ||
| 13 | - "name": "id" | ||
| 14 | - } | ||
| 15 | - } | ||
| 16 | - }, | ||
| 17 | - { | ||
| 18 | - "ordinal": 1, | ||
| 19 | - "name": "class: ClassGroupId", | ||
| 20 | - "type_info": "Uuid", | ||
| 21 | - "origin": { | ||
| 22 | - "Table": { | ||
| 23 | - "table": "class_course", | ||
| 24 | - "name": "class" | ||
| 25 | - } | ||
| 26 | - } | ||
| 27 | - }, | ||
| 28 | - { | ||
| 29 | - "ordinal": 2, | ||
| 30 | - "name": "course: CourseId", | ||
| 31 | - "type_info": "Uuid", | ||
| 32 | - "origin": { | ||
| 33 | - "Table": { | ||
| 34 | - "table": "class_course", | ||
| 35 | - "name": "course" | ||
| 36 | - } | ||
| 37 | - } | ||
| 38 | - }, | ||
| 39 | - { | ||
| 40 | - "ordinal": 3, | ||
| 41 | - "name": "attached_by: UserId", | ||
| 42 | - "type_info": "Uuid", | ||
| 43 | - "origin": { | ||
| 44 | - "Table": { | ||
| 45 | - "table": "class_course", | ||
| 46 | - "name": "attached_by" | ||
| 47 | - } | ||
| 48 | - } | ||
| 49 | - }, | ||
| 50 | - { | ||
| 51 | - "ordinal": 4, | ||
| 52 | - "name": "source?: ClassBlueprintId", | ||
| 53 | - "type_info": "Text", | ||
| 54 | - "origin": { | ||
| 55 | - "Table": { | ||
| 56 | - "table": "class_blueprint", | ||
| 57 | - "name": "grade" | ||
| 58 | - } | ||
| 59 | - } | ||
| 60 | - }, | ||
| 61 | - { | ||
| 62 | - "ordinal": 5, | ||
| 63 | - "name": "ders_saati!: DersSaati", | ||
| 64 | - "type_info": "Int8", | ||
| 65 | - "origin": "Expression" | ||
| 66 | - }, | ||
| 67 | - { | ||
| 68 | - "ordinal": 6, | ||
| 69 | - "name": "counts_toward_karne", | ||
| 70 | - "type_info": "Bool", | ||
| 71 | - "origin": { | ||
| 72 | - "Table": { | ||
| 73 | - "table": "class_course", | ||
| 74 | - "name": "counts_toward_karne" | ||
| 75 | - } | ||
| 76 | - } | ||
| 77 | - }, | ||
| 78 | - { | ||
| 79 | - "ordinal": 7, | ||
| 80 | - "name": "enrollment_count", | ||
| 81 | - "type_info": "Int8", | ||
| 82 | - "origin": { | ||
| 83 | - "Table": { | ||
| 84 | - "table": "class_course", | ||
| 85 | - "name": "enrollment_count" | ||
| 86 | - } | ||
| 87 | - } | ||
| 88 | - }, | ||
| 89 | - { | ||
| 90 | - "ordinal": 8, | ||
| 91 | - "name": "attached_at: Timestamp", | ||
| 92 | - "type_info": "Int8", | ||
| 93 | - "origin": { | ||
| 94 | - "Table": { | ||
| 95 | - "table": "class_course", | ||
| 96 | - "name": "attached_at" | ||
| 97 | - } | ||
| 98 | - } | ||
| 99 | - } | ||
| 100 | - ], | ||
| 101 | - "parameters": { | ||
| 102 | - "Left": [ | ||
| 103 | - "UuidArray" | ||
| 104 | - ] | ||
| 105 | - }, | ||
| 106 | - "nullable": [ | ||
| 107 | - false, | ||
| 108 | - false, | ||
| 109 | - false, | ||
| 110 | - false, | ||
| 111 | - false, | ||
| 112 | - null, | ||
| 113 | - false, | ||
| 114 | - false, | ||
| 115 | - false | ||
| 116 | - ] | ||
| 117 | - }, | ||
| 118 | - "hash": "63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414" | ||
| 119 | -} | ||
.sqlx/query-6423c5c6d3d4fd79ca2dbe114a576ac6ba2b766dcd148e2a69cbe89ea9af3e8d.jsonadded+64 -0
| @@ -0,0 +1,64 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: SubjectId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "subject", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "course: CourseId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "subject", | ||
| 24 | + "name": "course" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "name: SubjectName", | ||
| 31 | + "type_info": "Text", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "subject", | ||
| 35 | + "name": "name" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "description: SubjectDescription", | ||
| 42 | + "type_info": "Text", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "subject", | ||
| 46 | + "name": "description" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + } | ||
| 50 | + ], | ||
| 51 | + "parameters": { | ||
| 52 | + "Left": [ | ||
| 53 | + "Uuid" | ||
| 54 | + ] | ||
| 55 | + }, | ||
| 56 | + "nullable": [ | ||
| 57 | + false, | ||
| 58 | + false, | ||
| 59 | + false, | ||
| 60 | + false | ||
| 61 | + ] | ||
| 62 | + }, | ||
| 63 | + "hash": "6423c5c6d3d4fd79ca2dbe114a576ac6ba2b766dcd148e2a69cbe89ea9af3e8d" | ||
| 64 | +} | ||
.sqlx/query-704e608a4d2d4c1e7f7c074fc50aa93dbea4b41fb0aca74bdc7eea4c67516b61.jsonadded+30 -0
| @@ -0,0 +1,30 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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!\"", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "swept!: i64", | ||
| 9 | + "type_info": "Int8", | ||
| 10 | + "origin": "Expression" | ||
| 11 | + }, | ||
| 12 | + { | ||
| 13 | + "ordinal": 1, | ||
| 14 | + "name": "live!", | ||
| 15 | + "type_info": "Bool", | ||
| 16 | + "origin": "Expression" | ||
| 17 | + } | ||
| 18 | + ], | ||
| 19 | + "parameters": { | ||
| 20 | + "Left": [ | ||
| 21 | + "Uuid" | ||
| 22 | + ] | ||
| 23 | + }, | ||
| 24 | + "nullable": [ | ||
| 25 | + null, | ||
| 26 | + null | ||
| 27 | + ] | ||
| 28 | + }, | ||
| 29 | + "hash": "704e608a4d2d4c1e7f7c074fc50aa93dbea4b41fb0aca74bdc7eea4c67516b61" | ||
| 30 | +} | ||
.sqlx/query-72e1bd0ea654b5fedc586273f41ac084feae1400c53631f766fbcb8ef5bd280a.jsonadded+29 -0
| @@ -0,0 +1,29 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassCourseId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "parameters": { | ||
| 19 | + "Left": [ | ||
| 20 | + "Uuid", | ||
| 21 | + "Uuid" | ||
| 22 | + ] | ||
| 23 | + }, | ||
| 24 | + "nullable": [ | ||
| 25 | + false | ||
| 26 | + ] | ||
| 27 | + }, | ||
| 28 | + "hash": "72e1bd0ea654b5fedc586273f41ac084feae1400c53631f766fbcb8ef5bd280a" | ||
| 29 | +} | ||
.sqlx/query-744c8ef425e5e4fe9af88506e0210dcb368c1a315ee6809f8f34e837b7eae57f.jsonadded+191 -0
| @@ -0,0 +1,191 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.offering AS \"offering: CourseOfferingId\",\n cc.attached_by AS \"attached_by: UserId\",\n b.grade_level AS \"source?: ClassBlueprintId\",\n cc.title AS \"title?: CourseTitle\",\n cc.description AS \"description?: CourseDescription\",\n cc.ders_saati::bigint AS \"ders_saati?: DersSaati\",\n cc.counts_toward_karne,\n cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,\n cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.id = ANY($1)\n ORDER BY cc.attached_at DESC, cc.id DESC", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassCourseId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "class: ClassGroupId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "class_course", | ||
| 24 | + "name": "class" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "course: CourseId", | ||
| 31 | + "type_info": "Uuid", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "class_course", | ||
| 35 | + "name": "course" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "offering: CourseOfferingId", | ||
| 42 | + "type_info": "Uuid", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "class_course", | ||
| 46 | + "name": "offering" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "attached_by: UserId", | ||
| 53 | + "type_info": "Uuid", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "class_course", | ||
| 57 | + "name": "attached_by" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "source?: ClassBlueprintId", | ||
| 64 | + "type_info": "Int2", | ||
| 65 | + "origin": { | ||
| 66 | + "Table": { | ||
| 67 | + "table": "class_blueprint", | ||
| 68 | + "name": "grade_level" | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | + }, | ||
| 72 | + { | ||
| 73 | + "ordinal": 6, | ||
| 74 | + "name": "title?: CourseTitle", | ||
| 75 | + "type_info": "Text", | ||
| 76 | + "origin": { | ||
| 77 | + "Table": { | ||
| 78 | + "table": "class_course", | ||
| 79 | + "name": "title" | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + }, | ||
| 83 | + { | ||
| 84 | + "ordinal": 7, | ||
| 85 | + "name": "description?: CourseDescription", | ||
| 86 | + "type_info": "Text", | ||
| 87 | + "origin": { | ||
| 88 | + "Table": { | ||
| 89 | + "table": "class_course", | ||
| 90 | + "name": "description" | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + }, | ||
| 94 | + { | ||
| 95 | + "ordinal": 8, | ||
| 96 | + "name": "ders_saati?: DersSaati", | ||
| 97 | + "type_info": "Int8", | ||
| 98 | + "origin": "Expression" | ||
| 99 | + }, | ||
| 100 | + { | ||
| 101 | + "ordinal": 9, | ||
| 102 | + "name": "counts_toward_karne", | ||
| 103 | + "type_info": "Bool", | ||
| 104 | + "origin": { | ||
| 105 | + "Table": { | ||
| 106 | + "table": "class_course", | ||
| 107 | + "name": "counts_toward_karne" | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + }, | ||
| 111 | + { | ||
| 112 | + "ordinal": 10, | ||
| 113 | + "name": "subjects_inherited", | ||
| 114 | + "type_info": "Bool", | ||
| 115 | + "origin": { | ||
| 116 | + "Table": { | ||
| 117 | + "table": "class_course", | ||
| 118 | + "name": "subjects_inherited" | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + }, | ||
| 122 | + { | ||
| 123 | + "ordinal": 11, | ||
| 124 | + "name": "exam_weights_inherited", | ||
| 125 | + "type_info": "Bool", | ||
| 126 | + "origin": { | ||
| 127 | + "Table": { | ||
| 128 | + "table": "class_course", | ||
| 129 | + "name": "exam_weights_inherited" | ||
| 130 | + } | ||
| 131 | + } | ||
| 132 | + }, | ||
| 133 | + { | ||
| 134 | + "ordinal": 12, | ||
| 135 | + "name": "weekly_plan_inherited", | ||
| 136 | + "type_info": "Bool", | ||
| 137 | + "origin": { | ||
| 138 | + "Table": { | ||
| 139 | + "table": "class_course", | ||
| 140 | + "name": "weekly_plan_inherited" | ||
| 141 | + } | ||
| 142 | + } | ||
| 143 | + }, | ||
| 144 | + { | ||
| 145 | + "ordinal": 13, | ||
| 146 | + "name": "enrollment_count", | ||
| 147 | + "type_info": "Int8", | ||
| 148 | + "origin": { | ||
| 149 | + "Table": { | ||
| 150 | + "table": "class_course", | ||
| 151 | + "name": "enrollment_count" | ||
| 152 | + } | ||
| 153 | + } | ||
| 154 | + }, | ||
| 155 | + { | ||
| 156 | + "ordinal": 14, | ||
| 157 | + "name": "attached_at: Timestamp", | ||
| 158 | + "type_info": "Int8", | ||
| 159 | + "origin": { | ||
| 160 | + "Table": { | ||
| 161 | + "table": "class_course", | ||
| 162 | + "name": "attached_at" | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + } | ||
| 166 | + ], | ||
| 167 | + "parameters": { | ||
| 168 | + "Left": [ | ||
| 169 | + "UuidArray" | ||
| 170 | + ] | ||
| 171 | + }, | ||
| 172 | + "nullable": [ | ||
| 173 | + false, | ||
| 174 | + false, | ||
| 175 | + false, | ||
| 176 | + false, | ||
| 177 | + false, | ||
| 178 | + false, | ||
| 179 | + true, | ||
| 180 | + true, | ||
| 181 | + null, | ||
| 182 | + true, | ||
| 183 | + false, | ||
| 184 | + false, | ||
| 185 | + false, | ||
| 186 | + false, | ||
| 187 | + false | ||
| 188 | + ] | ||
| 189 | + }, | ||
| 190 | + "hash": "744c8ef425e5e4fe9af88506e0210dcb368c1a315ee6809f8f34e837b7eae57f" | ||
| 191 | +} | ||
.sqlx/query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.json → .sqlx/query-7a23cb18cccbbda676484bfcedcb3953c2f44a93f7c597debe56eb6b21ce7fcf.jsonrenamed+3 -3
| @@ -1,15 +1,15 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "DELETE FROM blueprint_course\n WHERE course = $2\n AND blueprint = (SELECT id FROM class_blueprint WHERE grade = $1)", | 3 | + "query": "DELETE FROM blueprint_course\n WHERE course = $2\n AND blueprint = (SELECT id FROM class_blueprint WHERE grade_level = $1)", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [], | 5 | "columns": [], |
| 6 | "parameters": { | 6 | "parameters": { |
| 7 | "Left": [ | 7 | "Left": [ |
| 8 | - "Text", | 8 | + "Int2", |
| 9 | "Uuid" | 9 | "Uuid" |
| 10 | ] | 10 | ] |
| 11 | }, | 11 | }, |
| 12 | "nullable": [] | 12 | "nullable": [] |
| 13 | }, | 13 | }, |
| 14 | - "hash": "a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad" | 14 | + "hash": "7a23cb18cccbbda676484bfcedcb3953c2f44a93f7c597debe56eb6b21ce7fcf" |
| 15 | } | 15 | } |
.sqlx/query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.json → .sqlx/query-7bb873764f075c33eb5e71d0941255cf0a3cf01b761da187bd50deec4523d60f.jsonrenamed+3 -3
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "SELECT id AS \"key: uuid::Uuid\" FROM class_blueprint\n WHERE grade = $1 FOR UPDATE", | 3 | + "query": "SELECT id AS \"key: uuid::Uuid\" FROM class_blueprint\n WHERE grade_level = $1 FOR UPDATE", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -17,12 +17,12 @@ | |||
| 17 | ], | 17 | ], |
| 18 | "parameters": { | 18 | "parameters": { |
| 19 | "Left": [ | 19 | "Left": [ |
| 20 | - "Text" | 20 | + "Int2" |
| 21 | ] | 21 | ] |
| 22 | }, | 22 | }, |
| 23 | "nullable": [ | 23 | "nullable": [ |
| 24 | false | 24 | false |
| 25 | ] | 25 | ] |
| 26 | }, | 26 | }, |
| 27 | - "hash": "8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2" | 27 | + "hash": "7bb873764f075c33eb5e71d0941255cf0a3cf01b761da187bd50deec4523d60f" |
| 28 | } | 28 | } |
.sqlx/query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.json → .sqlx/query-80ca84ff3ec8a4ede6d8f9a9ccaedfe02ba5c16d2b9a46646d5649fc1f9fd4fd.jsonrenamed+6 -6
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "SELECT id AS \"key: uuid::Uuid\", grade AS \"grade: ClassGrade\",\n creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade = $1", | 3 | + "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", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -16,12 +16,12 @@ | |||
| 16 | }, | 16 | }, |
| 17 | { | 17 | { |
| 18 | "ordinal": 1, | 18 | "ordinal": 1, |
| 19 | - "name": "grade: ClassGrade", | 19 | + "name": "grade_level: GradeLevel", |
| 20 | - "type_info": "Text", | 20 | + "type_info": "Int2", |
| 21 | "origin": { | 21 | "origin": { |
| 22 | "Table": { | 22 | "Table": { |
| 23 | "table": "class_blueprint", | 23 | "table": "class_blueprint", |
| 24 | - "name": "grade" | 24 | + "name": "grade_level" |
| 25 | } | 25 | } |
| 26 | } | 26 | } |
| 27 | }, | 27 | }, |
| @@ -39,7 +39,7 @@ | |||
| 39 | ], | 39 | ], |
| 40 | "parameters": { | 40 | "parameters": { |
| 41 | "Left": [ | 41 | "Left": [ |
| 42 | - "Text" | 42 | + "Int2" |
| 43 | ] | 43 | ] |
| 44 | }, | 44 | }, |
| 45 | "nullable": [ | 45 | "nullable": [ |
| @@ -48,5 +48,5 @@ | |||
| 48 | false | 48 | false |
| 49 | ] | 49 | ] |
| 50 | }, | 50 | }, |
| 51 | - "hash": "c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5" | 51 | + "hash": "80ca84ff3ec8a4ede6d8f9a9ccaedfe02ba5c16d2b9a46646d5649fc1f9fd4fd" |
| 52 | } | 52 | } |
.sqlx/query-855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d.jsonadded+58 -0
| @@ -0,0 +1,58 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "WITH ins AS (\n INSERT INTO class_course_slot (id, class_course, weekday, starts_at, ends_at)\n VALUES ($1, $2, $3,\n ($4::bigint * interval '1 minute')::time,\n ($5::bigint * interval '1 minute')::time)\n RETURNING id, weekday, starts_at, ends_at\n ), flip AS (\n UPDATE class_course SET weekly_plan_inherited = FALSE\n WHERE id = $2 AND EXISTS (SELECT 1 FROM ins)\n RETURNING id\n )\n SELECT ins.id AS \"id: WeeklySlotId\",\n ins.weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM ins.starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ins.ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\"\n FROM ins\n WHERE EXISTS (SELECT 1 FROM flip)", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: WeeklySlotId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course_slot", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "weekday: Weekday", | ||
| 20 | + "type_info": "Int2", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "class_course_slot", | ||
| 24 | + "name": "weekday" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "starts_at!: SlotMinute", | ||
| 31 | + "type_info": "Int8", | ||
| 32 | + "origin": "Expression" | ||
| 33 | + }, | ||
| 34 | + { | ||
| 35 | + "ordinal": 3, | ||
| 36 | + "name": "ends_at!: SlotMinute", | ||
| 37 | + "type_info": "Int8", | ||
| 38 | + "origin": "Expression" | ||
| 39 | + } | ||
| 40 | + ], | ||
| 41 | + "parameters": { | ||
| 42 | + "Left": [ | ||
| 43 | + "Uuid", | ||
| 44 | + "Uuid", | ||
| 45 | + "Int2", | ||
| 46 | + "Int8", | ||
| 47 | + "Int8" | ||
| 48 | + ] | ||
| 49 | + }, | ||
| 50 | + "nullable": [ | ||
| 51 | + false, | ||
| 52 | + false, | ||
| 53 | + null, | ||
| 54 | + null | ||
| 55 | + ] | ||
| 56 | + }, | ||
| 57 | + "hash": "855316157629bcc63776b4f6d2ed8745b37d88ff00f48812498dc87c9b5fb51d" | ||
| 58 | +} | ||
.sqlx/query-b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59.json → .sqlx/query-85cd8f96075296070428fcbe59a136252078a07cc4b7807788e08b171c8cdf9a.jsonrenamed+7 -7
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "WITH seat AS (\n UPDATE academic_year SET class_count = class_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO class_group (id, creator, name, grade, year, teacher)\n SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"", | 3 | + "query": "WITH seat AS (\n UPDATE academic_year SET class_count = class_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO class_group (id, creator, name, grade_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\"", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -38,12 +38,12 @@ | |||
| 38 | }, | 38 | }, |
| 39 | { | 39 | { |
| 40 | "ordinal": 3, | 40 | "ordinal": 3, |
| 41 | - "name": "grade: ClassGrade", | 41 | + "name": "grade_level: GradeLevel", |
| 42 | - "type_info": "Text", | 42 | + "type_info": "Int2", |
| 43 | "origin": { | 43 | "origin": { |
| 44 | "Table": { | 44 | "Table": { |
| 45 | "table": "class_group", | 45 | "table": "class_group", |
| 46 | - "name": "grade" | 46 | + "name": "grade_level" |
| 47 | } | 47 | } |
| 48 | } | 48 | } |
| 49 | }, | 49 | }, |
| @@ -76,7 +76,7 @@ | |||
| 76 | "Uuid", | 76 | "Uuid", |
| 77 | "Uuid", | 77 | "Uuid", |
| 78 | "Text", | 78 | "Text", |
| 79 | - "Text", | 79 | + "Int2", |
| 80 | "Uuid" | 80 | "Uuid" |
| 81 | ] | 81 | ] |
| 82 | }, | 82 | }, |
| @@ -84,10 +84,10 @@ | |||
| 84 | false, | 84 | false, |
| 85 | false, | 85 | false, |
| 86 | false, | 86 | false, |
| 87 | - true, | 87 | + false, |
| 88 | true, | 88 | true, |
| 89 | true | 89 | true |
| 90 | ] | 90 | ] |
| 91 | }, | 91 | }, |
| 92 | - "hash": "b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59" | 92 | + "hash": "85cd8f96075296070428fcbe59a136252078a07cc4b7807788e08b171c8cdf9a" |
| 93 | } | 93 | } |
.sqlx/query-b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5.json → .sqlx/query-860e57dee5cc91e6477ac1e7650ae4031a4b0a06e9b4e2710b9943252462d7dc.jsonrenamed+6 -6
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = $1", | 3 | + "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", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -38,12 +38,12 @@ | |||
| 38 | }, | 38 | }, |
| 39 | { | 39 | { |
| 40 | "ordinal": 3, | 40 | "ordinal": 3, |
| 41 | - "name": "grade: ClassGrade", | 41 | + "name": "grade_level: GradeLevel", |
| 42 | - "type_info": "Text", | 42 | + "type_info": "Int2", |
| 43 | "origin": { | 43 | "origin": { |
| 44 | "Table": { | 44 | "Table": { |
| 45 | "table": "class_group", | 45 | "table": "class_group", |
| 46 | - "name": "grade" | 46 | + "name": "grade_level" |
| 47 | } | 47 | } |
| 48 | } | 48 | } |
| 49 | }, | 49 | }, |
| @@ -79,10 +79,10 @@ | |||
| 79 | false, | 79 | false, |
| 80 | false, | 80 | false, |
| 81 | false, | 81 | false, |
| 82 | - true, | 82 | + false, |
| 83 | true, | 83 | true, |
| 84 | true | 84 | true |
| 85 | ] | 85 | ] |
| 86 | }, | 86 | }, |
| 87 | - "hash": "b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5" | 87 | + "hash": "860e57dee5cc91e6477ac1e7650ae4031a4b0a06e9b4e2710b9943252462d7dc" |
| 88 | } | 88 | } |
.sqlx/query-8613f11afd0f7a09653c3bde7a25b6c98f1aa548e5adf13260939390db5aab0f.jsonadded+15 -0
| @@ -0,0 +1,15 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "INSERT INTO offering_subject (offering, subject)\n VALUES ($1, $2)\n ON CONFLICT DO NOTHING", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid", | ||
| 9 | + "Uuid" | ||
| 10 | + ] | ||
| 11 | + }, | ||
| 12 | + "nullable": [] | ||
| 13 | + }, | ||
| 14 | + "hash": "8613f11afd0f7a09653c3bde7a25b6c98f1aa548e5adf13260939390db5aab0f" | ||
| 15 | +} | ||
.sqlx/query-90313888df75e74f326c9731c88340ede5fb34c70b0b0d837a378fe6b92afc94.jsonadded+28 -0
| @@ -0,0 +1,28 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT grade_level AS \"grade_level: GradeLevel\" FROM class_group\n WHERE id = $1 FOR KEY SHARE", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "grade_level: GradeLevel", | ||
| 9 | + "type_info": "Int2", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_group", | ||
| 13 | + "name": "grade_level" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "parameters": { | ||
| 19 | + "Left": [ | ||
| 20 | + "Uuid" | ||
| 21 | + ] | ||
| 22 | + }, | ||
| 23 | + "nullable": [ | ||
| 24 | + false | ||
| 25 | + ] | ||
| 26 | + }, | ||
| 27 | + "hash": "90313888df75e74f326c9731c88340ede5fb34c70b0b0d837a378fe6b92afc94" | ||
| 28 | +} | ||
.sqlx/query-92a2fd1dbde98ae6cb59dd691c4efee61e93775bc39519714dc122790a448285.jsonadded+15 -0
| @@ -0,0 +1,15 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "DELETE FROM offering_subject\n WHERE offering = $1 AND subject = $2", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid", | ||
| 9 | + "Uuid" | ||
| 10 | + ] | ||
| 11 | + }, | ||
| 12 | + "nullable": [] | ||
| 13 | + }, | ||
| 14 | + "hash": "92a2fd1dbde98ae6cb59dd691c4efee61e93775bc39519714dc122790a448285" | ||
| 15 | +} | ||
.sqlx/query-9f90a0a4125b00161e377a19a73020cd6fd3ea903470e9b153d02352b12118cc.jsonadded+191 -0
| @@ -0,0 +1,191 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.offering AS \"offering: CourseOfferingId\",\n cc.attached_by AS \"attached_by: UserId\",\n b.grade_level AS \"source?: ClassBlueprintId\",\n cc.title AS \"title?: CourseTitle\",\n cc.description AS \"description?: CourseDescription\",\n cc.ders_saati::bigint AS \"ders_saati?: DersSaati\",\n cc.counts_toward_karne,\n cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,\n cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.id = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassCourseId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "class: ClassGroupId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "class_course", | ||
| 24 | + "name": "class" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "course: CourseId", | ||
| 31 | + "type_info": "Uuid", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "class_course", | ||
| 35 | + "name": "course" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "offering: CourseOfferingId", | ||
| 42 | + "type_info": "Uuid", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "class_course", | ||
| 46 | + "name": "offering" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "attached_by: UserId", | ||
| 53 | + "type_info": "Uuid", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "class_course", | ||
| 57 | + "name": "attached_by" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "source?: ClassBlueprintId", | ||
| 64 | + "type_info": "Int2", | ||
| 65 | + "origin": { | ||
| 66 | + "Table": { | ||
| 67 | + "table": "class_blueprint", | ||
| 68 | + "name": "grade_level" | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | + }, | ||
| 72 | + { | ||
| 73 | + "ordinal": 6, | ||
| 74 | + "name": "title?: CourseTitle", | ||
| 75 | + "type_info": "Text", | ||
| 76 | + "origin": { | ||
| 77 | + "Table": { | ||
| 78 | + "table": "class_course", | ||
| 79 | + "name": "title" | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + }, | ||
| 83 | + { | ||
| 84 | + "ordinal": 7, | ||
| 85 | + "name": "description?: CourseDescription", | ||
| 86 | + "type_info": "Text", | ||
| 87 | + "origin": { | ||
| 88 | + "Table": { | ||
| 89 | + "table": "class_course", | ||
| 90 | + "name": "description" | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + }, | ||
| 94 | + { | ||
| 95 | + "ordinal": 8, | ||
| 96 | + "name": "ders_saati?: DersSaati", | ||
| 97 | + "type_info": "Int8", | ||
| 98 | + "origin": "Expression" | ||
| 99 | + }, | ||
| 100 | + { | ||
| 101 | + "ordinal": 9, | ||
| 102 | + "name": "counts_toward_karne", | ||
| 103 | + "type_info": "Bool", | ||
| 104 | + "origin": { | ||
| 105 | + "Table": { | ||
| 106 | + "table": "class_course", | ||
| 107 | + "name": "counts_toward_karne" | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + }, | ||
| 111 | + { | ||
| 112 | + "ordinal": 10, | ||
| 113 | + "name": "subjects_inherited", | ||
| 114 | + "type_info": "Bool", | ||
| 115 | + "origin": { | ||
| 116 | + "Table": { | ||
| 117 | + "table": "class_course", | ||
| 118 | + "name": "subjects_inherited" | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + }, | ||
| 122 | + { | ||
| 123 | + "ordinal": 11, | ||
| 124 | + "name": "exam_weights_inherited", | ||
| 125 | + "type_info": "Bool", | ||
| 126 | + "origin": { | ||
| 127 | + "Table": { | ||
| 128 | + "table": "class_course", | ||
| 129 | + "name": "exam_weights_inherited" | ||
| 130 | + } | ||
| 131 | + } | ||
| 132 | + }, | ||
| 133 | + { | ||
| 134 | + "ordinal": 12, | ||
| 135 | + "name": "weekly_plan_inherited", | ||
| 136 | + "type_info": "Bool", | ||
| 137 | + "origin": { | ||
| 138 | + "Table": { | ||
| 139 | + "table": "class_course", | ||
| 140 | + "name": "weekly_plan_inherited" | ||
| 141 | + } | ||
| 142 | + } | ||
| 143 | + }, | ||
| 144 | + { | ||
| 145 | + "ordinal": 13, | ||
| 146 | + "name": "enrollment_count", | ||
| 147 | + "type_info": "Int8", | ||
| 148 | + "origin": { | ||
| 149 | + "Table": { | ||
| 150 | + "table": "class_course", | ||
| 151 | + "name": "enrollment_count" | ||
| 152 | + } | ||
| 153 | + } | ||
| 154 | + }, | ||
| 155 | + { | ||
| 156 | + "ordinal": 14, | ||
| 157 | + "name": "attached_at: Timestamp", | ||
| 158 | + "type_info": "Int8", | ||
| 159 | + "origin": { | ||
| 160 | + "Table": { | ||
| 161 | + "table": "class_course", | ||
| 162 | + "name": "attached_at" | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + } | ||
| 166 | + ], | ||
| 167 | + "parameters": { | ||
| 168 | + "Left": [ | ||
| 169 | + "Uuid" | ||
| 170 | + ] | ||
| 171 | + }, | ||
| 172 | + "nullable": [ | ||
| 173 | + false, | ||
| 174 | + false, | ||
| 175 | + false, | ||
| 176 | + false, | ||
| 177 | + false, | ||
| 178 | + true, | ||
| 179 | + true, | ||
| 180 | + true, | ||
| 181 | + null, | ||
| 182 | + true, | ||
| 183 | + false, | ||
| 184 | + false, | ||
| 185 | + false, | ||
| 186 | + false, | ||
| 187 | + false | ||
| 188 | + ] | ||
| 189 | + }, | ||
| 190 | + "hash": "9f90a0a4125b00161e377a19a73020cd6fd3ea903470e9b153d02352b12118cc" | ||
| 191 | +} | ||
.sqlx/query-0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4.json → .sqlx/query-a3db9a0caa7b47888741c892b1bdee2772a3590e71d0e0a23fcecb8dba228e81.jsonrenamed+3 -3
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course\n WHERE class = $1 AND course = $2\n AND source = (SELECT id FROM class_blueprint WHERE grade = $3)\n FOR UPDATE", | 3 | + "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course\n WHERE class = $1 AND course = $2\n AND source = (SELECT id FROM class_blueprint WHERE grade_level = $3)\n FOR UPDATE", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -19,12 +19,12 @@ | |||
| 19 | "Left": [ | 19 | "Left": [ |
| 20 | "Uuid", | 20 | "Uuid", |
| 21 | "Uuid", | 21 | "Uuid", |
| 22 | - "Text" | 22 | + "Int2" |
| 23 | ] | 23 | ] |
| 24 | }, | 24 | }, |
| 25 | "nullable": [ | 25 | "nullable": [ |
| 26 | false | 26 | false |
| 27 | ] | 27 | ] |
| 28 | }, | 28 | }, |
| 29 | - "hash": "0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4" | 29 | + "hash": "a3db9a0caa7b47888741c892b1bdee2772a3590e71d0e0a23fcecb8dba228e81" |
| 30 | } | 30 | } |
.sqlx/query-a63cae3c38fc5ab52786505d1944169bab3769effe0dccbed8587f89d788a1f2.jsonadded+88 -0
| @@ -0,0 +1,88 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade_level AS \"grade_level: GradeLevel\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE grade_level = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassGroupId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_group", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "creator: UserId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "class_group", | ||
| 24 | + "name": "creator" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "name: ClassName", | ||
| 31 | + "type_info": "Text", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "class_group", | ||
| 35 | + "name": "name" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "grade_level: GradeLevel", | ||
| 42 | + "type_info": "Int2", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "class_group", | ||
| 46 | + "name": "grade_level" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "year: AcademicYearId", | ||
| 53 | + "type_info": "Uuid", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "class_group", | ||
| 57 | + "name": "year" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "teacher: UserId", | ||
| 64 | + "type_info": "Uuid", | ||
| 65 | + "origin": { | ||
| 66 | + "Table": { | ||
| 67 | + "table": "class_group", | ||
| 68 | + "name": "teacher" | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | + } | ||
| 72 | + ], | ||
| 73 | + "parameters": { | ||
| 74 | + "Left": [ | ||
| 75 | + "Int2" | ||
| 76 | + ] | ||
| 77 | + }, | ||
| 78 | + "nullable": [ | ||
| 79 | + false, | ||
| 80 | + false, | ||
| 81 | + false, | ||
| 82 | + false, | ||
| 83 | + true, | ||
| 84 | + true | ||
| 85 | + ] | ||
| 86 | + }, | ||
| 87 | + "hash": "a63cae3c38fc5ab52786505d1944169bab3769effe0dccbed8587f89d788a1f2" | ||
| 88 | +} | ||
.sqlx/query-cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7.json → .sqlx/query-a7aed9e7c0d53a5e944ad27f13c7dcc078b9ce93ba209d3b2ca1d16382b62f45.jsonrenamed+3 -2
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "WITH seat AS (\n UPDATE class_group SET class_course_count = class_course_count + 1\n WHERE id = $1 AND class_course_count < $2\n RETURNING 1)\n INSERT INTO class_course (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\"", | 3 | + "query": "WITH seat AS (\n UPDATE class_group SET class_course_count = class_course_count + 1\n WHERE id = $1 AND class_course_count < $2\n RETURNING 1)\n INSERT INTO class_course (id, class, course, attached_by, attached_at, source, offering)\n SELECT $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -18,6 +18,7 @@ | |||
| 18 | "Uuid", | 18 | "Uuid", |
| 19 | "Uuid", | 19 | "Uuid", |
| 20 | "Int8", | 20 | "Int8", |
| 21 | + "Uuid", | ||
| 21 | "Uuid" | 22 | "Uuid" |
| 22 | ] | 23 | ] |
| 23 | }, | 24 | }, |
| @@ -25,5 +26,5 @@ | |||
| 25 | null | 26 | null |
| 26 | ] | 27 | ] |
| 27 | }, | 28 | }, |
| 28 | - "hash": "cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7" | 29 | + "hash": "a7aed9e7c0d53a5e944ad27f13c7dcc078b9ce93ba209d3b2ca1d16382b62f45" |
| 29 | } | 30 | } |
.sqlx/query-a8ca6711e03ab03d9d6526c95853c5b62ea7b6ac7f3046b6fd1c784cb5979618.jsonadded+36 -0
| @@ -0,0 +1,36 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT kind, weight::bigint AS \"weight!: i64\"\n FROM class_course_exam_weight WHERE class_course = $1 AND kind = $2", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "kind", | ||
| 9 | + "type_info": "Text", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course_exam_weight", | ||
| 13 | + "name": "kind" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "weight!: i64", | ||
| 20 | + "type_info": "Int8", | ||
| 21 | + "origin": "Expression" | ||
| 22 | + } | ||
| 23 | + ], | ||
| 24 | + "parameters": { | ||
| 25 | + "Left": [ | ||
| 26 | + "Uuid", | ||
| 27 | + "Text" | ||
| 28 | + ] | ||
| 29 | + }, | ||
| 30 | + "nullable": [ | ||
| 31 | + false, | ||
| 32 | + null | ||
| 33 | + ] | ||
| 34 | + }, | ||
| 35 | + "hash": "a8ca6711e03ab03d9d6526c95853c5b62ea7b6ac7f3046b6fd1c784cb5979618" | ||
| 36 | +} | ||
.sqlx/query-a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3.jsondeleted+0 -119
| @@ -1,119 +0,0 @@ | |||
| 1 | -{ | ||
| 2 | - "db_name": "PostgreSQL", | ||
| 3 | - "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.id = $1", | ||
| 4 | - "describe": { | ||
| 5 | - "columns": [ | ||
| 6 | - { | ||
| 7 | - "ordinal": 0, | ||
| 8 | - "name": "id: ClassCourseId", | ||
| 9 | - "type_info": "Uuid", | ||
| 10 | - "origin": { | ||
| 11 | - "Table": { | ||
| 12 | - "table": "class_course", | ||
| 13 | - "name": "id" | ||
| 14 | - } | ||
| 15 | - } | ||
| 16 | - }, | ||
| 17 | - { | ||
| 18 | - "ordinal": 1, | ||
| 19 | - "name": "class: ClassGroupId", | ||
| 20 | - "type_info": "Uuid", | ||
| 21 | - "origin": { | ||
| 22 | - "Table": { | ||
| 23 | - "table": "class_course", | ||
| 24 | - "name": "class" | ||
| 25 | - } | ||
| 26 | - } | ||
| 27 | - }, | ||
| 28 | - { | ||
| 29 | - "ordinal": 2, | ||
| 30 | - "name": "course: CourseId", | ||
| 31 | - "type_info": "Uuid", | ||
| 32 | - "origin": { | ||
| 33 | - "Table": { | ||
| 34 | - "table": "class_course", | ||
| 35 | - "name": "course" | ||
| 36 | - } | ||
| 37 | - } | ||
| 38 | - }, | ||
| 39 | - { | ||
| 40 | - "ordinal": 3, | ||
| 41 | - "name": "attached_by: UserId", | ||
| 42 | - "type_info": "Uuid", | ||
| 43 | - "origin": { | ||
| 44 | - "Table": { | ||
| 45 | - "table": "class_course", | ||
| 46 | - "name": "attached_by" | ||
| 47 | - } | ||
| 48 | - } | ||
| 49 | - }, | ||
| 50 | - { | ||
| 51 | - "ordinal": 4, | ||
| 52 | - "name": "source?: ClassBlueprintId", | ||
| 53 | - "type_info": "Text", | ||
| 54 | - "origin": { | ||
| 55 | - "Table": { | ||
| 56 | - "table": "class_blueprint", | ||
| 57 | - "name": "grade" | ||
| 58 | - } | ||
| 59 | - } | ||
| 60 | - }, | ||
| 61 | - { | ||
| 62 | - "ordinal": 5, | ||
| 63 | - "name": "ders_saati!: DersSaati", | ||
| 64 | - "type_info": "Int8", | ||
| 65 | - "origin": "Expression" | ||
| 66 | - }, | ||
| 67 | - { | ||
| 68 | - "ordinal": 6, | ||
| 69 | - "name": "counts_toward_karne", | ||
| 70 | - "type_info": "Bool", | ||
| 71 | - "origin": { | ||
| 72 | - "Table": { | ||
| 73 | - "table": "class_course", | ||
| 74 | - "name": "counts_toward_karne" | ||
| 75 | - } | ||
| 76 | - } | ||
| 77 | - }, | ||
| 78 | - { | ||
| 79 | - "ordinal": 7, | ||
| 80 | - "name": "enrollment_count", | ||
| 81 | - "type_info": "Int8", | ||
| 82 | - "origin": { | ||
| 83 | - "Table": { | ||
| 84 | - "table": "class_course", | ||
| 85 | - "name": "enrollment_count" | ||
| 86 | - } | ||
| 87 | - } | ||
| 88 | - }, | ||
| 89 | - { | ||
| 90 | - "ordinal": 8, | ||
| 91 | - "name": "attached_at: Timestamp", | ||
| 92 | - "type_info": "Int8", | ||
| 93 | - "origin": { | ||
| 94 | - "Table": { | ||
| 95 | - "table": "class_course", | ||
| 96 | - "name": "attached_at" | ||
| 97 | - } | ||
| 98 | - } | ||
| 99 | - } | ||
| 100 | - ], | ||
| 101 | - "parameters": { | ||
| 102 | - "Left": [ | ||
| 103 | - "Uuid" | ||
| 104 | - ] | ||
| 105 | - }, | ||
| 106 | - "nullable": [ | ||
| 107 | - false, | ||
| 108 | - false, | ||
| 109 | - false, | ||
| 110 | - false, | ||
| 111 | - true, | ||
| 112 | - null, | ||
| 113 | - false, | ||
| 114 | - false, | ||
| 115 | - false | ||
| 116 | - ] | ||
| 117 | - }, | ||
| 118 | - "hash": "a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3" | ||
| 119 | -} | ||
.sqlx/query-a91d1a048aed0671318c7c2faf3537a93f34014875f1df15279d500f0c2927e7.jsonadded+15 -0
| @@ -0,0 +1,15 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "DELETE FROM offering_slot WHERE id = $1 AND offering = $2", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid", | ||
| 9 | + "Uuid" | ||
| 10 | + ] | ||
| 11 | + }, | ||
| 12 | + "nullable": [] | ||
| 13 | + }, | ||
| 14 | + "hash": "a91d1a048aed0671318c7c2faf3537a93f34014875f1df15279d500f0c2927e7" | ||
| 15 | +} | ||
.sqlx/query-ab7ce121deae040653c2886cda93146a6c02d1d932da63f364a78a56dee79eed.jsonadded+28 -0
| @@ -0,0 +1,28 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT id AS \"id: CourseOfferingId\" FROM course_offering WHERE id = $1\n FOR NO KEY UPDATE", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: CourseOfferingId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "course_offering", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "parameters": { | ||
| 19 | + "Left": [ | ||
| 20 | + "Uuid" | ||
| 21 | + ] | ||
| 22 | + }, | ||
| 23 | + "nullable": [ | ||
| 24 | + false | ||
| 25 | + ] | ||
| 26 | + }, | ||
| 27 | + "hash": "ab7ce121deae040653c2886cda93146a6c02d1d932da63f364a78a56dee79eed" | ||
| 28 | +} | ||
.sqlx/query-ad70c205e5c81bbb3fb230215a00fbb18af95e8b1bb437b87bd31e38fb804bdc.jsonadded+64 -0
| @@ -0,0 +1,64 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: SubjectId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "subject", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "course: CourseId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "subject", | ||
| 24 | + "name": "course" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "name: SubjectName", | ||
| 31 | + "type_info": "Text", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "subject", | ||
| 35 | + "name": "name" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "description: SubjectDescription", | ||
| 42 | + "type_info": "Text", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "subject", | ||
| 46 | + "name": "description" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + } | ||
| 50 | + ], | ||
| 51 | + "parameters": { | ||
| 52 | + "Left": [ | ||
| 53 | + "Uuid" | ||
| 54 | + ] | ||
| 55 | + }, | ||
| 56 | + "nullable": [ | ||
| 57 | + false, | ||
| 58 | + false, | ||
| 59 | + false, | ||
| 60 | + false | ||
| 61 | + ] | ||
| 62 | + }, | ||
| 63 | + "hash": "ad70c205e5c81bbb3fb230215a00fbb18af95e8b1bb437b87bd31e38fb804bdc" | ||
| 64 | +} | ||
.sqlx/query-b026b654310663a018f93884e2a015ab473efa48671c58ff10f33ed8b89dc803.jsonadded+28 -0
| @@ -0,0 +1,28 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT kind AS \"kind: CourseKind\" FROM course WHERE id = $1 FOR KEY SHARE", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "kind: CourseKind", | ||
| 9 | + "type_info": "Text", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "course", | ||
| 13 | + "name": "kind" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "parameters": { | ||
| 19 | + "Left": [ | ||
| 20 | + "Uuid" | ||
| 21 | + ] | ||
| 22 | + }, | ||
| 23 | + "nullable": [ | ||
| 24 | + false | ||
| 25 | + ] | ||
| 26 | + }, | ||
| 27 | + "hash": "b026b654310663a018f93884e2a015ab473efa48671c58ff10f33ed8b89dc803" | ||
| 28 | +} | ||
.sqlx/query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.json → .sqlx/query-b3e310ca3331217df9d486461ce82cb568bbcfcb88386270920f3eb6579a526e.jsonrenamed+6 -6
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "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", | 3 | + "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", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -16,12 +16,12 @@ | |||
| 16 | }, | 16 | }, |
| 17 | { | 17 | { |
| 18 | "ordinal": 1, | 18 | "ordinal": 1, |
| 19 | - "name": "grade: ClassGrade", | 19 | + "name": "grade_level: GradeLevel", |
| 20 | - "type_info": "Text", | 20 | + "type_info": "Int2", |
| 21 | "origin": { | 21 | "origin": { |
| 22 | "Table": { | 22 | "Table": { |
| 23 | "table": "class_blueprint", | 23 | "table": "class_blueprint", |
| 24 | - "name": "grade" | 24 | + "name": "grade_level" |
| 25 | } | 25 | } |
| 26 | } | 26 | } |
| 27 | }, | 27 | }, |
| @@ -39,7 +39,7 @@ | |||
| 39 | ], | 39 | ], |
| 40 | "parameters": { | 40 | "parameters": { |
| 41 | "Left": [ | 41 | "Left": [ |
| 42 | - "Text" | 42 | + "Int2" |
| 43 | ] | 43 | ] |
| 44 | }, | 44 | }, |
| 45 | "nullable": [ | 45 | "nullable": [ |
| @@ -48,5 +48,5 @@ | |||
| 48 | false | 48 | false |
| 49 | ] | 49 | ] |
| 50 | }, | 50 | }, |
| 51 | - "hash": "5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c" | 51 | + "hash": "b3e310ca3331217df9d486461ce82cb568bbcfcb88386270920f3eb6579a526e" |
| 52 | } | 52 | } |
.sqlx/query-b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9.jsonadded+54 -0
| @@ -0,0 +1,54 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT id AS \"id: WeeklySlotId\",\n weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\"\n FROM offering_slot\n WHERE offering = $1\n ORDER BY weekday, starts_at", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: WeeklySlotId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "offering_slot", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "weekday: Weekday", | ||
| 20 | + "type_info": "Int2", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "offering_slot", | ||
| 24 | + "name": "weekday" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "starts_at!: SlotMinute", | ||
| 31 | + "type_info": "Int8", | ||
| 32 | + "origin": "Expression" | ||
| 33 | + }, | ||
| 34 | + { | ||
| 35 | + "ordinal": 3, | ||
| 36 | + "name": "ends_at!: SlotMinute", | ||
| 37 | + "type_info": "Int8", | ||
| 38 | + "origin": "Expression" | ||
| 39 | + } | ||
| 40 | + ], | ||
| 41 | + "parameters": { | ||
| 42 | + "Left": [ | ||
| 43 | + "Uuid" | ||
| 44 | + ] | ||
| 45 | + }, | ||
| 46 | + "nullable": [ | ||
| 47 | + false, | ||
| 48 | + false, | ||
| 49 | + null, | ||
| 50 | + null | ||
| 51 | + ] | ||
| 52 | + }, | ||
| 53 | + "hash": "b739aee4f8d5166fd0001bf15efe4955db70f6a5073d3b14098fe591d23366f9" | ||
| 54 | +} | ||
.sqlx/query-bd186c14f1a5c0dc4b4f7fb543ebd4484136dd6aa75069f987075137e1b99b00.jsonadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [], | ||
| 6 | + "parameters": { | ||
| 7 | + "Left": [ | ||
| 8 | + "Uuid", | ||
| 9 | + "Text", | ||
| 10 | + "Int8" | ||
| 11 | + ] | ||
| 12 | + }, | ||
| 13 | + "nullable": [] | ||
| 14 | + }, | ||
| 15 | + "hash": "bd186c14f1a5c0dc4b4f7fb543ebd4484136dd6aa75069f987075137e1b99b00" | ||
| 16 | +} | ||
.sqlx/query-d692aa84085905ea3e70d4a94b5e81ff85548c6aeb096ee914d5349bf525137a.jsonadded+131 -0
| @@ -0,0 +1,131 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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)", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: CourseOfferingId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "course_offering", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "course: CourseId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "course_offering", | ||
| 24 | + "name": "course" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "grade_level: GradeLevel", | ||
| 31 | + "type_info": "Int2", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "course_offering", | ||
| 35 | + "name": "grade_level" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "title?: CourseTitle", | ||
| 42 | + "type_info": "Text", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "course_offering", | ||
| 46 | + "name": "title" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "description?: CourseDescription", | ||
| 53 | + "type_info": "Text", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "course_offering", | ||
| 57 | + "name": "description" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "default_ders_saati?: DersSaati", | ||
| 64 | + "type_info": "Int8", | ||
| 65 | + "origin": "Expression" | ||
| 66 | + }, | ||
| 67 | + { | ||
| 68 | + "ordinal": 6, | ||
| 69 | + "name": "default_counts_toward_karne", | ||
| 70 | + "type_info": "Bool", | ||
| 71 | + "origin": { | ||
| 72 | + "Table": { | ||
| 73 | + "table": "course_offering", | ||
| 74 | + "name": "default_counts_toward_karne" | ||
| 75 | + } | ||
| 76 | + } | ||
| 77 | + }, | ||
| 78 | + { | ||
| 79 | + "ordinal": 7, | ||
| 80 | + "name": "created_by: UserId", | ||
| 81 | + "type_info": "Uuid", | ||
| 82 | + "origin": { | ||
| 83 | + "Table": { | ||
| 84 | + "table": "course_offering", | ||
| 85 | + "name": "created_by" | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + }, | ||
| 89 | + { | ||
| 90 | + "ordinal": 8, | ||
| 91 | + "name": "created_at: Timestamp", | ||
| 92 | + "type_info": "Int8", | ||
| 93 | + "origin": { | ||
| 94 | + "Table": { | ||
| 95 | + "table": "course_offering", | ||
| 96 | + "name": "created_at" | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + }, | ||
| 100 | + { | ||
| 101 | + "ordinal": 9, | ||
| 102 | + "name": "updated_at: Timestamp", | ||
| 103 | + "type_info": "Int8", | ||
| 104 | + "origin": { | ||
| 105 | + "Table": { | ||
| 106 | + "table": "course_offering", | ||
| 107 | + "name": "updated_at" | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | + ], | ||
| 112 | + "parameters": { | ||
| 113 | + "Left": [ | ||
| 114 | + "UuidArray" | ||
| 115 | + ] | ||
| 116 | + }, | ||
| 117 | + "nullable": [ | ||
| 118 | + false, | ||
| 119 | + false, | ||
| 120 | + false, | ||
| 121 | + true, | ||
| 122 | + true, | ||
| 123 | + null, | ||
| 124 | + true, | ||
| 125 | + false, | ||
| 126 | + false, | ||
| 127 | + false | ||
| 128 | + ] | ||
| 129 | + }, | ||
| 130 | + "hash": "d692aa84085905ea3e70d4a94b5e81ff85548c6aeb096ee914d5349bf525137a" | ||
| 131 | +} | ||
.sqlx/query-d863a8f429da502da7981c356a262f553ea0b23b4fd1569241119aac0f8d62cc.jsonadded+36 -0
| @@ -0,0 +1,36 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT kind, weight::bigint AS \"weight!: i64\"\n FROM offering_exam_weight WHERE offering = $1 AND kind = $2", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "kind", | ||
| 9 | + "type_info": "Text", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "offering_exam_weight", | ||
| 13 | + "name": "kind" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "weight!: i64", | ||
| 20 | + "type_info": "Int8", | ||
| 21 | + "origin": "Expression" | ||
| 22 | + } | ||
| 23 | + ], | ||
| 24 | + "parameters": { | ||
| 25 | + "Left": [ | ||
| 26 | + "Uuid", | ||
| 27 | + "Text" | ||
| 28 | + ] | ||
| 29 | + }, | ||
| 30 | + "nullable": [ | ||
| 31 | + false, | ||
| 32 | + null | ||
| 33 | + ] | ||
| 34 | + }, | ||
| 35 | + "hash": "d863a8f429da502da7981c356a262f553ea0b23b4fd1569241119aac0f8d62cc" | ||
| 36 | +} | ||
.sqlx/query-d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738.jsonadded+58 -0
| @@ -0,0 +1,58 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "INSERT INTO offering_slot (id, offering, weekday, starts_at, ends_at)\n VALUES ($1, $2, $3,\n ($4::bigint * interval '1 minute')::time,\n ($5::bigint * interval '1 minute')::time)\n RETURNING id AS \"id: WeeklySlotId\",\n weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\"", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: WeeklySlotId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "offering_slot", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "weekday: Weekday", | ||
| 20 | + "type_info": "Int2", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "offering_slot", | ||
| 24 | + "name": "weekday" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "starts_at!: SlotMinute", | ||
| 31 | + "type_info": "Int8", | ||
| 32 | + "origin": "Expression" | ||
| 33 | + }, | ||
| 34 | + { | ||
| 35 | + "ordinal": 3, | ||
| 36 | + "name": "ends_at!: SlotMinute", | ||
| 37 | + "type_info": "Int8", | ||
| 38 | + "origin": "Expression" | ||
| 39 | + } | ||
| 40 | + ], | ||
| 41 | + "parameters": { | ||
| 42 | + "Left": [ | ||
| 43 | + "Uuid", | ||
| 44 | + "Uuid", | ||
| 45 | + "Int2", | ||
| 46 | + "Int8", | ||
| 47 | + "Int8" | ||
| 48 | + ] | ||
| 49 | + }, | ||
| 50 | + "nullable": [ | ||
| 51 | + false, | ||
| 52 | + false, | ||
| 53 | + null, | ||
| 54 | + null | ||
| 55 | + ] | ||
| 56 | + }, | ||
| 57 | + "hash": "d930c577b90a403e259f6c1e8c4d4be6648243c4627e8719fff5cc4d38efb738" | ||
| 58 | +} | ||
.sqlx/query-e0876982733c62617ab8446239526f4da6f49846a4e7ee948a173ef54aafed1a.jsonadded+191 -0
| @@ -0,0 +1,191 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.offering AS \"offering: CourseOfferingId\",\n cc.attached_by AS \"attached_by: UserId\",\n b.grade_level AS \"source?: ClassBlueprintId\",\n cc.title AS \"title?: CourseTitle\",\n cc.description AS \"description?: CourseDescription\",\n cc.ders_saati::bigint AS \"ders_saati?: DersSaati\",\n cc.counts_toward_karne,\n cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,\n cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.class = ANY($1)\n ORDER BY cc.attached_at DESC, cc.id DESC", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: ClassCourseId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "class: ClassGroupId", | ||
| 20 | + "type_info": "Uuid", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "class_course", | ||
| 24 | + "name": "class" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "course: CourseId", | ||
| 31 | + "type_info": "Uuid", | ||
| 32 | + "origin": { | ||
| 33 | + "Table": { | ||
| 34 | + "table": "class_course", | ||
| 35 | + "name": "course" | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + }, | ||
| 39 | + { | ||
| 40 | + "ordinal": 3, | ||
| 41 | + "name": "offering: CourseOfferingId", | ||
| 42 | + "type_info": "Uuid", | ||
| 43 | + "origin": { | ||
| 44 | + "Table": { | ||
| 45 | + "table": "class_course", | ||
| 46 | + "name": "offering" | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + { | ||
| 51 | + "ordinal": 4, | ||
| 52 | + "name": "attached_by: UserId", | ||
| 53 | + "type_info": "Uuid", | ||
| 54 | + "origin": { | ||
| 55 | + "Table": { | ||
| 56 | + "table": "class_course", | ||
| 57 | + "name": "attached_by" | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + }, | ||
| 61 | + { | ||
| 62 | + "ordinal": 5, | ||
| 63 | + "name": "source?: ClassBlueprintId", | ||
| 64 | + "type_info": "Int2", | ||
| 65 | + "origin": { | ||
| 66 | + "Table": { | ||
| 67 | + "table": "class_blueprint", | ||
| 68 | + "name": "grade_level" | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | + }, | ||
| 72 | + { | ||
| 73 | + "ordinal": 6, | ||
| 74 | + "name": "title?: CourseTitle", | ||
| 75 | + "type_info": "Text", | ||
| 76 | + "origin": { | ||
| 77 | + "Table": { | ||
| 78 | + "table": "class_course", | ||
| 79 | + "name": "title" | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + }, | ||
| 83 | + { | ||
| 84 | + "ordinal": 7, | ||
| 85 | + "name": "description?: CourseDescription", | ||
| 86 | + "type_info": "Text", | ||
| 87 | + "origin": { | ||
| 88 | + "Table": { | ||
| 89 | + "table": "class_course", | ||
| 90 | + "name": "description" | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + }, | ||
| 94 | + { | ||
| 95 | + "ordinal": 8, | ||
| 96 | + "name": "ders_saati?: DersSaati", | ||
| 97 | + "type_info": "Int8", | ||
| 98 | + "origin": "Expression" | ||
| 99 | + }, | ||
| 100 | + { | ||
| 101 | + "ordinal": 9, | ||
| 102 | + "name": "counts_toward_karne", | ||
| 103 | + "type_info": "Bool", | ||
| 104 | + "origin": { | ||
| 105 | + "Table": { | ||
| 106 | + "table": "class_course", | ||
| 107 | + "name": "counts_toward_karne" | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + }, | ||
| 111 | + { | ||
| 112 | + "ordinal": 10, | ||
| 113 | + "name": "subjects_inherited", | ||
| 114 | + "type_info": "Bool", | ||
| 115 | + "origin": { | ||
| 116 | + "Table": { | ||
| 117 | + "table": "class_course", | ||
| 118 | + "name": "subjects_inherited" | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + }, | ||
| 122 | + { | ||
| 123 | + "ordinal": 11, | ||
| 124 | + "name": "exam_weights_inherited", | ||
| 125 | + "type_info": "Bool", | ||
| 126 | + "origin": { | ||
| 127 | + "Table": { | ||
| 128 | + "table": "class_course", | ||
| 129 | + "name": "exam_weights_inherited" | ||
| 130 | + } | ||
| 131 | + } | ||
| 132 | + }, | ||
| 133 | + { | ||
| 134 | + "ordinal": 12, | ||
| 135 | + "name": "weekly_plan_inherited", | ||
| 136 | + "type_info": "Bool", | ||
| 137 | + "origin": { | ||
| 138 | + "Table": { | ||
| 139 | + "table": "class_course", | ||
| 140 | + "name": "weekly_plan_inherited" | ||
| 141 | + } | ||
| 142 | + } | ||
| 143 | + }, | ||
| 144 | + { | ||
| 145 | + "ordinal": 13, | ||
| 146 | + "name": "enrollment_count", | ||
| 147 | + "type_info": "Int8", | ||
| 148 | + "origin": { | ||
| 149 | + "Table": { | ||
| 150 | + "table": "class_course", | ||
| 151 | + "name": "enrollment_count" | ||
| 152 | + } | ||
| 153 | + } | ||
| 154 | + }, | ||
| 155 | + { | ||
| 156 | + "ordinal": 14, | ||
| 157 | + "name": "attached_at: Timestamp", | ||
| 158 | + "type_info": "Int8", | ||
| 159 | + "origin": { | ||
| 160 | + "Table": { | ||
| 161 | + "table": "class_course", | ||
| 162 | + "name": "attached_at" | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + } | ||
| 166 | + ], | ||
| 167 | + "parameters": { | ||
| 168 | + "Left": [ | ||
| 169 | + "UuidArray" | ||
| 170 | + ] | ||
| 171 | + }, | ||
| 172 | + "nullable": [ | ||
| 173 | + false, | ||
| 174 | + false, | ||
| 175 | + false, | ||
| 176 | + false, | ||
| 177 | + false, | ||
| 178 | + false, | ||
| 179 | + true, | ||
| 180 | + true, | ||
| 181 | + null, | ||
| 182 | + true, | ||
| 183 | + false, | ||
| 184 | + false, | ||
| 185 | + false, | ||
| 186 | + false, | ||
| 187 | + false | ||
| 188 | + ] | ||
| 189 | + }, | ||
| 190 | + "hash": "e0876982733c62617ab8446239526f4da6f49846a4e7ee948a173ef54aafed1a" | ||
| 191 | +} | ||
.sqlx/query-e17820680b6881ea134fe37906611bc25d774d21850be124025fda552104867b.jsonadded+35 -0
| @@ -0,0 +1,35 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT kind, weight::bigint AS \"weight!: i64\"\n FROM offering_exam_weight WHERE offering = $1\n ORDER BY kind", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "kind", | ||
| 9 | + "type_info": "Text", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "offering_exam_weight", | ||
| 13 | + "name": "kind" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "weight!: i64", | ||
| 20 | + "type_info": "Int8", | ||
| 21 | + "origin": "Expression" | ||
| 22 | + } | ||
| 23 | + ], | ||
| 24 | + "parameters": { | ||
| 25 | + "Left": [ | ||
| 26 | + "Uuid" | ||
| 27 | + ] | ||
| 28 | + }, | ||
| 29 | + "nullable": [ | ||
| 30 | + false, | ||
| 31 | + null | ||
| 32 | + ] | ||
| 33 | + }, | ||
| 34 | + "hash": "e17820680b6881ea134fe37906611bc25d774d21850be124025fda552104867b" | ||
| 35 | +} | ||
.sqlx/query-e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351.jsonadded+54 -0
| @@ -0,0 +1,54 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT id AS \"id: WeeklySlotId\",\n weekday AS \"weekday: Weekday\",\n (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS \"starts_at!: SlotMinute\",\n (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS \"ends_at!: SlotMinute\"\n FROM class_course_slot\n WHERE class_course = $1\n ORDER BY weekday, starts_at", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "id: WeeklySlotId", | ||
| 9 | + "type_info": "Uuid", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course_slot", | ||
| 13 | + "name": "id" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "weekday: Weekday", | ||
| 20 | + "type_info": "Int2", | ||
| 21 | + "origin": { | ||
| 22 | + "Table": { | ||
| 23 | + "table": "class_course_slot", | ||
| 24 | + "name": "weekday" | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }, | ||
| 28 | + { | ||
| 29 | + "ordinal": 2, | ||
| 30 | + "name": "starts_at!: SlotMinute", | ||
| 31 | + "type_info": "Int8", | ||
| 32 | + "origin": "Expression" | ||
| 33 | + }, | ||
| 34 | + { | ||
| 35 | + "ordinal": 3, | ||
| 36 | + "name": "ends_at!: SlotMinute", | ||
| 37 | + "type_info": "Int8", | ||
| 38 | + "origin": "Expression" | ||
| 39 | + } | ||
| 40 | + ], | ||
| 41 | + "parameters": { | ||
| 42 | + "Left": [ | ||
| 43 | + "Uuid" | ||
| 44 | + ] | ||
| 45 | + }, | ||
| 46 | + "nullable": [ | ||
| 47 | + false, | ||
| 48 | + false, | ||
| 49 | + null, | ||
| 50 | + null | ||
| 51 | + ] | ||
| 52 | + }, | ||
| 53 | + "hash": "e5505bb02b156cc94939881d352b2ff94efb5d2bef4ec746afdd68d65746d351" | ||
| 54 | +} | ||
.sqlx/query-e6c03c7c747131bd9060a3f8a8eff1cf34e8727b6c3ac7222620b87b0dc1eeb1.jsonadded+23 -0
| @@ -0,0 +1,23 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT 1 AS \"one\" FROM course_offering WHERE id = $1", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "one", | ||
| 9 | + "type_info": "Int4", | ||
| 10 | + "origin": "Expression" | ||
| 11 | + } | ||
| 12 | + ], | ||
| 13 | + "parameters": { | ||
| 14 | + "Left": [ | ||
| 15 | + "Uuid" | ||
| 16 | + ] | ||
| 17 | + }, | ||
| 18 | + "nullable": [ | ||
| 19 | + null | ||
| 20 | + ] | ||
| 21 | + }, | ||
| 22 | + "hash": "e6c03c7c747131bd9060a3f8a8eff1cf34e8727b6c3ac7222620b87b0dc1eeb1" | ||
| 23 | +} | ||
.sqlx/query-5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b.json → .sqlx/query-e8784821e75fe4ab681ff91695d953af6c4abd32821251f7804ef02c4e637cf8.jsonrenamed+3 -3
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "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)", | 3 | + "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)", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -28,7 +28,7 @@ | |||
| 28 | ], | 28 | ], |
| 29 | "parameters": { | 29 | "parameters": { |
| 30 | "Left": [ | 30 | "Left": [ |
| 31 | - "Text", | 31 | + "Int2", |
| 32 | "UuidArray" | 32 | "UuidArray" |
| 33 | ] | 33 | ] |
| 34 | }, | 34 | }, |
| @@ -37,5 +37,5 @@ | |||
| 37 | false | 37 | false |
| 38 | ] | 38 | ] |
| 39 | }, | 39 | }, |
| 40 | - "hash": "5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b" | 40 | + "hash": "e8784821e75fe4ab681ff91695d953af6c4abd32821251f7804ef02c4e637cf8" |
| 41 | } | 41 | } |
.sqlx/query-eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e.jsondeleted+0 -88
| @@ -1,88 +0,0 @@ | |||
| 1 | -{ | ||
| 2 | - "db_name": "PostgreSQL", | ||
| 3 | - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE grade = $1", | ||
| 4 | - "describe": { | ||
| 5 | - "columns": [ | ||
| 6 | - { | ||
| 7 | - "ordinal": 0, | ||
| 8 | - "name": "id: ClassGroupId", | ||
| 9 | - "type_info": "Uuid", | ||
| 10 | - "origin": { | ||
| 11 | - "Table": { | ||
| 12 | - "table": "class_group", | ||
| 13 | - "name": "id" | ||
| 14 | - } | ||
| 15 | - } | ||
| 16 | - }, | ||
| 17 | - { | ||
| 18 | - "ordinal": 1, | ||
| 19 | - "name": "creator: UserId", | ||
| 20 | - "type_info": "Uuid", | ||
| 21 | - "origin": { | ||
| 22 | - "Table": { | ||
| 23 | - "table": "class_group", | ||
| 24 | - "name": "creator" | ||
| 25 | - } | ||
| 26 | - } | ||
| 27 | - }, | ||
| 28 | - { | ||
| 29 | - "ordinal": 2, | ||
| 30 | - "name": "name: ClassName", | ||
| 31 | - "type_info": "Text", | ||
| 32 | - "origin": { | ||
| 33 | - "Table": { | ||
| 34 | - "table": "class_group", | ||
| 35 | - "name": "name" | ||
| 36 | - } | ||
| 37 | - } | ||
| 38 | - }, | ||
| 39 | - { | ||
| 40 | - "ordinal": 3, | ||
| 41 | - "name": "grade: ClassGrade", | ||
| 42 | - "type_info": "Text", | ||
| 43 | - "origin": { | ||
| 44 | - "Table": { | ||
| 45 | - "table": "class_group", | ||
| 46 | - "name": "grade" | ||
| 47 | - } | ||
| 48 | - } | ||
| 49 | - }, | ||
| 50 | - { | ||
| 51 | - "ordinal": 4, | ||
| 52 | - "name": "year: AcademicYearId", | ||
| 53 | - "type_info": "Uuid", | ||
| 54 | - "origin": { | ||
| 55 | - "Table": { | ||
| 56 | - "table": "class_group", | ||
| 57 | - "name": "year" | ||
| 58 | - } | ||
| 59 | - } | ||
| 60 | - }, | ||
| 61 | - { | ||
| 62 | - "ordinal": 5, | ||
| 63 | - "name": "teacher: UserId", | ||
| 64 | - "type_info": "Uuid", | ||
| 65 | - "origin": { | ||
| 66 | - "Table": { | ||
| 67 | - "table": "class_group", | ||
| 68 | - "name": "teacher" | ||
| 69 | - } | ||
| 70 | - } | ||
| 71 | - } | ||
| 72 | - ], | ||
| 73 | - "parameters": { | ||
| 74 | - "Left": [ | ||
| 75 | - "Text" | ||
| 76 | - ] | ||
| 77 | - }, | ||
| 78 | - "nullable": [ | ||
| 79 | - false, | ||
| 80 | - false, | ||
| 81 | - false, | ||
| 82 | - true, | ||
| 83 | - true, | ||
| 84 | - true | ||
| 85 | - ] | ||
| 86 | - }, | ||
| 87 | - "hash": "eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e" | ||
| 88 | -} | ||
.sqlx/query-b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f.json → .sqlx/query-f0638db11ad696e78ee6a72951c1983881eafa5fafeb80813293bd778717080f.jsonrenamed+6 -6
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "db_name": "PostgreSQL", | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE year = $1 ORDER BY id", | 3 | + "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", |
| 4 | "describe": { | 4 | "describe": { |
| 5 | "columns": [ | 5 | "columns": [ |
| 6 | { | 6 | { |
| @@ -38,12 +38,12 @@ | |||
| 38 | }, | 38 | }, |
| 39 | { | 39 | { |
| 40 | "ordinal": 3, | 40 | "ordinal": 3, |
| 41 | - "name": "grade: ClassGrade", | 41 | + "name": "grade_level: GradeLevel", |
| 42 | - "type_info": "Text", | 42 | + "type_info": "Int2", |
| 43 | "origin": { | 43 | "origin": { |
| 44 | "Table": { | 44 | "Table": { |
| 45 | "table": "class_group", | 45 | "table": "class_group", |
| 46 | - "name": "grade" | 46 | + "name": "grade_level" |
| 47 | } | 47 | } |
| 48 | } | 48 | } |
| 49 | }, | 49 | }, |
| @@ -79,10 +79,10 @@ | |||
| 79 | false, | 79 | false, |
| 80 | false, | 80 | false, |
| 81 | false, | 81 | false, |
| 82 | - true, | 82 | + false, |
| 83 | true, | 83 | true, |
| 84 | true | 84 | true |
| 85 | ] | 85 | ] |
| 86 | }, | 86 | }, |
| 87 | - "hash": "b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f" | 87 | + "hash": "f0638db11ad696e78ee6a72951c1983881eafa5fafeb80813293bd778717080f" |
| 88 | } | 88 | } |
.sqlx/query-f085293284bed3226150271a91561f7c1d3953b66c413aa1b0f0349fa350f8ab.jsonadded+35 -0
| @@ -0,0 +1,35 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "query": "SELECT kind, weight::bigint AS \"weight!: i64\"\n FROM class_course_exam_weight WHERE class_course = $1\n ORDER BY kind", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "kind", | ||
| 9 | + "type_info": "Text", | ||
| 10 | + "origin": { | ||
| 11 | + "Table": { | ||
| 12 | + "table": "class_course_exam_weight", | ||
| 13 | + "name": "kind" | ||
| 14 | + } | ||
| 15 | + } | ||
| 16 | + }, | ||
| 17 | + { | ||
| 18 | + "ordinal": 1, | ||
| 19 | + "name": "weight!: i64", | ||
| 20 | + "type_info": "Int8", | ||
| 21 | + "origin": "Expression" | ||
| 22 | + } | ||
| 23 | + ], | ||
| 24 | + "parameters": { | ||
| 25 | + "Left": [ | ||
| 26 | + "Uuid" | ||
| 27 | + ] | ||
| 28 | + }, | ||
| 29 | + "nullable": [ | ||
| 30 | + false, | ||
| 31 | + null | ||
| 32 | + ] | ||
| 33 | + }, | ||
| 34 | + "hash": "f085293284bed3226150271a91561f7c1d3953b66c413aa1b0f0349fa350f8ab" | ||
| 35 | +} | ||
.sqlx/query-f46c1dcb86e2a1a7a542afaed21054de776315e010bfd709f5408df7259ed02b.jsonadded+31 -0
| @@ -0,0 +1,31 @@ | |||
| 1 | +{ | ||
| 2 | + "db_name": "PostgreSQL", | ||
| 3 | + "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!\"", | ||
| 4 | + "describe": { | ||
| 5 | + "columns": [ | ||
| 6 | + { | ||
| 7 | + "ordinal": 0, | ||
| 8 | + "name": "live!", | ||
| 9 | + "type_info": "Bool", | ||
| 10 | + "origin": "Expression" | ||
| 11 | + }, | ||
| 12 | + { | ||
| 13 | + "ordinal": 1, | ||
| 14 | + "name": "added!", | ||
| 15 | + "type_info": "Bool", | ||
| 16 | + "origin": "Expression" | ||
| 17 | + } | ||
| 18 | + ], | ||
| 19 | + "parameters": { | ||
| 20 | + "Left": [ | ||
| 21 | + "Uuid", | ||
| 22 | + "Uuid" | ||
| 23 | + ] | ||
| 24 | + }, | ||
| 25 | + "nullable": [ | ||
| 26 | + null, | ||
| 27 | + null | ||
| 28 | + ] | ||
| 29 | + }, | ||
| 30 | + "hash": "f46c1dcb86e2a1a7a542afaed21054de776315e010bfd709f5408df7259ed02b" | ||
| 31 | +} | ||
README.mdmodified+55 -15
| @@ -33,7 +33,17 @@ teaching happens in the **instance** — one class section × one course, create | |||
| 33 | when the course is attached to the section (`POST /classes/{id}/instances`) and | 33 | when the course is attached to the section (`POST /classes/{id}/instances`) and |
| 34 | living at `/instances/{id}` with its own `ders_saati` (weekly lesson hours, its | 34 | living at `/instances/{id}` with its own `ders_saati` (weekly lesson hours, its |
| 35 | weight in the karne average), `counts_toward_karne` flag, teachers, roster, | 35 | weight in the karne average), `counts_toward_karne` flag, teachers, roster, |
| 36 | -exams, lesson sessions and homework. Two sections that attach Matematik get | 36 | +exams, lesson sessions and homework. Between catalog and instance sits the |
| 37 | +**grade-level template**: attaching a course to a section resolves (or mints) | ||
| 38 | +an **offering** (`/offerings`) — one row per course × `grade_level` carrying | ||
| 39 | +the grade's title, description, weekly-hours and report-card defaults, syllabus | ||
| 40 | +topics, exam-kind weights and weekly plan. The instance **overrides or | ||
| 41 | +inherits**, never merges: an unset scalar follows the offering (and through it | ||
| 42 | +the catalog row or the constant), a set is flag-driven and authoritative even | ||
| 43 | +when empty, and every instance-scoped read — instance, marks, attendance, | ||
| 44 | +karne — displays the **resolved** result, so a 9th-grade and a 12th-grade | ||
| 45 | +section teaching the same ders each show their own grade's content. Two sections | ||
| 46 | +that attach Matematik get | ||
| 37 | **two** instances and share nothing: adding a student to 5-A enrolls them in | 47 | **two** instances and share nothing: adding a student to 5-A enrolls them in |
| 38 | 5-A's Matematik only, and an exam written on 5-A's Matematik is invisible to | 48 | 5-A's Matematik only, and an exam written on 5-A's Matematik is invisible to |
| 39 | 5-B — unless the exam is **announced** to 5-B as an *ortak sınav* | 49 | 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: | |||
| 723 | and fails unless each one is either referenced by `src/web/limits.rs` or | 733 | and fails unless each one is either referenced by `src/web/limits.rs` or |
| 724 | listed as a deliberate exclusion *with a reason*. A new constant breaks the | 734 | listed as a deliberate exclusion *with a reason*. A new constant breaks the |
| 725 | suite until someone decides, consciously, whether clients need it. | 735 | suite until someone decides, consciously, whether clients need it. |
| 726 | -- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 220 published | 736 | +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 239 published |
| 727 | bounds back out of the emitted JSON, and asserts each equals its constant. | 737 | bounds back out of the emitted JSON, and asserts each equals its constant. |
| 728 | This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal | 738 | This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal |
| 729 | only** — a `const` there does not compile — so the annotations are | 739 | 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. | |||
| 1213 | | 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. | | 1223 | | 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. | |
| 1214 | | 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. | | 1224 | | 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. | |
| 1215 | | 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. | | 1225 | | 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. | |
| 1216 | -| 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. | | 1226 | +| 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. | |
| 1217 | -| 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. | | 1227 | +| 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. | |
| 1218 | | GET | `/classes/blueprints` | manager | List every grade blueprint, by grade label. Requires manager+. Paged via `?limit=&offset=` (omit `limit` for all of them). | | 1228 | | GET | `/classes/blueprints` | manager | List every grade blueprint, by grade label. Requires manager+. Paged via `?limit=&offset=` (omit `limit` for all of them). | |
| 1219 | | POST | `/classes/blueprints` | manager | Create a grade's course blueprint and stock every class section already at that grade with it. Requires manager+. | | 1229 | | POST | `/classes/blueprints` | manager | Create a grade's course blueprint and stock every class section already at that grade with it. Requires manager+. | |
| 1220 | | GET | `/classes/blueprints/{grade}` | manager | Fetch one grade's blueprint. Requires manager+. | | 1230 | | 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. | |||
| 1287 | | 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`. | | 1297 | | 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`. | |
| 1288 | | 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. | | 1298 | | 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. | |
| 1289 | | 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. | | 1299 | | 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. | |
| 1290 | -| 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. | | 1300 | +| 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. | |
| 1291 | | 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. | | 1301 | | 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. | |
| 1292 | | 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. | | 1302 | | 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. | |
| 1293 | | 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. | | 1303 | | 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. | |||
| 1316 | | 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. | | 1326 | | 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. | |
| 1317 | | 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. | | 1327 | | 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. | |
| 1318 | | 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. | | 1328 | | 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. | |
| 1319 | -| 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. | | 1329 | +| 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. | |
| 1320 | | 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. | | 1330 | | 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. | |
| 1321 | | 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. | | 1331 | | 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. | |
| 1322 | | 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. | | 1332 | | 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. | |||
| 1346 | | POST | `/insights/sweep` | manager | Delete every `zeka_*` row whose retention window has closed. | | 1356 | | POST | `/insights/sweep` | manager | Delete every `zeka_*` row whose retention window has closed. | |
| 1347 | | 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. | | 1357 | | 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. | |
| 1348 | | 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. | | 1358 | | 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. | |
| 1349 | -| 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. | | 1359 | +| 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. | |
| 1350 | | 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. | | 1360 | | 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. | |
| 1351 | | 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. | | 1361 | | 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. | |
| 1352 | | 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). | | 1362 | | 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). | |
| 1363 | +| 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. | | ||
| 1364 | +| 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). | | ||
| 1365 | +| 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. | | ||
| 1366 | +| 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. | | ||
| 1353 | | 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. | | 1367 | | 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. | |
| 1354 | | 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. | | 1368 | | 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. | |
| 1355 | | 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. | | 1369 | | 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. | |
| 1356 | | 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). | | 1370 | | 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). | |
| 1371 | +| 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. | | ||
| 1357 | | 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. | | 1372 | | 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. | |
| 1358 | | 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. | | 1373 | | 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. | |
| 1374 | +| 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. | | ||
| 1375 | +| 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. | | ||
| 1376 | +| 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. | | ||
| 1377 | +| 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. | | ||
| 1359 | | 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. | | 1378 | | 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. | |
| 1360 | | 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. | | 1379 | | 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. | |
| 1380 | +| 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. | | ||
| 1381 | +| 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. | | ||
| 1382 | +| 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. | | ||
| 1383 | +| 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. | | ||
| 1361 | | 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. | | 1384 | | 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. | |
| 1362 | | 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. | | 1385 | | 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. | |
| 1363 | | 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`]). | | 1386 | | 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. | |||
| 1400 | | 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). | | 1423 | | 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). | |
| 1401 | | 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. | | 1424 | | 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. | |
| 1402 | | DELETE | `/notes/{id}/files/{file_id}` | student | Delete a note file (row first, then its blob). | | 1425 | | DELETE | `/notes/{id}/files/{file_id}` | student | Delete a note file (row first, then its blob). | |
| 1426 | +| 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. | | ||
| 1427 | +| 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`. | | ||
| 1428 | +| 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. | | ||
| 1429 | +| 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. | | ||
| 1430 | +| 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). | | ||
| 1431 | +| GET | `/offerings/{id}/exam-weights` | student | The grade-level template's resolved exam-kind weights. Any signed-in session. | | ||
| 1432 | +| 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. | | ||
| 1433 | +| 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. | | ||
| 1434 | +| 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. | | ||
| 1435 | +| 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). | | ||
| 1436 | +| 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. | | ||
| 1437 | +| 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. | | ||
| 1438 | +| 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. | | ||
| 1439 | +| 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. | | ||
| 1403 | | GET | `/payments/balance/me` | student | What the caller owes the school (or has on account). | | 1440 | | GET | `/payments/balance/me` | student | What the caller owes the school (or has on account). | |
| 1404 | | GET | `/payments/balance/{user}` | manager | One student's fee balance. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). | | 1441 | | GET | `/payments/balance/{user}` | manager | One student's fee balance. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). | |
| 1405 | | 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". | | 1442 | | 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. | |||
| 3490 | 3527 | ||
| 3491 | A **class section** is the group a school actually teaches in — 9-A, 10-B — and | 3528 | A **class section** is the group a school actually teaches in — 9-A, 10-B — and |
| 3492 | it is the **academic anchor**: a student's membership, the courses it carries, | 3529 | it is the **academic anchor**: a student's membership, the courses it carries, |
| 3493 | -their exams and their homework all hang off it. Its row carries a name, an | 3530 | +their exams and their homework all hang off it. Its row carries a name, its |
| 3494 | -optional free-text `grade` label in the school's own vocabulary (`"9"`, | 3531 | +rung on the school's grade ladder (`grade_level`, `0` = anaokulu, `1..=12` the |
| 3495 | -`"Lise 2"`; `""` means no grade, exactly like omitting it) and the **academic | 3532 | +school years) and the **academic year** it runs in (`year`, nullable while a |
| 3496 | -year** it runs in (`year`, nullable while a section is being prepared). A | 3533 | +section is being prepared). A section does not teach a course directly: |
| 3497 | -section does not teach a course directly: attaching one mints an **instance** | 3534 | +attaching one mints an **instance** |
| 3498 | -(`/instances`) — its own row, with its own teachers, `ders_saati`, karne weight, | 3535 | +(`/instances`) — its own row, teaching from its grade's **offering** template |
| 3536 | +(`/offerings`, overridable per section: title, description, weekly hours, | ||
| 3537 | +report-card policy, syllabus, weights, weekly plan — unset fields inherit), | ||
| 3538 | +with its own teachers, `ders_saati`, karne weight, | ||
| 3499 | roster, exams, sessions and homework — and two sections that attach the same | 3539 | roster, exams, sessions and homework — and two sections that attach the same |
| 3500 | course share nothing at all. Schools that run electives or a college-style | 3540 | course share nothing at all. Schools that run electives or a college-style |
| 3501 | timetable simply never create one — individual enrollment and the school-scoped | 3541 | timetable simply never create one — individual enrollment and the school-scoped |
| @@ -3675,9 +3715,9 @@ overloaded axis clears it. | |||
| 3675 | 3715 | ||
| 3676 | A Turkish school runs many şube at one grade and stocks each with the same | 3716 | A Turkish school runs many şube at one grade and stocks each with the same |
| 3677 | courses. A blueprint says that list once: `POST /classes/blueprints` with a | 3717 | courses. A blueprint says that list once: `POST /classes/blueprints` with a |
| 3678 | -`grade` label and `course_ids`, and every section already at that grade is | 3718 | +`grade_level` rung and `course_ids`, and every section already at that rung is |
| 3679 | stocked immediately. `POST /classes/{id}/blueprint` stocks one section from its | 3719 | stocked immediately. `POST /classes/{id}/blueprint` stocks one section from its |
| 3680 | -grade's template — idempotent, so it is safe on a class that already carries | 3720 | +rung's template — idempotent, so it is safe on a class that already carries |
| 3681 | some of the courses. | 3721 | some of the courses. |
| 3682 | 3722 | ||
| 3683 | The blueprint is a template, not a new kind of membership. Applying it calls | 3723 | The blueprint is a template, not a new kind of membership. Applying it calls |
src/constant.rsmodified+25 -5
| @@ -107,12 +107,17 @@ pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; | |||
| 107 | pub const MAX_COURSE_TITLE_LEN: usize = 200; | 107 | pub const MAX_COURSE_TITLE_LEN: usize = 200; |
| 108 | pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; | 108 | pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; |
| 109 | 109 | ||
| 110 | -/// A class section is named like a course, but its optional `grade` is | 110 | +/// A class section is named like a course. `MAX_CLASS_GRADE_LEN` is gone with |
| 111 | -/// a free-text label the school picks ("9", "10-A", "kindergarten") — a line of | 111 | +/// the free-text grade it bounded: a class now carries a validated ladder |
| 112 | -/// display text, so it is bounded like the other short labels, not like a | 112 | +/// position (`MIN_GRADE_LEVEL`..=`MAX_GRADE_LEVEL`, `0` = anaokulu), which |
| 113 | -/// description. | 113 | +/// needs a length bound no more than a week day does. |
| 114 | pub const MAX_CLASS_NAME_LEN: usize = 200; | 114 | pub const MAX_CLASS_NAME_LEN: usize = 200; |
| 115 | -pub const MAX_CLASS_GRADE_LEN: usize = 20; | 115 | + |
| 116 | +/// The grade ladder every class section and course template sits on. `0` is | ||
| 117 | +/// anaokulu (kindergarten), `1..=12` the school years; [`MAX_GRADE_LEVEL`] | ||
| 118 | +/// graduating is expressed by the absence of a promotion, not a 13th rung. | ||
| 119 | +pub const MIN_GRADE_LEVEL: i16 = 0; | ||
| 120 | +pub const MAX_GRADE_LEVEL: i16 = 12; | ||
| 116 | 121 | ||
| 117 | /// How big one class may get, on each of its two axes. These are not comfort | 122 | /// How big one class may get, on each of its two axes. These are not comfort |
| 118 | /// numbers: attaching a course to a class writes one enrollment per member and | 123 | /// numbers: attaching a course to a class writes one enrollment per member and |
| @@ -137,6 +142,21 @@ pub const MAX_CLASS_COURSES: i64 = 50; | |||
| 137 | pub const MIN_DERS_SAATI: i64 = 1; | 142 | pub const MIN_DERS_SAATI: i64 = 1; |
| 138 | pub const MAX_DERS_SAATI: i64 = 40; | 143 | pub const MAX_DERS_SAATI: i64 = 40; |
| 139 | 144 | ||
| 145 | +/// How many slots one owner's weekly plan may hold. A slot is where one of | ||
| 146 | +/// the week's lesson hours lands, and a course teaches at most | ||
| 147 | +/// `MAX_DERS_SAATI` (40) hours a week — so 40 bounds any honest timetable | ||
| 148 | +/// (the bounds are the same number by construction) and stops a pathological | ||
| 149 | +/// client at the bound every other weekly-hours loop already answers to. | ||
| 150 | +pub const MAX_WEEKLY_SLOTS: usize = MAX_DERS_SAATI as usize; | ||
| 151 | + | ||
| 152 | +/// The earliest minute a weekly-plan slot may start or end: midnight. | ||
| 153 | +pub const MIN_SLOT_MINUTE: i64 = 0; | ||
| 154 | + | ||
| 155 | +/// The latest minute a weekly-plan slot may start or end: 23:59. (A `TIME` | ||
| 156 | +/// column has no `24:00` to carry a midnight end, and the | ||
| 157 | +/// minutes-past-midnight wire form never lies about it.) | ||
| 158 | +pub const MAX_SLOT_MINUTE: i64 = 24 * 60 - 1; | ||
| 159 | + | ||
| 140 | /// The default grade-display bands: the Turkish 5-point scale (85–100 = 5, | 160 | /// The default grade-display bands: the Turkish 5-point scale (85–100 = 5, |
| 141 | /// … 0–44 = 1). Schools edit the list via `PATCH /settings`; the report-card | 161 | /// … 0–44 = 1). Schools edit the list via `PATCH /settings`; the report-card |
| 142 | /// verdict reads the band labelled `"2"` as the pass boundary. | 162 | /// verdict reads the band labelled `"2"` as the pass boundary. |
src/db/class_blueprint.rsmodified+29 -29
| @@ -1,4 +1,4 @@ | |||
| 1 | -//! The `class_blueprint` table: the row keyed by its grade label, the | 1 | +//! The `class_blueprint` table: the row keyed by its ladder rung, the |
| 2 | //! compare-and-set writes the edit and the delete go through, and the reads | 2 | //! compare-and-set writes the edit and the delete go through, and the reads |
| 3 | //! the sweep and the status screen are built on. The workflows that sequence | 3 | //! the sweep and the status screen are built on. The workflows that sequence |
| 4 | //! these — and the row lock that serializes a delete against the attaches | 4 | //! 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}; | |||
| 13 | use crate::db::class_pump; | 13 | use crate::db::class_pump; |
| 14 | use crate::db::page::PagedList; | 14 | use crate::db::page::PagedList; |
| 15 | use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId}; | 15 | use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId}; |
| 16 | -use crate::domain::class_group::{ClassGrade, ClassGroupId}; | 16 | +use crate::domain::class_group::ClassGroupId; |
| 17 | +use crate::domain::grade::GradeLevel; | ||
| 17 | use crate::domain::course::CourseId; | 18 | use crate::domain::course::CourseId; |
| 18 | use crate::domain::monotonic_id::next_uuid; | 19 | use crate::domain::monotonic_id::next_uuid; |
| 19 | use crate::domain::user::UserId; | 20 | use crate::domain::user::UserId; |
| @@ -29,17 +30,17 @@ struct BlueprintRow { | |||
| 29 | /// The surrogate uuid primary key — the key the junction rows reference. | 30 | /// The surrogate uuid primary key — the key the junction rows reference. |
| 30 | #[sqlx(rename = "id")] | 31 | #[sqlx(rename = "id")] |
| 31 | key: uuid::Uuid, | 32 | key: uuid::Uuid, |
| 32 | - grade: ClassGrade, | 33 | + grade_level: GradeLevel, |
| 33 | creator: UserId, | 34 | creator: UserId, |
| 34 | } | 35 | } |
| 35 | 36 | ||
| 36 | impl BlueprintRow { | 37 | impl BlueprintRow { |
| 37 | fn into_blueprint(self, courses: Vec<CourseId>) -> ClassBlueprint { | 38 | fn into_blueprint(self, courses: Vec<CourseId>) -> ClassBlueprint { |
| 38 | ClassBlueprint { | 39 | ClassBlueprint { |
| 39 | - // The API identity is the grade label, which the key column also | 40 | + // The API identity is the ladder rung, which the key column also |
| 40 | - // stores — the id *is* the grade. | 41 | + // stores — the id *is* the grade level. |
| 41 | - id: ClassBlueprintId::for_grade(&self.grade), | 42 | + id: ClassBlueprintId::for_grade(&self.grade_level), |
| 42 | - grade: self.grade, | 43 | + grade_level: self.grade_level, |
| 43 | courses, | 44 | courses, |
| 44 | creator: self.creator, | 45 | creator: self.creator, |
| 45 | } | 46 | } |
| @@ -155,16 +156,16 @@ fn no_such_course() -> AppError { | |||
| 155 | /// carries a UNIQUE constraint, so the duplicate is seen rather than raced | 156 | /// carries a UNIQUE constraint, so the duplicate is seen rather than raced |
| 156 | /// (`23505` on `class_blueprint_grade_key`, mapped right here: a duplicate is | 157 | /// (`23505` on `class_blueprint_grade_key`, mapped right here: a duplicate is |
| 157 | /// a decision, never a retry). The surrogate `id` is minted here and never | 158 | /// a decision, never a retry). The surrogate `id` is minted here and never |
| 158 | -/// read back: the grade label stays the only identity the API speaks. | 159 | +/// read back: the ladder rung stays the only identity the API speaks. |
| 159 | pub async fn create( | 160 | pub async fn create( |
| 160 | db: &Database, | 161 | db: &Database, |
| 161 | creator: &UserId, | 162 | creator: &UserId, |
| 162 | - grade: ClassGrade, | 163 | + grade_level: GradeLevel, |
| 163 | courses: Vec<CourseId>, | 164 | courses: Vec<CourseId>, |
| 164 | ) -> Result<ClassBlueprint, AppError> { | 165 | ) -> Result<ClassBlueprint, AppError> { |
| 165 | let blueprint = ClassBlueprint { | 166 | let blueprint = ClassBlueprint { |
| 166 | - id: ClassBlueprintId::for_grade(&grade), | 167 | + id: ClassBlueprintId::for_grade(&grade_level), |
| 167 | - grade: grade.clone(), | 168 | + grade_level, |
| 168 | courses: courses.clone(), | 169 | courses: courses.clone(), |
| 169 | creator: *creator, | 170 | creator: *creator, |
| 170 | }; | 171 | }; |
| @@ -173,10 +174,10 @@ pub async fn create( | |||
| 173 | tx_with_retry(db, false, async move |tx| { | 174 | tx_with_retry(db, false, async move |tx| { |
| 174 | courses_alive(tx, &courses).await?; | 175 | courses_alive(tx, &courses).await?; |
| 175 | let inserted = sqlx::query!( | 176 | let inserted = sqlx::query!( |
| 176 | - r#"INSERT INTO class_blueprint (id, grade, creator) | 177 | + r#"INSERT INTO class_blueprint (id, grade_level, creator) |
| 177 | VALUES ($1, $2, $3)"#, | 178 | VALUES ($1, $2, $3)"#, |
| 178 | id, | 179 | id, |
| 179 | - grade as _, | 180 | + grade_level as _, |
| 180 | creator as _ | 181 | creator as _ |
| 181 | ) | 182 | ) |
| 182 | .execute(&mut *tx) | 183 | .execute(&mut *tx) |
| @@ -209,9 +210,9 @@ pub async fn read( | |||
| 209 | ) -> Result<Option<ClassBlueprint>, AppError> { | 210 | ) -> Result<Option<ClassBlueprint>, AppError> { |
| 210 | let row = sqlx::query_as!( | 211 | let row = sqlx::query_as!( |
| 211 | BlueprintRow, | 212 | BlueprintRow, |
| 212 | - r#"SELECT id AS "key: uuid::Uuid", grade AS "grade: ClassGrade", | 213 | + r#"SELECT id AS "key: uuid::Uuid", grade_level AS "grade_level: GradeLevel", |
| 213 | creator AS "creator: UserId" | 214 | creator AS "creator: UserId" |
| 214 | - FROM class_blueprint WHERE grade = $1"#, | 215 | + FROM class_blueprint WHERE grade_level = $1"#, |
| 215 | id as _ | 216 | id as _ |
| 216 | ) | 217 | ) |
| 217 | .fetch_optional(db) | 218 | .fetch_optional(db) |
| @@ -225,14 +226,14 @@ pub async fn read( | |||
| 225 | } | 226 | } |
| 226 | } | 227 | } |
| 227 | 228 | ||
| 228 | -/// Every blueprint, by grade label — the id *is* the label, so this is the | 229 | +/// Every blueprint, by ladder rung — the id *is* the rung, so this is the |
| 229 | /// only ordering that means anything here. | 230 | /// only ordering that means anything here. |
| 230 | pub async fn list_all( | 231 | pub async fn list_all( |
| 231 | db: &Database, | 232 | db: &Database, |
| 232 | limit: Option<i64>, | 233 | limit: Option<i64>, |
| 233 | offset: i64, | 234 | offset: i64, |
| 234 | ) -> Result<(Vec<ClassBlueprint>, i64), AppError> { | 235 | ) -> Result<(Vec<ClassBlueprint>, i64), AppError> { |
| 235 | - let (rows, total) = PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade ASC") | 236 | + let (rows, total) = PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade_level ASC") |
| 236 | .run::<BlueprintRow>(limit, offset, db) | 237 | .run::<BlueprintRow>(limit, offset, db) |
| 237 | .await?; | 238 | .await?; |
| 238 | Ok((with_courses(db, rows).await?, total)) | 239 | Ok((with_courses(db, rows).await?, total)) |
| @@ -261,17 +262,17 @@ pub async fn set_courses_if_unchanged( | |||
| 261 | held: Vec<CourseId>, | 262 | held: Vec<CourseId>, |
| 262 | wanted: Vec<CourseId>, | 263 | wanted: Vec<CourseId>, |
| 263 | ) -> Result<Option<ClassBlueprint>, AppError> { | 264 | ) -> Result<Option<ClassBlueprint>, AppError> { |
| 264 | - let grade = id.clone(); | 265 | + let grade = id.get(); |
| 265 | let mut held = held; | 266 | let mut held = held; |
| 266 | held.sort_by_key(|course| course.uuid()); | 267 | held.sort_by_key(|course| course.uuid()); |
| 267 | let keys: Vec<uuid::Uuid> = wanted.iter().map(CourseId::uuid).collect(); | 268 | let keys: Vec<uuid::Uuid> = wanted.iter().map(CourseId::uuid).collect(); |
| 268 | tx_with_retry(db, false, async move |tx| { | 269 | tx_with_retry(db, false, async move |tx| { |
| 269 | courses_alive(tx, &wanted).await?; | 270 | courses_alive(tx, &wanted).await?; |
| 270 | let row = sqlx::query!( | 271 | let row = sqlx::query!( |
| 271 | - r#"SELECT id AS "key: uuid::Uuid", grade AS "grade: ClassGrade", | 272 | + r#"SELECT id AS "key: uuid::Uuid", grade_level AS "grade_level: GradeLevel", |
| 272 | creator AS "creator: UserId" | 273 | creator AS "creator: UserId" |
| 273 | - FROM class_blueprint WHERE grade = $1 FOR UPDATE"#, | 274 | + FROM class_blueprint WHERE grade_level = $1 FOR UPDATE"#, |
| 274 | - grade.key(), | 275 | + grade, |
| 275 | ) | 276 | ) |
| 276 | .fetch_optional(&mut *tx) | 277 | .fetch_optional(&mut *tx) |
| 277 | .await?; | 278 | .await?; |
| @@ -303,8 +304,8 @@ pub async fn set_courses_if_unchanged( | |||
| 303 | .execute(&mut *tx) | 304 | .execute(&mut *tx) |
| 304 | .await?; | 305 | .await?; |
| 305 | Ok(Some(ClassBlueprint { | 306 | Ok(Some(ClassBlueprint { |
| 306 | - id: ClassBlueprintId::for_grade(&row.grade), | 307 | + id: ClassBlueprintId::for_grade(&row.grade_level), |
| 307 | - grade: row.grade, | 308 | + grade_level: row.grade_level, |
| 308 | courses: wanted.clone(), | 309 | courses: wanted.clone(), |
| 309 | creator: row.creator, | 310 | creator: row.creator, |
| 310 | })) | 311 | })) |
| @@ -328,9 +329,8 @@ pub async fn delete_if_unchanged( | |||
| 328 | id: &ClassBlueprintId, | 329 | id: &ClassBlueprintId, |
| 329 | held: Vec<CourseId>, | 330 | held: Vec<CourseId>, |
| 330 | ) -> Result<bool, AppError> { | 331 | ) -> Result<bool, AppError> { |
| 331 | - let grade = id.clone(); | ||
| 332 | tx_with_retry(db, false, async move |tx| { | 332 | tx_with_retry(db, false, async move |tx| { |
| 333 | - delete_claimed(&mut *tx, &grade, &held).await | 333 | + delete_claimed(&mut *tx, id, &held).await |
| 334 | }) | 334 | }) |
| 335 | .await | 335 | .await |
| 336 | } | 336 | } |
| @@ -361,7 +361,7 @@ async fn delete_claimed( | |||
| 361 | ) -> Result<bool, AppError> { | 361 | ) -> Result<bool, AppError> { |
| 362 | let row = sqlx::query!( | 362 | let row = sqlx::query!( |
| 363 | r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint | 363 | r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint |
| 364 | - WHERE grade = $1 FOR UPDATE"#, | 364 | + WHERE grade_level = $1 FOR UPDATE"#, |
| 365 | id as _, | 365 | id as _, |
| 366 | ) | 366 | ) |
| 367 | .fetch_optional(&mut *tx) | 367 | .fetch_optional(&mut *tx) |
| @@ -398,7 +398,7 @@ pub(crate) async fn held_courses_for_update( | |||
| 398 | ) -> Result<Option<Vec<CourseId>>, AppError> { | 398 | ) -> Result<Option<Vec<CourseId>>, AppError> { |
| 399 | let row = sqlx::query!( | 399 | let row = sqlx::query!( |
| 400 | r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint | 400 | r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint |
| 401 | - WHERE grade = $1 FOR UPDATE"#, | 401 | + WHERE grade_level = $1 FOR UPDATE"#, |
| 402 | id as _, | 402 | id as _, |
| 403 | ) | 403 | ) |
| 404 | .fetch_optional(&mut *tx) | 404 | .fetch_optional(&mut *tx) |
| @@ -466,7 +466,7 @@ pub async fn prune( | |||
| 466 | sqlx::query!( | 466 | sqlx::query!( |
| 467 | r#"DELETE FROM blueprint_course | 467 | r#"DELETE FROM blueprint_course |
| 468 | WHERE course = $2 | 468 | WHERE course = $2 |
| 469 | - AND blueprint = (SELECT id FROM class_blueprint WHERE grade = $1)"#, | 469 | + AND blueprint = (SELECT id FROM class_blueprint WHERE grade_level = $1)"#, |
| 470 | id as _, | 470 | id as _, |
| 471 | course as _, | 471 | course as _, |
| 472 | ) | 472 | ) |
| @@ -500,7 +500,7 @@ pub async fn sourced_links( | |||
| 500 | let rows = sqlx::query!( | 500 | let rows = sqlx::query!( |
| 501 | r#"SELECT class AS "class: ClassGroupId", course AS "course: CourseId" | 501 | r#"SELECT class AS "class: ClassGroupId", course AS "course: CourseId" |
| 502 | FROM class_course | 502 | FROM class_course |
| 503 | - WHERE source = (SELECT id FROM class_blueprint WHERE grade = $1) | 503 | + WHERE source = (SELECT id FROM class_blueprint WHERE grade_level = $1) |
| 504 | AND course <> ALL($2)"#, | 504 | AND course <> ALL($2)"#, |
| 505 | id as _, | 505 | id as _, |
| 506 | keep as _ | 506 | keep as _ |
src/db/class_course.rsmodified+143 -42
| @@ -4,35 +4,43 @@ | |||
| 4 | //! [`crate::service::class_course`]; the transaction itself is the pump's, | 4 | //! [`crate::service::class_course`]; the transaction itself is the pump's, |
| 5 | //! [`crate::db::class_pump`]. | 5 | //! [`crate::db::class_pump`]. |
| 6 | //! | 6 | //! |
| 7 | -//! An instance is the academic anchor now: it carries the weekly hours | 7 | +//! An instance is the academic anchor now: it points at its grade-level |
| 8 | -//! (`ders_saati`), whether it counts toward the report card, the roster counter | 8 | +//! **offering** template, carries its own content *overrides* (title, |
| 9 | -//! its own teachers ([`crate::db::class_course_teacher`]). Reads speak the | 9 | +//! description, and the nullable `ders_saati` / `counts_toward_karne` — a |
| 10 | -//! *bare uuid* id of the instance; the (class, course) pair survives as the | 10 | +//! `NULL` inherits from the offering chain, so every read goes through |
| 11 | -//! UNIQUE key the attach gates on. | 11 | +//! [`crate::service::class_course::resolve_policy`], never a blind unwrap), |
| 12 | +//! the three `*_inherited` set flags, and the roster counter its own teachers | ||
| 13 | +//! ([`crate::db::class_course_teacher`]). Reads speak the *bare uuid* id of | ||
| 14 | +//! the instance; the (class, course) pair survives as the UNIQUE key the | ||
| 15 | +//! attach gates on. | ||
| 12 | 16 | ||
| 13 | use crate::constant::CLASS_COURSE_TABLE; | 17 | use crate::constant::CLASS_COURSE_TABLE; |
| 14 | use crate::database::Database; | 18 | use crate::database::Database; |
| 15 | use crate::db::class_pump::Attached; | 19 | use crate::db::class_pump::Attached; |
| 16 | use crate::db::page::PagedList; | 20 | use crate::db::page::PagedList; |
| 17 | use crate::domain::class_blueprint::ClassBlueprintId; | 21 | use crate::domain::class_blueprint::ClassBlueprintId; |
| 18 | -use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; | 22 | +use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati, OverrideField}; |
| 19 | use crate::domain::class_group::ClassGroupId; | 23 | use crate::domain::class_group::ClassGroupId; |
| 20 | -use crate::domain::course::CourseId; | 24 | +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; |
| 25 | +use crate::domain::course_offering::CourseOfferingId; | ||
| 21 | use crate::domain::timestamp::Timestamp; | 26 | use crate::domain::timestamp::Timestamp; |
| 22 | use crate::domain::user::UserId; | 27 | use crate::domain::user::UserId; |
| 23 | use crate::error::AppError; | 28 | use crate::error::AppError; |
| 24 | 29 | ||
| 25 | /// The projection every instance read shares. | 30 | /// The projection every instance read shares. |
| 26 | /// | 31 | /// |
| 27 | -/// Two translations ride it: `source` is stored as the blueprint's surrogate | 32 | +/// Three translations ride it: `source` is stored as the blueprint's surrogate |
| 28 | /// uuid while the domain speaks the grade label the API does (a hand attach, | 33 | /// uuid while the domain speaks the grade label the API does (a hand attach, |
| 29 | -/// source NULL, survives the LEFT JOIN as NULL), and `ders_saati` is a | 34 | +/// source NULL, survives the LEFT JOIN as NULL), `ders_saati` is a *nullable* |
| 30 | /// `SMALLINT` column while [`DersSaati`] is an `i64` newtype — decoded | 35 | /// `SMALLINT` column while [`DersSaati`] is an `i64` newtype — decoded |
| 31 | /// through a `bigint` cast so the type the driver checks is the one the | 36 | /// through a `bigint` cast so the type the driver checks is the one the |
| 32 | -/// newtype names. | 37 | +/// newtype names, its `NULL` meaning *inherit* — and the overrides/flags ride |
| 33 | -const INSTANCE_COLUMNS: &str = "cc.id, cc.class, cc.course, cc.attached_by, \ | 38 | +/// along as their plain column shapes. |
| 34 | - b.grade AS source, cc.ders_saati::bigint AS ders_saati, \ | 39 | +const INSTANCE_COLUMNS: &str = "cc.id, cc.class, cc.course, cc.offering, cc.attached_by, \ |
| 35 | - cc.counts_toward_karne, cc.enrollment_count, cc.attached_at"; | 40 | + b.grade_level AS source, cc.title, cc.description, \ |
| 41 | + cc.ders_saati::bigint AS ders_saati, cc.counts_toward_karne, \ | ||
| 42 | + cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited, \ | ||
| 43 | + cc.enrollment_count, cc.attached_at"; | ||
| 36 | 44 | ||
| 37 | /// The attach itself, with the refusals left *unmapped*. | 45 | /// The attach itself, with the refusals left *unmapped*. |
| 38 | /// | 46 | /// |
| @@ -117,10 +125,15 @@ pub async fn list_for_class_ids( | |||
| 117 | let rows = sqlx::query_as!( | 125 | let rows = sqlx::query_as!( |
| 118 | ClassCourse, | 126 | ClassCourse, |
| 119 | r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", | 127 | r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", |
| 120 | - cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId", | 128 | + cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId", |
| 121 | - b.grade AS "source?: ClassBlueprintId", | 129 | + cc.attached_by AS "attached_by: UserId", |
| 122 | - cc.ders_saati::bigint AS "ders_saati!: DersSaati", | 130 | + b.grade_level AS "source?: ClassBlueprintId", |
| 123 | - cc.counts_toward_karne, cc.enrollment_count, | 131 | + cc.title AS "title?: CourseTitle", |
| 132 | + cc.description AS "description?: CourseDescription", | ||
| 133 | + cc.ders_saati::bigint AS "ders_saati?: DersSaati", | ||
| 134 | + cc.counts_toward_karne, | ||
| 135 | + cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited, | ||
| 136 | + cc.enrollment_count, | ||
| 124 | cc.attached_at AS "attached_at: Timestamp" | 137 | cc.attached_at AS "attached_at: Timestamp" |
| 125 | FROM class_course cc | 138 | FROM class_course cc |
| 126 | LEFT JOIN class_blueprint b ON b.id = cc.source | 139 | LEFT JOIN class_blueprint b ON b.id = cc.source |
| @@ -146,10 +159,15 @@ pub async fn list_by_ids( | |||
| 146 | let rows = sqlx::query_as!( | 159 | let rows = sqlx::query_as!( |
| 147 | ClassCourse, | 160 | ClassCourse, |
| 148 | r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", | 161 | r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", |
| 149 | - cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId", | 162 | + cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId", |
| 150 | - b.grade AS "source?: ClassBlueprintId", | 163 | + cc.attached_by AS "attached_by: UserId", |
| 151 | - cc.ders_saati::bigint AS "ders_saati!: DersSaati", | 164 | + b.grade_level AS "source?: ClassBlueprintId", |
| 152 | - cc.counts_toward_karne, cc.enrollment_count, | 165 | + cc.title AS "title?: CourseTitle", |
| 166 | + cc.description AS "description?: CourseDescription", | ||
| 167 | + cc.ders_saati::bigint AS "ders_saati?: DersSaati", | ||
| 168 | + cc.counts_toward_karne, | ||
| 169 | + cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited, | ||
| 170 | + cc.enrollment_count, | ||
| 153 | cc.attached_at AS "attached_at: Timestamp" | 171 | cc.attached_at AS "attached_at: Timestamp" |
| 154 | FROM class_course cc | 172 | FROM class_course cc |
| 155 | LEFT JOIN class_blueprint b ON b.id = cc.source | 173 | LEFT JOIN class_blueprint b ON b.id = cc.source |
| @@ -167,10 +185,15 @@ pub async fn read(db: &Database, id: &ClassCourseId) -> Result<Option<ClassCours | |||
| 167 | let row = sqlx::query_as!( | 185 | let row = sqlx::query_as!( |
| 168 | ClassCourse, | 186 | ClassCourse, |
| 169 | r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", | 187 | r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", |
| 170 | - cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId", | 188 | + cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId", |
| 171 | - b.grade AS "source?: ClassBlueprintId", | 189 | + cc.attached_by AS "attached_by: UserId", |
| 172 | - cc.ders_saati::bigint AS "ders_saati!: DersSaati", | 190 | + b.grade_level AS "source?: ClassBlueprintId", |
| 173 | - cc.counts_toward_karne, cc.enrollment_count, | 191 | + cc.title AS "title?: CourseTitle", |
| 192 | + cc.description AS "description?: CourseDescription", | ||
| 193 | + cc.ders_saati::bigint AS "ders_saati?: DersSaati", | ||
| 194 | + cc.counts_toward_karne, | ||
| 195 | + cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited, | ||
| 196 | + cc.enrollment_count, | ||
| 174 | cc.attached_at AS "attached_at: Timestamp" | 197 | cc.attached_at AS "attached_at: Timestamp" |
| 175 | FROM class_course cc | 198 | FROM class_course cc |
| 176 | LEFT JOIN class_blueprint b ON b.id = cc.source | 199 | LEFT JOIN class_blueprint b ON b.id = cc.source |
| @@ -195,42 +218,57 @@ pub async fn class_of(db: &Database, id: &ClassCourseId) -> Result<Option<ClassG | |||
| 195 | Ok(row.map(|row| row.class)) | 218 | Ok(row.map(|row| row.class)) |
| 196 | } | 219 | } |
| 197 | 220 | ||
| 198 | -/// Write only the fields the PATCH carried — `None` means the request omitted | 221 | +/// Set the instance's own policy overrides — the PATCH behind |
| 199 | -/// it, so the column keeps the value it holds rather than being re-stated | 222 | +/// `PATCH /instances/{id}`. Each `Some(_)` *sets* the column (a PATCH never |
| 200 | -/// from the snapshot the handler read. Both fields are non-clearable, so | 223 | +/// clears; clearing is [`clear_overrides`]'s job); `None` keeps what the |
| 201 | -/// `COALESCE` is the whole rule: absent = keep the stored value. | 224 | +/// column holds. |
| 202 | /// | 225 | /// |
| 203 | -/// No counter moves and no compare-and-set is needed: neither field is | 226 | +/// No counter moves and no compare-and-set is needed: every field is an |
| 204 | -/// refcounted, and each is an independent scalar, so two PATCHes touching | 227 | +/// independent scalar, so two PATCHes touching different ones cannot revert |
| 205 | -/// different ones cannot revert each other. `Err(NotFound)` when the instance | 228 | +/// each other. `Err(NotFound)` when the instance is gone — the same answer |
| 206 | -/// is gone — the same answer the caller's own read gives one instant earlier. | 229 | +/// the caller's own read gives one instant earlier. |
| 207 | pub async fn update( | 230 | pub async fn update( |
| 208 | db: &Database, | 231 | db: &Database, |
| 209 | id: &ClassCourseId, | 232 | id: &ClassCourseId, |
| 233 | + title: Option<CourseTitle>, | ||
| 234 | + description: Option<CourseDescription>, | ||
| 210 | staff: Option<DersSaati>, | 235 | staff: Option<DersSaati>, |
| 211 | counts: Option<bool>, | 236 | counts: Option<bool>, |
| 212 | ) -> Result<ClassCourse, AppError> { | 237 | ) -> Result<ClassCourse, AppError> { |
| 213 | - // `i64`, cast down by the statement itself: the column is a `SMALLINT` | 238 | + // `i64`, cast down by the statement itself: the column is a nullable |
| 214 | - // and the newtype wraps an `i64`, so naming both types explicitly is what | 239 | + // `SMALLINT` and the newtype wraps an `i64`, so naming both types |
| 215 | - // keeps the driver's type check honest in either direction. | 240 | + // explicitly is what keeps the driver's type check honest in either |
| 241 | + // direction. The text columns set-only via `COALESCE` for the same | ||
| 242 | + // never-clears rule. | ||
| 216 | let hours = staff.map(|hours| hours.as_i64()); | 243 | let hours = staff.map(|hours| hours.as_i64()); |
| 244 | + let title = title.map(|title| title.as_str().to_string()); | ||
| 245 | + let description = description.map(|d| d.as_str().to_string()); | ||
| 217 | let row = sqlx::query_as!( | 246 | let row = sqlx::query_as!( |
| 218 | ClassCourse, | 247 | ClassCourse, |
| 219 | r#"WITH updated AS ( | 248 | r#"WITH updated AS ( |
| 220 | UPDATE class_course | 249 | UPDATE class_course |
| 221 | - SET ders_saati = COALESCE($2::bigint, ders_saati::bigint)::smallint, | 250 | + SET title = COALESCE($2, title), |
| 222 | - counts_toward_karne = COALESCE($3, counts_toward_karne) | 251 | + description = COALESCE($3, description), |
| 252 | + ders_saati = COALESCE($4::bigint, ders_saati::bigint)::smallint, | ||
| 253 | + counts_toward_karne = COALESCE($5, counts_toward_karne) | ||
| 223 | WHERE id = $1 | 254 | WHERE id = $1 |
| 224 | RETURNING *) | 255 | RETURNING *) |
| 225 | SELECT u.id AS "id: ClassCourseId", u.class AS "class: ClassGroupId", | 256 | SELECT u.id AS "id: ClassCourseId", u.class AS "class: ClassGroupId", |
| 226 | - u.course AS "course: CourseId", u.attached_by AS "attached_by: UserId", | 257 | + u.course AS "course: CourseId", u.offering AS "offering: CourseOfferingId", |
| 227 | - b.grade AS "source?: ClassBlueprintId", | 258 | + u.attached_by AS "attached_by: UserId", |
| 228 | - u.ders_saati::bigint AS "ders_saati!: DersSaati", | 259 | + b.grade_level AS "source?: ClassBlueprintId", |
| 229 | - u.counts_toward_karne, u.enrollment_count, | 260 | + u.title AS "title?: CourseTitle", |
| 261 | + u.description AS "description?: CourseDescription", | ||
| 262 | + u.ders_saati::bigint AS "ders_saati?: DersSaati", | ||
| 263 | + u.counts_toward_karne, | ||
| 264 | + u.subjects_inherited, u.exam_weights_inherited, u.weekly_plan_inherited, | ||
| 265 | + u.enrollment_count, | ||
| 230 | u.attached_at AS "attached_at: Timestamp" | 266 | u.attached_at AS "attached_at: Timestamp" |
| 231 | FROM updated u | 267 | FROM updated u |
| 232 | LEFT JOIN class_blueprint b ON b.id = u.source"#, | 268 | LEFT JOIN class_blueprint b ON b.id = u.source"#, |
| 233 | id.uuid(), | 269 | id.uuid(), |
| 270 | + title, | ||
| 271 | + description, | ||
| 234 | hours, | 272 | hours, |
| 235 | counts, | 273 | counts, |
| 236 | ) | 274 | ) |
| @@ -239,3 +277,66 @@ pub async fn update( | |||
| 239 | .ok_or(AppError::NotFound)?; | 277 | .ok_or(AppError::NotFound)?; |
| 240 | Ok(row) | 278 | Ok(row) |
| 241 | } | 279 | } |
| 280 | + | ||
| 281 | +/// Clear the named overrides back to **inherit**: the scalars go `NULL` (the | ||
| 282 | +/// offering's default, then the constants, apply again) and a set flag goes | ||
| 283 | +/// back to `TRUE` (the offering's set is authoritative again — deleting the | ||
| 284 | +/// section's own set rows rides the child-table lanes' reset). The empty | ||
| 285 | +/// request is refused by the service before it gets here; a gone instance is | ||
| 286 | +/// the usual 404. | ||
| 287 | +/// | ||
| 288 | +/// The whole reset is one statement: the named clears are judged on the row | ||
| 289 | +/// as it is *at the write*, so a PATCH landing between the caller's read and | ||
| 290 | +/// this write cannot be silently reverted field-by-field. | ||
| 291 | +pub async fn clear_overrides( | ||
| 292 | + db: &Database, | ||
| 293 | + id: &ClassCourseId, | ||
| 294 | + fields: &[OverrideField], | ||
| 295 | +) -> Result<ClassCourse, AppError> { | ||
| 296 | + let title = fields.contains(&OverrideField::Title); | ||
| 297 | + let description = fields.contains(&OverrideField::Description); | ||
| 298 | + let staff = fields.contains(&OverrideField::DersSaati); | ||
| 299 | + let counts = fields.contains(&OverrideField::CountsTowardKarne); | ||
| 300 | + let subjects = fields.contains(&OverrideField::Subjects); | ||
| 301 | + let exam_weights = fields.contains(&OverrideField::ExamWeights); | ||
| 302 | + let weekly_plan = fields.contains(&OverrideField::WeeklyPlan); | ||
| 303 | + let row = sqlx::query_as!( | ||
| 304 | + ClassCourse, | ||
| 305 | + r#"WITH updated AS ( | ||
| 306 | + UPDATE class_course SET | ||
| 307 | + title = CASE WHEN $2 THEN NULL ELSE title END, | ||
| 308 | + description = CASE WHEN $3 THEN NULL ELSE description END, | ||
| 309 | + ders_saati = CASE WHEN $4 THEN NULL ELSE ders_saati END, | ||
| 310 | + counts_toward_karne = CASE WHEN $5 THEN NULL ELSE counts_toward_karne END, | ||
| 311 | + subjects_inherited = CASE WHEN $6 THEN TRUE ELSE subjects_inherited END, | ||
| 312 | + exam_weights_inherited = CASE WHEN $7 THEN TRUE ELSE exam_weights_inherited END, | ||
| 313 | + weekly_plan_inherited = CASE WHEN $8 THEN TRUE ELSE weekly_plan_inherited END | ||
| 314 | + WHERE id = $1 | ||
| 315 | + RETURNING *) | ||
| 316 | + SELECT u.id AS "id: ClassCourseId", u.class AS "class: ClassGroupId", | ||
| 317 | + u.course AS "course: CourseId", u.offering AS "offering: CourseOfferingId", | ||
| 318 | + u.attached_by AS "attached_by: UserId", | ||
| 319 | + b.grade_level AS "source?: ClassBlueprintId", | ||
| 320 | + u.title AS "title?: CourseTitle", | ||
| 321 | + u.description AS "description?: CourseDescription", | ||
| 322 | + u.ders_saati::bigint AS "ders_saati?: DersSaati", | ||
| 323 | + u.counts_toward_karne, | ||
| 324 | + u.subjects_inherited, u.exam_weights_inherited, u.weekly_plan_inherited, | ||
| 325 | + u.enrollment_count, | ||
| 326 | + u.attached_at AS "attached_at: Timestamp" | ||
| 327 | + FROM updated u | ||
| 328 | + LEFT JOIN class_blueprint b ON b.id = u.source"#, | ||
| 329 | + id.uuid(), | ||
| 330 | + title, | ||
| 331 | + description, | ||
| 332 | + staff, | ||
| 333 | + counts, | ||
| 334 | + subjects, | ||
| 335 | + exam_weights, | ||
| 336 | + weekly_plan, | ||
| 337 | + ) | ||
| 338 | + .fetch_optional(db) | ||
| 339 | + .await? | ||
| 340 | + .ok_or(AppError::NotFound)?; | ||
| 341 | + Ok(row) | ||
| 342 | +} | ||
src/db/class_group.rsmodified+39 -42
| @@ -8,7 +8,8 @@ use crate::database::{Database, tx_with_retry}; | |||
| 8 | use crate::db::field_update::{FieldUpdate, Refcount}; | 8 | use crate::db::field_update::{FieldUpdate, Refcount}; |
| 9 | use crate::db::page::PagedList; | 9 | use crate::db::page::PagedList; |
| 10 | use crate::domain::academic_year::AcademicYearId; | 10 | use crate::domain::academic_year::AcademicYearId; |
| 11 | -use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; | 11 | +use crate::domain::class_group::{ClassGroup, ClassGroupId, ClassName}; |
| 12 | +use crate::domain::grade::GradeLevel; | ||
| 12 | use crate::domain::user::UserId; | 13 | use crate::domain::user::UserId; |
| 13 | use crate::error::{AppError, ValidationError}; | 14 | use crate::error::{AppError, ValidationError}; |
| 14 | 15 | ||
| @@ -48,7 +49,7 @@ pub async fn create( | |||
| 48 | db: &Database, | 49 | db: &Database, |
| 49 | creator: &UserId, | 50 | creator: &UserId, |
| 50 | name: ClassName, | 51 | name: ClassName, |
| 51 | - grade: Option<ClassGrade>, | 52 | + grade_level: GradeLevel, |
| 52 | year: Option<AcademicYearId>, | 53 | year: Option<AcademicYearId>, |
| 53 | teacher: Option<UserId>, | 54 | teacher: Option<UserId>, |
| 54 | ) -> Result<ClassGroup, AppError> { | 55 | ) -> Result<ClassGroup, AppError> { |
| @@ -64,16 +65,16 @@ pub async fn create( | |||
| 64 | UPDATE academic_year SET class_count = class_count + 1 | 65 | UPDATE academic_year SET class_count = class_count + 1 |
| 65 | WHERE id = $1 | 66 | WHERE id = $1 |
| 66 | RETURNING 1) | 67 | RETURNING 1) |
| 67 | - INSERT INTO class_group (id, creator, name, grade, year, teacher) | 68 | + INSERT INTO class_group (id, creator, name, grade_level, year, teacher) |
| 68 | SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat) | 69 | SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat) |
| 69 | RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", | 70 | RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 70 | - name AS "name: ClassName", grade AS "grade: ClassGrade", | 71 | + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 71 | year AS "year: AcademicYearId", teacher AS "teacher: UserId""#, | 72 | year AS "year: AcademicYearId", teacher AS "teacher: UserId""#, |
| 72 | year.uuid(), | 73 | year.uuid(), |
| 73 | id.uuid(), | 74 | id.uuid(), |
| 74 | creator.uuid(), | 75 | creator.uuid(), |
| 75 | name.as_str(), | 76 | name.as_str(), |
| 76 | - grade.as_ref().map(ClassGrade::as_str), | 77 | + grade_level.get(), |
| 77 | teacher.as_ref().map(UserId::uuid) | 78 | teacher.as_ref().map(UserId::uuid) |
| 78 | ) | 79 | ) |
| 79 | .fetch_optional(db) | 80 | .fetch_optional(db) |
| @@ -97,15 +98,15 @@ pub async fn create( | |||
| 97 | None => { | 98 | None => { |
| 98 | let created = sqlx::query_as!( | 99 | let created = sqlx::query_as!( |
| 99 | ClassGroup, | 100 | ClassGroup, |
| 100 | - r#"INSERT INTO class_group (id, creator, name, grade, year, teacher) | 101 | + r#"INSERT INTO class_group (id, creator, name, grade_level, year, teacher) |
| 101 | VALUES ($1, $2, $3, $4, $5, $6) | 102 | VALUES ($1, $2, $3, $4, $5, $6) |
| 102 | RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", | 103 | RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 103 | - name AS "name: ClassName", grade AS "grade: ClassGrade", | 104 | + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 104 | year AS "year: AcademicYearId", teacher AS "teacher: UserId""#, | 105 | year AS "year: AcademicYearId", teacher AS "teacher: UserId""#, |
| 105 | id.uuid(), | 106 | id.uuid(), |
| 106 | creator.uuid(), | 107 | creator.uuid(), |
| 107 | name.as_str(), | 108 | name.as_str(), |
| 108 | - grade.as_ref().map(ClassGrade::as_str), | 109 | + grade_level.get(), |
| 109 | year.as_ref().map(AcademicYearId::uuid), | 110 | year.as_ref().map(AcademicYearId::uuid), |
| 110 | teacher.as_ref().map(UserId::uuid) | 111 | teacher.as_ref().map(UserId::uuid) |
| 111 | ) | 112 | ) |
| @@ -121,7 +122,7 @@ pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup> | |||
| 121 | let class = sqlx::query_as!( | 122 | let class = sqlx::query_as!( |
| 122 | ClassGroup, | 123 | ClassGroup, |
| 123 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", | 124 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 124 | - name AS "name: ClassName", grade AS "grade: ClassGrade", | 125 | + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 125 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" | 126 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" |
| 126 | FROM class_group WHERE id = $1"#, | 127 | FROM class_group WHERE id = $1"#, |
| 127 | id.uuid() | 128 | id.uuid() |
| @@ -131,40 +132,36 @@ pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup> | |||
| 131 | Ok(class) | 132 | Ok(class) |
| 132 | } | 133 | } |
| 133 | 134 | ||
| 134 | -/// Every class, newest first — or one grade's, when `grade` narrows it: | 135 | +/// Every class, newest first — or one rung's, when `grade_level` narrows it: |
| 135 | -/// `Some(Some(label))` is the sections carrying that exact label (no trim, | 136 | +/// `Some(level)` is the sections carrying that exact ladder position (the |
| 136 | -/// no case folding, matching [`list_for_grade`] and the | 137 | +/// same equality [`list_for_grade`] and the blueprint keyed by that rung |
| 137 | -/// blueprint keyed by that very string), `Some(None)` the sections carrying | 138 | +/// use), `None` the whole list. |
| 138 | -/// no grade at all, `None` the whole list. | ||
| 139 | /// | 139 | /// |
| 140 | /// The narrowing is the `WHERE`, so the `total` [`PagedList`] counts is the | 140 | /// The narrowing is the `WHERE`, so the `total` [`PagedList`] counts is the |
| 141 | /// filtered set and a client can page through it. | 141 | /// filtered set and a client can page through it. |
| 142 | pub async fn list_all( | 142 | pub async fn list_all( |
| 143 | db: &Database, | 143 | db: &Database, |
| 144 | - grade: Option<Option<ClassGrade>>, | 144 | + grade_level: Option<GradeLevel>, |
| 145 | limit: Option<i64>, | 145 | limit: Option<i64>, |
| 146 | offset: i64, | 146 | offset: i64, |
| 147 | ) -> Result<(Vec<ClassGroup>, i64), AppError> { | 147 | ) -> Result<(Vec<ClassGroup>, i64), AppError> { |
| 148 | - let list = match grade { | 148 | + let list = match grade_level { |
| 149 | None => PagedList::new(CLASS_GROUP_TABLE, "ORDER BY id DESC"), | 149 | None => PagedList::new(CLASS_GROUP_TABLE, "ORDER BY id DESC"), |
| 150 | - Some(None) => PagedList::new( | 150 | + Some(grade_level) => PagedList::new( |
| 151 | - format!("{CLASS_GROUP_TABLE} WHERE grade IS NULL"), | 151 | + format!("{CLASS_GROUP_TABLE} WHERE grade_level = $1"), |
| 152 | - "ORDER BY id DESC", | ||
| 153 | - ), | ||
| 154 | - Some(Some(grade)) => PagedList::new( | ||
| 155 | - format!("{CLASS_GROUP_TABLE} WHERE grade = $1"), | ||
| 156 | "ORDER BY id DESC", | 152 | "ORDER BY id DESC", |
| 157 | ) | 153 | ) |
| 158 | - .bind(grade.as_str().to_string()), | 154 | + .bind(grade_level.get() as i64), |
| 159 | }; | 155 | }; |
| 160 | list.run(limit, offset, db).await | 156 | list.run(limit, offset, db).await |
| 161 | } | 157 | } |
| 162 | 158 | ||
| 163 | /// Write only the fields the PATCH carried — `None` means the request | 159 | /// Write only the fields the PATCH carried — `None` means the request |
| 164 | /// omitted it, so the column is left alone rather than re-stated from the | 160 | /// omitted it, so the column is left alone rather than re-stated from the |
| 165 | -/// snapshot this struct was read into. `grade`, `year` and `teacher` are | 161 | +/// snapshot this struct was read into. `grade_level` is a plain `Option` |
| 166 | -/// nullable, so they take the outer/inner `Option<Option<_>>`: `None` = | 162 | +/// (the column is NOT NULL: a PATCH may set a rung, never clear it); |
| 167 | -/// omitted (keep), `Some(None)` = clear. | 163 | +/// `year` and `teacher` are nullable, so they take the outer/inner |
| 164 | +/// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear. | ||
| 168 | /// | 165 | /// |
| 169 | /// A year move claims the new year and releases the old one inside the very | 166 | /// A year move claims the new year and releases the old one inside the very |
| 170 | /// transaction that moves the link, exactly as in | 167 | /// transaction that moves the link, exactly as in |
| @@ -174,7 +171,7 @@ pub async fn update( | |||
| 174 | db: &Database, | 171 | db: &Database, |
| 175 | class: ClassGroup, | 172 | class: ClassGroup, |
| 176 | name: Option<ClassName>, | 173 | name: Option<ClassName>, |
| 177 | - grade: Option<Option<ClassGrade>>, | 174 | + grade_level: Option<GradeLevel>, |
| 178 | year: Option<Option<AcademicYearId>>, | 175 | year: Option<Option<AcademicYearId>>, |
| 179 | teacher: Option<Option<UserId>>, | 176 | teacher: Option<Option<UserId>>, |
| 180 | ) -> Result<ClassGroup, AppError> { | 177 | ) -> Result<ClassGroup, AppError> { |
| @@ -182,10 +179,10 @@ pub async fn update( | |||
| 182 | let expected = class.year.as_ref().map(AcademicYearId::uuid); | 179 | let expected = class.year.as_ref().map(AcademicYearId::uuid); |
| 183 | FieldUpdate::new(CLASS_GROUP_TABLE, class.id.uuid()) | 180 | FieldUpdate::new(CLASS_GROUP_TABLE, class.id.uuid()) |
| 184 | .set("name", name.map(|name| name.as_str().to_string())) | 181 | .set("name", name.map(|name| name.as_str().to_string())) |
| 185 | - .set( | 182 | + // `Param` has no i16 arm (and db/page.rs is a shared seam): the rung |
| 186 | - "grade", | 183 | + // rides as BIGINT, which Postgres assignment-casts into the SMALLINT |
| 187 | - grade.map(|grade| grade.map(|grade| grade.as_str().to_string())), | 184 | + // column. |
| 188 | - ) | 185 | + .set("grade_level", grade_level.map(|grade| grade.get() as i64)) |
| 189 | .set("year", year.map(|year| year.map(|year| year.uuid()))) | 186 | .set("year", year.map(|year| year.map(|year| year.uuid()))) |
| 190 | // Not refcounted: a homeroom assignment is a label, so it rides the | 187 | // Not refcounted: a homeroom assignment is a label, so it rides the |
| 191 | // plain `set` path and never arms the year CAS. | 188 | // plain `set` path and never arms the year CAS. |
| @@ -218,7 +215,7 @@ pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result<Vec<Clas | |||
| 218 | let classes = sqlx::query_as!( | 215 | let classes = sqlx::query_as!( |
| 219 | ClassGroup, | 216 | ClassGroup, |
| 220 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", | 217 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 221 | - name AS "name: ClassName", grade AS "grade: ClassGrade", | 218 | + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 222 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" | 219 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" |
| 223 | FROM class_group WHERE id = ANY($1)"#, | 220 | FROM class_group WHERE id = ANY($1)"#, |
| 224 | &ids | 221 | &ids |
| @@ -228,20 +225,20 @@ pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result<Vec<Clas | |||
| 228 | Ok(classes) | 225 | Ok(classes) |
| 229 | } | 226 | } |
| 230 | 227 | ||
| 231 | -/// Every class section at one grade label, in no particular order — what a | 228 | +/// Every class section at one ladder rung, in no particular order — what a |
| 232 | /// grade blueprint pumps. Unpaged on purpose: the caller is reconciling all | 229 | /// grade blueprint pumps. Unpaged on purpose: the caller is reconciling all |
| 233 | /// of them, and a page would silently stock only the first window. | 230 | /// of them, and a page would silently stock only the first window. |
| 234 | pub async fn list_for_grade( | 231 | pub async fn list_for_grade( |
| 235 | db: &Database, | 232 | db: &Database, |
| 236 | - grade: &ClassGrade, | 233 | + grade_level: GradeLevel, |
| 237 | ) -> Result<Vec<ClassGroup>, AppError> { | 234 | ) -> Result<Vec<ClassGroup>, AppError> { |
| 238 | let classes = sqlx::query_as!( | 235 | let classes = sqlx::query_as!( |
| 239 | ClassGroup, | 236 | ClassGroup, |
| 240 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", | 237 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 241 | - name AS "name: ClassName", grade AS "grade: ClassGrade", | 238 | + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 242 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" | 239 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" |
| 243 | - FROM class_group WHERE grade = $1"#, | 240 | + FROM class_group WHERE grade_level = $1"#, |
| 244 | - grade.as_str() | 241 | + grade_level.get() |
| 245 | ) | 242 | ) |
| 246 | .fetch_all(db) | 243 | .fetch_all(db) |
| 247 | .await?; | 244 | .await?; |
| @@ -258,7 +255,7 @@ pub async fn list_for_year( | |||
| 258 | let classes = sqlx::query_as!( | 255 | let classes = sqlx::query_as!( |
| 259 | ClassGroup, | 256 | ClassGroup, |
| 260 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", | 257 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 261 | - name AS "name: ClassName", grade AS "grade: ClassGrade", | 258 | + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 262 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" | 259 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" |
| 263 | FROM class_group WHERE year = $1 ORDER BY id"#, | 260 | FROM class_group WHERE year = $1 ORDER BY id"#, |
| 264 | year.uuid() | 261 | year.uuid() |
| @@ -287,7 +284,7 @@ pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<ClassG | |||
| 287 | let classes = sqlx::query_as!( | 284 | let classes = sqlx::query_as!( |
| 288 | ClassGroup, | 285 | ClassGroup, |
| 289 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", | 286 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 290 | - name AS "name: ClassName", grade AS "grade: ClassGrade", | 287 | + name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 291 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" | 288 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" |
| 292 | FROM class_group WHERE teacher = $1 ORDER BY id DESC"#, | 289 | FROM class_group WHERE teacher = $1 ORDER BY id DESC"#, |
| 293 | user.uuid() | 290 | user.uuid() |
| @@ -464,7 +461,7 @@ mod tests { | |||
| 464 | db, | 461 | db, |
| 465 | &manager, | 462 | &manager, |
| 466 | ClassName::try_new("9-A").unwrap(), | 463 | ClassName::try_new("9-A").unwrap(), |
| 467 | - None, | 464 | + GradeLevel::new(9).unwrap(), |
| 468 | year, | 465 | year, |
| 469 | None, | 466 | None, |
| 470 | ) | 467 | ) |
| @@ -479,7 +476,7 @@ mod tests { | |||
| 479 | db, | 476 | db, |
| 480 | &manager, | 477 | &manager, |
| 481 | ClassName::try_new("9-A").unwrap(), | 478 | ClassName::try_new("9-A").unwrap(), |
| 482 | - None, | 479 | + GradeLevel::new(9).unwrap(), |
| 483 | None, | 480 | None, |
| 484 | teacher, | 481 | teacher, |
| 485 | ) | 482 | ) |
| @@ -740,7 +737,7 @@ mod tests { | |||
| 740 | &db, | 737 | &db, |
| 741 | &a_named_user(&db, "manager").await, | 738 | &a_named_user(&db, "manager").await, |
| 742 | ClassName::try_new("9-A").unwrap(), | 739 | ClassName::try_new("9-A").unwrap(), |
| 743 | - None, | 740 | + GradeLevel::anaokulu(), |
| 744 | Some(id), | 741 | Some(id), |
| 745 | None, | 742 | None, |
| 746 | ) | 743 | ) |
src/db/class_member.rsmodified+4 -3
| @@ -102,15 +102,16 @@ pub(crate) mod tests { | |||
| 102 | UserId::from_key(&id.to_string()) | 102 | UserId::from_key(&id.to_string()) |
| 103 | } | 103 | } |
| 104 | 104 | ||
| 105 | - /// A class with no year and no grade: the shape most fixtures want, since | 105 | + /// A class with no year, at a fixed ladder rung: the shape most fixtures |
| 106 | - /// the year only matters to the academic-calendar reads. | 106 | + /// want, since the year only matters to the academic-calendar reads and |
| 107 | + /// the grade level only to the blueprint/rollover ones. | ||
| 107 | pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { | 108 | pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { |
| 108 | let manager = fixture_user(db, "manager").await; | 109 | let manager = fixture_user(db, "manager").await; |
| 109 | crate::db::class_group::create( | 110 | crate::db::class_group::create( |
| 110 | db, | 111 | db, |
| 111 | &manager, | 112 | &manager, |
| 112 | ClassName::try_new(name).unwrap(), | 113 | ClassName::try_new(name).unwrap(), |
| 113 | - None, | 114 | + crate::domain::grade::GradeLevel::new(9).unwrap(), |
| 114 | None, | 115 | None, |
| 115 | None, | 116 | None, |
| 116 | ) | 117 | ) |
src/db/class_pump.rsmodified+95 -28
| @@ -34,14 +34,16 @@ use sqlx::postgres::PgConnection; | |||
| 34 | use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; | 34 | use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; |
| 35 | use crate::database::{Database, foreign_key_violation, tx_with_retry, unique_violation}; | 35 | use crate::database::{Database, foreign_key_violation, tx_with_retry, unique_violation}; |
| 36 | use crate::domain::class_blueprint::ClassBlueprintId; | 36 | use crate::domain::class_blueprint::ClassBlueprintId; |
| 37 | -use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; | 37 | +use crate::domain::class_course::{ClassCourse, ClassCourseId}; |
| 38 | use crate::domain::class_group::ClassGroupId; | 38 | use crate::domain::class_group::ClassGroupId; |
| 39 | use crate::domain::class_member::{ClassMember, ClassMemberId}; | 39 | use crate::domain::class_member::{ClassMember, ClassMemberId}; |
| 40 | use crate::domain::course::CourseId; | 40 | use crate::domain::course::CourseId; |
| 41 | +use crate::domain::course::CourseKind; | ||
| 42 | +use crate::domain::grade::GradeLevel; | ||
| 41 | use crate::domain::role::Role; | 43 | use crate::domain::role::Role; |
| 42 | use crate::domain::timestamp::Timestamp; | 44 | use crate::domain::timestamp::Timestamp; |
| 43 | use crate::domain::user::UserId; | 45 | use crate::domain::user::UserId; |
| 44 | -use crate::error::AppError; | 46 | +use crate::error::{AppError, ValidationError}; |
| 45 | 47 | ||
| 46 | /// What [`attach_course`]'s attach settled. The caller answers each verdict — | 48 | /// What [`attach_course`]'s attach settled. The caller answers each verdict — |
| 47 | /// a hand attach turns them into this route's errors; a blueprint pump reads | 49 | /// a hand attach turns them into this route's errors; a blueprint pump reads |
| @@ -268,7 +270,7 @@ async fn early_verdicts( | |||
| 268 | axis: Axis, | 270 | axis: Axis, |
| 269 | pivot: Pivot<'_>, | 271 | pivot: Pivot<'_>, |
| 270 | source: Option<&ClassBlueprintId>, | 272 | source: Option<&ClassBlueprintId>, |
| 271 | -) -> Result<(Option<Early>, Option<uuid::Uuid>), AppError> { | 273 | +) -> Result<(Option<Early>, Option<uuid::Uuid>, Option<CourseKind>), AppError> { |
| 272 | let held = match pivot { | 274 | let held = match pivot { |
| 273 | Pivot::User(user) => sqlx::query_scalar!( | 275 | Pivot::User(user) => sqlx::query_scalar!( |
| 274 | r#"SELECT 1 AS "one" FROM class_member | 276 | r#"SELECT 1 AS "one" FROM class_member |
| @@ -289,7 +291,7 @@ async fn early_verdicts( | |||
| 289 | .is_some(), | 291 | .is_some(), |
| 290 | }; | 292 | }; |
| 291 | if held { | 293 | if held { |
| 292 | - return Ok((Some(Early::Duplicate), None)); | 294 | + return Ok((Some(Early::Duplicate), None, None)); |
| 293 | } | 295 | } |
| 294 | // The lock and the resolution are one read: the stored `source` is the | 296 | // The lock and the resolution are one read: the stored `source` is the |
| 295 | // blueprint's surrogate uuid, and the row this read returns it from is | 297 | // blueprint's surrogate uuid, and the row this read returns it from is |
| @@ -297,16 +299,17 @@ async fn early_verdicts( | |||
| 297 | let mut source_id = None; | 299 | let mut source_id = None; |
| 298 | if let Some(source) = source { | 300 | if let Some(source) = source { |
| 299 | let locked = sqlx::query_scalar!( | 301 | let locked = sqlx::query_scalar!( |
| 300 | - r#"SELECT id FROM class_blueprint WHERE grade = $1 FOR KEY SHARE"#, | 302 | + r#"SELECT id FROM class_blueprint WHERE grade_level = $1 FOR KEY SHARE"#, |
| 301 | source as _ | 303 | source as _ |
| 302 | ) | 304 | ) |
| 303 | .fetch_optional(&mut *tx) | 305 | .fetch_optional(&mut *tx) |
| 304 | .await?; | 306 | .await?; |
| 305 | let Some(id) = locked else { | 307 | let Some(id) = locked else { |
| 306 | - return Ok((Some(Early::SourceGone), None)); | 308 | + return Ok((Some(Early::SourceGone), None, None)); |
| 307 | }; | 309 | }; |
| 308 | source_id = Some(id); | 310 | source_id = Some(id); |
| 309 | } | 311 | } |
| 312 | + let mut kind = None; | ||
| 310 | match pivot { | 313 | match pivot { |
| 311 | Pivot::User(user) => { | 314 | Pivot::User(user) => { |
| 312 | let row = sqlx::query!( | 315 | let row = sqlx::query!( |
| @@ -316,20 +319,24 @@ async fn early_verdicts( | |||
| 316 | .fetch_optional(&mut *tx) | 319 | .fetch_optional(&mut *tx) |
| 317 | .await?; | 320 | .await?; |
| 318 | if row.map(|row| row.role) != Some(Role::Student) { | 321 | if row.map(|row| row.role) != Some(Role::Student) { |
| 319 | - return Ok((Some(Early::PivotGone), None)); | 322 | + return Ok((Some(Early::PivotGone), None, None)); |
| 320 | } | 323 | } |
| 321 | } | 324 | } |
| 322 | Pivot::Course(course) => { | 325 | Pivot::Course(course) => { |
| 323 | - let alive = sqlx::query_scalar!( | 326 | + // The lock and the kind in one read: the same `FOR KEY SHARE` the |
| 324 | - r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#, | 327 | + // attach needs against a concurrent course delete answers what |
| 328 | + // kind of course it is locking — and only a class-delivered ders | ||
| 329 | + // may become an instance (the gate lives in [`attach_course`]). | ||
| 330 | + let locked = sqlx::query!( | ||
| 331 | + r#"SELECT kind AS "kind: CourseKind" FROM course WHERE id = $1 FOR KEY SHARE"#, | ||
| 325 | course as _ | 332 | course as _ |
| 326 | ) | 333 | ) |
| 327 | .fetch_optional(&mut *tx) | 334 | .fetch_optional(&mut *tx) |
| 328 | - .await? | 335 | + .await?; |
| 329 | - .is_some(); | 336 | + let Some(locked_kind) = locked else { |
| 330 | - if !alive { | 337 | + return Ok((Some(Early::PivotGone), None, None)); |
| 331 | - return Ok((Some(Early::PivotGone), None)); | 338 | + }; |
| 332 | - } | 339 | + kind = Some(locked_kind.kind); |
| 333 | } | 340 | } |
| 334 | } | 341 | } |
| 335 | // Read off the class row inside the transaction that claims it, so the | 342 | // Read off the class row inside the transaction that claims it, so the |
| @@ -354,7 +361,7 @@ async fn early_verdicts( | |||
| 354 | .await? | 361 | .await? |
| 355 | .is_some(), | 362 | .is_some(), |
| 356 | }; | 363 | }; |
| 357 | - Ok((over.then_some(Early::Overloaded), source_id)) | 364 | + Ok((over.then_some(Early::Overloaded), source_id, kind)) |
| 358 | } | 365 | } |
| 359 | 366 | ||
| 360 | /// Write the member stint and enroll the student into every instance the | 367 | /// Write the member stint and enroll the student into every instance the |
| @@ -410,7 +417,7 @@ pub(crate) async fn add_member_sourced( | |||
| 410 | let (user, by) = (*user, *by); | 417 | let (user, by) = (*user, *by); |
| 411 | let id = ClassMemberId::generate(); | 418 | let id = ClassMemberId::generate(); |
| 412 | let outcome = tx_with_retry(db, false, async move |tx| { | 419 | let outcome = tx_with_retry(db, false, async move |tx| { |
| 413 | - let (early, _) = early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?; | 420 | + let (early, _, _) = early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?; |
| 414 | if let Some(early) = early { | 421 | if let Some(early) = early { |
| 415 | return Ok(refusal_of(early)); | 422 | return Ok(refusal_of(early)); |
| 416 | } | 423 | } |
| @@ -498,7 +505,8 @@ pub(crate) async fn add_member_sourced( | |||
| 498 | /// Students already enrolled in it keep the rows they have — no count charged, | 505 | /// Students already enrolled in it keep the rows they have — no count charged, |
| 499 | /// `source` untouched. There is no roster-size gate any more (D5: the | 506 | /// `source` untouched. There is no roster-size gate any more (D5: the |
| 500 | /// counter is a count, not a capacity), so the only refusals left are the | 507 | /// counter is a count, not a capacity), so the only refusals left are the |
| 501 | -/// class's own ceilings and a vanished pivot. | 508 | +/// class's own ceilings, a vanished pivot, and a course kind that is not |
| 509 | +/// class-delivered (a 400 straight out of the transaction). | ||
| 502 | /// | 510 | /// |
| 503 | /// `source` is the blueprint whose behalf this attach runs on, and supplying | 511 | /// `source` is the blueprint whose behalf this attach runs on, and supplying |
| 504 | /// it adds one more claim: that it is still there when the transaction runs | 512 | /// 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( | |||
| 507 | /// and passes `None`. | 515 | /// and passes `None`. |
| 508 | /// | 516 | /// |
| 509 | /// The instance's own id is minted here (v7, so a class's instances list in | 517 | /// The instance's own id is minted here (v7, so a class's instances list in |
| 510 | -/// creation order) and its policy columns take the schema defaults: one weekly | 518 | +/// creation order) and its content columns are born `NULL` — the *inherit* |
| 511 | -/// hour, counted toward the report card, an empty roster. A PATCH on `/instances` | 519 | +/// state: what the section teaches is whatever its grade-level |
| 512 | -/// changes them afterwards. | 520 | +/// [`crate::domain::course_offering::CourseOffering`] says, and through it |
| 521 | +/// the catalog course. That template is resolved (auto-created empty, with | ||
| 522 | +/// `created_by` naming the attaching actor, when the (course, grade_level) | ||
| 523 | +/// pair has none yet) in this same transaction — the class row is read under | ||
| 524 | +/// `FOR KEY SHARE`, so the offering the insert names is the one for the | ||
| 525 | +/// grade the class carries *at the attach*, not at the caller's read. A | ||
| 526 | +/// PATCH on `/instances` overrides the content afterwards. | ||
| 527 | +/// | ||
| 528 | +/// Only a **class-delivered** course | ||
| 529 | +/// ([`CourseKind::is_class_delivered`], `kind = 'course'`) becomes an | ||
| 530 | +/// instance: a club or an etüt is joined individually and is refused with a | ||
| 531 | +/// 400, whatever axis asked for the attach. | ||
| 513 | /// | 532 | /// |
| 514 | /// Two counters ride the write, both in this one transaction: the class's | 533 | /// Two counters ride the write, both in this one transaction: the class's |
| 515 | /// `class_course_count` (claimed by the conditional CTE, so a full or gone | 534 | /// `class_course_count` (claimed by the conditional CTE, so a full or gone |
| @@ -532,7 +551,7 @@ pub(crate) async fn attach_course( | |||
| 532 | let source = source.cloned(); | 551 | let source = source.cloned(); |
| 533 | let id = ClassCourseId::generate(); | 552 | let id = ClassCourseId::generate(); |
| 534 | let outcome = tx_with_retry(db, false, async move |tx| { | 553 | let outcome = tx_with_retry(db, false, async move |tx| { |
| 535 | - let (early, source_id) = early_verdicts( | 554 | + let (early, source_id, kind) = early_verdicts( |
| 536 | tx, | 555 | tx, |
| 537 | &class, | 556 | &class, |
| 538 | Axis::Course, | 557 | Axis::Course, |
| @@ -543,13 +562,55 @@ pub(crate) async fn attach_course( | |||
| 543 | if let Some(early) = early { | 562 | if let Some(early) = early { |
| 544 | return Ok(refusal_of(early)); | 563 | return Ok(refusal_of(early)); |
| 545 | } | 564 | } |
| 565 | + let Some(kind) = kind else { | ||
| 566 | + // Unreachable on this axis — the course pivot always answers its | ||
| 567 | + // kind when it is alive. A future axis change should surface as | ||
| 568 | + // this 500, not as a wrong-looking refusal. | ||
| 569 | + return Err(AppError::Internal( | ||
| 570 | + "a course attach locked a course but read no kind".into(), | ||
| 571 | + )); | ||
| 572 | + }; | ||
| 573 | + if !kind.is_class_delivered() { | ||
| 574 | + // The gate from the locked row itself, so a concurrent kind | ||
| 575 | + // change cannot slip between a pre-flight check and the insert. | ||
| 576 | + // A blueprint listing a study/club aborts that whole pump run | ||
| 577 | + // with this 400 — fail-closed, naming the row to fix. | ||
| 578 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 579 | + field: "course", | ||
| 580 | + reason: "only a ders attaches to a class — a club or etüt is joined individually, not attached", | ||
| 581 | + })); | ||
| 582 | + } | ||
| 583 | + // The class's own grade, locked: the offering the insert names is the | ||
| 584 | + // one for the grade the class carries *now* (a concurrent grade move | ||
| 585 | + // waits behind this KEY SHARE). A gone class answers `Gone` — the | ||
| 586 | + // same verdict the seat claim below would have produced, one read | ||
| 587 | + // earlier. | ||
| 588 | + let grade_level = sqlx::query_scalar!( | ||
| 589 | + r#"SELECT grade_level AS "grade_level: GradeLevel" FROM class_group | ||
| 590 | + WHERE id = $1 FOR KEY SHARE"#, | ||
| 591 | + class as _ | ||
| 592 | + ) | ||
| 593 | + .fetch_optional(&mut *tx) | ||
| 594 | + .await?; | ||
| 595 | + let Some(grade_level) = grade_level else { | ||
| 596 | + return Ok(Attached::Gone); | ||
| 597 | + }; | ||
| 598 | + // The template the instance teaches from: found, or minted empty | ||
| 599 | + // (every content column NULL — inherit the catalog) with this actor | ||
| 600 | + // as its `created_by`. Race-closed inside `ensure_tx`. Minted before | ||
| 601 | + // the seat claim, so a refused attach (a full class) may leave an | ||
| 602 | + // empty template behind — harmless: an empty template inherits the | ||
| 603 | + // catalog exactly as no template would, and the next attach at that | ||
| 604 | + // grade reuses it. | ||
| 605 | + let offering = | ||
| 606 | + crate::db::course_offering::ensure_tx(tx, &course, grade_level, &by).await?; | ||
| 546 | let inserted = match sqlx::query_scalar!( | 607 | let inserted = match sqlx::query_scalar!( |
| 547 | r#"WITH seat AS ( | 608 | r#"WITH seat AS ( |
| 548 | UPDATE class_group SET class_course_count = class_course_count + 1 | 609 | UPDATE class_group SET class_course_count = class_course_count + 1 |
| 549 | WHERE id = $1 AND class_course_count < $2 | 610 | WHERE id = $1 AND class_course_count < $2 |
| 550 | RETURNING 1) | 611 | RETURNING 1) |
| 551 | - INSERT INTO class_course (id, class, course, attached_by, attached_at, source) | 612 | + INSERT INTO class_course (id, class, course, attached_by, attached_at, source, offering) |
| 552 | - SELECT $3, $1, $4, $5, $6, $7 WHERE EXISTS (SELECT 1 FROM seat) | 613 | + SELECT $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat) |
| 553 | RETURNING 1 AS "one""#, | 614 | RETURNING 1 AS "one""#, |
| 554 | class as _, | 615 | class as _, |
| 555 | Axis::Course.cap(), | 616 | Axis::Course.cap(), |
| @@ -558,6 +619,7 @@ pub(crate) async fn attach_course( | |||
| 558 | by as _, | 619 | by as _, |
| 559 | attached_at as _, | 620 | attached_at as _, |
| 560 | source_id, | 621 | source_id, |
| 622 | + offering as _, | ||
| 561 | ) | 623 | ) |
| 562 | .fetch_optional(&mut *tx) | 624 | .fetch_optional(&mut *tx) |
| 563 | .await | 625 | .await |
| @@ -621,11 +683,16 @@ pub(crate) async fn attach_course( | |||
| 621 | id: id.clone(), | 683 | id: id.clone(), |
| 622 | class: class.clone(), | 684 | class: class.clone(), |
| 623 | course: course.clone(), | 685 | course: course.clone(), |
| 686 | + offering: offering.clone(), | ||
| 624 | attached_by: by, | 687 | attached_by: by, |
| 625 | - source: source.clone(), | 688 | + source, |
| 626 | - ders_saati: DersSaati::try_new(crate::constant::MIN_DERS_SAATI) | 689 | + title: None, |
| 627 | - .expect("the schema default is a valid weekly-hours count"), | 690 | + description: None, |
| 628 | - counts_toward_karne: true, | 691 | + ders_saati: None, |
| 692 | + counts_toward_karne: None, | ||
| 693 | + subjects_inherited: true, | ||
| 694 | + exam_weights_inherited: true, | ||
| 695 | + weekly_plan_inherited: true, | ||
| 629 | enrollment_count, | 696 | enrollment_count, |
| 630 | attached_at, | 697 | attached_at, |
| 631 | })) | 698 | })) |
| @@ -933,7 +1000,7 @@ pub(crate) async fn detach_course( | |||
| 933 | sqlx::query_scalar!( | 1000 | sqlx::query_scalar!( |
| 934 | r#"SELECT id AS "id: uuid::Uuid" FROM class_course | 1001 | r#"SELECT id AS "id: uuid::Uuid" FROM class_course |
| 935 | WHERE class = $1 AND course = $2 | 1002 | WHERE class = $1 AND course = $2 |
| 936 | - AND source = (SELECT id FROM class_blueprint WHERE grade = $3) | 1003 | + AND source = (SELECT id FROM class_blueprint WHERE grade_level = $3) |
| 937 | FOR UPDATE"#, | 1004 | FOR UPDATE"#, |
| 938 | class as _, | 1005 | class as _, |
| 939 | course as _, | 1006 | course as _, |
src/db/course.rsmodified+2 -2
| @@ -703,7 +703,7 @@ pub(crate) async fn a_test_instance( | |||
| 703 | db, | 703 | db, |
| 704 | &manager, | 704 | &manager, |
| 705 | ClassName::try_new("9-A").unwrap(), | 705 | ClassName::try_new("9-A").unwrap(), |
| 706 | - None, | 706 | + crate::domain::grade::GradeLevel::new(9).unwrap(), |
| 707 | None, | 707 | None, |
| 708 | None, | 708 | None, |
| 709 | ) | 709 | ) |
| @@ -934,7 +934,7 @@ mod tests { | |||
| 934 | db, | 934 | db, |
| 935 | on, | 935 | on, |
| 936 | crate::domain::class_group::ClassName::try_new(name).unwrap(), | 936 | crate::domain::class_group::ClassName::try_new(name).unwrap(), |
| 937 | - None, | 937 | + crate::domain::grade::GradeLevel::new(9).unwrap(), |
| 938 | None, | 938 | None, |
| 939 | None, | 939 | None, |
| 940 | ) | 940 | ) |
src/db/course_offering.rsadded+429 -0
| @@ -0,0 +1,429 @@ | |||
| 1 | +//! The `course_offering` table: the grade-level course template and the reads | ||
| 2 | +//! and writes behind `/offerings`. The row shape lives in | ||
| 3 | +//! [`crate::domain::course_offering`]; the workflows (the class-delivered | ||
| 4 | +//! gate, the duplicate refusal) in [`crate::service::course_offering`]. | ||
| 5 | +//! | ||
| 6 | +//! One row per (course, grade_level) — the `UNIQUE` key the attach pump's | ||
| 7 | +//! auto-create races on: [`ensure_tx`] inserts `ON CONFLICT DO NOTHING` and | ||
| 8 | +//! reads the winner's id back, so two attaches landing together share one | ||
| 9 | +//! template whatever the interleaving was. | ||
| 10 | +//! | ||
| 11 | +//! Every content column is nullable by design — `NULL` means *inherit* (from | ||
| 12 | +//! the catalog course, or from the constants), never "missing". The update is | ||
| 13 | +//! field-scoped in the `set_or_clear` shape the other PATCH handlers speak: | ||
| 14 | +//! an absent field keeps its column, an explicit `null` clears back to | ||
| 15 | +//! inherit, a value sets the override. | ||
| 16 | + | ||
| 17 | +use sqlx::postgres::PgConnection; | ||
| 18 | + | ||
| 19 | +use crate::database::{Database, unique_violation}; | ||
| 20 | +use crate::db::page::PagedList; | ||
| 21 | +use crate::domain::class_course::DersSaati; | ||
| 22 | +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; | ||
| 23 | +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; | ||
| 24 | +use crate::domain::grade::GradeLevel; | ||
| 25 | +use crate::domain::timestamp::Timestamp; | ||
| 26 | +use crate::domain::user::UserId; | ||
| 27 | +use crate::error::AppError; | ||
| 28 | + | ||
| 29 | +/// One offering as the *runtime* row decode sees it. Identical to | ||
| 30 | +/// [`CourseOffering`] except `default_ders_saati` stays the raw `SMALLINT` | ||
| 31 | +/// (`Option<i16>`): the runtime [`sqlx::FromRow`] path cannot name the | ||
| 32 | +/// `::bigint` cast the static `query_as!` projections use, and | ||
| 33 | +/// [`DersSaati`]'s transparent `i64` would refuse a `SMALLINT` at decode. | ||
| 34 | +/// [`OfferingRow::into_course_offering`] does the two-step conversions the | ||
| 35 | +/// column `CHECK`s already guarantee. | ||
| 36 | +#[derive(Debug, sqlx::FromRow)] | ||
| 37 | +struct OfferingRow { | ||
| 38 | + id: CourseOfferingId, | ||
| 39 | + course: CourseId, | ||
| 40 | + grade_level: GradeLevel, | ||
| 41 | + title: Option<CourseTitle>, | ||
| 42 | + description: Option<CourseDescription>, | ||
| 43 | + default_ders_saati: Option<i16>, | ||
| 44 | + default_counts_toward_karne: Option<bool>, | ||
| 45 | + created_by: UserId, | ||
| 46 | + created_at: Timestamp, | ||
| 47 | + updated_at: Timestamp, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +impl OfferingRow { | ||
| 51 | + fn into_course_offering(self) -> CourseOffering { | ||
| 52 | + CourseOffering { | ||
| 53 | + id: self.id, | ||
| 54 | + course: self.course, | ||
| 55 | + grade_level: self.grade_level, | ||
| 56 | + title: self.title, | ||
| 57 | + description: self.description, | ||
| 58 | + default_ders_saati: self.default_ders_saati.map(|hours| { | ||
| 59 | + DersSaati::try_new(i64::from(hours)) | ||
| 60 | + .expect("the column CHECK keeps the weekly hours between 1 and 40") | ||
| 61 | + }), | ||
| 62 | + default_counts_toward_karne: self.default_counts_toward_karne, | ||
| 63 | + created_by: self.created_by, | ||
| 64 | + created_at: self.created_at, | ||
| 65 | + updated_at: self.updated_at, | ||
| 66 | + } | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// One offering by id, or `None` when the id names no row. | ||
| 71 | +pub async fn read(db: &Database, id: &CourseOfferingId) -> Result<Option<CourseOffering>, AppError> { | ||
| 72 | + let row = sqlx::query_as!( | ||
| 73 | + CourseOffering, | ||
| 74 | + r#"SELECT id AS "id: CourseOfferingId", | ||
| 75 | + course AS "course: CourseId", | ||
| 76 | + grade_level AS "grade_level: GradeLevel", | ||
| 77 | + title AS "title?: CourseTitle", | ||
| 78 | + description AS "description?: CourseDescription", | ||
| 79 | + default_ders_saati::bigint AS "default_ders_saati?: DersSaati", | ||
| 80 | + default_counts_toward_karne, | ||
| 81 | + created_by AS "created_by: UserId", | ||
| 82 | + created_at AS "created_at: Timestamp", | ||
| 83 | + updated_at AS "updated_at: Timestamp" | ||
| 84 | + FROM course_offering WHERE id = $1"#, | ||
| 85 | + id.uuid(), | ||
| 86 | + ) | ||
| 87 | + .fetch_optional(db) | ||
| 88 | + .await?; | ||
| 89 | + Ok(row) | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +/// Load every offering behind `ids` (one query) — the batch half of the | ||
| 93 | +/// resolved-content reads (`service::instance_resolve::resolved_content`), | ||
| 94 | +/// which map a page of instances onto their templates without an N+1. | ||
| 95 | +pub async fn list_by_ids( | ||
| 96 | + db: &Database, | ||
| 97 | + ids: &[CourseOfferingId], | ||
| 98 | +) -> Result<Vec<CourseOffering>, AppError> { | ||
| 99 | + if ids.is_empty() { | ||
| 100 | + return Ok(Vec::new()); | ||
| 101 | + } | ||
| 102 | + let keys: Vec<uuid::Uuid> = ids.iter().map(CourseOfferingId::uuid).collect(); | ||
| 103 | + let rows = sqlx::query_as!( | ||
| 104 | + CourseOffering, | ||
| 105 | + r#"SELECT id AS "id: CourseOfferingId", | ||
| 106 | + course AS "course: CourseId", | ||
| 107 | + grade_level AS "grade_level: GradeLevel", | ||
| 108 | + title AS "title?: CourseTitle", | ||
| 109 | + description AS "description?: CourseDescription", | ||
| 110 | + default_ders_saati::bigint AS "default_ders_saati?: DersSaati", | ||
| 111 | + default_counts_toward_karne, | ||
| 112 | + created_by AS "created_by: UserId", | ||
| 113 | + created_at AS "created_at: Timestamp", | ||
| 114 | + updated_at AS "updated_at: Timestamp" | ||
| 115 | + FROM course_offering WHERE id = ANY($1)"#, | ||
| 116 | + &keys, | ||
| 117 | + ) | ||
| 118 | + .fetch_all(db) | ||
| 119 | + .await?; | ||
| 120 | + Ok(rows) | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// The offering a (course, grade_level) pair resolves to, or `None` when no | ||
| 124 | +/// template exists there yet — the read behind "what does this grade teach | ||
| 125 | +/// from" outside a pump transaction. | ||
| 126 | +pub async fn find( | ||
| 127 | + db: &Database, | ||
| 128 | + course: &CourseId, | ||
| 129 | + grade: GradeLevel, | ||
| 130 | +) -> Result<Option<CourseOffering>, AppError> { | ||
| 131 | + let row = sqlx::query_as!( | ||
| 132 | + CourseOffering, | ||
| 133 | + r#"SELECT id AS "id: CourseOfferingId", | ||
| 134 | + course AS "course: CourseId", | ||
| 135 | + grade_level AS "grade_level: GradeLevel", | ||
| 136 | + title AS "title?: CourseTitle", | ||
| 137 | + description AS "description?: CourseDescription", | ||
| 138 | + default_ders_saati::bigint AS "default_ders_saati?: DersSaati", | ||
| 139 | + default_counts_toward_karne, | ||
| 140 | + created_by AS "created_by: UserId", | ||
| 141 | + created_at AS "created_at: Timestamp", | ||
| 142 | + updated_at AS "updated_at: Timestamp" | ||
| 143 | + FROM course_offering WHERE course = $1 AND grade_level = $2"#, | ||
| 144 | + course.uuid(), | ||
| 145 | + grade.get(), | ||
| 146 | + ) | ||
| 147 | + .fetch_optional(db) | ||
| 148 | + .await?; | ||
| 149 | + Ok(row) | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +/// The offerings, grade ladder first, paged via `limit`/`offset`; both | ||
| 153 | +/// filters are optional and combine. The page and its count share the same | ||
| 154 | +/// predicate ([`PagedList`]). | ||
| 155 | +pub async fn list( | ||
| 156 | + db: &Database, | ||
| 157 | + course: Option<&CourseId>, | ||
| 158 | + grade: Option<GradeLevel>, | ||
| 159 | + limit: Option<i64>, | ||
| 160 | + offset: i64, | ||
| 161 | +) -> Result<(Vec<CourseOffering>, i64), AppError> { | ||
| 162 | + let from_where = match (course, grade) { | ||
| 163 | + (Some(_), Some(_)) => "course_offering WHERE course = $1 AND grade_level = $2", | ||
| 164 | + (Some(_), None) => "course_offering WHERE course = $1", | ||
| 165 | + (None, Some(_)) => "course_offering WHERE grade_level = $1", | ||
| 166 | + (None, None) => "course_offering", | ||
| 167 | + }; | ||
| 168 | + let mut page = PagedList::new(from_where, "ORDER BY grade_level, course"); | ||
| 169 | + if let Some(course) = course { | ||
| 170 | + page = page.bind(course.uuid()); | ||
| 171 | + } | ||
| 172 | + if let Some(grade) = grade { | ||
| 173 | + page = page.bind(i64::from(grade.get())); | ||
| 174 | + } | ||
| 175 | + let (rows, total) = page.run::<OfferingRow>(limit, offset, db).await?; | ||
| 176 | + Ok(( | ||
| 177 | + rows.into_iter() | ||
| 178 | + .map(OfferingRow::into_course_offering) | ||
| 179 | + .collect(), | ||
| 180 | + total, | ||
| 181 | + )) | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +/// Mint the template. The duplicate (course, grade_level) answer is a **409 | ||
| 185 | +/// `offering_exists`**, not a store error: a manager creating the same | ||
| 186 | +/// template twice wants to be told it exists, and the attach pump's | ||
| 187 | +/// auto-create would have silently shared the row instead. | ||
| 188 | +#[allow(clippy::too_many_arguments)] // the offering row, spelled field by field | ||
| 189 | +pub async fn create( | ||
| 190 | + db: &Database, | ||
| 191 | + course: &CourseId, | ||
| 192 | + grade: GradeLevel, | ||
| 193 | + title: Option<CourseTitle>, | ||
| 194 | + description: Option<CourseDescription>, | ||
| 195 | + default_ders_saati: Option<DersSaati>, | ||
| 196 | + default_counts_toward_karne: Option<bool>, | ||
| 197 | + by: &UserId, | ||
| 198 | +) -> Result<CourseOffering, AppError> { | ||
| 199 | + let now = Timestamp::now(); | ||
| 200 | + let title = title.map(|title| title.as_str().to_string()); | ||
| 201 | + let description = description.map(|d| d.as_str().to_string()); | ||
| 202 | + // An `i64` bound into a `SMALLINT` column: the assignment cast is the | ||
| 203 | + // statement's own, and the newtype has already range-checked the value. | ||
| 204 | + let hours = default_ders_saati.map(DersSaati::as_i64); | ||
| 205 | + let row = sqlx::query_as!( | ||
| 206 | + CourseOffering, | ||
| 207 | + r#"INSERT INTO course_offering | ||
| 208 | + (id, course, grade_level, title, description, | ||
| 209 | + default_ders_saati, default_counts_toward_karne, | ||
| 210 | + created_by, created_at, updated_at) | ||
| 211 | + VALUES ($1, $2, $3, $4, $5, $6::bigint, $7, $8, $9, $9) | ||
| 212 | + RETURNING id AS "id: CourseOfferingId", | ||
| 213 | + course AS "course: CourseId", | ||
| 214 | + grade_level AS "grade_level: GradeLevel", | ||
| 215 | + title AS "title?: CourseTitle", | ||
| 216 | + description AS "description?: CourseDescription", | ||
| 217 | + default_ders_saati::bigint AS "default_ders_saati?: DersSaati", | ||
| 218 | + default_counts_toward_karne, | ||
| 219 | + created_by AS "created_by: UserId", | ||
| 220 | + created_at AS "created_at: Timestamp", | ||
| 221 | + updated_at AS "updated_at: Timestamp""#, | ||
| 222 | + CourseOfferingId::generate().uuid(), | ||
| 223 | + course.uuid(), | ||
| 224 | + grade.get(), | ||
| 225 | + title, | ||
| 226 | + description, | ||
| 227 | + hours, | ||
| 228 | + default_counts_toward_karne, | ||
| 229 | + by.uuid(), | ||
| 230 | + now.as_millis(), | ||
| 231 | + ) | ||
| 232 | + .fetch_one(db) | ||
| 233 | + .await | ||
| 234 | + .map_err(|e| { | ||
| 235 | + // The table carries exactly one `UNIQUE` constraint — the (course, | ||
| 236 | + // grade_level) template key — so *any* unique violation here is the | ||
| 237 | + // duplicate template, whatever Postgres named it. | ||
| 238 | + if unique_violation(&e).is_some() { | ||
| 239 | + AppError::ConflictCoded { | ||
| 240 | + code: "offering_exists", | ||
| 241 | + message: "this course already has an offering for this grade".into(), | ||
| 242 | + } | ||
| 243 | + } else { | ||
| 244 | + e.into() | ||
| 245 | + } | ||
| 246 | + })?; | ||
| 247 | + Ok(row) | ||
| 248 | +} | ||
| 249 | + | ||
| 250 | +/// Field-scoped PATCH in the `set_or_clear` shape: an absent field keeps its | ||
| 251 | +/// column, `Some(None)` clears back to inherit (`NULL`), `Some(Some(v))` sets | ||
| 252 | +/// the override. `updated_at` moves with every write that changes anything. | ||
| 253 | +/// An empty request writes nothing and reads the row back. `Err(NotFound)` | ||
| 254 | +/// when the offering is gone. | ||
| 255 | +pub async fn update( | ||
| 256 | + db: &Database, | ||
| 257 | + id: &CourseOfferingId, | ||
| 258 | + title: Option<Option<CourseTitle>>, | ||
| 259 | + description: Option<Option<CourseDescription>>, | ||
| 260 | + default_ders_saati: Option<Option<DersSaati>>, | ||
| 261 | + default_counts_toward_karne: Option<Option<bool>>, | ||
| 262 | +) -> Result<CourseOffering, AppError> { | ||
| 263 | + if title.is_none() | ||
| 264 | + && description.is_none() | ||
| 265 | + && default_ders_saati.is_none() | ||
| 266 | + && default_counts_toward_karne.is_none() | ||
| 267 | + { | ||
| 268 | + return read(db, id).await?.ok_or(AppError::NotFound); | ||
| 269 | + } | ||
| 270 | + // Present-flag + nullable-value pairs: the flag decides *whether* the | ||
| 271 | + // column moves, the value decides to what (a typed `NULL` is the inherit | ||
| 272 | + // state). The weekly hours ride the `::bigint` round-trip cast like every | ||
| 273 | + // other `DersSaati` read, and the column `CHECK` re-checks the range at | ||
| 274 | + // the store. | ||
| 275 | + let title_present = title.is_some(); | ||
| 276 | + let title = title.flatten().map(|t| t.as_str().to_string()); | ||
| 277 | + let description_present = description.is_some(); | ||
| 278 | + let description = description.flatten().map(|d| d.as_str().to_string()); | ||
| 279 | + let hours_present = default_ders_saati.is_some(); | ||
| 280 | + let hours = default_ders_saati.flatten().map(DersSaati::as_i64); | ||
| 281 | + let counts_present = default_counts_toward_karne.is_some(); | ||
| 282 | + let counts = default_counts_toward_karne.flatten(); | ||
| 283 | + let now = Timestamp::now(); | ||
| 284 | + let row = sqlx::query_as!( | ||
| 285 | + CourseOffering, | ||
| 286 | + r#"WITH updated AS ( | ||
| 287 | + UPDATE course_offering SET | ||
| 288 | + title = CASE WHEN $2 THEN $3::text ELSE title END, | ||
| 289 | + description = CASE WHEN $4 THEN $5::text ELSE description END, | ||
| 290 | + default_ders_saati = CASE WHEN $6 THEN | ||
| 291 | + COALESCE($7::bigint, default_ders_saati::bigint)::smallint | ||
| 292 | + ELSE default_ders_saati END, | ||
| 293 | + default_counts_toward_karne = CASE WHEN $8 THEN $9 | ||
| 294 | + ELSE default_counts_toward_karne END, | ||
| 295 | + updated_at = $10 | ||
| 296 | + WHERE id = $1 | ||
| 297 | + RETURNING id, course, grade_level, title, description, | ||
| 298 | + default_ders_saati, default_counts_toward_karne, | ||
| 299 | + created_by, created_at, updated_at) | ||
| 300 | + SELECT u.id AS "id: CourseOfferingId", | ||
| 301 | + u.course AS "course: CourseId", | ||
| 302 | + u.grade_level AS "grade_level: GradeLevel", | ||
| 303 | + u.title AS "title?: CourseTitle", | ||
| 304 | + u.description AS "description?: CourseDescription", | ||
| 305 | + u.default_ders_saati::bigint AS "default_ders_saati?: DersSaati", | ||
| 306 | + u.default_counts_toward_karne, | ||
| 307 | + u.created_by AS "created_by: UserId", | ||
| 308 | + u.created_at AS "created_at: Timestamp", | ||
| 309 | + u.updated_at AS "updated_at: Timestamp" | ||
| 310 | + FROM updated u"#, | ||
| 311 | + id.uuid(), | ||
| 312 | + title_present, | ||
| 313 | + title, | ||
| 314 | + description_present, | ||
| 315 | + description, | ||
| 316 | + hours_present, | ||
| 317 | + hours, | ||
| 318 | + counts_present, | ||
| 319 | + counts, | ||
| 320 | + now.as_millis(), | ||
| 321 | + ) | ||
| 322 | + .fetch_optional(db) | ||
| 323 | + .await? | ||
| 324 | + .ok_or(AppError::NotFound)?; | ||
| 325 | + Ok(row) | ||
| 326 | +} | ||
| 327 | + | ||
| 328 | +/// The offering's two defaults, straight off its row — `(default_ders_saati, | ||
| 329 | +/// default_counts_toward_karne)`, `None`s *included* (a `NULL` default is the | ||
| 330 | +/// inherit state, and the caller layers its own fallbacks on top). `None` when | ||
| 331 | +/// the id names no offering: the `RESTRICT` foreign key on `class_course` | ||
| 332 | +/// keeps every instance's offering alive, so a missing row is the honest 404 | ||
| 333 | +/// the service turns into one, not a case to paper over. | ||
| 334 | +pub async fn defaults( | ||
| 335 | + db: &Database, | ||
| 336 | + id: &CourseOfferingId, | ||
| 337 | +) -> Result<Option<(Option<DersSaati>, Option<bool>)>, AppError> { | ||
| 338 | + let row = sqlx::query!( | ||
| 339 | + r#"SELECT default_ders_saati::bigint AS "default_ders_saati?: DersSaati", | ||
| 340 | + default_counts_toward_karne | ||
| 341 | + FROM course_offering WHERE id = $1"#, | ||
| 342 | + id.uuid(), | ||
| 343 | + ) | ||
| 344 | + .fetch_optional(db) | ||
| 345 | + .await?; | ||
| 346 | + Ok(row.map(|row| (row.default_ders_saati, row.default_counts_toward_karne))) | ||
| 347 | +} | ||
| 348 | + | ||
| 349 | +/// Delete the template — refused while any instance still teaches from it. | ||
| 350 | +/// The refusal is a **409 `offering_in_use`** (the foreign key's `RESTRICT` | ||
| 351 | +/// is the store's mirror of the same rule); a gone id is the usual 404. One | ||
| 352 | +/// conditional statement is the whole invariant, so a check-then-delete race | ||
| 353 | +/// cannot exist: the `NOT EXISTS` is judged on the row as it is *at the | ||
| 354 | +/// delete*. | ||
| 355 | +pub async fn delete(db: &Database, id: &CourseOfferingId) -> Result<(), AppError> { | ||
| 356 | + let deleted = sqlx::query!( | ||
| 357 | + r#"DELETE FROM course_offering | ||
| 358 | + WHERE id = $1 | ||
| 359 | + AND NOT EXISTS (SELECT 1 FROM class_course cc WHERE cc.offering = $1)"#, | ||
| 360 | + id.uuid(), | ||
| 361 | + ) | ||
| 362 | + .execute(db) | ||
| 363 | + .await? | ||
| 364 | + .rows_affected(); | ||
| 365 | + if deleted > 0 { | ||
| 366 | + return Ok(()); | ||
| 367 | + } | ||
| 368 | + // Zero rows: in use, or already gone. The read tells the two apart. | ||
| 369 | + let standing = sqlx::query_scalar!( | ||
| 370 | + r#"SELECT 1 AS "one" FROM course_offering WHERE id = $1"#, | ||
| 371 | + id.uuid() | ||
| 372 | + ) | ||
| 373 | + .fetch_optional(db) | ||
| 374 | + .await? | ||
| 375 | + .is_some(); | ||
| 376 | + if standing { | ||
| 377 | + Err(AppError::ConflictCoded { | ||
| 378 | + code: "offering_in_use", | ||
| 379 | + message: | ||
| 380 | + "instances still teach this offering — detach the course from those classes first" | ||
| 381 | + .into(), | ||
| 382 | + }) | ||
| 383 | + } else { | ||
| 384 | + Err(AppError::NotFound) | ||
| 385 | + } | ||
| 386 | +} | ||
| 387 | + | ||
| 388 | +/// Resolve — or mint empty — the template a (course, grade_level) pair | ||
| 389 | +/// teaches from, inside the caller's transaction. The attach pump's helper: | ||
| 390 | +/// every instance insert needs its offering link, and an untouched grade | ||
| 391 | +/// mints an *empty* template (every content column `NULL`) so it inherits the | ||
| 392 | +/// catalog course until a manager fills it in. `created_by` is the actor | ||
| 393 | +/// whose attach asked. | ||
| 394 | +/// | ||
| 395 | +/// The `ON CONFLICT DO NOTHING` + read-back pair is the race-closer: two | ||
| 396 | +/// attaches landing on the same (course, grade_level) together both insert, | ||
| 397 | +/// one wins, and the loser's read-back returns the winner's row — one | ||
| 398 | +/// template per pair, whatever the order was. The table's only `UNIQUE` | ||
| 399 | +/// constraint is that pair, so the bare `DO NOTHING` cannot swallow a | ||
| 400 | +/// different conflict. | ||
| 401 | +pub(crate) async fn ensure_tx( | ||
| 402 | + tx: &mut PgConnection, | ||
| 403 | + course: &CourseId, | ||
| 404 | + grade: GradeLevel, | ||
| 405 | + by: &UserId, | ||
| 406 | +) -> Result<CourseOfferingId, AppError> { | ||
| 407 | + let now = Timestamp::now(); | ||
| 408 | + sqlx::query!( | ||
| 409 | + r#"INSERT INTO course_offering (id, course, grade_level, created_by, created_at, updated_at) | ||
| 410 | + VALUES ($1, $2, $3, $4, $5, $5) | ||
| 411 | + ON CONFLICT DO NOTHING"#, | ||
| 412 | + CourseOfferingId::generate().uuid(), | ||
| 413 | + course.uuid(), | ||
| 414 | + grade.get(), | ||
| 415 | + by.uuid(), | ||
| 416 | + now.as_millis(), | ||
| 417 | + ) | ||
| 418 | + .execute(&mut *tx) | ||
| 419 | + .await?; | ||
| 420 | + let id = sqlx::query_scalar!( | ||
| 421 | + r#"SELECT id AS "id: CourseOfferingId" FROM course_offering | ||
| 422 | + WHERE course = $1 AND grade_level = $2"#, | ||
| 423 | + course.uuid(), | ||
| 424 | + grade.get(), | ||
| 425 | + ) | ||
| 426 | + .fetch_one(&mut *tx) | ||
| 427 | + .await?; | ||
| 428 | + Ok(id) | ||
| 429 | +} | ||
src/db/course_session.rsmodified+1 -1
| @@ -202,7 +202,7 @@ mod tests { | |||
| 202 | &db, | 202 | &db, |
| 203 | &creator, | 203 | &creator, |
| 204 | crate::domain::class_group::ClassName::try_new("9-A").unwrap(), | 204 | crate::domain::class_group::ClassName::try_new("9-A").unwrap(), |
| 205 | - None, | 205 | + crate::domain::grade::GradeLevel::new(9).unwrap(), |
| 206 | None, | 206 | None, |
| 207 | None, | 207 | None, |
| 208 | ) | 208 | ) |
src/db/event.rsmodified+1 -1
| @@ -331,7 +331,7 @@ mod tests { | |||
| 331 | let creator = a_person(&db, "event-guard").await; | 331 | let creator = a_person(&db, "event-guard").await; |
| 332 | // `audience_class` is a foreign key too: the class case needs a real group. | 332 | // `audience_class` is a foreign key too: the class case needs a real group. |
| 333 | let class = ClassGroupId::generate(); | 333 | let class = ClassGroupId::generate(); |
| 334 | - sqlx::query("INSERT INTO class_group (id, name, creator) VALUES ($1, 'g1', $2)") | 334 | + sqlx::query("INSERT INTO class_group (id, name, creator, grade_level) VALUES ($1, 'g1', $2, 9)") |
| 335 | .bind(class.uuid()) | 335 | .bind(class.uuid()) |
| 336 | .bind(creator.uuid()) | 336 | .bind(creator.uuid()) |
| 337 | .execute(&db) | 337 | .execute(&db) |
src/db/exam.rsmodified+1 -1
| @@ -771,7 +771,7 @@ mod tests { | |||
| 771 | &db, | 771 | &db, |
| 772 | &creator, | 772 | &creator, |
| 773 | crate::domain::class_group::ClassName::try_new("9-A").unwrap(), | 773 | crate::domain::class_group::ClassName::try_new("9-A").unwrap(), |
| 774 | - None, | 774 | + crate::domain::grade::GradeLevel::new(9).unwrap(), |
| 775 | None, | 775 | None, |
| 776 | None, | 776 | None, |
| 777 | ) | 777 | ) |
src/db/exam_result.rsmodified+7 -6
| @@ -551,7 +551,7 @@ pub(crate) mod tests { | |||
| 551 | db, | 551 | db, |
| 552 | &office, | 552 | &office, |
| 553 | ClassName::try_new(name).unwrap(), | 553 | ClassName::try_new(name).unwrap(), |
| 554 | - None, | 554 | + crate::domain::grade::GradeLevel::new(5).unwrap(), |
| 555 | Some(*year.get_id()), | 555 | Some(*year.get_id()), |
| 556 | None, | 556 | None, |
| 557 | ) | 557 | ) |
| @@ -570,9 +570,10 @@ pub(crate) mod tests { | |||
| 570 | let addressed = instances[1].clone(); | 570 | let addressed = instances[1].clone(); |
| 571 | 571 | ||
| 572 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); | 572 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); |
| 573 | - for (title, addressed_to_both, mark) in | 573 | + for (title, addressed_to_both, kind, mark) in [ |
| 574 | - [("ortak", true, ORTAK_MARK), ("tek", false, OWNER_MARK)] | 574 | + ("ortak", true, "yazili", ORTAK_MARK), |
| 575 | - { | 575 | + ("tek", false, "sozlu", OWNER_MARK), |
| 576 | + ] { | ||
| 576 | let exam = crate::db::exam::create( | 577 | let exam = crate::db::exam::create( |
| 577 | db, | 578 | db, |
| 578 | &office, | 579 | &office, |
| @@ -580,7 +581,7 @@ pub(crate) mod tests { | |||
| 580 | term.get_id(), | 581 | term.get_id(), |
| 581 | ExamTitle::try_new(title).unwrap(), | 582 | ExamTitle::try_new(title).unwrap(), |
| 582 | ExamDescription::try_new("").unwrap(), | 583 | ExamDescription::try_new("").unwrap(), |
| 583 | - ExamKind::try_new("yazili", &kinds).unwrap(), | 584 | + ExamKind::try_new(kind, &kinds).unwrap(), |
| 584 | ExamSchedule::try_new(None, None, None, None).unwrap(), | 585 | ExamSchedule::try_new(None, None, None, None).unwrap(), |
| 585 | ExamAttemptLimit::try_new(1).unwrap(), | 586 | ExamAttemptLimit::try_new(1).unwrap(), |
| 586 | true, | 587 | true, |
| @@ -606,7 +607,7 @@ pub(crate) mod tests { | |||
| 606 | 1, | 607 | 1, |
| 607 | Mark::try_new(mark).unwrap(), | 608 | Mark::try_new(mark).unwrap(), |
| 608 | &office, | 609 | &office, |
| 609 | - "yazili", | 610 | + kind, |
| 610 | ) | 611 | ) |
| 611 | .await | 612 | .await |
| 612 | .unwrap(); | 613 | .unwrap(); |
src/db/exam_weight.rsadded+239 -0
| @@ -0,0 +1,239 @@ | |||
| 1 | +//! The `offering_exam_weight` / `class_course_exam_weight` tables: per-kind | ||
| 2 | +//! weight overrides under the grade-level template and the class section. | ||
| 3 | +//! | ||
| 4 | +//! Every class-owned write keeps the override flag honest **in the same | ||
| 5 | +//! statement**: a data-modifying CTE flips `class_course.exam_weights_inherited` | ||
| 6 | +//! to `FALSE` while the weight row is written (or dropped), so a crash between | ||
| 7 | +//! "row changed" and "flag changed" is impossible and | ||
| 8 | +//! `class_course`'s own module never enters the picture. The reset deletes the | ||
| 9 | +//! section's rows and restores `TRUE` in one statement too — the shape | ||
| 10 | +//! [`crate::db::class_course::clear_overrides`] uses for the scalar overrides. | ||
| 11 | +//! | ||
| 12 | +//! The chain that *reads* these rows lives in | ||
| 13 | +//! [`crate::service::exam_weight`]; this file is the SQL executor only. | ||
| 14 | + | ||
| 15 | +use crate::database::Database; | ||
| 16 | +use crate::domain::class_course::ClassCourseId; | ||
| 17 | +use crate::domain::course_offering::CourseOfferingId; | ||
| 18 | +use crate::domain::exam_weight::ExamWeight; | ||
| 19 | +use crate::error::AppError; | ||
| 20 | + | ||
| 21 | +/// The offering's own weight rows, by kind — the override set of the | ||
| 22 | +/// grade-level template. | ||
| 23 | +pub async fn list_for_offering( | ||
| 24 | + db: &Database, | ||
| 25 | + offering: &CourseOfferingId, | ||
| 26 | +) -> Result<Vec<ExamWeight>, AppError> { | ||
| 27 | + let rows = sqlx::query!( | ||
| 28 | + r#"SELECT kind, weight::bigint AS "weight!: i64" | ||
| 29 | + FROM offering_exam_weight WHERE offering = $1 | ||
| 30 | + ORDER BY kind"#, | ||
| 31 | + offering.uuid(), | ||
| 32 | + ) | ||
| 33 | + .fetch_all(db) | ||
| 34 | + .await?; | ||
| 35 | + Ok(rows | ||
| 36 | + .into_iter() | ||
| 37 | + .map(|row| ExamWeight { | ||
| 38 | + kind: row.kind, | ||
| 39 | + weight: row.weight, | ||
| 40 | + }) | ||
| 41 | + .collect()) | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// One offering weight row, or `None` when the pair holds none — the second | ||
| 45 | +/// step of [`crate::service::exam_weight::resolve`]. | ||
| 46 | +pub async fn offering_weight( | ||
| 47 | + db: &Database, | ||
| 48 | + offering: &CourseOfferingId, | ||
| 49 | + kind: &str, | ||
| 50 | +) -> Result<Option<ExamWeight>, AppError> { | ||
| 51 | + let row = sqlx::query!( | ||
| 52 | + r#"SELECT kind, weight::bigint AS "weight!: i64" | ||
| 53 | + FROM offering_exam_weight WHERE offering = $1 AND kind = $2"#, | ||
| 54 | + offering.uuid(), | ||
| 55 | + kind, | ||
| 56 | + ) | ||
| 57 | + .fetch_optional(db) | ||
| 58 | + .await?; | ||
| 59 | + Ok(row.map(|row| ExamWeight { | ||
| 60 | + kind: row.kind, | ||
| 61 | + weight: row.weight, | ||
| 62 | + })) | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +/// Upsert one weight on the template. A duplicate (offering, kind) pair | ||
| 66 | +/// *rewrites* the weight — a PATCH of an existing kind is the normal path, not | ||
| 67 | +/// a conflict. | ||
| 68 | +pub async fn upsert_for_offering( | ||
| 69 | + db: &Database, | ||
| 70 | + offering: &CourseOfferingId, | ||
| 71 | + kind: &str, | ||
| 72 | + weight: &ExamWeight, | ||
| 73 | +) -> Result<(), AppError> { | ||
| 74 | + sqlx::query!( | ||
| 75 | + r#"INSERT INTO offering_exam_weight (offering, kind, weight) | ||
| 76 | + VALUES ($1, $2, $3::bigint::smallint) | ||
| 77 | + ON CONFLICT (offering, kind) DO UPDATE SET weight = EXCLUDED.weight"#, | ||
| 78 | + offering.uuid(), | ||
| 79 | + kind, | ||
| 80 | + weight.get_weight(), | ||
| 81 | + ) | ||
| 82 | + .execute(db) | ||
| 83 | + .await?; | ||
| 84 | + Ok(()) | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/// Drop one weight row from the template. `false` when the pair held no row — | ||
| 88 | +/// the caller's 404. | ||
| 89 | +pub async fn delete_from_offering( | ||
| 90 | + db: &Database, | ||
| 91 | + offering: &CourseOfferingId, | ||
| 92 | + kind: &str, | ||
| 93 | +) -> Result<bool, AppError> { | ||
| 94 | + let result = sqlx::query!( | ||
| 95 | + r#"DELETE FROM offering_exam_weight WHERE offering = $1 AND kind = $2"#, | ||
| 96 | + offering.uuid(), | ||
| 97 | + kind, | ||
| 98 | + ) | ||
| 99 | + .execute(db) | ||
| 100 | + .await?; | ||
| 101 | + Ok(result.rows_affected() > 0) | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// The section's own weight rows, by kind — authoritative exactly while | ||
| 105 | +/// `exam_weights_inherited` is `FALSE`, **including when empty**. | ||
| 106 | +pub async fn list_for_class( | ||
| 107 | + db: &Database, | ||
| 108 | + instance: &ClassCourseId, | ||
| 109 | +) -> Result<Vec<ExamWeight>, AppError> { | ||
| 110 | + let rows = sqlx::query!( | ||
| 111 | + r#"SELECT kind, weight::bigint AS "weight!: i64" | ||
| 112 | + FROM class_course_exam_weight WHERE class_course = $1 | ||
| 113 | + ORDER BY kind"#, | ||
| 114 | + instance.uuid(), | ||
| 115 | + ) | ||
| 116 | + .fetch_all(db) | ||
| 117 | + .await?; | ||
| 118 | + Ok(rows | ||
| 119 | + .into_iter() | ||
| 120 | + .map(|row| ExamWeight { | ||
| 121 | + kind: row.kind, | ||
| 122 | + weight: row.weight, | ||
| 123 | + }) | ||
| 124 | + .collect()) | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// One section weight row, or `None` — the first step of | ||
| 128 | +/// [`crate::service::exam_weight::resolve`] while the section's own set is in | ||
| 129 | +/// force. | ||
| 130 | +pub async fn class_weight( | ||
| 131 | + db: &Database, | ||
| 132 | + instance: &ClassCourseId, | ||
| 133 | + kind: &str, | ||
| 134 | +) -> Result<Option<ExamWeight>, AppError> { | ||
| 135 | + let row = sqlx::query!( | ||
| 136 | + r#"SELECT kind, weight::bigint AS "weight!: i64" | ||
| 137 | + FROM class_course_exam_weight WHERE class_course = $1 AND kind = $2"#, | ||
| 138 | + instance.uuid(), | ||
| 139 | + kind, | ||
| 140 | + ) | ||
| 141 | + .fetch_optional(db) | ||
| 142 | + .await?; | ||
| 143 | + Ok(row.map(|row| ExamWeight { | ||
| 144 | + kind: row.kind, | ||
| 145 | + weight: row.weight, | ||
| 146 | + })) | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// Upsert one weight on the section **and** take the set own — both in the | ||
| 150 | +/// statement that writes the row, so `exam_weights_inherited` can never claim | ||
| 151 | +/// "inherit" over a row the section actually carries. `Err(NotFound)` when the | ||
| 152 | +/// instance is gone (the CTE's UPDATE finds no row). | ||
| 153 | +pub async fn upsert_for_class( | ||
| 154 | + db: &Database, | ||
| 155 | + instance: &ClassCourseId, | ||
| 156 | + kind: &str, | ||
| 157 | + weight: &ExamWeight, | ||
| 158 | +) -> Result<(), AppError> { | ||
| 159 | + sqlx::query!( | ||
| 160 | + r#"WITH updated AS ( | ||
| 161 | + UPDATE class_course | ||
| 162 | + SET exam_weights_inherited = FALSE | ||
| 163 | + WHERE id = $1 | ||
| 164 | + RETURNING id | ||
| 165 | + ), written AS ( | ||
| 166 | + INSERT INTO class_course_exam_weight (class_course, kind, weight) | ||
| 167 | + SELECT $1, $2, $3::bigint::smallint | ||
| 168 | + WHERE EXISTS (SELECT 1 FROM updated) | ||
| 169 | + ON CONFLICT (class_course, kind) DO UPDATE SET weight = EXCLUDED.weight | ||
| 170 | + RETURNING class_course | ||
| 171 | + ) | ||
| 172 | + SELECT u.id AS "id: ClassCourseId" FROM updated u"#, | ||
| 173 | + instance.uuid(), | ||
| 174 | + kind, | ||
| 175 | + weight.get_weight(), | ||
| 176 | + ) | ||
| 177 | + .fetch_optional(db) | ||
| 178 | + .await? | ||
| 179 | + .ok_or(AppError::NotFound)?; | ||
| 180 | + Ok(()) | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +/// Drop one weight row from the section, flipping the flag to `FALSE` **only | ||
| 184 | +/// when a row was actually dropped** — a DELETE naming a kind the section | ||
| 185 | +/// carries no row for mutates nothing and answers `false` (the caller's 404), | ||
| 186 | +/// so a refused delete never changes the inheritance state. `Err(NotFound)` | ||
| 187 | +/// when the instance itself is gone. | ||
| 188 | +pub async fn delete_from_class( | ||
| 189 | + db: &Database, | ||
| 190 | + instance: &ClassCourseId, | ||
| 191 | + kind: &str, | ||
| 192 | +) -> Result<bool, AppError> { | ||
| 193 | + let row = sqlx::query!( | ||
| 194 | + r#"WITH kicked AS ( | ||
| 195 | + DELETE FROM class_course_exam_weight | ||
| 196 | + WHERE class_course = $1 AND kind = $2 | ||
| 197 | + RETURNING class_course | ||
| 198 | + ), updated AS ( | ||
| 199 | + UPDATE class_course | ||
| 200 | + SET exam_weights_inherited = | ||
| 201 | + CASE WHEN EXISTS (SELECT 1 FROM kicked) | ||
| 202 | + THEN FALSE ELSE exam_weights_inherited END | ||
| 203 | + WHERE id = $1 | ||
| 204 | + RETURNING exam_weights_inherited | ||
| 205 | + ) | ||
| 206 | + SELECT u.exam_weights_inherited AS "inherited: bool", | ||
| 207 | + (SELECT count(*)::bigint FROM kicked) AS "removed!: i64" | ||
| 208 | + FROM updated u"#, | ||
| 209 | + instance.uuid(), | ||
| 210 | + kind, | ||
| 211 | + ) | ||
| 212 | + .fetch_optional(db) | ||
| 213 | + .await? | ||
| 214 | + .ok_or(AppError::NotFound)?; | ||
| 215 | + Ok(row.removed > 0) | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +/// The reset door: delete every section weight row and restore | ||
| 219 | +/// `exam_weights_inherited = TRUE` in one statement — the offering's set (then | ||
| 220 | +/// the settings, then 1) applies again. `Err(NotFound)` when the instance is | ||
| 221 | +/// gone; otherwise idempotent. | ||
| 222 | +pub async fn reset_class(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> { | ||
| 223 | + sqlx::query!( | ||
| 224 | + r#"WITH kicked AS ( | ||
| 225 | + DELETE FROM class_course_exam_weight WHERE class_course = $1 | ||
| 226 | + ), updated AS ( | ||
| 227 | + UPDATE class_course | ||
| 228 | + SET exam_weights_inherited = TRUE | ||
| 229 | + WHERE id = $1 | ||
| 230 | + RETURNING id | ||
| 231 | + ) | ||
| 232 | + SELECT u.id AS "id: ClassCourseId" FROM updated u"#, | ||
| 233 | + instance.uuid(), | ||
| 234 | + ) | ||
| 235 | + .fetch_optional(db) | ||
| 236 | + .await? | ||
| 237 | + .ok_or(AppError::NotFound)?; | ||
| 238 | + Ok(()) | ||
| 239 | +} | ||
src/db/mod.rsmodified+4 -0
| @@ -23,6 +23,7 @@ pub mod course; | |||
| 23 | pub mod course_membership; | 23 | pub mod course_membership; |
| 24 | pub mod course_note; | 24 | pub mod course_note; |
| 25 | pub mod course_note_file; | 25 | pub mod course_note_file; |
| 26 | +pub mod course_offering; | ||
| 26 | pub mod course_session; | 27 | pub mod course_session; |
| 27 | pub mod dietary_profile; | 28 | pub mod dietary_profile; |
| 28 | pub mod enrollment; | 29 | pub mod enrollment; |
| @@ -33,6 +34,7 @@ pub mod exam_attempt; | |||
| 33 | pub mod exam_audience; | 34 | pub mod exam_audience; |
| 34 | pub mod exam_question; | 35 | pub mod exam_question; |
| 35 | pub mod exam_result; | 36 | pub mod exam_result; |
| 37 | +pub mod exam_weight; | ||
| 36 | pub mod fee_plan; | 38 | pub mod fee_plan; |
| 37 | pub mod fee_plan_assignment; | 39 | pub mod fee_plan_assignment; |
| 38 | pub mod field_update; | 40 | pub mod field_update; |
| @@ -50,6 +52,7 @@ pub mod menu_dish; | |||
| 50 | pub mod message; | 52 | pub mod message; |
| 51 | pub mod note; | 53 | pub mod note; |
| 52 | pub mod note_file; | 54 | pub mod note_file; |
| 55 | +pub mod offering_subject; | ||
| 53 | pub mod page; | 56 | pub mod page; |
| 54 | pub mod parent_link; | 57 | pub mod parent_link; |
| 55 | pub mod payment_ledger; | 58 | pub mod payment_ledger; |
| @@ -72,4 +75,5 @@ pub mod solution_image; | |||
| 72 | pub mod subject; | 75 | pub mod subject; |
| 73 | pub mod term; | 76 | pub mod term; |
| 74 | pub mod user; | 77 | pub mod user; |
| 78 | +pub mod weekly_slot; | ||
| 75 | pub mod work_entry; | 79 | pub mod work_entry; |
src/db/offering_subject.rsadded+244 -0
| @@ -0,0 +1,244 @@ | |||
| 1 | +//! The syllabus selection junctions: `offering_subject` (what the grade-level | ||
| 2 | +//! template teaches) and `class_course_subject` (what one section teaches for | ||
| 3 | +//! itself), over the subject rows of [`crate::db::subject`]. The row types are | ||
| 4 | +//! the subjects themselves — a selection is only membership — so every read | ||
| 5 | +//! here answers `Vec<Subject>` in the resolved listing order: **by subject | ||
| 6 | +//! name, then subject id** (deterministic under any insert order). | ||
| 7 | +//! | ||
| 8 | +//! The class-side writes are the override machinery: each is **one | ||
| 9 | +//! data-modifying-CTE statement** that flips `class_course.subjects_inherited` | ||
| 10 | +//! in the same breath it inserts, deletes or sweeps the section's rows — the | ||
| 11 | +//! flag can never drift from the table it governs, and this module never | ||
| 12 | +//! touches `class_course` outside that flag. The reset is the same shape in | ||
| 13 | +//! reverse: sweep the rows, flip the flag back to TRUE, one statement. | ||
| 14 | + | ||
| 15 | +use crate::database::Database; | ||
| 16 | +use crate::domain::class_course::ClassCourseId; | ||
| 17 | +use crate::domain::course::CourseId; | ||
| 18 | +use crate::domain::course_offering::CourseOfferingId; | ||
| 19 | +use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; | ||
| 20 | +use crate::error::AppError; | ||
| 21 | + | ||
| 22 | +/// Map the junctions' foreign-key refusals to the caller's 404: an offering, | ||
| 23 | +/// a section or a subject deleted between the service's up-front read and | ||
| 24 | +/// this write cannot half-land (the same mapping | ||
| 25 | +/// [`crate::db::subject::create`] uses for its course key). | ||
| 26 | +fn gone(err: sqlx::Error) -> AppError { | ||
| 27 | + if crate::database::foreign_key_violation(&err) { | ||
| 28 | + AppError::NotFound | ||
| 29 | + } else { | ||
| 30 | + err.into() | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +/// The offering's selected topics, name-then-id order. | ||
| 35 | +pub async fn list_for_offering( | ||
| 36 | + db: &Database, | ||
| 37 | + offering: &CourseOfferingId, | ||
| 38 | +) -> Result<Vec<Subject>, AppError> { | ||
| 39 | + let rows = sqlx::query_as!( | ||
| 40 | + Subject, | ||
| 41 | + r#"SELECT s.id AS "id: SubjectId", | ||
| 42 | + s.course AS "course: CourseId", | ||
| 43 | + s.name AS "name: SubjectName", | ||
| 44 | + s.description AS "description: SubjectDescription" | ||
| 45 | + FROM offering_subject os | ||
| 46 | + JOIN subject s ON s.id = os.subject | ||
| 47 | + WHERE os.offering = $1 | ||
| 48 | + ORDER BY s.name ASC, s.id ASC"#, | ||
| 49 | + offering.uuid(), | ||
| 50 | + ) | ||
| 51 | + .fetch_all(db) | ||
| 52 | + .await?; | ||
| 53 | + Ok(rows) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +/// The section's own selected topics — authoritative only while | ||
| 57 | +/// `subjects_inherited` is FALSE, and empty-list-is-a-set then — name-then-id | ||
| 58 | +/// order. | ||
| 59 | +pub async fn list_for_class_course( | ||
| 60 | + db: &Database, | ||
| 61 | + class_course: &ClassCourseId, | ||
| 62 | +) -> Result<Vec<Subject>, AppError> { | ||
| 63 | + let rows = sqlx::query_as!( | ||
| 64 | + Subject, | ||
| 65 | + r#"SELECT s.id AS "id: SubjectId", | ||
| 66 | + s.course AS "course: CourseId", | ||
| 67 | + s.name AS "name: SubjectName", | ||
| 68 | + s.description AS "description: SubjectDescription" | ||
| 69 | + FROM class_course_subject ccs | ||
| 70 | + JOIN subject s ON s.id = ccs.subject | ||
| 71 | + WHERE ccs.class_course = $1 | ||
| 72 | + ORDER BY s.name ASC, s.id ASC"#, | ||
| 73 | + class_course.uuid(), | ||
| 74 | + ) | ||
| 75 | + .fetch_all(db) | ||
| 76 | + .await?; | ||
| 77 | + Ok(rows) | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +/// Add one topic to the offering's selection. Idempotent: re-adding a | ||
| 81 | +/// selection the offering already holds writes nothing and answers `false` | ||
| 82 | +/// (`true` = newly added), matching the junction idiom. | ||
| 83 | +pub async fn add_for_offering( | ||
| 84 | + db: &Database, | ||
| 85 | + offering: &CourseOfferingId, | ||
| 86 | + subject: &SubjectId, | ||
| 87 | +) -> Result<bool, AppError> { | ||
| 88 | + let added = sqlx::query!( | ||
| 89 | + r#"INSERT INTO offering_subject (offering, subject) | ||
| 90 | + VALUES ($1, $2) | ||
| 91 | + ON CONFLICT DO NOTHING"#, | ||
| 92 | + offering.uuid(), | ||
| 93 | + subject.uuid(), | ||
| 94 | + ) | ||
| 95 | + .execute(db) | ||
| 96 | + .await | ||
| 97 | + .map_err(gone)?; | ||
| 98 | + Ok(added.rows_affected() > 0) | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +/// Drop one topic from the offering's selection. `false` when it was not | ||
| 102 | +/// selected — an honest nothing-changed, which the service answers as a 404. | ||
| 103 | +pub async fn remove_for_offering( | ||
| 104 | + db: &Database, | ||
| 105 | + offering: &CourseOfferingId, | ||
| 106 | + subject: &SubjectId, | ||
| 107 | +) -> Result<bool, AppError> { | ||
| 108 | + let dropped = sqlx::query!( | ||
| 109 | + r#"DELETE FROM offering_subject | ||
| 110 | + WHERE offering = $1 AND subject = $2"#, | ||
| 111 | + offering.uuid(), | ||
| 112 | + subject.uuid(), | ||
| 113 | + ) | ||
| 114 | + .execute(db) | ||
| 115 | + .await?; | ||
| 116 | + Ok(dropped.rows_affected() > 0) | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +/// Add one topic to the section's own set, flipping `subjects_inherited` to | ||
| 120 | +/// FALSE **in the same statement** — the insert and the override switch are | ||
| 121 | +/// one data-modifying-CTE unit, so a reader can never see a class-owned row | ||
| 122 | +/// under a still-inheriting flag. Idempotent like the offering side: the | ||
| 123 | +/// second add of one topic writes no row (`added` = false) but the intent — | ||
| 124 | +/// "this section owns its set" — still stands, so the flip is unconditional | ||
| 125 | +/// on a live instance. `live` = false means the instance vanished mid-flight; | ||
| 126 | +/// the service answers that 404. | ||
| 127 | +pub async fn add_for_class_course( | ||
| 128 | + db: &Database, | ||
| 129 | + class_course: &ClassCourseId, | ||
| 130 | + subject: &SubjectId, | ||
| 131 | +) -> Result<(bool, bool), AppError> { | ||
| 132 | + let row = sqlx::query!( | ||
| 133 | + r#"WITH flipped AS ( | ||
| 134 | + UPDATE class_course | ||
| 135 | + SET subjects_inherited = FALSE | ||
| 136 | + WHERE id = $1 | ||
| 137 | + RETURNING id | ||
| 138 | + ), inserted AS ( | ||
| 139 | + INSERT INTO class_course_subject (class_course, subject) | ||
| 140 | + SELECT $1, $2 | ||
| 141 | + WHERE EXISTS (SELECT 1 FROM flipped) | ||
| 142 | + ON CONFLICT DO NOTHING | ||
| 143 | + RETURNING subject | ||
| 144 | + ) | ||
| 145 | + SELECT EXISTS (SELECT 1 FROM flipped) AS "live!", | ||
| 146 | + EXISTS (SELECT 1 FROM inserted) AS "added!""#, | ||
| 147 | + class_course.uuid(), | ||
| 148 | + subject.uuid(), | ||
| 149 | + ) | ||
| 150 | + .fetch_one(db) | ||
| 151 | + .await | ||
| 152 | + .map_err(gone)?; | ||
| 153 | + Ok((row.live, row.added)) | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// Drop one topic from the section's own set, flipping `subjects_inherited` | ||
| 157 | +/// to FALSE in the same statement — but **only when a row actually went**: | ||
| 158 | +/// a delete that finds nothing flips nothing, so the service can answer 404 | ||
| 159 | +/// for a missing selection without a stray side effect on the flag. (`live` | ||
| 160 | +/// = false: the instance is gone mid-flight.) | ||
| 161 | +pub async fn remove_for_class_course( | ||
| 162 | + db: &Database, | ||
| 163 | + class_course: &ClassCourseId, | ||
| 164 | + subject: &SubjectId, | ||
| 165 | +) -> Result<(bool, bool), AppError> { | ||
| 166 | + let row = sqlx::query!( | ||
| 167 | + r#"WITH dropped AS ( | ||
| 168 | + DELETE FROM class_course_subject | ||
| 169 | + WHERE class_course = $1 AND subject = $2 | ||
| 170 | + RETURNING subject | ||
| 171 | + ), flipped AS ( | ||
| 172 | + UPDATE class_course | ||
| 173 | + SET subjects_inherited = FALSE | ||
| 174 | + WHERE id = $1 AND EXISTS (SELECT 1 FROM dropped) | ||
| 175 | + RETURNING id | ||
| 176 | + ) | ||
| 177 | + SELECT EXISTS (SELECT 1 FROM flipped) AS "live!", | ||
| 178 | + EXISTS (SELECT 1 FROM dropped) AS "dropped!""#, | ||
| 179 | + class_course.uuid(), | ||
| 180 | + subject.uuid(), | ||
| 181 | + ) | ||
| 182 | + .fetch_one(db) | ||
| 183 | + .await?; | ||
| 184 | + Ok((row.live, row.dropped)) | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +/// The reset door: sweep every class-owned row and flip | ||
| 188 | +/// `subjects_inherited` back to TRUE — one statement, so the set and its | ||
| 189 | +/// switch agree at every instant. The flip is unconditional on a live | ||
| 190 | +/// instance: clearing an already-empty own set is exactly the request that | ||
| 191 | +/// must restore inheritance. Answers the swept row count; `live` = false | ||
| 192 | +/// means the instance vanished mid-flight. | ||
| 193 | +pub async fn reset_for_class_course( | ||
| 194 | + db: &Database, | ||
| 195 | + class_course: &ClassCourseId, | ||
| 196 | +) -> Result<(i64, bool), AppError> { | ||
| 197 | + let row = sqlx::query!( | ||
| 198 | + r#"WITH swept AS ( | ||
| 199 | + DELETE FROM class_course_subject | ||
| 200 | + WHERE class_course = $1 | ||
| 201 | + RETURNING subject | ||
| 202 | + ), restored AS ( | ||
| 203 | + UPDATE class_course | ||
| 204 | + SET subjects_inherited = TRUE | ||
| 205 | + WHERE id = $1 | ||
| 206 | + RETURNING id | ||
| 207 | + ) | ||
| 208 | + SELECT (SELECT count(*) FROM swept) AS "swept!: i64", | ||
| 209 | + EXISTS (SELECT 1 FROM restored) AS "live!""#, | ||
| 210 | + class_course.uuid(), | ||
| 211 | + ) | ||
| 212 | + .fetch_one(db) | ||
| 213 | + .await?; | ||
| 214 | + Ok((row.swept, row.live)) | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +/// The resolved-membership probe behind the exam-question/homework tag rewire: | ||
| 218 | +/// does `subject` sit in what this section *teaches* — its own rows while | ||
| 219 | +/// `subjects_inherited` is FALSE, else the offering's set? One statement, so | ||
| 220 | +/// the flag and the rows it reads agree as of one snapshot. `None` = the | ||
| 221 | +/// instance is gone. | ||
| 222 | +pub async fn resolves_for_class_course( | ||
| 223 | + db: &Database, | ||
| 224 | + class_course: &ClassCourseId, | ||
| 225 | + subject: &SubjectId, | ||
| 226 | +) -> Result<Option<bool>, AppError> { | ||
| 227 | + let row = sqlx::query!( | ||
| 228 | + r#"SELECT CASE WHEN cc.subjects_inherited | ||
| 229 | + THEN EXISTS (SELECT 1 | ||
| 230 | + FROM offering_subject os | ||
| 231 | + WHERE os.offering = cc.offering AND os.subject = $2) | ||
| 232 | + ELSE EXISTS (SELECT 1 | ||
| 233 | + FROM class_course_subject ccs | ||
| 234 | + WHERE ccs.class_course = cc.id AND ccs.subject = $2) | ||
| 235 | + END AS "member!" | ||
| 236 | + FROM class_course cc | ||
| 237 | + WHERE cc.id = $1"#, | ||
| 238 | + class_course.uuid(), | ||
| 239 | + subject.uuid(), | ||
| 240 | + ) | ||
| 241 | + .fetch_optional(db) | ||
| 242 | + .await?; | ||
| 243 | + Ok(row.map(|row| row.member)) | ||
| 244 | +} | ||
src/db/weekly_slot.rsadded+275 -0
| @@ -0,0 +1,275 @@ | |||
| 1 | +//! The `offering_slot` and `class_course_slot` tables: the reads and writes | ||
| 2 | +//! behind the weekly plan. The row shape lives in | ||
| 3 | +//! [`crate::domain::weekly_slot`]; the workflows (the overlap and cap checks, | ||
| 4 | +//! the offer-side vs class-side doors) in [`crate::service::weekly_slot`]. | ||
| 5 | +//! | ||
| 6 | +//! Reads are plain ordered lists (`weekday`, then `starts_at`). The class-side | ||
| 7 | +//! writes are the override doors: every statement that adds or drops a | ||
| 8 | +//! section's own row also flips `class_course.weekly_plan_inherited` to | ||
| 9 | +//! `FALSE`, and the reset flips it back to `TRUE` while deleting the rows — | ||
| 10 | +//! flag and data in one statement, so the two can never be observed | ||
| 11 | +//! disagreeing. | ||
| 12 | +//! | ||
| 13 | +//! Times cross the statement boundary as minutes past midnight: the | ||
| 14 | +//! `::bigint`-bound minute is multiplied into an `interval` and cast to | ||
| 15 | +//! `TIME` on the way in, and the read casts the stored `TIME` back through | ||
| 16 | +//! `EXTRACT(EPOCH ...)` — the same "the cast is the statement's own" shape | ||
| 17 | +//! every `SMALLINT`↔`i64` column here uses. | ||
| 18 | + | ||
| 19 | +use sqlx::postgres::PgConnection; | ||
| 20 | + | ||
| 21 | +use crate::database::{Database, unique_violation}; | ||
| 22 | +use crate::domain::class_course::ClassCourseId; | ||
| 23 | +use crate::domain::course_offering::CourseOfferingId; | ||
| 24 | +use crate::domain::weekly_slot::{SlotMinute, Weekday, WeeklySlot, WeeklySlotId}; | ||
| 25 | +use crate::error::AppError; | ||
| 26 | + | ||
| 27 | +/// One offering's slots, weekday first then start time. | ||
| 28 | +pub async fn list_for_offering( | ||
| 29 | + db: &Database, | ||
| 30 | + offering: &CourseOfferingId, | ||
| 31 | +) -> Result<Vec<WeeklySlot>, AppError> { | ||
| 32 | + let mut conn = db.acquire().await?; | ||
| 33 | + list_for_offering_on(&mut conn, offering).await | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +/// One section's own slots, weekday first then start time — the offering's | ||
| 37 | +/// rows are *not* consulted; that choice is the resolver's, off the flag. | ||
| 38 | +pub async fn list_for_class( | ||
| 39 | + db: &Database, | ||
| 40 | + instance: &ClassCourseId, | ||
| 41 | +) -> Result<Vec<WeeklySlot>, AppError> { | ||
| 42 | + let mut conn = db.acquire().await?; | ||
| 43 | + list_for_class_on(&mut conn, instance).await | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +pub(crate) async fn list_for_offering_on( | ||
| 47 | + db: &mut PgConnection, | ||
| 48 | + offering: &CourseOfferingId, | ||
| 49 | +) -> Result<Vec<WeeklySlot>, AppError> { | ||
| 50 | + sqlx::query_as!( | ||
| 51 | + WeeklySlot, | ||
| 52 | + r#"SELECT id AS "id: WeeklySlotId", | ||
| 53 | + weekday AS "weekday: Weekday", | ||
| 54 | + (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute", | ||
| 55 | + (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute" | ||
| 56 | + FROM offering_slot | ||
| 57 | + WHERE offering = $1 | ||
| 58 | + ORDER BY weekday, starts_at"#, | ||
| 59 | + offering.uuid(), | ||
| 60 | + ) | ||
| 61 | + .fetch_all(db) | ||
| 62 | + .await | ||
| 63 | + .map_err(Into::into) | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +pub(crate) async fn list_for_class_on( | ||
| 67 | + db: &mut PgConnection, | ||
| 68 | + instance: &ClassCourseId, | ||
| 69 | +) -> Result<Vec<WeeklySlot>, AppError> { | ||
| 70 | + sqlx::query_as!( | ||
| 71 | + WeeklySlot, | ||
| 72 | + r#"SELECT id AS "id: WeeklySlotId", | ||
| 73 | + weekday AS "weekday: Weekday", | ||
| 74 | + (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute", | ||
| 75 | + (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute" | ||
| 76 | + FROM class_course_slot | ||
| 77 | + WHERE class_course = $1 | ||
| 78 | + ORDER BY weekday, starts_at"#, | ||
| 79 | + instance.uuid(), | ||
| 80 | + ) | ||
| 81 | + .fetch_all(db) | ||
| 82 | + .await | ||
| 83 | + .map_err(Into::into) | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/// Take the owner's row lock inside the caller's transaction, so two adds for | ||
| 87 | +/// one owner cannot both clear the overlap/cap pre-check (READ COMMITTED sees | ||
| 88 | +/// the rival's uncommitted insert as absent). `FOR NO KEY UPDATE`: it | ||
| 89 | +/// serializes the slot writers against each other without blocking the | ||
| 90 | +/// attach pump's `FOR KEY SHARE` reads. `Err(NotFound)` when the owner is | ||
| 91 | +/// gone. | ||
| 92 | +pub(crate) async fn lock_offering_tx( | ||
| 93 | + tx: &mut PgConnection, | ||
| 94 | + offering: &CourseOfferingId, | ||
| 95 | +) -> Result<(), AppError> { | ||
| 96 | + sqlx::query!( | ||
| 97 | + r#"SELECT id AS "id: CourseOfferingId" FROM course_offering WHERE id = $1 | ||
| 98 | + FOR NO KEY UPDATE"#, | ||
| 99 | + offering.uuid(), | ||
| 100 | + ) | ||
| 101 | + .fetch_optional(&mut *tx) | ||
| 102 | + .await? | ||
| 103 | + .ok_or(AppError::NotFound) | ||
| 104 | + .map(|_| ()) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// The class-side twin of [`lock_offering_tx`]. | ||
| 108 | +pub(crate) async fn lock_class_tx( | ||
| 109 | + tx: &mut PgConnection, | ||
| 110 | + instance: &ClassCourseId, | ||
| 111 | +) -> Result<(), AppError> { | ||
| 112 | + sqlx::query!( | ||
| 113 | + r#"SELECT id AS "id: ClassCourseId" FROM class_course WHERE id = $1 | ||
| 114 | + FOR NO KEY UPDATE"#, | ||
| 115 | + instance.uuid(), | ||
| 116 | + ) | ||
| 117 | + .fetch_optional(&mut *tx) | ||
| 118 | + .await? | ||
| 119 | + .ok_or(AppError::NotFound) | ||
| 120 | + .map(|_| ()) | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// Insert one slot of the offering's template week, inside the caller's | ||
| 124 | +/// transaction. The `(offering, weekday, starts_at)` `UNIQUE` — reachable | ||
| 125 | +/// only by a duplicate insert that raced the caller's pre-check — answers | ||
| 126 | +/// 409 `slot_overlap`, the same refusal the pre-check gives the settled | ||
| 127 | +/// duplicate. | ||
| 128 | +pub(crate) async fn add_for_offering_tx( | ||
| 129 | + tx: &mut PgConnection, | ||
| 130 | + slot: &WeeklySlot, | ||
| 131 | + offering: &CourseOfferingId, | ||
| 132 | +) -> Result<WeeklySlot, AppError> { | ||
| 133 | + sqlx::query_as!( | ||
| 134 | + WeeklySlot, | ||
| 135 | + r#"INSERT INTO offering_slot (id, offering, weekday, starts_at, ends_at) | ||
| 136 | + VALUES ($1, $2, $3, | ||
| 137 | + ($4::bigint * interval '1 minute')::time, | ||
| 138 | + ($5::bigint * interval '1 minute')::time) | ||
| 139 | + RETURNING id AS "id: WeeklySlotId", | ||
| 140 | + weekday AS "weekday: Weekday", | ||
| 141 | + (EXTRACT(EPOCH FROM starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute", | ||
| 142 | + (EXTRACT(EPOCH FROM ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute""#, | ||
| 143 | + slot.get_id().uuid(), | ||
| 144 | + offering.uuid(), | ||
| 145 | + slot.get_weekday().get(), | ||
| 146 | + slot.get_starts_at().get(), | ||
| 147 | + slot.get_ends_at().get(), | ||
| 148 | + ) | ||
| 149 | + .fetch_one(&mut *tx) | ||
| 150 | + .await | ||
| 151 | + .map_err(|e| { | ||
| 152 | + if unique_violation(&e).is_some() { | ||
| 153 | + AppError::ConflictCoded { | ||
| 154 | + code: "slot_overlap", | ||
| 155 | + message: "a slot already occupies this weekday and start time".into(), | ||
| 156 | + } | ||
| 157 | + } else { | ||
| 158 | + e.into() | ||
| 159 | + } | ||
| 160 | + }) | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +/// Insert one slot of the section's own week **and flip | ||
| 164 | +/// `weekly_plan_inherited = FALSE` in the same statement** — the data-modifying | ||
| 165 | +/// CTE that makes the row and the override one write. A `flip` that matched no | ||
| 166 | +/// row means the instance vanished mid-transaction: `Err(NotFound)` rolls the | ||
| 167 | +/// insert back. | ||
| 168 | +pub(crate) async fn add_for_class_tx( | ||
| 169 | + tx: &mut PgConnection, | ||
| 170 | + slot: &WeeklySlot, | ||
| 171 | + instance: &ClassCourseId, | ||
| 172 | +) -> Result<WeeklySlot, AppError> { | ||
| 173 | + sqlx::query_as!( | ||
| 174 | + WeeklySlot, | ||
| 175 | + r#"WITH ins AS ( | ||
| 176 | + INSERT INTO class_course_slot (id, class_course, weekday, starts_at, ends_at) | ||
| 177 | + VALUES ($1, $2, $3, | ||
| 178 | + ($4::bigint * interval '1 minute')::time, | ||
| 179 | + ($5::bigint * interval '1 minute')::time) | ||
| 180 | + RETURNING id, weekday, starts_at, ends_at | ||
| 181 | + ), flip AS ( | ||
| 182 | + UPDATE class_course SET weekly_plan_inherited = FALSE | ||
| 183 | + WHERE id = $2 AND EXISTS (SELECT 1 FROM ins) | ||
| 184 | + RETURNING id | ||
| 185 | + ) | ||
| 186 | + SELECT ins.id AS "id: WeeklySlotId", | ||
| 187 | + ins.weekday AS "weekday: Weekday", | ||
| 188 | + (EXTRACT(EPOCH FROM ins.starts_at - TIME '00:00:00') / 60)::bigint AS "starts_at!: SlotMinute", | ||
| 189 | + (EXTRACT(EPOCH FROM ins.ends_at - TIME '00:00:00') / 60)::bigint AS "ends_at!: SlotMinute" | ||
| 190 | + FROM ins | ||
| 191 | + WHERE EXISTS (SELECT 1 FROM flip)"#, | ||
| 192 | + slot.get_id().uuid(), | ||
| 193 | + instance.uuid(), | ||
| 194 | + slot.get_weekday().get(), | ||
| 195 | + slot.get_starts_at().get(), | ||
| 196 | + slot.get_ends_at().get(), | ||
| 197 | + ) | ||
| 198 | + .fetch_optional(&mut *tx) | ||
| 199 | + .await? | ||
| 200 | + .ok_or(AppError::NotFound) | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +/// Drop one slot of the offering's template week. A slot of another offering, | ||
| 204 | +/// or one already gone, is `Err(NotFound)` — the id alone never deletes; the | ||
| 205 | +/// owner scoping does. | ||
| 206 | +pub async fn remove_for_offering( | ||
| 207 | + db: &Database, | ||
| 208 | + offering: &CourseOfferingId, | ||
| 209 | + slot: &WeeklySlotId, | ||
| 210 | +) -> Result<(), AppError> { | ||
| 211 | + let result = sqlx::query!( | ||
| 212 | + "DELETE FROM offering_slot WHERE id = $1 AND offering = $2", | ||
| 213 | + slot.uuid(), | ||
| 214 | + offering.uuid(), | ||
| 215 | + ) | ||
| 216 | + .execute(db) | ||
| 217 | + .await?; | ||
| 218 | + if result.rows_affected() == 0 { | ||
| 219 | + return Err(AppError::NotFound); | ||
| 220 | + } | ||
| 221 | + Ok(()) | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// Drop one slot of the section's own week **and flip the flag to `FALSE` in | ||
| 225 | +/// the same statement** — dropping a row is an override decision even when it | ||
| 226 | +/// empties the set (an empty own set is how a section clears its timetable). | ||
| 227 | +/// `Err(NotFound)` when the id names no row of this instance: the flag stays | ||
| 228 | +/// as it was. | ||
| 229 | +pub async fn remove_for_class( | ||
| 230 | + db: &Database, | ||
| 231 | + instance: &ClassCourseId, | ||
| 232 | + slot: &WeeklySlotId, | ||
| 233 | +) -> Result<(), AppError> { | ||
| 234 | + sqlx::query!( | ||
| 235 | + r#"WITH del AS ( | ||
| 236 | + DELETE FROM class_course_slot WHERE id = $1 AND class_course = $2 | ||
| 237 | + RETURNING id | ||
| 238 | + ), flip AS ( | ||
| 239 | + UPDATE class_course SET weekly_plan_inherited = FALSE | ||
| 240 | + WHERE id = $2 AND EXISTS (SELECT 1 FROM del) | ||
| 241 | + RETURNING id | ||
| 242 | + ) | ||
| 243 | + SELECT id AS "id: ClassCourseId" FROM flip"#, | ||
| 244 | + slot.uuid(), | ||
| 245 | + instance.uuid(), | ||
| 246 | + ) | ||
| 247 | + .fetch_optional(db) | ||
| 248 | + .await? | ||
| 249 | + .ok_or(AppError::NotFound) | ||
| 250 | + .map(|_| ()) | ||
| 251 | +} | ||
| 252 | + | ||
| 253 | +/// Reset the section's weekly plan to inherit: delete every one of its own | ||
| 254 | +/// slots and flip `weekly_plan_inherited` back to `TRUE` in the same | ||
| 255 | +/// statement. Idempotent for an already-inherited section (the delete finds | ||
| 256 | +/// nothing, the flip re-asserts `TRUE`); `Err(NotFound)` when the instance | ||
| 257 | +/// itself is gone. | ||
| 258 | +pub async fn reset_for_class(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> { | ||
| 259 | + sqlx::query!( | ||
| 260 | + r#"WITH del AS ( | ||
| 261 | + DELETE FROM class_course_slot WHERE class_course = $1 | ||
| 262 | + RETURNING id | ||
| 263 | + ), flip AS ( | ||
| 264 | + UPDATE class_course SET weekly_plan_inherited = TRUE | ||
| 265 | + WHERE id = $1 | ||
| 266 | + RETURNING id | ||
| 267 | + ) | ||
| 268 | + SELECT id AS "id: ClassCourseId" FROM flip"#, | ||
| 269 | + instance.uuid(), | ||
| 270 | + ) | ||
| 271 | + .fetch_optional(db) | ||
| 272 | + .await? | ||
| 273 | + .ok_or(AppError::NotFound) | ||
| 274 | + .map(|_| ()) | ||
| 275 | +} | ||
src/domain/academic_year.rsmodified+35 -34
| @@ -13,7 +13,8 @@ | |||
| 13 | use serde::{Deserialize, Serialize}; | 13 | use serde::{Deserialize, Serialize}; |
| 14 | use sqlx::types::Json; | 14 | use sqlx::types::Json; |
| 15 | 15 | ||
| 16 | -use crate::constant::{MAX_ACADEMIC_YEAR_NAME_LEN, MAX_CLASS_GRADE_LEN}; | 16 | +use crate::constant::MAX_ACADEMIC_YEAR_NAME_LEN; |
| 17 | +use crate::domain::grade::GradeLevel; | ||
| 17 | use crate::domain::monotonic_id::next_uuid; | 18 | use crate::domain::monotonic_id::next_uuid; |
| 18 | use crate::domain::timestamp::Timestamp; | 19 | use crate::domain::timestamp::Timestamp; |
| 19 | use crate::domain::user::UserId; | 20 | use crate::domain::user::UserId; |
| @@ -81,39 +82,28 @@ impl AcademicYearName { | |||
| 81 | } | 82 | } |
| 82 | 83 | ||
| 83 | /// One grade-promotion mapping: a student who finished `from_grade` moves to | 84 | /// One grade-promotion mapping: a student who finished `from_grade` moves to |
| 84 | -/// `to_grade` at rollover. | 85 | +/// `to_grade` at rollover. Both ends are ladder rungs (`GradeLevel`), stored |
| 86 | +/// as the integers they are — the JSON column serializes them as numbers. | ||
| 85 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | 87 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 86 | pub struct GradePromotion { | 88 | pub struct GradePromotion { |
| 87 | - from_grade: String, | 89 | + from_grade: GradeLevel, |
| 88 | - to_grade: String, | 90 | + to_grade: GradeLevel, |
| 89 | } | 91 | } |
| 90 | 92 | ||
| 91 | impl GradePromotion { | 93 | impl GradePromotion { |
| 92 | - pub fn try_new(from_grade: &str, to_grade: &str) -> Result<Self, ValidationError> { | 94 | + pub fn new(from_grade: GradeLevel, to_grade: GradeLevel) -> Self { |
| 93 | - let bound = |field: &'static str, value: &str| { | 95 | + Self { |
| 94 | - if value.is_empty() || value.chars().count() > MAX_CLASS_GRADE_LEN { | 96 | + from_grade, |
| 95 | - Err(ValidationError::Invalid { | 97 | + to_grade, |
| 96 | - field, | 98 | + } |
| 97 | - reason: "grade labels must be 1 to 20 characters", | ||
| 98 | - }) | ||
| 99 | - } else { | ||
| 100 | - Ok(()) | ||
| 101 | - } | ||
| 102 | - }; | ||
| 103 | - bound("from_grade", from_grade)?; | ||
| 104 | - bound("to_grade", to_grade)?; | ||
| 105 | - Ok(Self { | ||
| 106 | - from_grade: from_grade.to_string(), | ||
| 107 | - to_grade: to_grade.to_string(), | ||
| 108 | - }) | ||
| 109 | } | 99 | } |
| 110 | 100 | ||
| 111 | - pub fn get_from_grade(&self) -> &str { | 101 | + pub fn get_from_grade(&self) -> GradeLevel { |
| 112 | - &self.from_grade | 102 | + self.from_grade |
| 113 | } | 103 | } |
| 114 | 104 | ||
| 115 | - pub fn get_to_grade(&self) -> &str { | 105 | + pub fn get_to_grade(&self) -> GradeLevel { |
| 116 | - &self.to_grade | 106 | + self.to_grade |
| 117 | } | 107 | } |
| 118 | } | 108 | } |
| 119 | 109 | ||
| @@ -188,12 +178,12 @@ impl AcademicYear { | |||
| 188 | 178 | ||
| 189 | /// The grade a section at `grade` rolls into, or `None` when the grade has no | 179 | /// The grade a section at `grade` rolls into, or `None` when the grade has no |
| 190 | /// promotion entry (graduation). | 180 | /// promotion entry (graduation). |
| 191 | - pub fn promotion_for(&self, grade: &str) -> Option<&str> { | 181 | + pub fn promotion_for(&self, grade: GradeLevel) -> Option<GradeLevel> { |
| 192 | self.grade_promotions | 182 | self.grade_promotions |
| 193 | .0 | 183 | .0 |
| 194 | .iter() | 184 | .iter() |
| 195 | .find(|promo| promo.from_grade == grade) | 185 | .find(|promo| promo.from_grade == grade) |
| 196 | - .map(|promo| promo.to_grade.as_str()) | 186 | + .map(|promo| promo.to_grade) |
| 197 | } | 187 | } |
| 198 | 188 | ||
| 199 | pub fn get_class_count(&self) -> i64 { | 189 | pub fn get_class_count(&self) -> i64 { |
| @@ -226,10 +216,14 @@ mod tests { | |||
| 226 | } | 216 | } |
| 227 | 217 | ||
| 228 | #[tokio::test] | 218 | #[tokio::test] |
| 229 | - async fn promotions_validate_both_labels() { | 219 | + async fn promotions_carry_ladder_rungs() { |
| 230 | - assert!(GradePromotion::try_new("5", "6").is_ok()); | 220 | + let (five, six) = ( |
| 231 | - assert!(GradePromotion::try_new("", "6").is_err()); | 221 | + GradeLevel::new(5).unwrap(), |
| 232 | - assert!(GradePromotion::try_new("5", &"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err()); | 222 | + GradeLevel::new(6).unwrap(), |
| 223 | + ); | ||
| 224 | + let promo = GradePromotion::new(five, six); | ||
| 225 | + assert_eq!(promo.get_from_grade(), five); | ||
| 226 | + assert_eq!(promo.get_to_grade(), six); | ||
| 233 | } | 227 | } |
| 234 | 228 | ||
| 235 | #[tokio::test] | 229 | #[tokio::test] |
| @@ -247,10 +241,17 @@ mod tests { | |||
| 247 | ts(0), | 241 | ts(0), |
| 248 | ts(1000), | 242 | ts(1000), |
| 249 | creator, | 243 | creator, |
| 250 | - vec![GradePromotion::try_new("5", "6").unwrap()], | 244 | + vec![GradePromotion::new( |
| 245 | + GradeLevel::new(5).unwrap(), | ||
| 246 | + GradeLevel::new(6).unwrap(), | ||
| 247 | + )], | ||
| 251 | ) | 248 | ) |
| 252 | .unwrap(); | 249 | .unwrap(); |
| 253 | - assert_eq!(year.promotion_for("5"), Some("6")); | 250 | + assert_eq!( |
| 254 | - assert_eq!(year.promotion_for("12"), None); | 251 | + year.promotion_for(GradeLevel::new(5).unwrap()), |
| 252 | + Some(GradeLevel::new(6).unwrap()) | ||
| 253 | + ); | ||
| 254 | + // The ladder's top rung graduates unless the school names a promotion. | ||
| 255 | + assert_eq!(year.promotion_for(GradeLevel::new(12).unwrap()), None); | ||
| 255 | } | 256 | } |
| 256 | } | 257 | } |
src/domain/class_blueprint.rsmodified+51 -61
| @@ -9,7 +9,7 @@ | |||
| 9 | //! `enrollment` rows, and an elective placed by hand next to them is still an | 9 | //! `enrollment` rows, and an elective placed by hand next to them is still an |
| 10 | //! individual enrollment nothing here can see. | 10 | //! individual enrollment nothing here can see. |
| 11 | //! | 11 | //! |
| 12 | -//! This module is the pure shape: the id (the grade label *is* the primary | 12 | +//! This module is the pure shape: the id (the ladder rung *is* the unique |
| 13 | //! key, so "one blueprint per grade" holds by construction), the row, the | 13 | //! key, so "one blueprint per grade" holds by construction), the row, the |
| 14 | //! pump's report types ([`Pumped`], [`Skip`], [`SectionStatus`]) and the | 14 | //! pump's report types ([`Pumped`], [`Skip`], [`SectionStatus`]) and the |
| 15 | //! shared skip vocabulary ([`skip_reason`]). | 15 | //! shared skip vocabulary ([`skip_reason`]). |
| @@ -21,43 +21,55 @@ | |||
| 21 | use crate::constant::MAX_CLASS_COURSES; | 21 | use crate::constant::MAX_CLASS_COURSES; |
| 22 | use crate::db::class_pump::{Attached, Axis}; | 22 | use crate::db::class_pump::{Attached, Axis}; |
| 23 | use crate::domain::class_course::ClassCourse; | 23 | use crate::domain::class_course::ClassCourse; |
| 24 | -use crate::domain::class_group::{ClassGrade, ClassGroupId}; | 24 | +use crate::domain::class_group::ClassGroupId; |
| 25 | use crate::domain::course::CourseId; | 25 | use crate::domain::course::CourseId; |
| 26 | +use crate::domain::grade::GradeLevel; | ||
| 26 | use crate::domain::user::UserId; | 27 | use crate::domain::user::UserId; |
| 27 | use crate::error::{AppError, ValidationError}; | 28 | use crate::error::{AppError, ValidationError}; |
| 28 | 29 | ||
| 29 | -/// A grade label as the table's `TEXT` primary key — one blueprint per grade | 30 | +/// A ladder rung as the table's unique key — one blueprint per grade by |
| 30 | -/// by construction, like the settings singleton's `'school'` row: the key is | 31 | +/// construction, like the settings singleton's `'school'` row: the key is a |
| 31 | -/// a name, not a minted entity id. | 32 | +/// position, not a minted entity id. The stored row keeps its surrogate uuid |
| 32 | -#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] | 33 | +/// primary key (what `class_course.source` references); this id is the |
| 34 | +/// identity the API speaks, and a key that parses to no rung (`from_key`'s | ||
| 35 | +/// `-1` fallback) matches no row. | ||
| 36 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 33 | #[sqlx(transparent)] | 37 | #[sqlx(transparent)] |
| 34 | -pub struct ClassBlueprintId(String); | 38 | +pub struct ClassBlueprintId(i16); |
| 35 | 39 | ||
| 36 | impl ClassBlueprintId { | 40 | impl ClassBlueprintId { |
| 37 | - /// The key one grade label always maps to. | 41 | + /// The key one ladder rung always maps to. |
| 38 | - pub fn for_grade(grade: &ClassGrade) -> Self { | 42 | + pub fn for_grade(grade: &GradeLevel) -> Self { |
| 39 | - Self(grade.as_str().to_string()) | 43 | + Self(grade.get()) |
| 40 | } | 44 | } |
| 41 | 45 | ||
| 46 | + /// Parses a wire path key. A key that is not a ladder number parses to | ||
| 47 | + /// `-1`, which matches no row — the nil-uuid shape [`ClassGroupId`] | ||
| 48 | + /// uses, so an unaddressable grade answers a `404`, never a decode panic. | ||
| 42 | pub fn from_key(key: &str) -> Self { | 49 | pub fn from_key(key: &str) -> Self { |
| 43 | - Self(key.to_string()) | 50 | + Self(key.trim().parse::<i16>().unwrap_or(-1)) |
| 44 | } | 51 | } |
| 45 | 52 | ||
| 46 | - pub fn key(&self) -> &str { | 53 | + /// The inner rung, for the queries that cannot take the newtype. |
| 47 | - &self.0 | 54 | + pub fn get(self) -> i16 { |
| 55 | + self.0 | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + pub fn key(&self) -> String { | ||
| 59 | + self.0.to_string() | ||
| 48 | } | 60 | } |
| 49 | } | 61 | } |
| 50 | 62 | ||
| 51 | -/// One grade's template. The id is the grade label itself — the key one | 63 | +/// One grade's template. The id is the ladder rung itself — the key one |
| 52 | -/// grade always maps to — stored here beside the `grade` field so a read | 64 | +/// grade always maps to — stored here beside the `grade_level` field so a |
| 53 | -/// never has to parse a record id back into a domain value. `courses` is | 65 | +/// read never has to parse a record id back into a domain value. `courses` |
| 54 | -/// not a column of the row: it is the `blueprint_course` junction, joined | 66 | +/// is not a column of the row: it is the `blueprint_course` junction, joined |
| 55 | /// on by the db layer (sorted by course, which is the order every CAS | 67 | /// on by the db layer (sorted by course, which is the order every CAS |
| 56 | /// comparison relies on). | 68 | /// comparison relies on). |
| 57 | #[derive(Debug, Clone)] | 69 | #[derive(Debug, Clone)] |
| 58 | pub struct ClassBlueprint { | 70 | pub struct ClassBlueprint { |
| 59 | pub(crate) id: ClassBlueprintId, | 71 | pub(crate) id: ClassBlueprintId, |
| 60 | - pub(crate) grade: ClassGrade, | 72 | + pub(crate) grade_level: GradeLevel, |
| 61 | pub(crate) courses: Vec<CourseId>, | 73 | pub(crate) courses: Vec<CourseId>, |
| 62 | pub(crate) creator: UserId, | 74 | pub(crate) creator: UserId, |
| 63 | } | 75 | } |
| @@ -75,13 +87,12 @@ pub struct Skip { | |||
| 75 | 87 | ||
| 76 | /// What a pump did: how many sections it reached, and the pairs it refused. | 88 | /// What a pump did: how many sections it reached, and the pairs it refused. |
| 77 | /// | 89 | /// |
| 78 | -/// `matched` exists because an empty `skipped` is not success on its own. A | 90 | +/// `matched` exists because an empty `skipped` is not success on its own. The |
| 79 | -/// grade label is free text ([`ClassGrade`]) and | 91 | +/// sections are matched by their ladder rung |
| 80 | -/// [`crate::db::class_group::list_for_grade`] | 92 | +/// ([`crate::db::class_group::list_for_grade`]), so a blueprint keyed `9` |
| 81 | -/// matches it exactly, so a blueprint keyed `"9 "` reaches none of the sections | 93 | +/// reaches none of the sections keyed `10` — and with nothing to skip it |
| 82 | -/// keyed `"9"` — and with nothing to skip it answers exactly like a pump that | 94 | +/// answers exactly like a pump that stocked every one of them. The count is |
| 83 | -/// stocked every one of them. The count is the only thing that tells those | 95 | +/// the only thing that tells those apart. |
| 84 | -/// apart. | ||
| 85 | /// | 96 | /// |
| 86 | /// A struct rather than a pair with | 97 | /// A struct rather than a pair with |
| 87 | /// [`crate::service::class_blueprint::set_courses`]'s: three | 98 | /// [`crate::service::class_blueprint::set_courses`]'s: three |
| @@ -129,8 +140,8 @@ impl ClassBlueprint { | |||
| 129 | &self.id | 140 | &self.id |
| 130 | } | 141 | } |
| 131 | 142 | ||
| 132 | - pub fn get_grade(&self) -> &ClassGrade { | 143 | + pub fn get_grade_level(&self) -> GradeLevel { |
| 133 | - &self.grade | 144 | + self.grade_level |
| 134 | } | 145 | } |
| 135 | 146 | ||
| 136 | pub fn get_courses(&self) -> &[CourseId] { | 147 | pub fn get_courses(&self) -> &[CourseId] { |
| @@ -141,30 +152,6 @@ impl ClassBlueprint { | |||
| 141 | &self.creator | 152 | &self.creator |
| 142 | } | 153 | } |
| 143 | 154 | ||
| 144 | - /// The grade a blueprint may be keyed on. Non-empty, because the label is | ||
| 145 | - /// the primary key and there is no blueprint for "no grade"; and free of | ||
| 146 | - /// the characters that would make that key unaddressable as a URL path | ||
| 147 | - /// segment, the second gate [`crate::domain::menu::MenuSlot`] carries for | ||
| 148 | - /// the same reason. Grades were never validated for this, so a *class* may | ||
| 149 | - /// already carry a label refused here — it simply cannot have a blueprint | ||
| 150 | - /// until it is renamed, which is a 400 the caller can read rather than a | ||
| 151 | - /// route nobody can reach. | ||
| 152 | - pub fn grade_key(value: &str) -> Result<ClassGrade, AppError> { | ||
| 153 | - if value.is_empty() { | ||
| 154 | - return Err(AppError::Validation(ValidationError::Empty("grade"))); | ||
| 155 | - } | ||
| 156 | - if value | ||
| 157 | - .chars() | ||
| 158 | - .any(|c| matches!(c, '/' | '\\' | '?' | '#' | '%')) | ||
| 159 | - { | ||
| 160 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 161 | - field: "grade", | ||
| 162 | - reason: "must not contain / \\ ? # or %", | ||
| 163 | - })); | ||
| 164 | - } | ||
| 165 | - Ok(ClassGrade::try_new(value)?) | ||
| 166 | - } | ||
| 167 | - | ||
| 168 | /// The course list a blueprint may hold: deduplicated, and no longer than | 155 | /// The course list a blueprint may hold: deduplicated, and no longer than |
| 169 | /// one class may carry — a blueprint above that ceiling would guarantee a | 156 | /// one class may carry — a blueprint above that ceiling would guarantee a |
| 170 | /// skip on every class it ever reached. | 157 | /// skip on every class it ever reached. |
| @@ -190,19 +177,22 @@ impl ClassBlueprint { | |||
| 190 | mod tests { | 177 | mod tests { |
| 191 | use super::*; | 178 | use super::*; |
| 192 | 179 | ||
| 180 | + /// A blueprint's key is a ladder rung: a key that names no rung (`from_key` | ||
| 181 | + /// falls back to `-1`) matches no row, so an unaddressable grade is a | ||
| 182 | + /// `404` at the route rather than a decode panic — and `for_grade` is the | ||
| 183 | + /// rung the class carries, byte for byte. | ||
| 193 | #[test] | 184 | #[test] |
| 194 | - fn a_grade_key_must_be_addressable() { | 185 | + fn a_blueprint_key_is_a_ladder_rung() { |
| 195 | - assert!(ClassBlueprint::grade_key("").is_err()); | 186 | + assert_eq!(ClassBlueprintId::from_key("9"), ClassBlueprintId(9)); |
| 196 | - assert!(ClassBlueprint::grade_key("9/A").is_err()); | 187 | + assert_eq!(ClassBlueprintId::from_key(" 9 "), ClassBlueprintId(9)); |
| 197 | - assert!(ClassBlueprint::grade_key("9%A").is_err()); | 188 | + assert_eq!(ClassBlueprintId::from_key("anaokulu"), ClassBlueprintId(-1)); |
| 189 | + assert_eq!(ClassBlueprintId::from_key(""), ClassBlueprintId(-1)); | ||
| 190 | + assert_eq!(ClassBlueprintId::from_key("9/A"), ClassBlueprintId(-1)); | ||
| 198 | assert_eq!( | 191 | assert_eq!( |
| 199 | - ClassBlueprint::grade_key("9-A") | 192 | + ClassBlueprintId::for_grade(&GradeLevel::new(9).unwrap()), |
| 200 | - .unwrap() | 193 | + ClassBlueprintId::from_key("9") |
| 201 | - .as_str() | ||
| 202 | - .to_string(), | ||
| 203 | - "9-A" | ||
| 204 | ); | 194 | ); |
| 205 | - assert!(ClassBlueprint::grade_key(&"x".repeat(1000)).is_err()); | 195 | + assert_eq!(ClassBlueprintId::from_key("9").key(), "9"); |
| 206 | } | 196 | } |
| 207 | 197 | ||
| 208 | /// The list is a *set*: a caller sending the same course twice must not | 198 | /// The list is a *set*: a caller sending the same course twice must not |
src/domain/class_course.rsmodified+108 -14
| @@ -4,17 +4,31 @@ | |||
| 4 | //! attaching it to a class section mints one of these rows, and exams, sessions, | 4 | //! attaching it to a class section mints one of these rows, and exams, sessions, |
| 5 | //! roll-call, homework and enrollments all key on the instance — so two | 5 | //! roll-call, homework and enrollments all key on the instance — so two |
| 6 | //! sections teaching the same course have separate rosters, exams, timetables | 6 | //! sections teaching the same course have separate rosters, exams, timetables |
| 7 | -//! and teachers. The row carries the weekly hours (`ders_saati`, the report-card | 7 | +//! and teachers. |
| 8 | -//! weight) and whether it counts toward the report card. | ||
| 9 | //! | 8 | //! |
| 10 | -//! The attach/detach workflows live in [`crate::service::class_course`]; the | 9 | +//! The row teaches **from its offering** — the |
| 11 | -//! row's reads in [`crate::db::class_course`] — this file is the row shape and | 10 | +//! [`crate::domain::course_offering::CourseOffering`] template for the |
| 12 | -//! its id. | 11 | +//! course × the class's grade level, resolved (and auto-created empty) by the |
| 12 | +//! attach pump. Every content field on the instance is an *override*: `title`, | ||
| 13 | +//! `description`, `ders_saati` and `counts_toward_karne` are nullable, and a | ||
| 14 | +//! `NULL` means inherit — from the offering, and through it from the catalog | ||
| 15 | +//! row / the constants (1 weekly hour, counted toward the karne). The three | ||
| 16 | +//! `*_inherited` flags carry the same rule for the set-valued policies | ||
| 17 | +//! (subjects, exam weights, weekly plan), which cannot be `NULL`: `TRUE` = | ||
| 18 | +//! follow the offering's set, `FALSE` = this section's own table is | ||
| 19 | +//! authoritative, including when it is empty. Override-or-inherit, never | ||
| 20 | +//! merge. | ||
| 21 | +//! | ||
| 22 | +//! The attach/detach workflows live in [`crate::service::class_course`] (which | ||
| 23 | +//! also owns [`crate::service::class_course::resolve_policy`], the effective | ||
| 24 | +//! `ders_saati`/`counts_toward_karne` a read should use); the row's reads in | ||
| 25 | +//! [`crate::db::class_course`] — this file is the row shape and its id. | ||
| 13 | 26 | ||
| 14 | use crate::constant::{MAX_DERS_SAATI, MIN_DERS_SAATI}; | 27 | use crate::constant::{MAX_DERS_SAATI, MIN_DERS_SAATI}; |
| 15 | use crate::domain::class_blueprint::ClassBlueprintId; | 28 | use crate::domain::class_blueprint::ClassBlueprintId; |
| 16 | use crate::domain::class_group::ClassGroupId; | 29 | use crate::domain::class_group::ClassGroupId; |
| 17 | -use crate::domain::course::CourseId; | 30 | +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; |
| 31 | +use crate::domain::course_offering::CourseOfferingId; | ||
| 18 | use crate::domain::monotonic_id::next_uuid; | 32 | use crate::domain::monotonic_id::next_uuid; |
| 19 | use crate::domain::timestamp::Timestamp; | 33 | use crate::domain::timestamp::Timestamp; |
| 20 | use crate::domain::user::UserId; | 34 | use crate::domain::user::UserId; |
| @@ -52,6 +66,9 @@ impl ClassCourseId { | |||
| 52 | 66 | ||
| 53 | /// Weekly lesson hours of an instance: the weight the instance carries in the | 67 | /// Weekly lesson hours of an instance: the weight the instance carries in the |
| 54 | /// year's report-card average, and the count a timetable grid would lay out. | 68 | /// year's report-card average, and the count a timetable grid would lay out. |
| 69 | +/// As a *column* it is the instance's own override — `NULL` inherits from the | ||
| 70 | +/// offering's `default_ders_saati`, and the offering's `NULL` means the | ||
| 71 | +/// constant floor ([`crate::constant::MIN_DERS_SAATI`]). | ||
| 55 | #[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | 72 | #[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 56 | #[sqlx(transparent)] | 73 | #[sqlx(transparent)] |
| 57 | pub struct DersSaati(i64); | 74 | pub struct DersSaati(i64); |
| @@ -67,20 +84,51 @@ impl DersSaati { | |||
| 67 | Ok(Self(value)) | 84 | Ok(Self(value)) |
| 68 | } | 85 | } |
| 69 | 86 | ||
| 70 | - pub fn as_i64(&self) -> i64 { | 87 | + pub fn as_i64(self) -> i64 { |
| 71 | self.0 | 88 | self.0 |
| 72 | } | 89 | } |
| 73 | } | 90 | } |
| 74 | 91 | ||
| 92 | +/// A named instance override the reset door can clear back to inherit. The | ||
| 93 | +/// scalars go `NULL` (the offering's default — then the catalog row or the | ||
| 94 | +/// constant — applies again); the three set flags flip back to `TRUE` (the | ||
| 95 | +/// offering's set is authoritative again). The wire spellings live with the | ||
| 96 | +/// reset route's parser in [`crate::service::class_course`]; this enum is the | ||
| 97 | +/// closed set both sides answer to. | ||
| 98 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 99 | +pub enum OverrideField { | ||
| 100 | + /// The section's own title. | ||
| 101 | + Title, | ||
| 102 | + /// The section's own description. | ||
| 103 | + Description, | ||
| 104 | + /// The section's own weekly hours. | ||
| 105 | + DersSaati, | ||
| 106 | + /// The section's own report-card policy. | ||
| 107 | + CountsTowardKarne, | ||
| 108 | + /// The section's own subject set (the flag; set-row deletion rides the | ||
| 109 | + /// subject lane's reset). | ||
| 110 | + Subjects, | ||
| 111 | + /// The section's own exam-kind weights (the flag). | ||
| 112 | + ExamWeights, | ||
| 113 | + /// The section's own weekly plan (the flag). | ||
| 114 | + WeeklyPlan, | ||
| 115 | +} | ||
| 116 | + | ||
| 75 | /// One course taught in one class. `attached_by` is who attached it, `source` | 117 | /// One course taught in one class. `attached_by` is who attached it, `source` |
| 76 | -/// the blueprint that placed it (absent for a hand attach). `ders_saati` and | 118 | +/// the blueprint that placed it (absent for a hand attach). The content |
| 77 | -/// `counts_toward_karne` are the instance's own policy — what two sections | 119 | +/// fields are the instance's own *overrides* — `None` inherits from the |
| 78 | -/// teaching the same catalog course may legitimately differ on. | 120 | +/// offering ([`Self::get_offering`]), which is what two sections teaching the |
| 121 | +/// same catalog course at the same grade usually want to differ from only | ||
| 122 | +/// deliberately. | ||
| 79 | #[derive(Debug, Clone, sqlx::FromRow)] | 123 | #[derive(Debug, Clone, sqlx::FromRow)] |
| 80 | pub struct ClassCourse { | 124 | pub struct ClassCourse { |
| 81 | pub(crate) id: ClassCourseId, | 125 | pub(crate) id: ClassCourseId, |
| 82 | pub(crate) class: ClassGroupId, | 126 | pub(crate) class: ClassGroupId, |
| 83 | pub(crate) course: CourseId, | 127 | pub(crate) course: CourseId, |
| 128 | + /// The grade-level template this instance teaches from — always set: the | ||
| 129 | + /// attach pump resolves it (auto-creating the empty template when the | ||
| 130 | + /// grade is untouched) in the same transaction as the insert. | ||
| 131 | + pub(crate) offering: CourseOfferingId, | ||
| 84 | pub(crate) attached_by: UserId, | 132 | pub(crate) attached_by: UserId, |
| 85 | /// The grade blueprint that placed this attachment, absent when a human | 133 | /// The grade blueprint that placed this attachment, absent when a human |
| 86 | /// attached the course to this class directly — read the same way as | 134 | /// attached the course to this class directly — read the same way as |
| @@ -88,8 +136,13 @@ pub struct ClassCourse { | |||
| 88 | /// is a blueprint's to take back, so a hand-attached course survives every | 136 | /// is a blueprint's to take back, so a hand-attached course survives every |
| 89 | /// blueprint sweep. | 137 | /// blueprint sweep. |
| 90 | pub(crate) source: Option<ClassBlueprintId>, | 138 | pub(crate) source: Option<ClassBlueprintId>, |
| 91 | - pub(crate) ders_saati: DersSaati, | 139 | + pub(crate) title: Option<CourseTitle>, |
| 92 | - pub(crate) counts_toward_karne: bool, | 140 | + pub(crate) description: Option<CourseDescription>, |
| 141 | + pub(crate) ders_saati: Option<DersSaati>, | ||
| 142 | + pub(crate) counts_toward_karne: Option<bool>, | ||
| 143 | + pub(crate) subjects_inherited: bool, | ||
| 144 | + pub(crate) exam_weights_inherited: bool, | ||
| 145 | + pub(crate) weekly_plan_inherited: bool, | ||
| 93 | pub(crate) enrollment_count: i64, | 146 | pub(crate) enrollment_count: i64, |
| 94 | pub(crate) attached_at: Timestamp, | 147 | pub(crate) attached_at: Timestamp, |
| 95 | } | 148 | } |
| @@ -107,6 +160,13 @@ impl ClassCourse { | |||
| 107 | &self.course | 160 | &self.course |
| 108 | } | 161 | } |
| 109 | 162 | ||
| 163 | + /// The grade-level template this instance teaches from. The effective | ||
| 164 | + /// values the instance inherits ride | ||
| 165 | + /// [`crate::service::class_course::resolve_policy`]. | ||
| 166 | + pub fn get_offering(&self) -> &CourseOfferingId { | ||
| 167 | + &self.offering | ||
| 168 | + } | ||
| 169 | + | ||
| 110 | pub fn get_attached_by(&self) -> &UserId { | 170 | pub fn get_attached_by(&self) -> &UserId { |
| 111 | &self.attached_by | 171 | &self.attached_by |
| 112 | } | 172 | } |
| @@ -116,14 +176,48 @@ impl ClassCourse { | |||
| 116 | self.source.as_ref() | 176 | self.source.as_ref() |
| 117 | } | 177 | } |
| 118 | 178 | ||
| 119 | - pub fn get_ders_saati(&self) -> DersSaati { | 179 | + /// The instance's own title override, `None` = inherit. |
| 180 | + pub fn get_title(&self) -> Option<&CourseTitle> { | ||
| 181 | + self.title.as_ref() | ||
| 182 | + } | ||
| 183 | + | ||
| 184 | + /// The instance's own description override, `None` = inherit. | ||
| 185 | + pub fn get_description(&self) -> Option<&CourseDescription> { | ||
| 186 | + self.description.as_ref() | ||
| 187 | + } | ||
| 188 | + | ||
| 189 | + /// The instance's own weekly-hours override, `None` = inherit (the | ||
| 190 | + /// offering's default, else 1). The *effective* value — what a read | ||
| 191 | + /// should present — is [`crate::service::class_course::resolve_policy`]'s | ||
| 192 | + /// answer, not this one. | ||
| 193 | + pub fn get_ders_saati(&self) -> Option<DersSaati> { | ||
| 120 | self.ders_saati | 194 | self.ders_saati |
| 121 | } | 195 | } |
| 122 | 196 | ||
| 123 | - pub fn counts_toward_karne(&self) -> bool { | 197 | + /// The instance's own report-card policy override, `None` = inherit (the |
| 198 | + /// offering's default, else counted). | ||
| 199 | + pub fn counts_toward_karne(&self) -> Option<bool> { | ||
| 124 | self.counts_toward_karne | 200 | self.counts_toward_karne |
| 125 | } | 201 | } |
| 126 | 202 | ||
| 203 | + /// Whether this section follows the offering's subject set (`TRUE`) or | ||
| 204 | + /// keeps its own `class_course_subject` table authoritative (`FALSE`, | ||
| 205 | + /// including when that table is empty — that is how a section clears its | ||
| 206 | + /// syllabus). | ||
| 207 | + pub fn subjects_inherited(&self) -> bool { | ||
| 208 | + self.subjects_inherited | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + /// The same override switch for the section's exam-kind weights. | ||
| 212 | + pub fn exam_weights_inherited(&self) -> bool { | ||
| 213 | + self.exam_weights_inherited | ||
| 214 | + } | ||
| 215 | + | ||
| 216 | + /// The same override switch for the section's weekly plan. | ||
| 217 | + pub fn weekly_plan_inherited(&self) -> bool { | ||
| 218 | + self.weekly_plan_inherited | ||
| 219 | + } | ||
| 220 | + | ||
| 127 | pub fn get_enrollment_count(&self) -> i64 { | 221 | pub fn get_enrollment_count(&self) -> i64 { |
| 128 | self.enrollment_count | 222 | self.enrollment_count |
| 129 | } | 223 | } |
src/domain/class_group.rsmodified+16 -27
| @@ -16,12 +16,13 @@ | |||
| 16 | //! the route-facing wrappers in [`crate::service::class_group`] — this file is | 16 | //! the route-facing wrappers in [`crate::service::class_group`] — this file is |
| 17 | //! the row shape, its newtypes and getters. | 17 | //! the row shape, its newtypes and getters. |
| 18 | 18 | ||
| 19 | -use crate::constant::{MAX_CLASS_GRADE_LEN, MAX_CLASS_NAME_LEN}; | 19 | +use crate::constant::MAX_CLASS_NAME_LEN; |
| 20 | use crate::domain::academic_year::AcademicYearId; | 20 | use crate::domain::academic_year::AcademicYearId; |
| 21 | +use crate::domain::grade::GradeLevel; | ||
| 21 | use crate::domain::monotonic_id::next_uuid; | 22 | use crate::domain::monotonic_id::next_uuid; |
| 22 | use crate::domain::user::UserId; | 23 | use crate::domain::user::UserId; |
| 23 | use crate::error::ValidationError; | 24 | use crate::error::ValidationError; |
| 24 | -use crate::validate::{validate_optional, validate_required}; | 25 | +use crate::validate::validate_required; |
| 25 | 26 | ||
| 26 | #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] | 27 | #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 27 | #[sqlx(transparent)] | 28 | #[sqlx(transparent)] |
| @@ -64,24 +65,6 @@ impl ClassName { | |||
| 64 | } | 65 | } |
| 65 | } | 66 | } |
| 66 | 67 | ||
| 67 | -/// The school's own label for the year a class sits in ("9", "10-A", | ||
| 68 | -/// "kindergarten"). Free text on purpose — no school's grade ladder is the next | ||
| 69 | -/// one's — and optional: a club-shaped class has no grade at all. | ||
| 70 | -#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] | ||
| 71 | -#[sqlx(transparent)] | ||
| 72 | -pub struct ClassGrade(String); | ||
| 73 | - | ||
| 74 | -impl ClassGrade { | ||
| 75 | - pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 76 | - validate_optional("grade", value, MAX_CLASS_GRADE_LEN)?; | ||
| 77 | - Ok(Self(value.to_string())) | ||
| 78 | - } | ||
| 79 | - | ||
| 80 | - pub fn as_str(&self) -> &str { | ||
| 81 | - &self.0 | ||
| 82 | - } | ||
| 83 | -} | ||
| 84 | - | ||
| 85 | /// One class. `creator` is who made it; the two refcounts behind the delete | 68 | /// One class. `creator` is who made it; the two refcounts behind the delete |
| 86 | /// guard are database-side columns only, so no whole-row save can clobber one | 69 | /// guard are database-side columns only, so no whole-row save can clobber one |
| 87 | /// (see [`crate::db::cap`]). | 70 | /// (see [`crate::db::cap`]). |
| @@ -90,12 +73,17 @@ impl ClassGrade { | |||
| 90 | /// refcounted, and merely a label pointing at a teacher-or-higher account — the | 73 | /// refcounted, and merely a label pointing at a teacher-or-higher account — the |
| 91 | /// web layer holds that bar, and a demotion sweeps the column | 74 | /// web layer holds that bar, and a demotion sweeps the column |
| 92 | /// ([`crate::db::class_group::unassign_everywhere`]). | 75 | /// ([`crate::db::class_group::unassign_everywhere`]). |
| 76 | +/// | ||
| 77 | +/// `grade_level` is the section's rung on the shared grade ladder | ||
| 78 | +/// ([`GradeLevel`]) — required, not a label the school makes up: a club-shaped | ||
| 79 | +/// *class* still sits at a grade, and it is the school-wide club/study | ||
| 80 | +/// *courses* that belong to no section at all. | ||
| 93 | #[derive(Debug, Clone, sqlx::FromRow)] | 81 | #[derive(Debug, Clone, sqlx::FromRow)] |
| 94 | pub struct ClassGroup { | 82 | pub struct ClassGroup { |
| 95 | pub(crate) id: ClassGroupId, | 83 | pub(crate) id: ClassGroupId, |
| 96 | pub(crate) creator: UserId, | 84 | pub(crate) creator: UserId, |
| 97 | pub(crate) name: ClassName, | 85 | pub(crate) name: ClassName, |
| 98 | - pub(crate) grade: Option<ClassGrade>, | 86 | + pub(crate) grade_level: GradeLevel, |
| 99 | pub(crate) year: Option<AcademicYearId>, | 87 | pub(crate) year: Option<AcademicYearId>, |
| 100 | pub(crate) teacher: Option<UserId>, | 88 | pub(crate) teacher: Option<UserId>, |
| 101 | } | 89 | } |
| @@ -113,8 +101,8 @@ impl ClassGroup { | |||
| 113 | &self.name | 101 | &self.name |
| 114 | } | 102 | } |
| 115 | 103 | ||
| 116 | - pub fn get_grade(&self) -> Option<&ClassGrade> { | 104 | + pub fn get_grade_level(&self) -> GradeLevel { |
| 117 | - self.grade.as_ref() | 105 | + self.grade_level |
| 118 | } | 106 | } |
| 119 | 107 | ||
| 120 | pub fn get_year(&self) -> Option<&AcademicYearId> { | 108 | pub fn get_year(&self) -> Option<&AcademicYearId> { |
| @@ -136,13 +124,14 @@ mod tests { | |||
| 136 | use super::*; | 124 | use super::*; |
| 137 | 125 | ||
| 138 | #[test] | 126 | #[test] |
| 139 | - fn name_is_required_and_grade_is_optional() { | 127 | + fn name_is_required_and_the_grade_is_a_ladder_rung() { |
| 140 | assert!(ClassName::try_new("9-A").is_ok()); | 128 | assert!(ClassName::try_new("9-A").is_ok()); |
| 141 | assert!(ClassName::try_new("").is_err()); | 129 | assert!(ClassName::try_new("").is_err()); |
| 142 | assert!(ClassName::try_new(" ").is_err()); | 130 | assert!(ClassName::try_new(" ").is_err()); |
| 143 | assert!(ClassName::try_new(&"x".repeat(MAX_CLASS_NAME_LEN + 1)).is_err()); | 131 | assert!(ClassName::try_new(&"x".repeat(MAX_CLASS_NAME_LEN + 1)).is_err()); |
| 144 | - assert!(ClassGrade::try_new("").is_ok()); | 132 | + assert!(GradeLevel::new(0).is_ok()); |
| 145 | - assert!(ClassGrade::try_new("anaokulu").is_ok()); | 133 | + assert!(GradeLevel::new(12).is_ok()); |
| 146 | - assert!(ClassGrade::try_new(&"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err()); | 134 | + assert!(GradeLevel::new(13).is_err()); |
| 135 | + assert!(GradeLevel::new(-1).is_err()); | ||
| 147 | } | 136 | } |
| 148 | } | 137 | } |
src/domain/course_offering.rsadded+120 -0
| @@ -0,0 +1,120 @@ | |||
| 1 | +//! The grade-level course **template**: one `course_offering` row per | ||
| 2 | +//! (course × grade_level), the content every section at that grade teaches | ||
| 3 | +//! from — title, description, the weekly-hours and report-card defaults. | ||
| 4 | +//! | ||
| 5 | +//! A course stays the school-wide catalog row and the identity of the ders; | ||
| 6 | +//! the offering is the grade axis' slice of it. Every | ||
| 7 | +//! [`crate::domain::class_course::ClassCourse`] instance points at exactly one | ||
| 8 | +//! offering (its `offering` link) and may override any content field on the | ||
| 9 | +//! instance row; **unset = inherit** from the offering, and the offering's | ||
| 10 | +//! unset = fall back to the catalog row / the constants (1 weekly hour, | ||
| 11 | +//! counted toward the karne). Override-or-inherit, never merge. | ||
| 12 | +//! | ||
| 13 | +//! The CRUD workflows live in [`crate::service::course_offering`], the SQL in | ||
| 14 | +//! [`crate::db::course_offering`]; this file is the row shape and its id. | ||
| 15 | + | ||
| 16 | +use crate::domain::class_course::DersSaati; | ||
| 17 | +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; | ||
| 18 | +use crate::domain::grade::GradeLevel; | ||
| 19 | +use crate::domain::monotonic_id::next_uuid; | ||
| 20 | +use crate::domain::timestamp::Timestamp; | ||
| 21 | +use crate::domain::user::UserId; | ||
| 22 | + | ||
| 23 | +/// The identity of one course×grade offering. A UUIDv7 minted by the | ||
| 24 | +/// process-wide monotonic generator, like every other row id in the repo. | ||
| 25 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] | ||
| 26 | +#[sqlx(transparent)] | ||
| 27 | +pub struct CourseOfferingId(uuid::Uuid); | ||
| 28 | + | ||
| 29 | +impl CourseOfferingId { | ||
| 30 | + pub fn generate() -> Self { | ||
| 31 | + Self(next_uuid()) | ||
| 32 | + } | ||
| 33 | + | ||
| 34 | + /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that | ||
| 35 | + /// cannot take the newtype. Static `query!` binds take `self` directly. | ||
| 36 | + pub fn uuid(&self) -> uuid::Uuid { | ||
| 37 | + self.0 | ||
| 38 | + } | ||
| 39 | + | ||
| 40 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 41 | + /// which matches no row. | ||
| 42 | + pub fn from_key(key: &str) -> Self { | ||
| 43 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + /// The bare uuid wire form. | ||
| 47 | + pub fn key(&self) -> String { | ||
| 48 | + self.0.to_string() | ||
| 49 | + } | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// One course as one grade teaches it — the template a class section's | ||
| 53 | +/// instance inherits from. Every content field is nullable: a `NULL` is not | ||
| 54 | +/// "no value" but "inherit from the catalog course" (`title`, `description`) | ||
| 55 | +/// or "use the constant" (`default_ders_saati` → 1, | ||
| 56 | +/// `default_counts_toward_karne` → `TRUE`). An offering minted by the attach | ||
| 57 | +/// pump starts with all of them unset, so an untouched grade teaches exactly | ||
| 58 | +/// what the catalog row says. | ||
| 59 | +/// | ||
| 60 | +/// `created_by` is who minted the row — the manager that created it on | ||
| 61 | +/// purpose, or the actor whose attach auto-created it. | ||
| 62 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 63 | +pub struct CourseOffering { | ||
| 64 | + pub(crate) id: CourseOfferingId, | ||
| 65 | + pub(crate) course: CourseId, | ||
| 66 | + pub(crate) grade_level: GradeLevel, | ||
| 67 | + pub(crate) title: Option<CourseTitle>, | ||
| 68 | + pub(crate) description: Option<CourseDescription>, | ||
| 69 | + pub(crate) default_ders_saati: Option<DersSaati>, | ||
| 70 | + pub(crate) default_counts_toward_karne: Option<bool>, | ||
| 71 | + pub(crate) created_by: UserId, | ||
| 72 | + pub(crate) created_at: Timestamp, | ||
| 73 | + pub(crate) updated_at: Timestamp, | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +impl CourseOffering { | ||
| 77 | + pub fn get_id(&self) -> &CourseOfferingId { | ||
| 78 | + &self.id | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + pub fn get_course(&self) -> &CourseId { | ||
| 82 | + &self.course | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + pub fn get_grade_level(&self) -> GradeLevel { | ||
| 86 | + self.grade_level | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + /// The offering's own title override, `None` = the catalog course's title. | ||
| 90 | + pub fn get_title(&self) -> Option<&CourseTitle> { | ||
| 91 | + self.title.as_ref() | ||
| 92 | + } | ||
| 93 | + | ||
| 94 | + /// The offering's own description override, `None` = the catalog's. | ||
| 95 | + pub fn get_description(&self) -> Option<&CourseDescription> { | ||
| 96 | + self.description.as_ref() | ||
| 97 | + } | ||
| 98 | + | ||
| 99 | + /// The grade's default weekly hours, `None` = the constant floor (1). | ||
| 100 | + pub fn get_default_ders_saati(&self) -> Option<DersSaati> { | ||
| 101 | + self.default_ders_saati | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + /// The grade's default report-card policy, `None` = counted (`TRUE`). | ||
| 105 | + pub fn get_default_counts_toward_karne(&self) -> Option<bool> { | ||
| 106 | + self.default_counts_toward_karne | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + pub fn get_created_by(&self) -> &UserId { | ||
| 110 | + &self.created_by | ||
| 111 | + } | ||
| 112 | + | ||
| 113 | + pub fn get_created_at(&self) -> Timestamp { | ||
| 114 | + self.created_at | ||
| 115 | + } | ||
| 116 | + | ||
| 117 | + pub fn get_updated_at(&self) -> Timestamp { | ||
| 118 | + self.updated_at | ||
| 119 | + } | ||
| 120 | +} | ||
src/domain/exam_question.rsmodified+4 -2
| @@ -291,8 +291,10 @@ impl QuestionSpec { | |||
| 291 | /// One question of an exam. Order within the exam is the id's creation order; | 291 | /// One question of an exam. Order within the exam is the id's creation order; |
| 292 | /// the kind-dependent columns always satisfy the | 292 | /// the kind-dependent columns always satisfy the |
| 293 | /// [`QuestionSpec`] invariants because every write goes through one. Every | 293 | /// [`QuestionSpec`] invariants because every write goes through one. Every |
| 294 | -/// question links to a subject of the exam's course — the handlers verify the | 294 | +/// question links to a subject of the exam's course, and — since the |
| 295 | -/// subject's course matches before any write. | 295 | +/// course-template system — to one the exam's *instance* actually teaches: |
| 296 | +/// the service validates both halves of that rule | ||
| 297 | +/// ([`crate::service::subject::in_instance`]) before any write. | ||
| 296 | #[derive(Debug, Clone, sqlx::FromRow)] | 298 | #[derive(Debug, Clone, sqlx::FromRow)] |
| 297 | pub struct ExamQuestion { | 299 | pub struct ExamQuestion { |
| 298 | pub(crate) id: ExamQuestionId, | 300 | pub(crate) id: ExamQuestionId, |
src/domain/exam_weight.rsadded+81 -0
| @@ -0,0 +1,81 @@ | |||
| 1 | +//! Exam-kind weights an offering or a class section overrides: one row per | ||
| 2 | +//! (owner, kind) naming a kind that exists in `settings.exam_kinds` and the | ||
| 3 | +//! weight it carries *there*. | ||
| 4 | +//! | ||
| 5 | +//! The rows are the override levels of the resolution chain | ||
| 6 | +//! ([`crate::service::exam_weight::resolve`]); this file is the row shape, its | ||
| 7 | +//! bounds and the constant floor. The school's settings keep the *default* | ||
| 8 | +//! weight of every kind — an override reweights one grade or one section, and | ||
| 9 | +//! the settings vocabulary is exactly what the rows may name. | ||
| 10 | + | ||
| 11 | +use crate::constant::{MAX_EXAM_KIND_WEIGHT, MIN_EXAM_KIND_WEIGHT}; | ||
| 12 | +use crate::error::ValidationError; | ||
| 13 | + | ||
| 14 | +/// The weight a kind resolves to when nothing in the chain names it: a retired | ||
| 15 | +/// kind (settings edits never rewrite history) and an own-set-in-force section | ||
| 16 | +/// with no row for the kind both count an exam of it once. | ||
| 17 | +pub const FALLBACK_WEIGHT: i64 = 1; | ||
| 18 | + | ||
| 19 | +/// One weight override: `kind` is the settings kind exactly as spelled there | ||
| 20 | +/// (the service layer refuses anything else before a row is written), `weight` | ||
| 21 | +/// the weight it takes in averages computed under the owning level. | ||
| 22 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::FromRow)] | ||
| 23 | +pub struct ExamWeight { | ||
| 24 | + pub(crate) kind: String, | ||
| 25 | + pub(crate) weight: i64, | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +impl ExamWeight { | ||
| 29 | + /// Bounds check only — `weight` must sit inside the same 1..=100 window | ||
| 30 | + /// the settings themselves enforce | ||
| 31 | + /// ([`crate::constant::MIN_EXAM_KIND_WEIGHT`]/[`MAX_EXAM_KIND_WEIGHT`]). | ||
| 32 | + /// Whether `kind` names a kind the school runs is the service layer's | ||
| 33 | + /// settings lookup; this constructor cannot see a store. | ||
| 34 | + pub fn try_new(kind: impl Into<String>, weight: i64) -> Result<Self, ValidationError> { | ||
| 35 | + if !(MIN_EXAM_KIND_WEIGHT..=MAX_EXAM_KIND_WEIGHT).contains(&weight) { | ||
| 36 | + return Err(ValidationError::Invalid { | ||
| 37 | + field: "weight", | ||
| 38 | + reason: "must be between 1 and 100", | ||
| 39 | + }); | ||
| 40 | + } | ||
| 41 | + Ok(Self { | ||
| 42 | + kind: kind.into(), | ||
| 43 | + weight, | ||
| 44 | + }) | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + pub fn get_kind(&self) -> &str { | ||
| 48 | + &self.kind | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + pub fn get_weight(&self) -> i64 { | ||
| 52 | + self.weight | ||
| 53 | + } | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +#[cfg(test)] | ||
| 57 | +mod tests { | ||
| 58 | + use super::*; | ||
| 59 | + | ||
| 60 | + #[test] | ||
| 61 | + fn bounds_reuse_the_settings_window() { | ||
| 62 | + assert!(ExamWeight::try_new("final", MIN_EXAM_KIND_WEIGHT).is_ok()); | ||
| 63 | + assert!(ExamWeight::try_new("final", MAX_EXAM_KIND_WEIGHT).is_ok()); | ||
| 64 | + let zero = ExamWeight::try_new("final", MIN_EXAM_KIND_WEIGHT - 1).unwrap_err(); | ||
| 65 | + let over = ExamWeight::try_new("final", MAX_EXAM_KIND_WEIGHT + 1).unwrap_err(); | ||
| 66 | + for err in [zero, over] { | ||
| 67 | + assert!( | ||
| 68 | + matches!(&err, ValidationError::Invalid { field: "weight", .. }), | ||
| 69 | + "a weight outside 1..=100 is a `weight` validation error: {err:?}" | ||
| 70 | + ); | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + #[test] | ||
| 75 | + fn the_floor_is_one_and_the_kind_rides_verbatim() { | ||
| 76 | + assert_eq!(FALLBACK_WEIGHT, 1); | ||
| 77 | + let row = ExamWeight::try_new("Final", 2).unwrap(); | ||
| 78 | + assert_eq!(row.get_kind(), "Final", "kind case is the caller's to match"); | ||
| 79 | + assert_eq!(row.get_weight(), 2); | ||
| 80 | + } | ||
| 81 | +} | ||
src/domain/grade.rsadded+89 -0
| @@ -0,0 +1,89 @@ | |||
| 1 | +//! The grade ladder: the validated position a class section — and, one layer | ||
| 2 | +//! up, its course blueprint — occupies on the school's single axis of years. | ||
| 3 | +//! | ||
| 4 | +//! It replaces the old free-text `ClassGrade`: "9", "10-A" and "anaokulu" were | ||
| 5 | +//! three spellings no query could order, group or blueprint against without a | ||
| 6 | +//! school-wide convention nobody enforced. The ladder is an integer | ||
| 7 | +//! `0..=12` — `0` is anaokulu, `1..=12` the school years — so "every section | ||
| 8 | +//! at one grade" is one equality and the blueprint is keyed by the same value | ||
| 9 | +//! the class carries. | ||
| 10 | +//! | ||
| 11 | +//! The wire format is the **integer** itself: every DTO carries | ||
| 12 | +//! `grade_level: 0..=12`, and the only strings are [`GradeLevel::label`]'s | ||
| 13 | +//! display/AI-scope labels (`"Anaokulu"`, `"1"`..`"12"`), which are rendered, | ||
| 14 | +//! never parsed back. | ||
| 15 | +//! | ||
| 16 | +//! The bounds live in [`crate::constant`] beside every other published limit | ||
| 17 | +//! (`GET /limits` serves them); this module owns the type. | ||
| 18 | + | ||
| 19 | +use crate::constant::{MAX_GRADE_LEVEL, MIN_GRADE_LEVEL}; | ||
| 20 | +use crate::error::ValidationError; | ||
| 21 | + | ||
| 22 | +/// One rung of the grade ladder: `0` = anaokulu, `1..=12` = school years. | ||
| 23 | +/// | ||
| 24 | +/// `sqlx(transparent)` over the `i16` is what makes the column a plain | ||
| 25 | +/// `SMALLINT` — the driver checks the type, the `CHECK | ||
| 26 | +/// (grade_level BETWEEN 0 AND 12)` in the DDL is the stored mirror of | ||
| 27 | +/// [`GradeLevel::new`], and nothing out of range can be constructed in Rust. | ||
| 28 | +#[derive( | ||
| 29 | + Debug, Clone, Copy, PartialEq, Eq, sqlx::Type, serde::Serialize, serde::Deserialize, | ||
| 30 | +)] | ||
| 31 | +#[sqlx(transparent)] | ||
| 32 | +#[serde(transparent)] | ||
| 33 | +pub struct GradeLevel(i16); | ||
| 34 | + | ||
| 35 | +impl GradeLevel { | ||
| 36 | + /// The rung `raw` names, or a validation error when it is off the ladder — | ||
| 37 | + /// the `400` both the class and the blueprint write paths answer with. | ||
| 38 | + pub fn new(raw: i16) -> Result<Self, ValidationError> { | ||
| 39 | + if !(MIN_GRADE_LEVEL..=MAX_GRADE_LEVEL).contains(&raw) { | ||
| 40 | + return Err(ValidationError::Invalid { | ||
| 41 | + field: "grade_level", | ||
| 42 | + reason: "must be 0 (anaokulu) through 12", | ||
| 43 | + }); | ||
| 44 | + } | ||
| 45 | + Ok(Self(raw)) | ||
| 46 | + } | ||
| 47 | + | ||
| 48 | + /// Kindergarten, the ladder's floor. | ||
| 49 | + pub fn anaokulu() -> Self { | ||
| 50 | + Self(MIN_GRADE_LEVEL) | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + /// The integer the wire and the `grade_level` column carry. | ||
| 54 | + pub fn get(self) -> i16 { | ||
| 55 | + self.0 | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + /// The display label: `"Anaokulu"` at the floor, the year number | ||
| 59 | + /// everywhere else. The one spelling the AI scope (`sinif`) and every | ||
| 60 | + /// human-facing surface see — an index is safe because the tuple field is | ||
| 61 | + /// private and only [`GradeLevel::new`]/[`GradeLevel::anaokulu`] construct. | ||
| 62 | + pub fn label(self) -> &'static str { | ||
| 63 | + const LABELS: [&str; 13] = [ | ||
| 64 | + "Anaokulu", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", | ||
| 65 | + ]; | ||
| 66 | + LABELS[self.0 as usize] | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +#[cfg(test)] | ||
| 71 | +mod tests { | ||
| 72 | + use super::*; | ||
| 73 | + | ||
| 74 | + #[test] | ||
| 75 | + fn the_ladder_is_bounded() { | ||
| 76 | + assert!(GradeLevel::new(MIN_GRADE_LEVEL).is_ok()); | ||
| 77 | + assert!(GradeLevel::new(MAX_GRADE_LEVEL).is_ok()); | ||
| 78 | + assert!(GradeLevel::new(-1).is_err()); | ||
| 79 | + assert!(GradeLevel::new(MAX_GRADE_LEVEL + 1).is_err()); | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + #[test] | ||
| 83 | + fn anaokulu_is_the_floor_and_labels_are_stable() { | ||
| 84 | + assert_eq!(GradeLevel::anaokulu().get(), 0); | ||
| 85 | + assert_eq!(GradeLevel::anaokulu().label(), "Anaokulu"); | ||
| 86 | + assert_eq!(GradeLevel::new(1).unwrap().label(), "1"); | ||
| 87 | + assert_eq!(GradeLevel::new(12).unwrap().label(), "12"); | ||
| 88 | + } | ||
| 89 | +} | ||
src/domain/homework.rsmodified+8 -0
| @@ -87,6 +87,14 @@ impl HomeworkDescription { | |||
| 87 | /// homework carries no roster, a student who enrolls later is covered | 87 | /// homework carries no roster, a student who enrolls later is covered |
| 88 | /// automatically; a subset is a fixed snapshot of the students named at | 88 | /// automatically; a subset is a fixed snapshot of the students named at |
| 89 | /// assign (or last PATCH) time. | 89 | /// assign (or last PATCH) time. |
| 90 | +/// | ||
| 91 | +/// The `subject` tag names a topic of the homework's course — and, since the | ||
| 92 | +/// course-template system, one the instance actually *teaches*: its resolved | ||
| 93 | +/// subject set (override-or-inherit), validated service-side | ||
| 94 | +/// ([`crate::service::subject::in_instance`] at tag time, | ||
| 95 | +/// [`crate::service::offering_subject::ensure_resolved_member`] on create), | ||
| 96 | +/// because the check needs the instance's override state and so cannot live | ||
| 97 | +/// as a pure rule on this row. | ||
| 90 | #[derive(Debug, Clone, sqlx::FromRow)] | 98 | #[derive(Debug, Clone, sqlx::FromRow)] |
| 91 | pub struct Homework { | 99 | pub struct Homework { |
| 92 | pub(crate) id: HomeworkId, | 100 | pub(crate) id: HomeworkId, |
src/domain/mod.rsmodified+5 -0
| @@ -25,6 +25,7 @@ pub mod course; | |||
| 25 | pub mod course_membership; | 25 | pub mod course_membership; |
| 26 | pub mod course_note; | 26 | pub mod course_note; |
| 27 | pub mod course_note_file; | 27 | pub mod course_note_file; |
| 28 | +pub mod course_offering; | ||
| 28 | pub mod course_session; | 29 | pub mod course_session; |
| 29 | pub mod dietary_profile; | 30 | pub mod dietary_profile; |
| 30 | pub mod enrollment; | 31 | pub mod enrollment; |
| @@ -34,8 +35,10 @@ pub mod exam_answer; | |||
| 34 | pub mod exam_attempt; | 35 | pub mod exam_attempt; |
| 35 | pub mod exam_question; | 36 | pub mod exam_question; |
| 36 | pub mod exam_result; | 37 | pub mod exam_result; |
| 38 | +pub mod exam_weight; | ||
| 37 | pub mod fee_plan; | 39 | pub mod fee_plan; |
| 38 | pub mod fee_plan_assignment; | 40 | pub mod fee_plan_assignment; |
| 41 | +pub mod grade; | ||
| 39 | pub mod homework; | 42 | pub mod homework; |
| 40 | pub mod homework_file; | 43 | pub mod homework_file; |
| 41 | pub mod homework_result; | 44 | pub mod homework_result; |
| @@ -50,6 +53,7 @@ pub mod message; | |||
| 50 | pub mod monotonic_id; | 53 | pub mod monotonic_id; |
| 51 | pub mod note; | 54 | pub mod note; |
| 52 | pub mod note_file; | 55 | pub mod note_file; |
| 56 | +pub mod offering_subject; | ||
| 53 | pub mod parent_link; | 57 | pub mod parent_link; |
| 54 | pub mod payment_ledger; | 58 | pub mod payment_ledger; |
| 55 | pub mod person; | 59 | pub mod person; |
| @@ -75,6 +79,7 @@ pub mod term; | |||
| 75 | pub mod text_fold; | 79 | pub mod text_fold; |
| 76 | pub mod timestamp; | 80 | pub mod timestamp; |
| 77 | pub mod user; | 81 | pub mod user; |
| 82 | +pub mod weekly_slot; | ||
| 78 | pub mod work_entry; | 83 | pub mod work_entry; |
| 79 | 84 | ||
| 80 | /// Fallback for lowercase-string enums whose `#[sqlx(type_name = "TEXT", | 85 | /// Fallback for lowercase-string enums whose `#[sqlx(type_name = "TEXT", |
src/domain/offering_subject.rsadded+82 -0
| @@ -0,0 +1,82 @@ | |||
| 1 | +//! The syllabus topic sets: which of a catalog course's subjects an offering | ||
| 2 | +//! ([`crate::domain::course_offering::CourseOffering`]) selects for its grade, | ||
| 3 | +//! and which one a class section ([`crate::domain::class_course::ClassCourse`]) | ||
| 4 | +//! selects for itself. Both are pure membership junctions over `subject` — | ||
| 5 | +//! there is no row type of their own, so this file carries the model's one | ||
| 6 | +//! pure rule and the docs. | ||
| 7 | +//! | ||
| 8 | +//! The rule: a subject may be selected only for an offering of the course the | ||
| 9 | +//! subject belongs to. "Lifted" from the course to the instance level, the | ||
| 10 | +//! same gate guards the class-side selections, because an instance's course | ||
| 11 | +//! is fixed at attach. | ||
| 12 | +//! | ||
| 13 | +//! Resolution is override-or-inherit, never merge, and is **flag-driven**: | ||
| 14 | +//! [`ClassCourse::subjects_inherited`](crate::domain::class_course::ClassCourse::subjects_inherited) | ||
| 15 | +//! `TRUE` = the offering's set applies, `FALSE` = the section's own | ||
| 16 | +//! `class_course_subject` rows are authoritative **including when there are | ||
| 17 | +//! none** (that is how a section clears its syllabus). The flag flips in the | ||
| 18 | +//! same statement that writes or deletes a class-side row | ||
| 19 | +//! ([`crate::db::offering_subject`]); the effective set is | ||
| 20 | +//! [`crate::service::offering_subject::resolved_for_instance`]. | ||
| 21 | + | ||
| 22 | +use crate::domain::course::CourseId; | ||
| 23 | +use crate::domain::subject::Subject; | ||
| 24 | +use crate::error::ValidationError; | ||
| 25 | + | ||
| 26 | +/// The membership precondition: `subject` may be selected for a set whose | ||
| 27 | +/// course is `offering_course` only when it belongs to that course. The same | ||
| 28 | +/// 400 the bare-course tag check (`service::subject::in_course`) has always | ||
| 29 | +/// answered — one condition, one error shape, now enforced at selection time | ||
| 30 | +/// as well as tag time. | ||
| 31 | +pub fn ensure_course_member( | ||
| 32 | + subject: &Subject, | ||
| 33 | + offering_course: &CourseId, | ||
| 34 | +) -> Result<(), ValidationError> { | ||
| 35 | + if subject.get_course() != offering_course { | ||
| 36 | + return Err(ValidationError::Invalid { | ||
| 37 | + field: "subject_id", | ||
| 38 | + reason: "subject belongs to a different course", | ||
| 39 | + }); | ||
| 40 | + } | ||
| 41 | + Ok(()) | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +#[cfg(test)] | ||
| 45 | +mod tests { | ||
| 46 | + use super::*; | ||
| 47 | + use crate::domain::subject::{SubjectDescription, SubjectId, SubjectName}; | ||
| 48 | + | ||
| 49 | + fn a_subject(course: CourseId) -> Subject { | ||
| 50 | + Subject { | ||
| 51 | + id: SubjectId::generate(), | ||
| 52 | + course, | ||
| 53 | + name: SubjectName::try_new("Limits").unwrap(), | ||
| 54 | + description: SubjectDescription::try_new("").unwrap(), | ||
| 55 | + } | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + /// The precondition refuses a subject of another course, naming the field | ||
| 59 | + /// with the exact reason the tag-time check uses — drops the guard and | ||
| 60 | + /// this fails on the `Ok`. | ||
| 61 | + #[test] | ||
| 62 | + fn a_foreign_course_subject_is_refused() { | ||
| 63 | + let subject = a_subject(CourseId::from_key( | ||
| 64 | + "019732e3-7b00-7000-8000-00000000dead", | ||
| 65 | + )); | ||
| 66 | + let offering_course = CourseId::from_key("019732e3-7b00-7000-8000-00000000beef"); | ||
| 67 | + let refused = ensure_course_member(&subject, &offering_course).unwrap_err(); | ||
| 68 | + assert_eq!( | ||
| 69 | + refused.to_string(), | ||
| 70 | + "subject_id: subject belongs to a different course" | ||
| 71 | + ); | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + /// A subject of the offering's own course passes — negates the guard's | ||
| 75 | + /// "always refuse" mutation. | ||
| 76 | + #[test] | ||
| 77 | + fn an_own_course_subject_passes() { | ||
| 78 | + let course = CourseId::from_key("019732e3-7b00-7000-8000-00000000dead"); | ||
| 79 | + let subject = a_subject(course.clone()); | ||
| 80 | + ensure_course_member(&subject, &course).unwrap(); | ||
| 81 | + } | ||
| 82 | +} | ||
src/domain/weekly_slot.rsadded+297 -0
| @@ -0,0 +1,297 @@ | |||
| 1 | +//! The weekly plan slot: one line of a course's timetable template — a | ||
| 2 | +//! weekday and the time-of-day window one lesson hour lands in. | ||
| 3 | +//! | ||
| 4 | +//! Slots live on one of two owners: the grade-level offering | ||
| 5 | +//! (`offering_slot`, the template) or the class×course instance | ||
| 6 | +//! (`class_course_slot`, the per-class override). Which set a reader sees is | ||
| 7 | +//! `class_course.weekly_plan_inherited`'s decision, applied by | ||
| 8 | +//! [`crate::service::weekly_slot::resolved_for_instance`]: `TRUE` follows the | ||
| 9 | +//! offering's rows, `FALSE` makes the section's own rows authoritative | ||
| 10 | +//! *including when they are empty* — that is how a section clears its | ||
| 11 | +//! timetable. Override-or-inherit, never merge. | ||
| 12 | +//! | ||
| 13 | +//! Two of one owner's slots may touch (one may start the minute another | ||
| 14 | +//! ends) but never overlap on the same weekday; the exact duplicate is the | ||
| 15 | +//! store's `UNIQUE (owner, weekday, starts_at)` key. The ordering a resolved | ||
| 16 | +//! list comes back in is `weekday` first, then `starts_at` — Monday through | ||
| 17 | +//! Sunday, each day dawn to dusk. | ||
| 18 | +//! | ||
| 19 | +//! **No scheduler.** Nothing generates dated `course_session` rows from a | ||
| 20 | +//! weekly plan — `course_session` stays the per-lesson occurrence, written by | ||
| 21 | +//! its own routes. This module is template + override + resolution only. | ||
| 22 | +//! | ||
| 23 | +//! The slot bounds live in [`crate::constant`] beside every other published | ||
| 24 | +//! bound, so `GET /limits` and the completeness guard see them. | ||
| 25 | + | ||
| 26 | +use crate::constant::{MAX_SLOT_MINUTE, MAX_WEEKLY_SLOTS, MIN_SLOT_MINUTE}; | ||
| 27 | +use crate::domain::monotonic_id::next_uuid; | ||
| 28 | +use crate::error::ValidationError; | ||
| 29 | + | ||
| 30 | +/// The identity of one slot row. A UUIDv7 minted by the process-wide | ||
| 31 | +/// monotonic generator, like every other row id in the repo. | ||
| 32 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] | ||
| 33 | +#[sqlx(transparent)] | ||
| 34 | +pub struct WeeklySlotId(uuid::Uuid); | ||
| 35 | + | ||
| 36 | +impl WeeklySlotId { | ||
| 37 | + pub fn generate() -> Self { | ||
| 38 | + Self(next_uuid()) | ||
| 39 | + } | ||
| 40 | + | ||
| 41 | + /// The inner uuid, for runtime-checked binds that cannot take the | ||
| 42 | + /// newtype. Static `query!` binds take `self` directly. | ||
| 43 | + pub fn uuid(&self) -> uuid::Uuid { | ||
| 44 | + self.0 | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 48 | + /// which matches no row. | ||
| 49 | + pub fn from_key(key: &str) -> Self { | ||
| 50 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + /// The bare uuid wire form. | ||
| 54 | + pub fn key(&self) -> String { | ||
| 55 | + self.0.to_string() | ||
| 56 | + } | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// An ISO weekday: `1` = Monday through `7` = Sunday. The same spell the | ||
| 60 | +/// DDL's `CHECK (weekday BETWEEN 1 AND 7)` enforces at the store. | ||
| 61 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 62 | +#[sqlx(transparent)] | ||
| 63 | +pub struct Weekday(i16); | ||
| 64 | + | ||
| 65 | +impl Weekday { | ||
| 66 | + /// The weekday `raw` names, or a validation error when it is off the | ||
| 67 | + /// ISO scale — the `400` the add routes answer with. | ||
| 68 | + pub fn new(raw: i16) -> Result<Self, ValidationError> { | ||
| 69 | + if !(1..=7).contains(&raw) { | ||
| 70 | + return Err(ValidationError::Invalid { | ||
| 71 | + field: "weekday", | ||
| 72 | + reason: "must be 1 (Monday) through 7 (Sunday)", | ||
| 73 | + }); | ||
| 74 | + } | ||
| 75 | + Ok(Self(raw)) | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + /// The integer the wire and the `weekday` column carry. | ||
| 79 | + pub fn get(self) -> i16 { | ||
| 80 | + self.0 | ||
| 81 | + } | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// A time of day as minutes past midnight — the wire form of the slot's | ||
| 85 | +/// `TIME` columns (`540` = 09:00). The `TIME` cast is the statement's own; | ||
| 86 | +/// this newtype range-checks what the statement binds. | ||
| 87 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, sqlx::Type)] | ||
| 88 | +#[sqlx(transparent)] | ||
| 89 | +pub struct SlotMinute(i64); | ||
| 90 | + | ||
| 91 | +impl SlotMinute { | ||
| 92 | + /// The minute `raw` names, or a validation error when it is not a minute | ||
| 93 | + /// of a real day — the `400` the add routes answer with. | ||
| 94 | + pub fn new(raw: i64) -> Result<Self, ValidationError> { | ||
| 95 | + if !(MIN_SLOT_MINUTE..=MAX_SLOT_MINUTE).contains(&raw) { | ||
| 96 | + return Err(ValidationError::Invalid { | ||
| 97 | + field: "slot time", | ||
| 98 | + reason: "must be minutes past midnight, 0 (00:00) through 1439 (23:59)", | ||
| 99 | + }); | ||
| 100 | + } | ||
| 101 | + Ok(Self(raw)) | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + /// The integer the wire carries. | ||
| 105 | + pub fn get(self) -> i64 { | ||
| 106 | + self.0 | ||
| 107 | + } | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// One weekly plan line: on `weekday`, from `starts_at` to `ends_at`. | ||
| 111 | +/// | ||
| 112 | +/// The list a resolver returns is ordered `weekday` first, then `starts_at`. | ||
| 113 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::FromRow)] | ||
| 114 | +pub struct WeeklySlot { | ||
| 115 | + pub(crate) id: WeeklySlotId, | ||
| 116 | + pub(crate) weekday: Weekday, | ||
| 117 | + pub(crate) starts_at: SlotMinute, | ||
| 118 | + pub(crate) ends_at: SlotMinute, | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +impl WeeklySlot { | ||
| 122 | + /// The slot `id` names, or a validation error when the window is not one | ||
| 123 | + /// (`ends_at` must land strictly after `starts_at` — equal times are an | ||
| 124 | + /// empty window, inverted ones a typo). The store's | ||
| 125 | + /// `CHECK (ends_at > starts_at)` is the same rule at rest. | ||
| 126 | + pub fn new( | ||
| 127 | + id: WeeklySlotId, | ||
| 128 | + weekday: Weekday, | ||
| 129 | + starts_at: SlotMinute, | ||
| 130 | + ends_at: SlotMinute, | ||
| 131 | + ) -> Result<Self, ValidationError> { | ||
| 132 | + if starts_at.get() >= ends_at.get() { | ||
| 133 | + return Err(ValidationError::Invalid { | ||
| 134 | + field: "ends_at", | ||
| 135 | + reason: "must be after starts_at — a slot needs a non-empty window", | ||
| 136 | + }); | ||
| 137 | + } | ||
| 138 | + Ok(Self { | ||
| 139 | + id, | ||
| 140 | + weekday, | ||
| 141 | + starts_at, | ||
| 142 | + ends_at, | ||
| 143 | + }) | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + pub fn get_id(&self) -> &WeeklySlotId { | ||
| 147 | + &self.id | ||
| 148 | + } | ||
| 149 | + | ||
| 150 | + pub fn get_weekday(&self) -> Weekday { | ||
| 151 | + self.weekday | ||
| 152 | + } | ||
| 153 | + | ||
| 154 | + pub fn get_starts_at(&self) -> SlotMinute { | ||
| 155 | + self.starts_at | ||
| 156 | + } | ||
| 157 | + | ||
| 158 | + pub fn get_ends_at(&self) -> SlotMinute { | ||
| 159 | + self.ends_at | ||
| 160 | + } | ||
| 161 | + | ||
| 162 | + /// Whether this and `other` cannot both stand in one owner's plan: the | ||
| 163 | + /// same weekday with intersecting windows. Touching endpoints are fine — | ||
| 164 | + /// a lesson may start the minute another ends. | ||
| 165 | + pub fn overlaps(&self, other: &WeeklySlot) -> bool { | ||
| 166 | + self.weekday == other.weekday | ||
| 167 | + && self.starts_at.get() < other.ends_at.get() | ||
| 168 | + && other.starts_at.get() < self.ends_at.get() | ||
| 169 | + } | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +/// Why [`check_add`] refused a slot. | ||
| 173 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 174 | +pub enum SlotAddError { | ||
| 175 | + /// A slot of the same owner already overlaps the candidate on its | ||
| 176 | + /// weekday. The exact duplicate overlaps too, so it answers here. | ||
| 177 | + Overlap, | ||
| 178 | + /// The owner's plan already holds [`MAX_WEEKLY_SLOTS`] slots. | ||
| 179 | + Full, | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// The add-time invariant, judged against the owner's current rows: overlap | ||
| 183 | +/// first (it names the concrete collision the caller must move), then the | ||
| 184 | +/// plan-size cap. A pure rule so the refusal order is one the tests can pin. | ||
| 185 | +pub fn check_add(existing: &[WeeklySlot], candidate: &WeeklySlot) -> Result<(), SlotAddError> { | ||
| 186 | + if existing.iter().any(|slot| slot.overlaps(candidate)) { | ||
| 187 | + return Err(SlotAddError::Overlap); | ||
| 188 | + } | ||
| 189 | + if existing.len() >= MAX_WEEKLY_SLOTS { | ||
| 190 | + return Err(SlotAddError::Full); | ||
| 191 | + } | ||
| 192 | + Ok(()) | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +#[cfg(test)] | ||
| 196 | +mod tests { | ||
| 197 | + use super::*; | ||
| 198 | + | ||
| 199 | + fn day(raw: i16) -> Weekday { | ||
| 200 | + Weekday::new(raw).unwrap() | ||
| 201 | + } | ||
| 202 | + | ||
| 203 | + fn mins(raw: i64) -> SlotMinute { | ||
| 204 | + SlotMinute::new(raw).unwrap() | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + fn slot(weekday: i16, starts: i64, ends: i64) -> WeeklySlot { | ||
| 208 | + WeeklySlot::new( | ||
| 209 | + WeeklySlotId::generate(), | ||
| 210 | + day(weekday), | ||
| 211 | + mins(starts), | ||
| 212 | + mins(ends), | ||
| 213 | + ) | ||
| 214 | + .unwrap() | ||
| 215 | + } | ||
| 216 | + | ||
| 217 | + #[test] | ||
| 218 | + fn weekdays_are_the_iso_scale() { | ||
| 219 | + assert!(Weekday::new(1).is_ok()); | ||
| 220 | + assert!(Weekday::new(7).is_ok()); | ||
| 221 | + assert!(Weekday::new(0).is_err()); | ||
| 222 | + assert!(Weekday::new(8).is_err()); | ||
| 223 | + } | ||
| 224 | + | ||
| 225 | + #[test] | ||
| 226 | + fn slot_minutes_are_one_real_day() { | ||
| 227 | + assert!(SlotMinute::new(0).is_ok()); | ||
| 228 | + assert!(SlotMinute::new(MAX_SLOT_MINUTE).is_ok()); | ||
| 229 | + assert!(SlotMinute::new(-1).is_err()); | ||
| 230 | + assert!(SlotMinute::new(MAX_SLOT_MINUTE + 1).is_err()); | ||
| 231 | + } | ||
| 232 | + | ||
| 233 | + #[test] | ||
| 234 | + fn a_slot_window_must_be_non_empty_and_forward() { | ||
| 235 | + // Zero-length and inverted windows are refused. | ||
| 236 | + assert!(WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(600)).is_err()); | ||
| 237 | + assert!(WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(540)).is_err()); | ||
| 238 | + // A one-minute window stands. | ||
| 239 | + assert!(WeeklySlot::new(WeeklySlotId::generate(), day(1), mins(600), mins(601)).is_ok()); | ||
| 240 | + } | ||
| 241 | + | ||
| 242 | + #[test] | ||
| 243 | + fn overlap_is_same_weekday_and_intersecting() { | ||
| 244 | + let monday_morning = slot(1, 540, 600); | ||
| 245 | + // Same window: an exact duplicate overlaps. | ||
| 246 | + assert!(monday_morning.overlaps(&slot(1, 540, 600))); | ||
| 247 | + // Partial and containing windows overlap. | ||
| 248 | + assert!(monday_morning.overlaps(&slot(1, 570, 630))); | ||
| 249 | + assert!(monday_morning.overlaps(&slot(1, 530, 610))); | ||
| 250 | + assert!(monday_morning.overlaps(&slot(1, 530, 630))); | ||
| 251 | + // Touching endpoints do not: one lesson may start when another ends. | ||
| 252 | + assert!(!monday_morning.overlaps(&slot(1, 600, 660))); | ||
| 253 | + assert!(!monday_morning.overlaps(&slot(1, 480, 540))); | ||
| 254 | + // The same window on another weekday is a different line of the week. | ||
| 255 | + assert!(!monday_morning.overlaps(&slot(2, 540, 600))); | ||
| 256 | + } | ||
| 257 | + | ||
| 258 | + #[test] | ||
| 259 | + fn check_add_refuses_overlap_before_the_cap() { | ||
| 260 | + let existing: Vec<WeeklySlot> = (0..MAX_WEEKLY_SLOTS) | ||
| 261 | + .map(|i| { | ||
| 262 | + slot( | ||
| 263 | + ((i % 7) + 1) as i16, | ||
| 264 | + 480 + (i as i64 / 7), | ||
| 265 | + 481 + (i as i64 / 7), | ||
| 266 | + ) | ||
| 267 | + }) | ||
| 268 | + .collect(); | ||
| 269 | + let colliding = slot(1, 480, 482); | ||
| 270 | + // Every plan below the cap still refuses the overlap first. | ||
| 271 | + let short: Vec<WeeklySlot> = existing[..MAX_WEEKLY_SLOTS - 1].to_vec(); | ||
| 272 | + assert_eq!(check_add(&short, &colliding), Err(SlotAddError::Overlap)); | ||
| 273 | + // A full plan refuses an overlap as an overlap, not as a full plan. | ||
| 274 | + assert_eq!(check_add(&existing, &colliding), Err(SlotAddError::Overlap)); | ||
| 275 | + } | ||
| 276 | + | ||
| 277 | + #[test] | ||
| 278 | + fn check_add_refuses_a_full_plan_with_room_for_nothing_more() { | ||
| 279 | + let existing: Vec<WeeklySlot> = (0..MAX_WEEKLY_SLOTS) | ||
| 280 | + .map(|i| { | ||
| 281 | + slot( | ||
| 282 | + ((i % 7) + 1) as i16, | ||
| 283 | + 480 + (i as i64 / 7), | ||
| 284 | + 481 + (i as i64 / 7), | ||
| 285 | + ) | ||
| 286 | + }) | ||
| 287 | + .collect(); | ||
| 288 | + // Touching, non-colliding, on a weekday with room: still refused — | ||
| 289 | + // the cap, not the overlap, is the reason. (Sunday holds five of the | ||
| 290 | + // forty, the last ending at 485; this one starts exactly there.) | ||
| 291 | + let free_slot = slot(7, 485, 486); | ||
| 292 | + assert_eq!(check_add(&existing, &free_slot), Err(SlotAddError::Full)); | ||
| 293 | + // Below the cap the same candidate is accepted. | ||
| 294 | + let short: Vec<WeeklySlot> = existing[..MAX_WEEKLY_SLOTS - 1].to_vec(); | ||
| 295 | + assert_eq!(check_add(&short, &free_slot), Ok(())); | ||
| 296 | + } | ||
| 297 | +} | ||
src/lib.rsmodified+51 -4
| @@ -67,6 +67,7 @@ use crate::web::module_gate::gate; | |||
| 67 | (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"), | 67 | (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"), |
| 68 | (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`."), | 68 | (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`."), |
| 69 | (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."), | 69 | (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."), |
| 70 | + (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."), | ||
| 70 | (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."), | 71 | (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."), |
| 71 | (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."), | 72 | (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."), |
| 72 | (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"), | 73 | (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<AppState> { | |||
| 120 | ) | 121 | ) |
| 121 | } | 122 | } |
| 122 | 123 | ||
| 123 | -/// `/instances` and the three foreign-module route pairs mounted inside it — | 124 | +/// `/offerings` and the three foreign-module route pairs mounted inside it — |
| 125 | +/// the same split as `/courses`: the grade-level template carries its own | ||
| 126 | +/// subject selection (`Subjects`), exam weights (`Exams`) and weekly plan | ||
| 127 | +/// (`Sessions`) beside the offering CRUD. Each child carries its own module's | ||
| 128 | +/// gate *and*, through the outer one applied here, the course gate — so either | ||
| 129 | +/// module being off refuses it. | ||
| 130 | +fn offerings_router(state: &AppState) -> OpenApiRouter<AppState> { | ||
| 131 | + let children = gate( | ||
| 132 | + web::offering_subjects::offering_routes(), | ||
| 133 | + state, | ||
| 134 | + Module::Subjects, | ||
| 135 | + ) | ||
| 136 | + .merge(gate( | ||
| 137 | + web::exam_weights::offering_routes(), | ||
| 138 | + state, | ||
| 139 | + Module::Exams, | ||
| 140 | + )) | ||
| 141 | + .merge(gate( | ||
| 142 | + web::weekly_plan::offering_routes(), | ||
| 143 | + state, | ||
| 144 | + Module::Sessions, | ||
| 145 | + )); | ||
| 146 | + gate( | ||
| 147 | + web::offerings::routes().merge(children), | ||
| 148 | + state, | ||
| 149 | + Module::Courses, | ||
| 150 | + ) | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +/// `/instances` and the six foreign-module route pairs mounted inside it — | ||
| 124 | /// the same split as `/courses`, one anchor down: the instance is what a class | 154 | /// the same split as `/courses`, one anchor down: the instance is what a class |
| 125 | -/// section teaches, and what exams, sessions and homework hang off. Each child carries | 155 | +/// section teaches, and what exams, sessions, homework, subject selection, |
| 126 | -/// its own module's gate *and*, through the outer one applied here, the course | 156 | +/// exam weights and the weekly plan hang off. Each child carries its own |
| 127 | -/// gate (an instance is a course taught somewhere), so either module being off | 157 | +/// module's gate *and*, through the outer one applied here, the course gate |
| 158 | +/// (an instance is a course taught somewhere), so either module being off | ||
| 128 | /// refuses it. | 159 | /// refuses it. |
| 129 | fn instances_router(state: &AppState) -> OpenApiRouter<AppState> { | 160 | fn instances_router(state: &AppState) -> OpenApiRouter<AppState> { |
| 130 | let children = gate(web::instances::exam_routes(), state, Module::Exams) | 161 | let children = gate(web::instances::exam_routes(), state, Module::Exams) |
| @@ -137,6 +168,21 @@ fn instances_router(state: &AppState) -> OpenApiRouter<AppState> { | |||
| 137 | web::instances::homework_routes(), | 168 | web::instances::homework_routes(), |
| 138 | state, | 169 | state, |
| 139 | Module::Homework, | 170 | Module::Homework, |
| 171 | + )) | ||
| 172 | + .merge(gate( | ||
| 173 | + web::offering_subjects::instance_routes(), | ||
| 174 | + state, | ||
| 175 | + Module::Subjects, | ||
| 176 | + )) | ||
| 177 | + .merge(gate( | ||
| 178 | + web::exam_weights::instance_routes(), | ||
| 179 | + state, | ||
| 180 | + Module::Exams, | ||
| 181 | + )) | ||
| 182 | + .merge(gate( | ||
| 183 | + web::weekly_plan::instance_routes(), | ||
| 184 | + state, | ||
| 185 | + Module::Sessions, | ||
| 140 | )); | 186 | )); |
| 141 | gate( | 187 | gate( |
| 142 | web::instances::routes().merge(children), | 188 | web::instances::routes().merge(children), |
| @@ -193,6 +239,7 @@ pub fn build_router(state: AppState) -> Router { | |||
| 193 | ) | 239 | ) |
| 194 | .nest("/courses", courses_router(&state)) | 240 | .nest("/courses", courses_router(&state)) |
| 195 | .nest("/instances", instances_router(&state)) | 241 | .nest("/instances", instances_router(&state)) |
| 242 | + .nest("/offerings", offerings_router(&state)) | ||
| 196 | .nest("/academic-years", web::academic_years::routes()) | 243 | .nest("/academic-years", web::academic_years::routes()) |
| 197 | .nest( | 244 | .nest( |
| 198 | "/course-notes", | 245 | "/course-notes", |
src/service/academic_year.rsmodified+16 -11
| @@ -14,7 +14,6 @@ use crate::domain::academic_year::{ | |||
| 14 | AcademicYear, AcademicYearId, AcademicYearName, GradePromotion, archived_error, | 14 | AcademicYear, AcademicYearId, AcademicYearName, GradePromotion, archived_error, |
| 15 | rollover_target_not_empty, | 15 | rollover_target_not_empty, |
| 16 | }; | 16 | }; |
| 17 | -use crate::domain::class_group::ClassGrade; | ||
| 18 | use crate::domain::timestamp::Timestamp; | 17 | use crate::domain::timestamp::Timestamp; |
| 19 | use crate::domain::user::UserId; | 18 | use crate::domain::user::UserId; |
| 20 | use crate::error::{AppError, ValidationError}; | 19 | use crate::error::{AppError, ValidationError}; |
| @@ -215,24 +214,21 @@ pub async fn rollover( | |||
| 215 | graduated: Vec::new(), | 214 | graduated: Vec::new(), |
| 216 | }; | 215 | }; |
| 217 | for class in class_group::list_for_year(db, from).await? { | 216 | for class in class_group::list_for_year(db, from).await? { |
| 218 | - let Some(grade) = class.get_grade() else { | 217 | + let grade = class.get_grade_level(); |
| 219 | - continue; | 218 | + let Some(next) = from_year.promotion_for(grade) else { |
| 220 | - }; | 219 | + // No promotion entry: this rung graduated. Reported once per |
| 221 | - let Some(mapped) = from_year.promotion_for(grade.as_str()) else { | ||
| 222 | - // No promotion entry: this grade graduated. Reported once per | ||
| 223 | // label, however many class sections carry it. | 220 | // label, however many class sections carry it. |
| 224 | - let label = grade.as_str().to_string(); | 221 | + let label = grade.label().to_string(); |
| 225 | if !report.graduated.contains(&label) { | 222 | if !report.graduated.contains(&label) { |
| 226 | report.graduated.push(label); | 223 | report.graduated.push(label); |
| 227 | } | 224 | } |
| 228 | continue; | 225 | continue; |
| 229 | }; | 226 | }; |
| 230 | - let next = ClassGrade::try_new(mapped)?; | ||
| 231 | let planted = class_group::create( | 227 | let planted = class_group::create( |
| 232 | db, | 228 | db, |
| 233 | by, | 229 | by, |
| 234 | class.get_name().clone(), | 230 | class.get_name().clone(), |
| 235 | - Some(next), | 231 | + next, |
| 236 | Some(*target), | 232 | Some(*target), |
| 237 | class.get_teacher().copied(), | 233 | class.get_teacher().copied(), |
| 238 | ) | 234 | ) |
| @@ -258,11 +254,20 @@ pub async fn rollover( | |||
| 258 | instance.get_course().key() | 254 | instance.get_course().key() |
| 259 | ))); | 255 | ))); |
| 260 | }; | 256 | }; |
| 257 | + // The section's own overrides ride along — a copy sets exactly | ||
| 258 | + // what the source had set (its `None`s are the inherit state, and | ||
| 259 | + // the fresh row is born NULL anyway). The *offering*, unlike these | ||
| 260 | + // scalars, is deliberately NOT copied: `attach_sourced` resolved | ||
| 261 | + // it against the new section's own `grade_level` (auto-creating | ||
| 262 | + // that grade's template), so a rolled-up section teaches from its | ||
| 263 | + // new grade's offering, never the source grade's. | ||
| 261 | class_course::update( | 264 | class_course::update( |
| 262 | db, | 265 | db, |
| 263 | copied.get_id(), | 266 | copied.get_id(), |
| 264 | - Some(instance.get_ders_saati()), | 267 | + instance.get_title().cloned(), |
| 265 | - Some(instance.counts_toward_karne()), | 268 | + instance.get_description().cloned(), |
| 269 | + instance.get_ders_saati(), | ||
| 270 | + instance.counts_toward_karne(), | ||
| 266 | ) | 271 | ) |
| 267 | .await?; | 272 | .await?; |
| 268 | for teacher in class_course_teacher::list_for_instance(db, instance.get_id()).await? { | 273 | for teacher in class_course_teacher::list_for_instance(db, instance.get_id()).await? { |
src/service/class_blueprint.rsmodified+14 -17
| @@ -35,7 +35,8 @@ use crate::db::class_pump::Attached; | |||
| 35 | use crate::domain::class_blueprint::{ | 35 | use crate::domain::class_blueprint::{ |
| 36 | ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason, | 36 | ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason, |
| 37 | }; | 37 | }; |
| 38 | -use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId}; | 38 | +use crate::domain::class_group::{ClassGroup, ClassGroupId}; |
| 39 | +use crate::domain::grade::GradeLevel; | ||
| 39 | use crate::domain::course::CourseId; | 40 | use crate::domain::course::CourseId; |
| 40 | use crate::domain::user::UserId; | 41 | use crate::domain::user::UserId; |
| 41 | use crate::error::AppError; | 42 | use crate::error::AppError; |
| @@ -47,11 +48,11 @@ use crate::error::AppError; | |||
| 47 | pub async fn create( | 48 | pub async fn create( |
| 48 | db: &Database, | 49 | db: &Database, |
| 49 | creator: &UserId, | 50 | creator: &UserId, |
| 50 | - grade: ClassGrade, | 51 | + grade_level: GradeLevel, |
| 51 | courses: Vec<CourseId>, | 52 | courses: Vec<CourseId>, |
| 52 | ) -> Result<ClassBlueprint, AppError> { | 53 | ) -> Result<ClassBlueprint, AppError> { |
| 53 | let courses = ClassBlueprint::course_list(courses)?; | 54 | let courses = ClassBlueprint::course_list(courses)?; |
| 54 | - class_blueprint::create(db, creator, grade, courses).await | 55 | + class_blueprint::create(db, creator, grade_level, courses).await |
| 55 | } | 56 | } |
| 56 | 57 | ||
| 57 | /// The row, for callers that only inspect it — the web layer's | 58 | /// The row, for callers that only inspect it — the web layer's |
| @@ -339,7 +340,7 @@ pub async fn pump( | |||
| 339 | skipped: Vec::new(), | 340 | skipped: Vec::new(), |
| 340 | }; | 341 | }; |
| 341 | let mut dead = Vec::new(); | 342 | let mut dead = Vec::new(); |
| 342 | - for class in class_group::list_for_grade(db, &blueprint.grade).await? { | 343 | + for class in class_group::list_for_grade(db, blueprint.grade_level).await? { |
| 343 | pumped.matched += 1; | 344 | pumped.matched += 1; |
| 344 | if !apply_courses(db, blueprint, &class, by, &mut dead, &mut pumped.skipped).await? { | 345 | if !apply_courses(db, blueprint, &class, by, &mut dead, &mut pumped.skipped).await? { |
| 345 | break; | 346 | break; |
| @@ -378,7 +379,7 @@ pub async fn status( | |||
| 378 | db: &Database, | 379 | db: &Database, |
| 379 | blueprint: &ClassBlueprint, | 380 | blueprint: &ClassBlueprint, |
| 380 | ) -> Result<Vec<SectionStatus>, AppError> { | 381 | ) -> Result<Vec<SectionStatus>, AppError> { |
| 381 | - let sections = class_group::list_for_grade(db, &blueprint.grade).await?; | 382 | + let sections = class_group::list_for_grade(db, blueprint.grade_level).await?; |
| 382 | if sections.is_empty() { | 383 | if sections.is_empty() { |
| 383 | return Ok(Vec::new()); | 384 | return Ok(Vec::new()); |
| 384 | } | 385 | } |
| @@ -415,14 +416,13 @@ mod tests { | |||
| 415 | }; | 416 | }; |
| 416 | use crate::domain::class_group::{ClassGroup, ClassName}; | 417 | use crate::domain::class_group::{ClassGroup, ClassName}; |
| 417 | 418 | ||
| 418 | - /// A section that a pump's own grade loop can actually find — [`a_class`] | 419 | + /// A section at the pump's own rung (9), so `list_for_grade` reaches it. |
| 419 | - /// carries no grade at all, so `list_for_grade` reaches none of them. | ||
| 420 | async fn a_section(name: &str, db: &Database) -> ClassGroup { | 420 | async fn a_section(name: &str, db: &Database) -> ClassGroup { |
| 421 | class_group::create( | 421 | class_group::create( |
| 422 | db, | 422 | db, |
| 423 | &fixture_user(db, "manager").await, | 423 | &fixture_user(db, "manager").await, |
| 424 | ClassName::try_new(name).unwrap(), | 424 | ClassName::try_new(name).unwrap(), |
| 425 | - Some(ClassBlueprint::grade_key("9").unwrap()), | 425 | + GradeLevel::new(9).unwrap(), |
| 426 | None, | 426 | None, |
| 427 | None, | 427 | None, |
| 428 | ) | 428 | ) |
| @@ -430,17 +430,12 @@ mod tests { | |||
| 430 | .unwrap() | 430 | .unwrap() |
| 431 | } | 431 | } |
| 432 | 432 | ||
| 433 | - /// A blueprint holding `courses`, at grade "9". | 433 | + /// A blueprint holding `courses`, at rung 9. |
| 434 | async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint { | 434 | async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint { |
| 435 | let manager = fixture_user(db, "manager").await; | 435 | let manager = fixture_user(db, "manager").await; |
| 436 | - create( | 436 | + create(db, &manager, GradeLevel::new(9).unwrap(), courses) |
| 437 | - db, | 437 | + .await |
| 438 | - &manager, | 438 | + .unwrap() |
| 439 | - ClassBlueprint::grade_key("9").unwrap(), | ||
| 440 | - courses, | ||
| 441 | - ) | ||
| 442 | - .await | ||
| 443 | - .unwrap() | ||
| 444 | } | 439 | } |
| 445 | 440 | ||
| 446 | /// Every skip names the record that actually failed. | 441 | /// Every skip names the record that actually failed. |
| @@ -498,6 +493,7 @@ mod tests { | |||
| 498 | // The class is deleted out from under the pump: the counter claim | 493 | // The class is deleted out from under the pump: the counter claim |
| 499 | // matches nothing and the read that follows finds no row. | 494 | // matches nothing and the read that follows finds no row. |
| 500 | let (db, _leases) = crate::database::init_test_db().await; | 495 | let (db, _leases) = crate::database::init_test_db().await; |
| 496 | + let manager = fixture_user(&db, "manager").await; | ||
| 501 | let course = a_course("algebra", &db).await; | 497 | let course = a_course("algebra", &db).await; |
| 502 | let class = class_group::read(&db, &a_class("9-A", &db).await) | 498 | let class = class_group::read(&db, &a_class("9-A", &db).await) |
| 503 | .await | 499 | .await |
| @@ -528,6 +524,7 @@ mod tests { | |||
| 528 | // The class stands at its own ceiling: the same claim matches nothing, | 524 | // The class stands at its own ceiling: the same claim matches nothing, |
| 529 | // but the row is there — and that is the one a manager can act on. | 525 | // but the row is there — and that is the one a manager can act on. |
| 530 | let (db, _leases) = crate::database::init_test_db().await; | 526 | let (db, _leases) = crate::database::init_test_db().await; |
| 527 | + let manager = fixture_user(&db, "manager").await; | ||
| 531 | let course = a_course("algebra", &db).await; | 528 | let course = a_course("algebra", &db).await; |
| 532 | let class = class_group::read(&db, &a_class("9-A", &db).await) | 529 | let class = class_group::read(&db, &a_class("9-A", &db).await) |
| 533 | .await | 530 | .await |
src/service/class_course.rsmodified+156 -17
| @@ -9,9 +9,9 @@ use crate::database::Database; | |||
| 9 | use crate::db::class_course; | 9 | use crate::db::class_course; |
| 10 | use crate::db::class_pump::{self, Axis}; | 10 | use crate::db::class_pump::{self, Axis}; |
| 11 | use crate::domain::academic_year::AcademicYearId; | 11 | use crate::domain::academic_year::AcademicYearId; |
| 12 | -use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; | 12 | +use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati, OverrideField}; |
| 13 | use crate::domain::class_group::ClassGroupId; | 13 | use crate::domain::class_group::ClassGroupId; |
| 14 | -use crate::domain::course::CourseId; | 14 | +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; |
| 15 | use crate::domain::role::Role; | 15 | use crate::domain::role::Role; |
| 16 | use crate::domain::user::{User, UserId}; | 16 | use crate::domain::user::{User, UserId}; |
| 17 | use crate::error::{AppError, ValidationError}; | 17 | use crate::error::{AppError, ValidationError}; |
| @@ -22,7 +22,10 @@ use crate::error::{AppError, ValidationError}; | |||
| 22 | /// Students already in the course keep the rows they have — no second | 22 | /// Students already in the course keep the rows they have — no second |
| 23 | /// enrollment written, `source` untouched — and the attach is one | 23 | /// enrollment written, `source` untouched — and the attach is one |
| 24 | /// `class_course` row per (class, course): the instance every exam, session, | 24 | /// `class_course` row per (class, course): the instance every exam, session, |
| 25 | -/// homework and enrollment under this class's course now keys on. | 25 | +/// homework and enrollment under this class's course now keys on. The row |
| 26 | +/// teaches from its grade-level offering (auto-created empty by the pump); | ||
| 27 | +/// only a class-delivered ders attaches — a club or etüt is a 400 naming the | ||
| 28 | +/// course. | ||
| 26 | pub async fn attach( | 29 | pub async fn attach( |
| 27 | db: &Database, | 30 | db: &Database, |
| 28 | class: &ClassGroupId, | 31 | class: &ClassGroupId, |
| @@ -120,16 +123,101 @@ pub async fn read(db: &Database, id: &ClassCourseId) -> Result<Option<ClassCours | |||
| 120 | class_course::read(db, id).await | 123 | class_course::read(db, id).await |
| 121 | } | 124 | } |
| 122 | 125 | ||
| 123 | -/// PATCH one instance's own policy: the weekly hours and whether it counts | 126 | +/// PATCH one instance's own content overrides: title, description, the |
| 124 | -/// toward the report card. Both are non-clearable, so an omitted field keeps | 127 | +/// weekly hours and the report-card policy. Each `Some(_)` **sets** the |
| 125 | -/// the stored value. | 128 | +/// override; `None` keeps what the column holds — a PATCH never clears |
| 129 | +/// (clearing back to inherit is [`reset_overrides`]' door, `POST | ||
| 130 | +/// /instances/{id}/reset`). | ||
| 126 | pub async fn update( | 131 | pub async fn update( |
| 127 | db: &Database, | 132 | db: &Database, |
| 128 | id: &ClassCourseId, | 133 | id: &ClassCourseId, |
| 134 | + title: Option<CourseTitle>, | ||
| 135 | + description: Option<CourseDescription>, | ||
| 129 | staff: Option<DersSaati>, | 136 | staff: Option<DersSaati>, |
| 130 | counts: Option<bool>, | 137 | counts: Option<bool>, |
| 131 | ) -> Result<ClassCourse, AppError> { | 138 | ) -> Result<ClassCourse, AppError> { |
| 132 | - class_course::update(db, id, staff, counts).await | 139 | + class_course::update(db, id, title, description, staff, counts).await |
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// The instance's **effective** weekly hours and report-card policy: its own | ||
| 143 | +/// override, else the offering's default, else the constants (one weekly | ||
| 144 | +/// hour, counted toward the karne). Every read of the now-nullable | ||
| 145 | +/// `ders_saati`/`counts_toward_karne` goes through here — a `NULL` on the | ||
| 146 | +/// instance is *inherit*, never a value, and unwrapping it would present "not | ||
| 147 | +/// decided" as a decision. | ||
| 148 | +/// | ||
| 149 | +/// One statement per call (the offering's two defaults off its row, which the | ||
| 150 | +/// instance's `RESTRICT` foreign key keeps alive); the composition with the | ||
| 151 | +/// full content chain (title, description, the set policies) is the Phase 3 | ||
| 152 | +/// resolver's job. | ||
| 153 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 154 | +pub struct InstancePolicy { | ||
| 155 | + pub ders_saati: DersSaati, | ||
| 156 | + pub counts_toward_karne: bool, | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +pub async fn resolve_policy( | ||
| 160 | + db: &Database, | ||
| 161 | + instance: &ClassCourse, | ||
| 162 | +) -> Result<InstancePolicy, AppError> { | ||
| 163 | + let (default_hours, default_counts) = | ||
| 164 | + crate::db::course_offering::defaults(db, instance.get_offering()) | ||
| 165 | + .await? | ||
| 166 | + .ok_or(AppError::NotFound)?; | ||
| 167 | + Ok(InstancePolicy { | ||
| 168 | + ders_saati: instance.get_ders_saati().or(default_hours).unwrap_or_else( | ||
| 169 | + || { | ||
| 170 | + DersSaati::try_new(crate::constant::MIN_DERS_SAATI) | ||
| 171 | + .expect("the floor is a valid weekly-hours count") | ||
| 172 | + }, | ||
| 173 | + ), | ||
| 174 | + counts_toward_karne: instance | ||
| 175 | + .counts_toward_karne() | ||
| 176 | + .or(default_counts) | ||
| 177 | + .unwrap_or(true), | ||
| 178 | + }) | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +/// Clear the named overrides back to **inherit** — the reset behind `POST | ||
| 182 | +/// /instances/{id}/reset`. The scalars go `NULL` (the offering's default, | ||
| 183 | +/// then the catalog row or the constant, applies again); the three set flags | ||
| 184 | +/// flip back to `TRUE` (the offering's set is authoritative again — deleting | ||
| 185 | +/// the section's own set rows rides the child-table lanes' reset doors). | ||
| 186 | +/// | ||
| 187 | +/// An empty list is a 400: a reset naming nothing would otherwise read as a | ||
| 188 | +/// success that did nothing. | ||
| 189 | +pub async fn reset_overrides( | ||
| 190 | + db: &Database, | ||
| 191 | + id: &ClassCourseId, | ||
| 192 | + fields: &[OverrideField], | ||
| 193 | +) -> Result<ClassCourse, AppError> { | ||
| 194 | + if fields.is_empty() { | ||
| 195 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 196 | + field: "fields", | ||
| 197 | + reason: "name at least one override to reset", | ||
| 198 | + })); | ||
| 199 | + } | ||
| 200 | + class_course::clear_overrides(db, id, fields).await | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +/// Parse the reset route's field names. The set-valued policies are named by | ||
| 204 | +/// their *set* (`subjects`, `exam_weights`, `weekly_plan`), not by the flag | ||
| 205 | +/// column — resetting one flips the flag back to inherit. | ||
| 206 | +pub fn parse_reset_field(name: &str) -> Result<OverrideField, AppError> { | ||
| 207 | + match name { | ||
| 208 | + "title" => Ok(OverrideField::Title), | ||
| 209 | + "description" => Ok(OverrideField::Description), | ||
| 210 | + "ders_saati" => Ok(OverrideField::DersSaati), | ||
| 211 | + "counts_toward_karne" => Ok(OverrideField::CountsTowardKarne), | ||
| 212 | + "subjects" => Ok(OverrideField::Subjects), | ||
| 213 | + "exam_weights" => Ok(OverrideField::ExamWeights), | ||
| 214 | + "weekly_plan" => Ok(OverrideField::WeeklyPlan), | ||
| 215 | + other => Err(ValidationError::Unknown { | ||
| 216 | + field: "fields", | ||
| 217 | + value: other.to_string(), | ||
| 218 | + } | ||
| 219 | + .into()), | ||
| 220 | + } | ||
| 133 | } | 221 | } |
| 134 | 222 | ||
| 135 | /// The academic year this instance sits under, if any — the seam every | 223 | /// The academic year this instance sits under, if any — the seam every |
| @@ -261,6 +349,7 @@ pub async fn ensure_instance_teacher( | |||
| 261 | #[cfg(test)] | 349 | #[cfg(test)] |
| 262 | mod tests { | 350 | mod tests { |
| 263 | use super::*; | 351 | use super::*; |
| 352 | + use crate::constant::MIN_DERS_SAATI; | ||
| 264 | use crate::db::class_group; | 353 | use crate::db::class_group; |
| 265 | use crate::db::class_member::tests::{ | 354 | use crate::db::class_member::tests::{ |
| 266 | a_class, a_course, counter, course_exists, link_exists, rows, source_of, | 355 | a_class, a_course, counter, course_exists, link_exists, rows, source_of, |
| @@ -473,7 +562,9 @@ mod tests { | |||
| 473 | ); | 562 | ); |
| 474 | } | 563 | } |
| 475 | 564 | ||
| 476 | - /// PATCHing the instance writes only what the request carried. | 565 | + /// PATCHing the instance writes only what the request carried, the reset |
| 566 | + /// door clears a named override back to inherit, and the resolver layers | ||
| 567 | + /// override → offering default → constant. | ||
| 477 | #[tokio::test] | 568 | #[tokio::test] |
| 478 | async fn an_update_writes_only_the_fields_it_carried() { | 569 | async fn an_update_writes_only_the_fields_it_carried() { |
| 479 | let (db, _leases) = crate::database::init_test_db().await; | 570 | let (db, _leases) = crate::database::init_test_db().await; |
| @@ -481,30 +572,78 @@ mod tests { | |||
| 481 | let class = a_class("9-A", &db).await; | 572 | let class = a_class("9-A", &db).await; |
| 482 | let algebra = a_course("algebra", &db).await; | 573 | let algebra = a_course("algebra", &db).await; |
| 483 | let instance = attach(&db, &class, &algebra, &manager).await.unwrap(); | 574 | let instance = attach(&db, &class, &algebra, &manager).await.unwrap(); |
| 575 | + // A fresh instance carries no overrides: the resolver falls through | ||
| 576 | + // the (empty, auto-created) offering to the constants. | ||
| 577 | + let fresh = read(&db, instance.get_id()).await.unwrap().unwrap(); | ||
| 578 | + assert_eq!(fresh.get_ders_saati(), None); | ||
| 579 | + let fresh_policy = resolve_policy(&db, &fresh).await.unwrap(); | ||
| 580 | + assert_eq!(fresh_policy.ders_saati.as_i64(), MIN_DERS_SAATI); | ||
| 581 | + assert!(fresh_policy.counts_toward_karne); | ||
| 484 | 582 | ||
| 485 | let updated = update( | 583 | let updated = update( |
| 486 | &db, | 584 | &db, |
| 487 | instance.get_id(), | 585 | instance.get_id(), |
| 586 | + Some(CourseTitle::try_new("9-A Matematik").unwrap()), | ||
| 587 | + None, | ||
| 488 | Some(DersSaati::try_new(5).unwrap()), | 588 | Some(DersSaati::try_new(5).unwrap()), |
| 489 | None, | 589 | None, |
| 490 | ) | 590 | ) |
| 491 | .await | 591 | .await |
| 492 | .unwrap(); | 592 | .unwrap(); |
| 493 | - assert_eq!(updated.get_ders_saati().as_i64(), 5); | 593 | + assert_eq!( |
| 494 | - assert!( | 594 | + updated.get_title().map(CourseTitle::as_str), |
| 595 | + Some("9-A Matematik") | ||
| 596 | + ); | ||
| 597 | + assert_eq!(updated.get_ders_saati().map(DersSaati::as_i64), Some(5)); | ||
| 598 | + assert_eq!( | ||
| 495 | updated.counts_toward_karne(), | 599 | updated.counts_toward_karne(), |
| 600 | + None, | ||
| 496 | "the omitted field keeps its stored value" | 601 | "the omitted field keeps its stored value" |
| 497 | ); | 602 | ); |
| 603 | + // The effective hours follow the override, not the constant. | ||
| 604 | + let policy = resolve_policy(&db, &updated).await.unwrap(); | ||
| 605 | + assert_eq!(policy.ders_saati.as_i64(), 5); | ||
| 498 | 606 | ||
| 499 | - let again = update(&db, instance.get_id(), None, Some(false)) | 607 | + let again = update( |
| 500 | - .await | 608 | + &db, |
| 501 | - .unwrap(); | 609 | + instance.get_id(), |
| 502 | - assert!(!again.counts_toward_karne()); | 610 | + None, |
| 611 | + None, | ||
| 612 | + None, | ||
| 613 | + Some(false), | ||
| 614 | + ) | ||
| 615 | + .await | ||
| 616 | + .unwrap(); | ||
| 617 | + assert_eq!(again.counts_toward_karne(), Some(false)); | ||
| 503 | assert_eq!( | 618 | assert_eq!( |
| 504 | - again.get_ders_saati().as_i64(), | 619 | + again.get_ders_saati().map(DersSaati::as_i64), |
| 505 | - 5, | 620 | + Some(5), |
| 506 | "…and the other direction holds too" | 621 | "…and the other direction holds too" |
| 507 | ); | 622 | ); |
| 623 | + | ||
| 624 | + // Reset: the named overrides go back to inherit, the unnamed (the | ||
| 625 | + // title) stay. | ||
| 626 | + let cleared = reset_overrides( | ||
| 627 | + &db, | ||
| 628 | + instance.get_id(), | ||
| 629 | + &[OverrideField::DersSaati, OverrideField::CountsTowardKarne], | ||
| 630 | + ) | ||
| 631 | + .await | ||
| 632 | + .unwrap(); | ||
| 633 | + assert_eq!(cleared.get_ders_saati(), None); | ||
| 634 | + assert_eq!(cleared.counts_toward_karne(), None); | ||
| 635 | + assert_eq!( | ||
| 636 | + cleared.get_title().map(CourseTitle::as_str), | ||
| 637 | + Some("9-A Matematik"), | ||
| 638 | + "the reset only touches the fields it names" | ||
| 639 | + ); | ||
| 640 | + let cleared_policy = resolve_policy(&db, &cleared).await.unwrap(); | ||
| 641 | + assert_eq!(cleared_policy.ders_saati.as_i64(), MIN_DERS_SAATI); | ||
| 642 | + assert!(cleared_policy.counts_toward_karne); | ||
| 643 | + assert!( | ||
| 644 | + reset_overrides(&db, instance.get_id(), &[]).await.is_err(), | ||
| 645 | + "a reset naming nothing is a 400, not a no-op success" | ||
| 646 | + ); | ||
| 508 | } | 647 | } |
| 509 | 648 | ||
| 510 | /// D10: the instance's own teacher, the section's homeroom teacher and a | 649 | /// D10: the instance's own teacher, the section's homeroom teacher and a |
| @@ -524,7 +663,7 @@ mod tests { | |||
| 524 | &db, | 663 | &db, |
| 525 | &manager, | 664 | &manager, |
| 526 | crate::domain::class_group::ClassName::try_new("9-A").unwrap(), | 665 | crate::domain::class_group::ClassName::try_new("9-A").unwrap(), |
| 527 | - None, | 666 | + crate::domain::grade::GradeLevel::new(9).unwrap(), |
| 528 | None, | 667 | None, |
| 529 | Some(homeroom), | 668 | Some(homeroom), |
| 530 | ) | 669 | ) |
src/service/class_group.rsmodified+10 -9
| @@ -5,7 +5,8 @@ | |||
| 5 | use crate::database::Database; | 5 | use crate::database::Database; |
| 6 | use crate::db::class_group; | 6 | use crate::db::class_group; |
| 7 | use crate::domain::academic_year::AcademicYearId; | 7 | use crate::domain::academic_year::AcademicYearId; |
| 8 | -use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; | 8 | +use crate::domain::class_group::{ClassGroup, ClassGroupId, ClassName}; |
| 9 | +use crate::domain::grade::GradeLevel; | ||
| 9 | use crate::domain::user::UserId; | 10 | use crate::domain::user::UserId; |
| 10 | use crate::error::AppError; | 11 | use crate::error::AppError; |
| 11 | 12 | ||
| @@ -25,11 +26,11 @@ pub async fn create( | |||
| 25 | db: &Database, | 26 | db: &Database, |
| 26 | creator: &UserId, | 27 | creator: &UserId, |
| 27 | name: ClassName, | 28 | name: ClassName, |
| 28 | - grade: Option<ClassGrade>, | 29 | + grade_level: GradeLevel, |
| 29 | year: Option<AcademicYearId>, | 30 | year: Option<AcademicYearId>, |
| 30 | teacher: Option<UserId>, | 31 | teacher: Option<UserId>, |
| 31 | ) -> Result<ClassGroup, AppError> { | 32 | ) -> Result<ClassGroup, AppError> { |
| 32 | - class_group::create(db, creator, name, grade, year, teacher).await | 33 | + class_group::create(db, creator, name, grade_level, year, teacher).await |
| 33 | } | 34 | } |
| 34 | 35 | ||
| 35 | /// The row, for callers that only inspect it — the web layer's | 36 | /// 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<Option<ClassGroup> | |||
| 38 | class_group::read(db, id).await | 39 | class_group::read(db, id).await |
| 39 | } | 40 | } |
| 40 | 41 | ||
| 41 | -/// Every class, newest first — or one grade's, when `grade` narrows it: the | 42 | +/// Every class, newest first — or one rung's, when `grade_level` narrows it: |
| 42 | -/// read behind the class index. | 43 | +/// the read behind the class index. |
| 43 | pub async fn list_all( | 44 | pub async fn list_all( |
| 44 | db: &Database, | 45 | db: &Database, |
| 45 | - grade: Option<Option<ClassGrade>>, | 46 | + grade_level: Option<GradeLevel>, |
| 46 | limit: Option<i64>, | 47 | limit: Option<i64>, |
| 47 | offset: i64, | 48 | offset: i64, |
| 48 | ) -> Result<(Vec<ClassGroup>, i64), AppError> { | 49 | ) -> Result<(Vec<ClassGroup>, i64), AppError> { |
| 49 | - class_group::list_all(db, grade, limit, offset).await | 50 | + class_group::list_all(db, grade_level, limit, offset).await |
| 50 | } | 51 | } |
| 51 | 52 | ||
| 52 | /// The classes `ids` names, in no particular order — the join behind the two | 53 | /// The classes `ids` names, in no particular order — the join behind the two |
| @@ -68,11 +69,11 @@ pub async fn update( | |||
| 68 | db: &Database, | 69 | db: &Database, |
| 69 | class: ClassGroup, | 70 | class: ClassGroup, |
| 70 | name: Option<ClassName>, | 71 | name: Option<ClassName>, |
| 71 | - grade: Option<Option<ClassGrade>>, | 72 | + grade_level: Option<GradeLevel>, |
| 72 | year: Option<Option<AcademicYearId>>, | 73 | year: Option<Option<AcademicYearId>>, |
| 73 | teacher: Option<Option<UserId>>, | 74 | teacher: Option<Option<UserId>>, |
| 74 | ) -> Result<ClassGroup, AppError> { | 75 | ) -> Result<ClassGroup, AppError> { |
| 75 | - class_group::update(db, class, name, grade, year, teacher).await | 76 | + class_group::update(db, class, name, grade_level, year, teacher).await |
| 76 | } | 77 | } |
| 77 | 78 | ||
| 78 | /// Delete the class and give its year reference back; `false` = refused, | 79 | /// Delete the class and give its year reference back; `false` = refused, |
src/service/course_offering.rsadded+95 -0
| @@ -0,0 +1,95 @@ | |||
| 1 | +//! Offering workflows: the one invariant the web layer cannot express alone — | ||
| 2 | +//! only a **class-delivered** course (`kind = 'course'`) has grade-level | ||
| 3 | +//! offerings, because only such a course is ever attached to a class section | ||
| 4 | +//! ([`crate::domain::course::CourseKind::is_class_delivered`]). A club or an | ||
| 5 | +//! etüt is joined individually, has no grade, and so has no template to | ||
| 6 | +//! inherit from. | ||
| 7 | +//! | ||
| 8 | +//! Everything else (the duplicate template's `offering_exists`, the in-use | ||
| 9 | +//! delete guard) is the store's own answer, mapped in | ||
| 10 | +//! [`crate::db::course_offering`]. The manager+ gate lives in the web layer. | ||
| 11 | + | ||
| 12 | +use crate::database::Database; | ||
| 13 | +use crate::db::{course, course_offering}; | ||
| 14 | +use crate::domain::class_course::DersSaati; | ||
| 15 | +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; | ||
| 16 | +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; | ||
| 17 | +use crate::domain::grade::GradeLevel; | ||
| 18 | +use crate::domain::user::UserId; | ||
| 19 | +use crate::error::{AppError, ValidationError}; | ||
| 20 | + | ||
| 21 | +/// Mint the grade-level template for a course. A course that is not | ||
| 22 | +/// class-delivered is a 400 (there is no grade an offering could hang off); | ||
| 23 | +/// a template that already exists is the db layer's 409 `offering_exists`. | ||
| 24 | +#[allow(clippy::too_many_arguments)] // the create body, spelled field by field | ||
| 25 | +pub async fn create( | ||
| 26 | + db: &Database, | ||
| 27 | + by: &UserId, | ||
| 28 | + course_id: &CourseId, | ||
| 29 | + grade: GradeLevel, | ||
| 30 | + title: Option<CourseTitle>, | ||
| 31 | + description: Option<CourseDescription>, | ||
| 32 | + default_ders_saati: Option<DersSaati>, | ||
| 33 | + default_counts_toward_karne: Option<bool>, | ||
| 34 | +) -> Result<CourseOffering, AppError> { | ||
| 35 | + let course = course::read(db, course_id).await?.ok_or(AppError::NotFound)?; | ||
| 36 | + if !course.get_kind().is_class_delivered() { | ||
| 37 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 38 | + field: "course", | ||
| 39 | + reason: "only a ders has grade-level offerings — a club or etüt is joined individually, not attached", | ||
| 40 | + })); | ||
| 41 | + } | ||
| 42 | + course_offering::create( | ||
| 43 | + db, | ||
| 44 | + course.get_id(), | ||
| 45 | + grade, | ||
| 46 | + title, | ||
| 47 | + description, | ||
| 48 | + default_ders_saati, | ||
| 49 | + default_counts_toward_karne, | ||
| 50 | + by, | ||
| 51 | + ) | ||
| 52 | + .await | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// One offering by id, or `None` when the id names no row — the read behind | ||
| 56 | +/// `GET /offerings/{id}`. | ||
| 57 | +pub async fn read( | ||
| 58 | + db: &Database, | ||
| 59 | + id: &CourseOfferingId, | ||
| 60 | +) -> Result<Option<CourseOffering>, AppError> { | ||
| 61 | + course_offering::read(db, id).await | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// The offerings, optionally narrowed by course and/or grade ladder rung, | ||
| 65 | +/// paged — the read behind `GET /offerings?course=&grade_level=`. | ||
| 66 | +pub async fn list( | ||
| 67 | + db: &Database, | ||
| 68 | + course: Option<&CourseId>, | ||
| 69 | + grade: Option<GradeLevel>, | ||
| 70 | + limit: Option<i64>, | ||
| 71 | + offset: i64, | ||
| 72 | +) -> Result<(Vec<CourseOffering>, i64), AppError> { | ||
| 73 | + course_offering::list(db, course, grade, limit, offset).await | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// Field-scoped PATCH: absent keeps, `null` clears back to inherit, a value | ||
| 77 | +/// sets the override. Shape flows straight through to | ||
| 78 | +/// [`course_offering::update`]; a gone id is a 404 there. | ||
| 79 | +pub async fn update( | ||
| 80 | + db: &Database, | ||
| 81 | + id: &CourseOfferingId, | ||
| 82 | + title: Option<Option<CourseTitle>>, | ||
| 83 | + description: Option<Option<CourseDescription>>, | ||
| 84 | + default_ders_saati: Option<Option<DersSaati>>, | ||
| 85 | + default_counts_toward_karne: Option<Option<bool>>, | ||
| 86 | +) -> Result<CourseOffering, AppError> { | ||
| 87 | + course_offering::update(db, id, title, description, default_ders_saati, default_counts_toward_karne) | ||
| 88 | + .await | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// Delete the template. In use by any instance → 409 `offering_in_use`; a | ||
| 92 | +/// gone id → 404. | ||
| 93 | +pub async fn delete(db: &Database, id: &CourseOfferingId) -> Result<(), AppError> { | ||
| 94 | + course_offering::delete(db, id).await | ||
| 95 | +} | ||
src/service/exam.rsmodified+1 -1
| @@ -547,7 +547,7 @@ mod tests { | |||
| 547 | db, | 547 | db, |
| 548 | manager, | 548 | manager, |
| 549 | ClassName::try_new(name).unwrap(), | 549 | ClassName::try_new(name).unwrap(), |
| 550 | - None, | 550 | + crate::domain::grade::GradeLevel::new(9).unwrap(), |
| 551 | year.cloned(), | 551 | year.cloned(), |
| 552 | None, | 552 | None, |
| 553 | ) | 553 | ) |
src/service/exam_weight.rsadded+404 -0
| @@ -0,0 +1,404 @@ | |||
| 1 | +//! Exam-weight overrides: the resolution chain and the write doors. | ||
| 2 | +//! | ||
| 3 | +//! **The chain** — [`resolve`] answers "what does an exam of this kind weigh | ||
| 4 | +//! *in this section*": the section's own row (only while its | ||
| 5 | +//! `exam_weights_inherited` flag is `FALSE`), else the grade-level template's | ||
| 6 | +//! row, else the school `settings.exam_kinds` weight for that kind, else | ||
| 7 | +//! [`crate::domain::exam_weight::FALLBACK_WEIGHT`] (1). The floor is what | ||
| 8 | +//! keeps a *retired* kind — settings edits never rewrite history — counting | ||
| 9 | +//! once, exactly as the pre-offering behaviour did. | ||
| 10 | +//! | ||
| 11 | +//! **Own set in force means authoritative, including when empty.** A section | ||
| 12 | +//! with `exam_weights_inherited = FALSE` and no row for a kind resolves that | ||
| 13 | +//! kind to 1 — *not* to the offering's or the settings' weight. That is how a | ||
| 14 | +//! section zeroes out the template's weights without renaming the school's | ||
| 15 | +//! vocabulary; the empty-own-set case is pinned by a test below. | ||
| 16 | +//! | ||
| 17 | +//! Every write validates the kind against `settings.exam_kinds` (the rows may | ||
| 18 | +//! only name kinds the school runs — the routes answer 400 | ||
| 19 | +//! `unknown_exam_kind`) and the weight against the same 1..=100 window the | ||
| 20 | +//! settings enforce. The class-side writes flip the flag inside the statement | ||
| 21 | +//! ([`crate::db::exam_weight`]); the reset restores it. | ||
| 22 | + | ||
| 23 | +use crate::database::Database; | ||
| 24 | +use crate::db; | ||
| 25 | +use crate::domain::class_course::{ClassCourse, ClassCourseId}; | ||
| 26 | +use crate::domain::course_offering::CourseOfferingId; | ||
| 27 | +use crate::domain::exam_weight::{ExamWeight, FALLBACK_WEIGHT}; | ||
| 28 | +use crate::error::{AppError, ValidationError}; | ||
| 29 | + | ||
| 30 | +/// What an exam of `kind` weighs inside `instance`: the section's own row | ||
| 31 | +/// while its own set is in force (a missing row is a 1, and the chain | ||
| 32 | +/// *stops* there), else the offering's row, else the settings weight, else 1. | ||
| 33 | +pub async fn resolve( | ||
| 34 | + db: &Database, | ||
| 35 | + instance: &ClassCourse, | ||
| 36 | + kind: &str, | ||
| 37 | +) -> Result<i64, AppError> { | ||
| 38 | + if !instance.exam_weights_inherited() { | ||
| 39 | + // The section's table is the whole answer — empty included. Falling | ||
| 40 | + // through to the offering/settings here would silently re-attach the | ||
| 41 | + // weights a section deliberately cleared. | ||
| 42 | + return Ok(db::exam_weight::class_weight(db, instance.get_id(), kind) | ||
| 43 | + .await? | ||
| 44 | + .map(|row| row.get_weight()) | ||
| 45 | + .unwrap_or(FALLBACK_WEIGHT)); | ||
| 46 | + } | ||
| 47 | + if let Some(row) = db::exam_weight::offering_weight(db, instance.get_offering(), kind).await? { | ||
| 48 | + return Ok(row.get_weight()); | ||
| 49 | + } | ||
| 50 | + let school = super::settings::load(db).await?; | ||
| 51 | + Ok(school.exam_kind_weight(kind).unwrap_or(FALLBACK_WEIGHT)) | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// The section's **effective** weight map: the (inherited flag, one resolved | ||
| 55 | +/// entry per kind). With the section's own set in force that map is exactly | ||
| 56 | +/// its rows — even when that is nothing; while it inherits, every settings | ||
| 57 | +/// kind (plus any kind an offering row adds) resolved off the offering → | ||
| 58 | +/// settings → 1 chain. A client renders this verbatim; it never re-implements | ||
| 59 | +/// the chain. | ||
| 60 | +pub async fn resolved_for_class( | ||
| 61 | + db: &Database, | ||
| 62 | + instance: &ClassCourse, | ||
| 63 | +) -> Result<(bool, Vec<ExamWeight>), AppError> { | ||
| 64 | + if !instance.exam_weights_inherited() { | ||
| 65 | + return Ok((false, db::exam_weight::list_for_class(db, instance.get_id()).await?)); | ||
| 66 | + } | ||
| 67 | + Ok((true, resolved_inherited(db, instance.get_offering()).await?)) | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// The template's effective weight map: every settings kind (plus any kind its | ||
| 71 | +/// rows add), each resolved off the offering's row → settings → 1. | ||
| 72 | +pub async fn resolved_for_offering( | ||
| 73 | + db: &Database, | ||
| 74 | + offering: &CourseOfferingId, | ||
| 75 | +) -> Result<Vec<ExamWeight>, AppError> { | ||
| 76 | + resolved_inherited(db, offering).await | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +/// The map an inheriting consumer sees: the settings vocabulary, extended by | ||
| 80 | +/// whatever kinds the offering's own rows name (a retired kind with a stored | ||
| 81 | +/// row keeps showing its stored weight), each resolved in memory off one batch | ||
| 82 | +/// read. | ||
| 83 | +async fn resolved_inherited( | ||
| 84 | + db: &Database, | ||
| 85 | + offering: &CourseOfferingId, | ||
| 86 | +) -> Result<Vec<ExamWeight>, AppError> { | ||
| 87 | + let school = super::settings::load(db).await?; | ||
| 88 | + let rows = db::exam_weight::list_for_offering(db, offering).await?; | ||
| 89 | + let weight_of = |kind: &str| { | ||
| 90 | + rows.iter() | ||
| 91 | + .find(|row| row.get_kind() == kind) | ||
| 92 | + .map(ExamWeight::get_weight) | ||
| 93 | + .or_else(|| school.exam_kind_weight(kind)) | ||
| 94 | + .unwrap_or(FALLBACK_WEIGHT) | ||
| 95 | + }; | ||
| 96 | + let mut kinds: Vec<String> = school | ||
| 97 | + .get_exam_kinds() | ||
| 98 | + .iter() | ||
| 99 | + .map(|def| def.get_name().to_string()) | ||
| 100 | + .collect(); | ||
| 101 | + for row in &rows { | ||
| 102 | + if !kinds.iter().any(|kind| kind == row.get_kind()) { | ||
| 103 | + kinds.push(row.get_kind().to_string()); | ||
| 104 | + } | ||
| 105 | + } | ||
| 106 | + kinds.sort(); | ||
| 107 | + Ok(kinds | ||
| 108 | + .into_iter() | ||
| 109 | + .map(|kind| ExamWeight { | ||
| 110 | + weight: weight_of(&kind), | ||
| 111 | + kind, | ||
| 112 | + }) | ||
| 113 | + .collect()) | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +/// The settings check behind every write: the row may only name a kind the | ||
| 117 | +/// school runs. The refusal is a plain 400-shaped | ||
| 118 | +/// [`ValidationError::Invalid`] on `field: "kind"` — the web layer re-renders | ||
| 119 | +/// that shape as the coded `unknown_exam_kind` body. | ||
| 120 | +async fn checked_weight(db: &Database, kind: &str, weight: i64) -> Result<ExamWeight, AppError> { | ||
| 121 | + let school = super::settings::load(db).await?; | ||
| 122 | + if !school.get_exam_kinds().iter().any(|def| def.get_name() == kind) { | ||
| 123 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 124 | + field: "kind", | ||
| 125 | + reason: "unknown exam kind (the school's settings.exam_kinds is the vocabulary)", | ||
| 126 | + })); | ||
| 127 | + } | ||
| 128 | + Ok(ExamWeight::try_new(kind, weight)?) | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +/// Upsert one weight on the grade-level template. Manager+ is the route's | ||
| 132 | +/// gate; a gone offering was the handler's 404 one instant earlier (the FK | ||
| 133 | +/// backs the race). | ||
| 134 | +pub async fn set_for_offering( | ||
| 135 | + db: &Database, | ||
| 136 | + offering: &CourseOfferingId, | ||
| 137 | + kind: &str, | ||
| 138 | + weight: i64, | ||
| 139 | +) -> Result<(), AppError> { | ||
| 140 | + let weight = checked_weight(db, kind, weight).await?; | ||
| 141 | + db::exam_weight::upsert_for_offering(db, offering, kind, &weight).await | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +/// Drop one weight row from the template; a pair with no row is a 404. | ||
| 145 | +pub async fn remove_from_offering( | ||
| 146 | + db: &Database, | ||
| 147 | + offering: &CourseOfferingId, | ||
| 148 | + kind: &str, | ||
| 149 | +) -> Result<(), AppError> { | ||
| 150 | + if !db::exam_weight::delete_from_offering(db, offering, kind).await? { | ||
| 151 | + return Err(AppError::NotFound); | ||
| 152 | + } | ||
| 153 | + Ok(()) | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// Upsert one weight on the section and take its set own — the flag flips in | ||
| 157 | +/// the same statement, so the write is never half an override. A gone instance | ||
| 158 | +/// is a 404. | ||
| 159 | +pub async fn set_for_class( | ||
| 160 | + db: &Database, | ||
| 161 | + instance: &ClassCourseId, | ||
| 162 | + kind: &str, | ||
| 163 | + weight: i64, | ||
| 164 | +) -> Result<(), AppError> { | ||
| 165 | + let weight = checked_weight(db, kind, weight).await?; | ||
| 166 | + db::exam_weight::upsert_for_class(db, instance, kind, &weight).await | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +/// Drop one weight row from the section — still taking the set own (a section | ||
| 170 | +/// that deletes its last row has *decided* on an empty set, and an empty own | ||
| 171 | +/// set resolves 1). No row for the kind, or a gone instance, is a 404. | ||
| 172 | +pub async fn remove_from_class( | ||
| 173 | + db: &Database, | ||
| 174 | + instance: &ClassCourseId, | ||
| 175 | + kind: &str, | ||
| 176 | +) -> Result<(), AppError> { | ||
| 177 | + if !db::exam_weight::delete_from_class(db, instance, kind).await? { | ||
| 178 | + return Err(AppError::NotFound); | ||
| 179 | + } | ||
| 180 | + Ok(()) | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +/// Restore inheritance: delete every section weight row and set the flag back | ||
| 184 | +/// to `TRUE`, in one statement. Idempotent; a gone instance is a 404. | ||
| 185 | +pub async fn reset_class(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> { | ||
| 186 | + db::exam_weight::reset_class(db, instance).await | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +#[cfg(test)] | ||
| 190 | +mod tests { | ||
| 191 | + use super::*; | ||
| 192 | + use crate::db::class_member::tests::{a_class, a_course}; | ||
| 193 | + use crate::error::ValidationError; | ||
| 194 | + | ||
| 195 | + /// A manager account and one attached instance — the attach auto-mints | ||
| 196 | + /// the grade-level offering the chain reads. The school's vocabulary is | ||
| 197 | + /// seeded to what the chain tests assume: `final` weighs 3 in the | ||
| 198 | + /// settings, `yazili` 1, and `oral` stays unknown so the refusal has a | ||
| 199 | + /// name. | ||
| 200 | + async fn an_instance(db: &Database) -> ClassCourse { | ||
| 201 | + let mut params = crate::domain::settings::Settings::defaults().params(); | ||
| 202 | + params.exam_kinds = vec![ | ||
| 203 | + crate::domain::settings::ExamKindDef::try_new("final", 3).unwrap(), | ||
| 204 | + crate::domain::settings::ExamKindDef::try_new("yazili", 1).unwrap(), | ||
| 205 | + ]; | ||
| 206 | + crate::db::settings::save(db, crate::domain::settings::Settings::try_new(params).unwrap()) | ||
| 207 | + .await | ||
| 208 | + .unwrap(); | ||
| 209 | + let manager = crate::db::class_member::tests::fixture_user(db, "weights-manager").await; | ||
| 210 | + let class = a_class("9-A", db).await; | ||
| 211 | + let algebra = a_course("algebra-weights", db).await; | ||
| 212 | + crate::service::class_course::attach(db, &class, &algebra, &manager) | ||
| 213 | + .await | ||
| 214 | + .unwrap() | ||
| 215 | + } | ||
| 216 | + | ||
| 217 | + async fn offering_id(db: &Database, instance: &ClassCourse) -> CourseOfferingId { | ||
| 218 | + crate::service::class_course::read(db, instance.get_id()) | ||
| 219 | + .await | ||
| 220 | + .unwrap() | ||
| 221 | + .unwrap() | ||
| 222 | + .get_offering() | ||
| 223 | + .clone() | ||
| 224 | + } | ||
| 225 | + | ||
| 226 | + /// The full chain on the default vocabulary (`final` weighs 3 in the | ||
| 227 | + /// settings): settings → offering row → class row → reset, plus the | ||
| 228 | + /// retired-kind floor. Each step *changes* the answer, so every | ||
| 229 | + /// assertion can fail. | ||
| 230 | + #[tokio::test] | ||
| 231 | + async fn the_chain_walks_class_then_offering_then_settings_then_one() { | ||
| 232 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 233 | + let instance = an_instance(&db).await; | ||
| 234 | + let offering = offering_id(&db, &instance).await; | ||
| 235 | + | ||
| 236 | + // Inheriting, nothing overridden anywhere: the settings weight. | ||
| 237 | + assert_eq!(resolve(&db, &instance, "final").await.unwrap(), 3); | ||
| 238 | + | ||
| 239 | + // The template overrides the settings… | ||
| 240 | + set_for_offering(&db, &offering, "final", 5).await.unwrap(); | ||
| 241 | + assert_eq!(resolve(&db, &instance, "final").await.unwrap(), 5); | ||
| 242 | + | ||
| 243 | + // …and the section overrides the template. | ||
| 244 | + set_for_class(&db, instance.get_id(), "final", 7).await.unwrap(); | ||
| 245 | + let own7 = instance_of(&db, instance.get_id()).await; | ||
| 246 | + assert!( | ||
| 247 | + !own7.exam_weights_inherited(), | ||
| 248 | + "the class-side write took the set own in the same statement" | ||
| 249 | + ); | ||
| 250 | + assert_eq!(resolve(&db, &own7, "final").await.unwrap(), 7); | ||
| 251 | + | ||
| 252 | + // Deleting the section's row takes the set own — and the chain | ||
| 253 | + // STOPS at the class: 1, not the offering's 5, not the settings' 3. | ||
| 254 | + // This is the empty-own-set contract: an own set in force is | ||
| 255 | + // authoritative including when it is empty. | ||
| 256 | + remove_from_class(&db, instance.get_id(), "final").await.unwrap(); | ||
| 257 | + let own = instance_of(&db, instance.get_id()).await; | ||
| 258 | + assert!(!own.exam_weights_inherited()); | ||
| 259 | + assert!(db::exam_weight::list_for_class(&db, instance.get_id()) | ||
| 260 | + .await | ||
| 261 | + .unwrap() | ||
| 262 | + .is_empty()); | ||
| 263 | + assert_eq!( | ||
| 264 | + resolve(&db, &own, "final").await.unwrap(), | ||
| 265 | + FALLBACK_WEIGHT, | ||
| 266 | + "an empty own set resolves 1 — the offering and settings weights stay out" | ||
| 267 | + ); | ||
| 268 | + // A kind the settings don't even list, under the same own set in | ||
| 269 | + // force: 1 as well — the chain never left the class table. | ||
| 270 | + assert_eq!( | ||
| 271 | + resolve(&db, &own, "oral").await.unwrap(), | ||
| 272 | + FALLBACK_WEIGHT, | ||
| 273 | + "an unknown kind under an own set in force counts once" | ||
| 274 | + ); | ||
| 275 | + | ||
| 276 | + // The reset restores inheritance: the offering's 5 applies again. | ||
| 277 | + reset_class(&db, instance.get_id()).await.unwrap(); | ||
| 278 | + let reset = instance_of(&db, instance.get_id()).await; | ||
| 279 | + assert!(reset.exam_weights_inherited()); | ||
| 280 | + assert_eq!(resolve(&db, &reset, "final").await.unwrap(), 5); | ||
| 281 | + | ||
| 282 | + // A kind the school does not list at all (no row anywhere) counts once. | ||
| 283 | + assert_eq!(resolve(&db, &reset, "oral").await.unwrap(), FALLBACK_WEIGHT); | ||
| 284 | + } | ||
| 285 | + | ||
| 286 | + /// While the section inherits, its effective map is the whole resolved | ||
| 287 | + /// vocabulary; the moment its own set is in force, the map is exactly its | ||
| 288 | + /// rows — nothing invented, nothing carried over. | ||
| 289 | + #[tokio::test] | ||
| 290 | + async fn the_resolved_map_switches_wholesale_with_the_flag() { | ||
| 291 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 292 | + let instance = an_instance(&db).await; | ||
| 293 | + let offering = offering_id(&db, &instance).await; | ||
| 294 | + set_for_offering(&db, &offering, "final", 5).await.unwrap(); | ||
| 295 | + | ||
| 296 | + let (inherited, map) = resolved_for_class(&db, &instance).await.unwrap(); | ||
| 297 | + assert!(inherited); | ||
| 298 | + let weight_of = |kind: &str| { | ||
| 299 | + map.iter() | ||
| 300 | + .find(|row| row.get_kind() == kind) | ||
| 301 | + .map(ExamWeight::get_weight) | ||
| 302 | + .unwrap_or_else(|| panic!("no `{kind}` in the resolved map")) | ||
| 303 | + }; | ||
| 304 | + assert_eq!(weight_of("final"), 5, "the offering row, not the settings 3"); | ||
| 305 | + assert_eq!(weight_of("yazili"), 1, "the settings weight shines through"); | ||
| 306 | + | ||
| 307 | + set_for_class(&db, instance.get_id(), "yazili", 4).await.unwrap(); | ||
| 308 | + let own = instance_of(&db, instance.get_id()).await; | ||
| 309 | + let (inherited, map) = resolved_for_class(&db, &own).await.unwrap(); | ||
| 310 | + assert!(!inherited); | ||
| 311 | + assert_eq!(map.len(), 1, "the own set is the map — no inherited kinds"); | ||
| 312 | + assert_eq!(map[0].get_kind(), "yazili"); | ||
| 313 | + assert_eq!(map[0].get_weight(), 4); | ||
| 314 | + } | ||
| 315 | + | ||
| 316 | + /// Writes refuse a kind the school does not run — before the weight is | ||
| 317 | + /// even looked at (the settings vocabulary check is the first 400). | ||
| 318 | + #[tokio::test] | ||
| 319 | + async fn writes_refuse_an_unknown_kind_before_the_weight() { | ||
| 320 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 321 | + let instance = an_instance(&db).await; | ||
| 322 | + let offering = offering_id(&db, &instance).await; | ||
| 323 | + | ||
| 324 | + for written in [ | ||
| 325 | + set_for_offering(&db, &offering, "oral", 2).await, | ||
| 326 | + set_for_class(&db, instance.get_id(), "oral", 2).await, | ||
| 327 | + // Both wrong at once: the *kind* is what the error names. | ||
| 328 | + set_for_class(&db, instance.get_id(), "oral", 500).await, | ||
| 329 | + ] { | ||
| 330 | + let err = written.unwrap_err(); | ||
| 331 | + assert!( | ||
| 332 | + matches!( | ||
| 333 | + &err, | ||
| 334 | + AppError::Validation(ValidationError::Invalid { field: "kind", .. }) | ||
| 335 | + ), | ||
| 336 | + "an unknown kind is refused on `kind`: {err:?}" | ||
| 337 | + ); | ||
| 338 | + } | ||
| 339 | + | ||
| 340 | + // A weight outside 1..=100 on a *known* kind is the bounds refusal. | ||
| 341 | + let err = set_for_class(&db, instance.get_id(), "final", 500) | ||
| 342 | + .await | ||
| 343 | + .unwrap_err(); | ||
| 344 | + assert!(matches!( | ||
| 345 | + &err, | ||
| 346 | + AppError::Validation(ValidationError::Invalid { field: "weight", .. }) | ||
| 347 | + )); | ||
| 348 | + } | ||
| 349 | + | ||
| 350 | + /// Deleting a row nobody wrote is a 404 and — per the flag-guarded | ||
| 351 | + /// delete — flips nothing: a refused delete must not take the set own. | ||
| 352 | + #[tokio::test] | ||
| 353 | + async fn a_delete_with_no_row_is_a_404_that_moves_nothing() { | ||
| 354 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 355 | + let instance = an_instance(&db).await; | ||
| 356 | + let offering = offering_id(&db, &instance).await; | ||
| 357 | + | ||
| 358 | + assert!(matches!( | ||
| 359 | + remove_from_class(&db, instance.get_id(), "final").await, | ||
| 360 | + Err(AppError::NotFound) | ||
| 361 | + )); | ||
| 362 | + assert!(matches!( | ||
| 363 | + remove_from_offering(&db, &offering, "final").await, | ||
| 364 | + Err(AppError::NotFound) | ||
| 365 | + )); | ||
| 366 | + let own = instance_of(&db, instance.get_id()).await; | ||
| 367 | + assert!( | ||
| 368 | + own.exam_weights_inherited(), | ||
| 369 | + "the refused delete left inheritance in place" | ||
| 370 | + ); | ||
| 371 | + assert_eq!(resolve(&db, &own, "final").await.unwrap(), 3); | ||
| 372 | + } | ||
| 373 | + | ||
| 374 | + /// The reset deletes every row and inherits again in one statement. | ||
| 375 | + #[tokio::test] | ||
| 376 | + async fn reset_drops_the_whole_own_set_and_inherits_again() { | ||
| 377 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 378 | + let instance = an_instance(&db).await; | ||
| 379 | + set_for_class(&db, instance.get_id(), "yazili", 4).await.unwrap(); | ||
| 380 | + set_for_class(&db, instance.get_id(), "final", 6).await.unwrap(); | ||
| 381 | + | ||
| 382 | + reset_class(&db, instance.get_id()).await.unwrap(); | ||
| 383 | + let own = instance_of(&db, instance.get_id()).await; | ||
| 384 | + assert!(own.exam_weights_inherited()); | ||
| 385 | + assert!(db::exam_weight::list_for_class(&db, instance.get_id()) | ||
| 386 | + .await | ||
| 387 | + .unwrap() | ||
| 388 | + .is_empty()); | ||
| 389 | + // Settings weights apply again (yazili defaults to 1; final to 3). | ||
| 390 | + assert_eq!(resolve(&db, &own, "final").await.unwrap(), 3); | ||
| 391 | + | ||
| 392 | + // A second reset is a no-op success, and a gone instance is a 404. | ||
| 393 | + reset_class(&db, instance.get_id()).await.unwrap(); | ||
| 394 | + let ghost = ClassCourseId::from_key("019732e3-7b00-7000-8000-00000000e1a1"); | ||
| 395 | + assert!(matches!(reset_class(&db, &ghost).await, Err(AppError::NotFound))); | ||
| 396 | + } | ||
| 397 | + | ||
| 398 | + async fn instance_of(db: &Database, id: &ClassCourseId) -> ClassCourse { | ||
| 399 | + crate::service::class_course::read(db, id) | ||
| 400 | + .await | ||
| 401 | + .unwrap() | ||
| 402 | + .unwrap() | ||
| 403 | + } | ||
| 404 | +} | ||
src/service/homework.rsmodified+9 -0
| @@ -35,6 +35,15 @@ pub async fn create( | |||
| 35 | assigned: Option<Vec<UserId>>, | 35 | assigned: Option<Vec<UserId>>, |
| 36 | created_by: &UserId, | 36 | created_by: &UserId, |
| 37 | ) -> Result<Homework, AppError> { | 37 | ) -> Result<Homework, AppError> { |
| 38 | + // The subject tag is checked against the instance's *resolved* subject | ||
| 39 | + // set — override-or-inherit — not merely against the catalog course. | ||
| 40 | + // Service-side, so every caller (the route under `/instances` included) | ||
| 41 | + // enforces the syllabus rule even though its own pre-flight only sees | ||
| 42 | + // the course. | ||
| 43 | + let instance = crate::service::class_course::read(db, class_course) | ||
| 44 | + .await? | ||
| 45 | + .ok_or(AppError::NotFound)?; | ||
| 46 | + crate::service::offering_subject::ensure_resolved_member(db, &instance, subject).await?; | ||
| 38 | homework::create( | 47 | homework::create( |
| 39 | db, | 48 | db, |
| 40 | class_course, | 49 | class_course, |
src/service/instance_resolve.rsadded+185 -0
| @@ -0,0 +1,185 @@ | |||
| 1 | +//! The composed resolved view of one instance — the one call every | ||
| 2 | +//! instance-scoped display rides. | ||
| 3 | +//! | ||
| 4 | +//! Wave 1/2 landed each axis's own resolver; this module composes them, so a | ||
| 5 | +//! read surface never re-implements a fallback chain. The scalar content runs | ||
| 6 | +//! instance → offering → catalog (`title`/`description`) or → constant | ||
| 7 | +//! (`ders_saati` 1, `counts_toward_karne` TRUE); the set axes stay | ||
| 8 | +//! flag-driven, exactly as their own resolvers rule — **override-or-inherit, | ||
| 9 | +//! never merge**. | ||
| 10 | +//! | ||
| 11 | +//! Everything here is composition: [`resolve`] calls | ||
| 12 | +//! [`crate::service::class_course::resolve_policy`], | ||
| 13 | +//! [`crate::service::offering_subject::resolved_for_instance`], | ||
| 14 | +//! [`crate::service::exam_weight::resolved_for_class`] and | ||
| 15 | +//! [`crate::service::weekly_slot::resolved_for_instance`] and adds only the | ||
| 16 | +//! title/description chain (whose two upper levels are a plain row read). | ||
| 17 | +//! [`resolved_content`] is the batch twin of that chain for report surfaces | ||
| 18 | +//! that already batch (karne, marks, attendance): two queries per batch, | ||
| 19 | +//! never one per instance. | ||
| 20 | + | ||
| 21 | +use std::collections::HashMap; | ||
| 22 | + | ||
| 23 | +use crate::database::Database; | ||
| 24 | +use crate::domain::class_course::{ClassCourse, DersSaati}; | ||
| 25 | +use crate::domain::course::Course; | ||
| 26 | +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; | ||
| 27 | +use crate::domain::exam_weight::ExamWeight; | ||
| 28 | +use crate::domain::subject::Subject; | ||
| 29 | +use crate::domain::weekly_slot::WeeklySlot; | ||
| 30 | +use crate::error::AppError; | ||
| 31 | + | ||
| 32 | +/// One instance's whole effective content: the resolved scalars plus *how* | ||
| 33 | +/// each axis was sourced. A client renders this verbatim and never | ||
| 34 | +/// re-implements the chain — the `*_overridden` flags tell an override from | ||
| 35 | +/// an inherited value, and the three `*_inherited` flags tell whose set | ||
| 36 | +/// (this section's own, possibly empty, or the offering template's) each | ||
| 37 | +/// resolved set answers from. | ||
| 38 | +#[derive(Debug, Clone)] | ||
| 39 | +pub struct ResolvedInstance { | ||
| 40 | + /// The display title: this section's override, else its offering's, else | ||
| 41 | + /// the catalog course's. | ||
| 42 | + pub title: String, | ||
| 43 | + /// `true` when `title` is this section's own override. | ||
| 44 | + pub title_overridden: bool, | ||
| 45 | + /// The display description, same chain as [`Self::title`]. | ||
| 46 | + pub description: String, | ||
| 47 | + /// `true` when `description` is this section's own override. | ||
| 48 | + pub description_overridden: bool, | ||
| 49 | + /// The effective weekly hours: override, else offering default, else 1. | ||
| 50 | + pub ders_saati: DersSaati, | ||
| 51 | + /// `true` when the hours are this section's own override. | ||
| 52 | + pub ders_saati_overridden: bool, | ||
| 53 | + /// The effective report-card policy: override, else offering default, | ||
| 54 | + /// else counted. | ||
| 55 | + pub counts_toward_karne: bool, | ||
| 56 | + /// `true` when the policy is this section's own override. | ||
| 57 | + pub counts_toward_karne_overridden: bool, | ||
| 58 | + /// `false` = the section's own subject table is authoritative, including | ||
| 59 | + /// when empty; `true` = the offering's set applies. | ||
| 60 | + pub subjects_inherited: bool, | ||
| 61 | + /// The syllabus the section teaches, resolved override-or-inherit. | ||
| 62 | + pub subjects: Vec<Subject>, | ||
| 63 | + /// The same switch for the section's exam-kind weights. | ||
| 64 | + pub exam_weights_inherited: bool, | ||
| 65 | + /// The section's effective weight map — every kind at its resolved | ||
| 66 | + /// weight (own rows in force, else the offering → settings → 1 chain). | ||
| 67 | + pub exam_weights: Vec<ExamWeight>, | ||
| 68 | + /// The same switch for the section's weekly plan. | ||
| 69 | + pub weekly_plan_inherited: bool, | ||
| 70 | + /// The resolved plan: the offering's template week while inheriting, the | ||
| 71 | + /// section's own rows (possibly empty) once it overrode. | ||
| 72 | + pub weekly_plan: Vec<WeeklySlot>, | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// The title/description a batch of instances should display, keyed by | ||
| 76 | +/// instance id key — the chain run once per batch: one offering read and one | ||
| 77 | +/// catalog read for the whole set, then the instance's own override judged | ||
| 78 | +/// in memory. An instance whose catalog row is unreachable renders an empty | ||
| 79 | +/// string (the delete cascade makes that unreachable too; the karne lines | ||
| 80 | +/// degrade rather than 500, the same as before this module existed). | ||
| 81 | +pub async fn resolved_content( | ||
| 82 | + db: &Database, | ||
| 83 | + instances: &[&ClassCourse], | ||
| 84 | +) -> Result<HashMap<String, ResolvedContent>, AppError> { | ||
| 85 | + let mut offering_ids: Vec<CourseOfferingId> = Vec::new(); | ||
| 86 | + let mut course_ids: Vec<crate::domain::course::CourseId> = Vec::new(); | ||
| 87 | + for instance in instances { | ||
| 88 | + if !offering_ids.contains(instance.get_offering()) { | ||
| 89 | + offering_ids.push(instance.get_offering().clone()); | ||
| 90 | + } | ||
| 91 | + if !course_ids.contains(instance.get_course()) { | ||
| 92 | + course_ids.push(instance.get_course().clone()); | ||
| 93 | + } | ||
| 94 | + } | ||
| 95 | + let offerings = crate::db::course_offering::list_by_ids(db, &offering_ids).await?; | ||
| 96 | + let courses = crate::db::course::list_by_ids(db, &course_ids).await?; | ||
| 97 | + let offering_by_key: HashMap<String, &CourseOffering> = offerings | ||
| 98 | + .iter() | ||
| 99 | + .map(|offering| (offering.get_id().key(), offering)) | ||
| 100 | + .collect(); | ||
| 101 | + let course_by_key: HashMap<String, &Course> = courses | ||
| 102 | + .iter() | ||
| 103 | + .map(|course| (course.get_id().key(), course)) | ||
| 104 | + .collect(); | ||
| 105 | + | ||
| 106 | + Ok(instances | ||
| 107 | + .iter() | ||
| 108 | + .map(|instance| { | ||
| 109 | + let template = offering_by_key | ||
| 110 | + .get(&instance.get_offering().key()) | ||
| 111 | + .copied(); | ||
| 112 | + let catalog = course_by_key.get(&instance.get_course().key()).copied(); | ||
| 113 | + let title = instance | ||
| 114 | + .get_title() | ||
| 115 | + .or(template.and_then(|o| o.get_title())) | ||
| 116 | + .or_else(|| catalog.map(|c| c.get_title())) | ||
| 117 | + .map(|title| title.as_str().to_string()) | ||
| 118 | + .unwrap_or_default(); | ||
| 119 | + let description = instance | ||
| 120 | + .get_description() | ||
| 121 | + .or(template.and_then(|o| o.get_description())) | ||
| 122 | + .or_else(|| catalog.map(|c| c.get_description())) | ||
| 123 | + .map(|description| description.as_str().to_string()) | ||
| 124 | + .unwrap_or_default(); | ||
| 125 | + ( | ||
| 126 | + instance.get_id().key().to_string(), | ||
| 127 | + ResolvedContent { title, description }, | ||
| 128 | + ) | ||
| 129 | + }) | ||
| 130 | + .collect()) | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +/// The display strings of one instance: its resolved title and description. | ||
| 134 | +pub struct ResolvedContent { | ||
| 135 | + pub title: String, | ||
| 136 | + pub description: String, | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +/// Compose the whole resolved view of `instance` — the one call a read | ||
| 140 | +/// surface pays instead of layering its own fallbacks. A gone offering or | ||
| 141 | +/// catalog row is a `NotFound` (the `RESTRICT` foreign keys make that | ||
| 142 | +/// unreachable; a missing row is never silently read as an empty template). | ||
| 143 | +pub async fn resolve( | ||
| 144 | + db: &Database, | ||
| 145 | + instance: &ClassCourse, | ||
| 146 | +) -> Result<ResolvedInstance, AppError> { | ||
| 147 | + let offering = crate::db::course_offering::read(db, instance.get_offering()) | ||
| 148 | + .await? | ||
| 149 | + .ok_or(AppError::NotFound)?; | ||
| 150 | + let course = crate::db::course::read(db, instance.get_course()) | ||
| 151 | + .await? | ||
| 152 | + .ok_or(AppError::NotFound)?; | ||
| 153 | + let policy = crate::service::class_course::resolve_policy(db, instance).await?; | ||
| 154 | + let subjects = | ||
| 155 | + crate::service::offering_subject::resolved_for_instance(db, instance).await?; | ||
| 156 | + let (exam_weights_inherited, exam_weights) = | ||
| 157 | + crate::service::exam_weight::resolved_for_class(db, instance).await?; | ||
| 158 | + let weekly_plan = crate::service::weekly_slot::resolved_for_instance(db, instance).await?; | ||
| 159 | + | ||
| 160 | + let title = instance | ||
| 161 | + .get_title() | ||
| 162 | + .or(offering.get_title()) | ||
| 163 | + .unwrap_or_else(|| course.get_title()); | ||
| 164 | + let description = instance | ||
| 165 | + .get_description() | ||
| 166 | + .or(offering.get_description()) | ||
| 167 | + .unwrap_or_else(|| course.get_description()); | ||
| 168 | + | ||
| 169 | + Ok(ResolvedInstance { | ||
| 170 | + title: title.as_str().to_string(), | ||
| 171 | + title_overridden: instance.get_title().is_some(), | ||
| 172 | + description: description.as_str().to_string(), | ||
| 173 | + description_overridden: instance.get_description().is_some(), | ||
| 174 | + ders_saati: policy.ders_saati, | ||
| 175 | + ders_saati_overridden: instance.get_ders_saati().is_some(), | ||
| 176 | + counts_toward_karne: policy.counts_toward_karne, | ||
| 177 | + counts_toward_karne_overridden: instance.counts_toward_karne().is_some(), | ||
| 178 | + subjects_inherited: instance.subjects_inherited(), | ||
| 179 | + subjects, | ||
| 180 | + exam_weights_inherited, | ||
| 181 | + exam_weights, | ||
| 182 | + weekly_plan_inherited: instance.weekly_plan_inherited(), | ||
| 183 | + weekly_plan, | ||
| 184 | + }) | ||
| 185 | +} | ||
src/service/karne.rsmodified+94 -35
| @@ -6,8 +6,10 @@ | |||
| 6 | //! average takes a label from the school's grade bands; and the term's own | 6 | //! average takes a label from the school's grade bands; and the term's own |
| 7 | //! number is a single average over the instances, each weighted by its | 7 | //! number is a single average over the instances, each weighted by its |
| 8 | //! `ders_saati` (the report-card weight the section set on the instance). The | 8 | //! `ders_saati` (the report-card weight the section set on the instance). The |
| 9 | -//! catalog's `course` row contributes only its title — the two class sections | 9 | +//! title a line shows is the instance's **resolved** one (override → offering |
| 10 | -//! teaching it are their own instances and their own report-card lines. | 10 | +//! → catalog, via [`crate::service::instance_resolve`]) — two class sections |
| 11 | +//! teaching the same catalog course are their own instances and their own | ||
| 12 | +//! report-card lines. | ||
| 11 | //! | 13 | //! |
| 12 | //! A line's marks are the exams *addressed to* its instance | 14 | //! A line's marks are the exams *addressed to* its instance |
| 13 | //! (`exam_audience`), not only the ones it owns: a shared exam announced to | 15 | //! (`exam_audience`), not only the ones it owns: a shared exam announced to |
| @@ -36,7 +38,8 @@ use crate::error::AppError; | |||
| 36 | 38 | ||
| 37 | /// One instance's line on a report card: the average of the marks the student | 39 | /// One instance's line on a report card: the average of the marks the student |
| 38 | /// holds in it this term, its band label, and the `ders_saati` it weighs into | 40 | /// holds in it this term, its band label, and the `ders_saati` it weighs into |
| 39 | -/// the year average with. `course` is the catalog course's title (what a | 41 | +/// the year average with. `course` is the instance's **resolved** title — its |
| 42 | +/// section's override, else its offering's, else the catalog course's (what a | ||
| 40 | /// family reads); `class_course` is the instance itself, for anything that | 43 | /// family reads); `class_course` is the instance itself, for anything that |
| 41 | /// must act on the line. | 44 | /// must act on the line. |
| 42 | #[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)] | 45 | #[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)] |
| @@ -150,14 +153,22 @@ async fn compute(db: &Database, user: &UserId, term: &Term) -> Result<KarneRepor | |||
| 150 | .map(|class| class.get_id().clone()) | 153 | .map(|class| class.get_id().clone()) |
| 151 | .collect(); | 154 | .collect(); |
| 152 | 155 | ||
| 153 | - let instances: Vec<crate::domain::class_course::ClassCourse> = | 156 | + // The report-card-counting instances, each with its **resolved** policy: |
| 154 | - crate::db::class_course::list_for_class_ids(db, &class_ids) | 157 | + // `counts_toward_karne` is nullable now (NULL = inherit the offering's |
| 155 | - .await? | 158 | + // default, else counted), so the filter and the weights both go through |
| 156 | - .into_iter() | 159 | + // the resolver — a raw read would treat "not decided" as a decision. |
| 157 | - .filter(|instance| instance.counts_toward_karne()) | 160 | + let mut counted: Vec<( |
| 158 | - .collect(); | 161 | + crate::domain::class_course::ClassCourse, |
| 162 | + crate::service::class_course::InstancePolicy, | ||
| 163 | + )> = Vec::new(); | ||
| 164 | + for instance in crate::db::class_course::list_for_class_ids(db, &class_ids).await? { | ||
| 165 | + let policy = crate::service::class_course::resolve_policy(db, &instance).await?; | ||
| 166 | + if policy.counts_toward_karne { | ||
| 167 | + counted.push((instance, policy)); | ||
| 168 | + } | ||
| 169 | + } | ||
| 159 | let instance_ids: Vec<crate::domain::class_course::ClassCourseId> = | 170 | let instance_ids: Vec<crate::domain::class_course::ClassCourseId> = |
| 160 | - instances.iter().map(|i| i.get_id().clone()).collect(); | 171 | + counted.iter().map(|(i, _)| i.get_id().clone()).collect(); |
| 161 | 172 | ||
| 162 | // The term's exams inside those instances, plus this student's marks on | 173 | // The term's exams inside those instances, plus this student's marks on |
| 163 | // them. An exam another term owns is not this report card's to weigh. | 174 | // 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<KarneRepor | |||
| 178 | crate::db::exam_result::list_for_user_in_term(db, user, term.get_id(), &instance_ids) | 189 | crate::db::exam_result::list_for_user_in_term(db, user, term.get_id(), &instance_ids) |
| 179 | .await?; | 190 | .await?; |
| 180 | 191 | ||
| 181 | - // Titles for the lines: one batch read for the whole report. | 192 | + // Titles for the lines: the sections' **resolved** titles (override → |
| 182 | - let course_ids: Vec<crate::domain::course::CourseId> = | 193 | + // offering → catalog), batched — one offering read + one catalog read |
| 183 | - instances.iter().map(|i| i.get_course().clone()).collect(); | 194 | + // for the whole report. |
| 184 | - let courses = crate::db::course::list_by_ids(db, &course_ids).await?; | 195 | + let line_refs: Vec<&crate::domain::class_course::ClassCourse> = |
| 185 | - let titles: HashMap<String, String> = courses | 196 | + counted.iter().map(|(i, _)| i).collect(); |
| 186 | - .iter() | 197 | + let titles = crate::service::instance_resolve::resolved_content(db, &line_refs).await?; |
| 187 | - .map(|course| { | ||
| 188 | - ( | ||
| 189 | - course.get_id().key(), | ||
| 190 | - course.get_title().as_str().to_string(), | ||
| 191 | - ) | ||
| 192 | - }) | ||
| 193 | - .collect(); | ||
| 194 | 198 | ||
| 195 | - let mut lines = Vec::with_capacity(instances.len()); | 199 | + let mut lines = Vec::with_capacity(counted.len()); |
| 196 | let mut weighted: Vec<(f64, i64)> = Vec::new(); | 200 | let mut weighted: Vec<(f64, i64)> = Vec::new(); |
| 197 | - for instance in &instances { | 201 | + for (instance, policy) in &counted { |
| 198 | let mut pairs: Vec<(i64, i64)> = Vec::new(); | 202 | let mut pairs: Vec<(i64, i64)> = Vec::new(); |
| 203 | + // The section's weight chain answer per kind, computed once — every | ||
| 204 | + // mark of a kind weighs the same inside one line. | ||
| 205 | + let mut line_weights: HashMap<String, i64> = HashMap::new(); | ||
| 199 | for (line, result) in &results { | 206 | for (line, result) in &results { |
| 200 | // Every mark the read attributed to another instance stays out of | 207 | // Every mark the read attributed to another instance stays out of |
| 201 | // this line; one line's marks are exactly those addressed under it. | 208 | // 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<KarneRepor | |||
| 207 | // term's exam that is no longer there): not this line's. | 214 | // term's exam that is no longer there): not this line's. |
| 208 | continue; | 215 | continue; |
| 209 | }; | 216 | }; |
| 210 | - // The kind's current settings weight; an exam keeps a retired | 217 | + // The kind's weight *in this section*: the section's own |
| 211 | - // kind, and its marks then count once. | 218 | + // override, else the offering's, else the settings weight, else 1 |
| 212 | - let weight = school | 219 | + // — a retired kind keeps counting once, an own set in force is |
| 213 | - .exam_kind_weight(exam.get_kind().as_str()) | 220 | + // the whole answer, empty included. |
| 214 | - .unwrap_or(1); | 221 | + let kind = exam.get_kind().as_str(); |
| 222 | + let weight = match line_weights.get(kind) { | ||
| 223 | + Some(weight) => *weight, | ||
| 224 | + None => { | ||
| 225 | + let weight = | ||
| 226 | + crate::service::exam_weight::resolve(db, instance, kind).await?; | ||
| 227 | + line_weights.insert(kind.to_string(), weight); | ||
| 228 | + weight | ||
| 229 | + } | ||
| 230 | + }; | ||
| 215 | pairs.push((result.get_mark().as_i64(), weight)); | 231 | pairs.push((result.get_mark().as_i64(), weight)); |
| 216 | } | 232 | } |
| 217 | let average = weighted_average(&pairs); | 233 | let average = weighted_average(&pairs); |
| 218 | if let Some(average) = average { | 234 | if let Some(average) = average { |
| 219 | - weighted.push((average, instance.get_ders_saati().as_i64())); | 235 | + weighted.push((average, policy.ders_saati.as_i64())); |
| 220 | } | 236 | } |
| 221 | lines.push(KarneInstance { | 237 | lines.push(KarneInstance { |
| 222 | class_course: instance.get_id().key(), | 238 | class_course: instance.get_id().key(), |
| 239 | + // The resolved display title: the section's override, else its | ||
| 240 | + // offering's, else the catalog's — never the bare catalog row. | ||
| 223 | course: titles | 241 | course: titles |
| 224 | - .get(instance.get_course().key().as_str()) | 242 | + .get(instance.get_id().key().as_str()) |
| 225 | - .cloned() | 243 | + .map(|content| content.title.clone()) |
| 226 | .unwrap_or_default(), | 244 | .unwrap_or_default(), |
| 227 | - ders_saati: instance.get_ders_saati().as_i64(), | 245 | + ders_saati: policy.ders_saati.as_i64(), |
| 228 | band: average.and_then(|average| school.grade_label(average).map(str::to_string)), | 246 | band: average.and_then(|average| school.grade_label(average).map(str::to_string)), |
| 229 | average, | 247 | average, |
| 230 | }); | 248 | }); |
| @@ -321,7 +339,7 @@ mod tests { | |||
| 321 | }; | 339 | }; |
| 322 | 340 | ||
| 323 | // The owner sits both exams; the addressed instance only the shared | 341 | // The owner sits both exams; the addressed instance only the shared |
| 324 | - // one. Both kinds are `yazili`, whose default weight is 1. | 342 | + // one. Both kinds (`yazili`, `sozlu`) weigh 1 in the default settings. |
| 325 | let owner = line(&fixture.owner); | 343 | let owner = line(&fixture.owner); |
| 326 | assert_eq!( | 344 | assert_eq!( |
| 327 | owner.average, | 345 | owner.average, |
| @@ -350,4 +368,45 @@ mod tests { | |||
| 350 | "75 clears the floor" | 368 | "75 clears the floor" |
| 351 | ); | 369 | ); |
| 352 | } | 370 | } |
| 371 | + | ||
| 372 | + /// A class-level weight moves the average: with the owner section's own | ||
| 373 | + /// set in force (`yazili` = 2), its ortak mark counts double — | ||
| 374 | + /// (85×2 + 45×1) / 3 — while the sibling section, still inheriting, keeps | ||
| 375 | + /// the plain settings weight and its plain mean. Read off the settings | ||
| 376 | + /// singleton both lines would have stayed at 65 and 85. | ||
| 377 | + #[tokio::test] | ||
| 378 | + async fn a_class_level_weight_changes_the_karne_average() { | ||
| 379 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 380 | + let fixture = crate::db::exam_result::tests::an_ortak_exam_karne(&db).await; | ||
| 381 | + | ||
| 382 | + let owner = crate::service::class_course::read(&db, &fixture.owner) | ||
| 383 | + .await | ||
| 384 | + .unwrap() | ||
| 385 | + .unwrap(); | ||
| 386 | + crate::service::exam_weight::set_for_class(&db, owner.get_id(), "yazili", 2) | ||
| 387 | + .await | ||
| 388 | + .unwrap(); | ||
| 389 | + | ||
| 390 | + let report = build(&db, &fixture.student, &fixture.term).await.unwrap(); | ||
| 391 | + let line = |instance: &crate::domain::class_course::ClassCourseId| { | ||
| 392 | + report | ||
| 393 | + .instances | ||
| 394 | + .iter() | ||
| 395 | + .find(|line| line.class_course == instance.key()) | ||
| 396 | + .unwrap_or_else(|| panic!("no line for {}", instance.key())) | ||
| 397 | + }; | ||
| 398 | + | ||
| 399 | + assert_eq!( | ||
| 400 | + line(&fixture.owner).average, | ||
| 401 | + Some((2.0 * crate::db::exam_result::tests::ORTAK_MARK as f64 | ||
| 402 | + + crate::db::exam_result::tests::OWNER_MARK as f64) | ||
| 403 | + / 3.0), | ||
| 404 | + "the ortak mark counts double under the section's own weight" | ||
| 405 | + ); | ||
| 406 | + assert_eq!( | ||
| 407 | + line(&fixture.addressed).average, | ||
| 408 | + Some(crate::db::exam_result::tests::ORTAK_MARK as f64), | ||
| 409 | + "the sibling still inherits — a class weight never leaks across sections" | ||
| 410 | + ); | ||
| 411 | + } | ||
| 353 | } | 412 | } |
src/service/mod.rsmodified+5 -0
| @@ -20,6 +20,7 @@ pub mod class_member; | |||
| 20 | pub mod course; | 20 | pub mod course; |
| 21 | pub mod course_note; | 21 | pub mod course_note; |
| 22 | pub mod course_note_file; | 22 | pub mod course_note_file; |
| 23 | +pub mod course_offering; | ||
| 23 | pub mod course_session; | 24 | pub mod course_session; |
| 24 | pub mod dietary_profile; | 25 | pub mod dietary_profile; |
| 25 | pub mod enrollment; | 26 | pub mod enrollment; |
| @@ -29,6 +30,7 @@ pub mod exam_answer; | |||
| 29 | pub mod exam_attempt; | 30 | pub mod exam_attempt; |
| 30 | pub mod exam_question; | 31 | pub mod exam_question; |
| 31 | pub mod exam_result; | 32 | pub mod exam_result; |
| 33 | +pub mod exam_weight; | ||
| 32 | pub mod fee_plan; | 34 | pub mod fee_plan; |
| 33 | pub mod fee_plan_assignment; | 35 | pub mod fee_plan_assignment; |
| 34 | pub mod homework; | 36 | pub mod homework; |
| @@ -36,6 +38,7 @@ pub mod homework_file; | |||
| 36 | pub mod homework_result; | 38 | pub mod homework_result; |
| 37 | pub mod homework_submission; | 39 | pub mod homework_submission; |
| 38 | pub mod instance; | 40 | pub mod instance; |
| 41 | +pub mod instance_resolve; | ||
| 39 | pub mod karne; | 42 | pub mod karne; |
| 40 | pub mod meal_attendance; | 43 | pub mod meal_attendance; |
| 41 | pub mod meal_booking; | 44 | pub mod meal_booking; |
| @@ -44,6 +47,7 @@ pub mod menu; | |||
| 44 | pub mod message; | 47 | pub mod message; |
| 45 | pub mod note; | 48 | pub mod note; |
| 46 | pub mod note_file; | 49 | pub mod note_file; |
| 50 | +pub mod offering_subject; | ||
| 47 | pub mod parent_link; | 51 | pub mod parent_link; |
| 48 | pub mod payment_ledger; | 52 | pub mod payment_ledger; |
| 49 | pub mod person; | 53 | pub mod person; |
| @@ -66,4 +70,5 @@ pub mod solution_image; | |||
| 66 | pub mod subject; | 70 | pub mod subject; |
| 67 | pub mod term; | 71 | pub mod term; |
| 68 | pub mod user; | 72 | pub mod user; |
| 73 | +pub mod weekly_slot; | ||
| 69 | pub mod work_entry; | 74 | pub mod work_entry; |
src/service/offering_subject.rsadded+470 -0
| @@ -0,0 +1,470 @@ | |||
| 1 | +//! Syllabus selection workflows: the offering's topic set (a manager curates | ||
| 2 | +//! the grade's template) and the section's own override of it, plus the two | ||
| 3 | +//! resolvers the read surfaces and the tag-validation rewire ride on. The SQL | ||
| 4 | +//! lives in [`crate::db::offering_subject`]; the one pure rule — a selection | ||
| 5 | +//! names a subject of the offering's own course — in | ||
| 6 | +//! [`crate::domain::offering_subject`]. | ||
| 7 | +//! | ||
| 8 | +//! Resolution is override-or-inherit, never merge, and flag-driven: | ||
| 9 | +//! `subjects_inherited` TRUE → the offering's set, FALSE → the section's own | ||
| 10 | +//! rows **even when that set is empty**. Every class-side write door here | ||
| 11 | +//! flips the flag in the same statement as its row change (the CTEs in the | ||
| 12 | +//! db module), so the flag can never describe a stale set; this module never | ||
| 13 | +//! writes `class_course` itself. | ||
| 14 | + | ||
| 15 | +use crate::database::Database; | ||
| 16 | +use crate::domain::class_course::ClassCourse; | ||
| 17 | +use crate::domain::course::CourseId; | ||
| 18 | +use crate::domain::course_offering::CourseOfferingId; | ||
| 19 | +use crate::domain::offering_subject::ensure_course_member; | ||
| 20 | +use crate::domain::subject::{Subject, SubjectId}; | ||
| 21 | +use crate::error::{AppError, ValidationError}; | ||
| 22 | +use crate::{db, service}; | ||
| 23 | + | ||
| 24 | +/// The topics the grade-level template selects, name-then-id order — the | ||
| 25 | +/// inheritance side of [`resolved_for_instance`]. | ||
| 26 | +pub async fn resolved_for_offering( | ||
| 27 | + db: &Database, | ||
| 28 | + offering: &CourseOfferingId, | ||
| 29 | +) -> Result<Vec<Subject>, AppError> { | ||
| 30 | + db::offering_subject::list_for_offering(db, offering).await | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/// The topics this section teaches, resolved override-or-inherit: its own | ||
| 34 | +/// rows while `subjects_inherited` is FALSE (including an empty set — a | ||
| 35 | +/// section may clear its syllabus), otherwise the offering's set. | ||
| 36 | +pub async fn resolved_for_instance( | ||
| 37 | + db: &Database, | ||
| 38 | + instance: &ClassCourse, | ||
| 39 | +) -> Result<Vec<Subject>, AppError> { | ||
| 40 | + if instance.subjects_inherited() { | ||
| 41 | + resolved_for_offering(db, instance.get_offering()).await | ||
| 42 | + } else { | ||
| 43 | + db::offering_subject::list_for_class_course(db, instance.get_id()).await | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// A 400 unless `subject` sits in what the section *teaches* — the resolved | ||
| 48 | +/// set, not the bare course. This is the half of the tag check the | ||
| 49 | +/// exam-question and homework writers now pay in addition to | ||
| 50 | +/// [`service::subject::in_course`](crate::service::subject::in_course): | ||
| 51 | +/// a subject of the right course can still be off the syllabus. | ||
| 52 | +pub async fn ensure_resolved_member( | ||
| 53 | + db: &Database, | ||
| 54 | + instance: &ClassCourse, | ||
| 55 | + subject: &SubjectId, | ||
| 56 | +) -> Result<(), AppError> { | ||
| 57 | + match db::offering_subject::resolves_for_class_course(db, instance.get_id(), subject).await? { | ||
| 58 | + Some(true) => Ok(()), | ||
| 59 | + Some(false) => Err(ValidationError::Invalid { | ||
| 60 | + field: "subject_id", | ||
| 61 | + reason: "subject is not in this section's subject set", | ||
| 62 | + } | ||
| 63 | + .into()), | ||
| 64 | + // The section vanished between the handler's read and this probe; | ||
| 65 | + // that is a 404, not a validation miss. | ||
| 66 | + None => Err(AppError::NotFound), | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// The request's subject as a validated selection candidate: it exists, and | ||
| 71 | +/// it belongs to `course` — the exact two 400s the tag-time check answers, | ||
| 72 | +/// reused so a refused selection and a refused tag read identically. | ||
| 73 | +async fn subject_of_course( | ||
| 74 | + db: &Database, | ||
| 75 | + key: &str, | ||
| 76 | + course: &CourseId, | ||
| 77 | +) -> Result<Subject, AppError> { | ||
| 78 | + let subject = db::subject::read(db, &SubjectId::from_key(key)) | ||
| 79 | + .await? | ||
| 80 | + .ok_or(ValidationError::Invalid { | ||
| 81 | + field: "subject_id", | ||
| 82 | + reason: "subject does not exist", | ||
| 83 | + })?; | ||
| 84 | + ensure_course_member(&subject, course)?; | ||
| 85 | + Ok(subject) | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// Select a topic for the offering. Manager-only at the route. Answers the | ||
| 89 | +/// subject and whether this call added it — re-adding a selection is a no-op | ||
| 90 | +/// success (`added` = false). | ||
| 91 | +pub async fn add_to_offering( | ||
| 92 | + db: &Database, | ||
| 93 | + offering: &CourseOfferingId, | ||
| 94 | + subject_key: &str, | ||
| 95 | +) -> Result<(Subject, bool), AppError> { | ||
| 96 | + let offering = service::course_offering::read(db, offering) | ||
| 97 | + .await? | ||
| 98 | + .ok_or(AppError::NotFound)?; | ||
| 99 | + let subject = subject_of_course(db, subject_key, offering.get_course()).await?; | ||
| 100 | + let added = db::offering_subject::add_for_offering(db, offering.get_id(), subject.get_id()) | ||
| 101 | + .await?; | ||
| 102 | + Ok((subject, added)) | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// Drop a topic from the offering's selection. A subject the offering never | ||
| 106 | +/// selected is a 404. | ||
| 107 | +pub async fn remove_from_offering( | ||
| 108 | + db: &Database, | ||
| 109 | + offering: &CourseOfferingId, | ||
| 110 | + subject_key: &str, | ||
| 111 | +) -> Result<(), AppError> { | ||
| 112 | + let offering = service::course_offering::read(db, offering) | ||
| 113 | + .await? | ||
| 114 | + .ok_or(AppError::NotFound)?; | ||
| 115 | + let dropped = | ||
| 116 | + db::offering_subject::remove_for_offering(db, offering.get_id(), &SubjectId::from_key(subject_key)) | ||
| 117 | + .await?; | ||
| 118 | + if !dropped { | ||
| 119 | + return Err(AppError::NotFound); | ||
| 120 | + } | ||
| 121 | + Ok(()) | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// Select a topic for the section's own set — the override: the CTE in the | ||
| 125 | +/// db module flips `subjects_inherited` to FALSE in the same statement, so | ||
| 126 | +/// from this call on the section's own table (not the offering's) is | ||
| 127 | +/// authoritative. Idempotent: re-adding is a no-op success (`added` = false). | ||
| 128 | +pub async fn add_to_instance( | ||
| 129 | + db: &Database, | ||
| 130 | + instance: &ClassCourse, | ||
| 131 | + subject_key: &str, | ||
| 132 | +) -> Result<(Subject, bool), AppError> { | ||
| 133 | + let subject = subject_of_course(db, subject_key, instance.get_course()).await?; | ||
| 134 | + let (live, added) = | ||
| 135 | + db::offering_subject::add_for_class_course(db, instance.get_id(), subject.get_id()) | ||
| 136 | + .await?; | ||
| 137 | + if !live { | ||
| 138 | + // The section was detached between the handler's gate and this write. | ||
| 139 | + return Err(AppError::NotFound); | ||
| 140 | + } | ||
| 141 | + Ok((subject, added)) | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +/// Drop a topic from the section's own set (flagging the set as its own in | ||
| 145 | +/// the same statement, when a row actually went). A subject the section | ||
| 146 | +/// never selected is a 404 — including while inheriting, where it must not | ||
| 147 | +/// silently start an override. | ||
| 148 | +pub async fn remove_from_instance( | ||
| 149 | + db: &Database, | ||
| 150 | + instance: &ClassCourse, | ||
| 151 | + subject_key: &str, | ||
| 152 | +) -> Result<(), AppError> { | ||
| 153 | + let (live, dropped) = db::offering_subject::remove_for_class_course( | ||
| 154 | + db, | ||
| 155 | + instance.get_id(), | ||
| 156 | + &SubjectId::from_key(subject_key), | ||
| 157 | + ) | ||
| 158 | + .await?; | ||
| 159 | + if !live || !dropped { | ||
| 160 | + return Err(AppError::NotFound); | ||
| 161 | + } | ||
| 162 | + Ok(()) | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +/// The section's reset door: sweep its own rows and restore inheritance — | ||
| 166 | +/// the flag goes back to TRUE in the same statement that sweeps. Answers the | ||
| 167 | +/// number of rows the sweep removed (0 is a fine answer: clearing an empty | ||
| 168 | +/// own set is exactly the request that must re-inherit). | ||
| 169 | +pub async fn reset_instance(db: &Database, instance: &ClassCourse) -> Result<i64, AppError> { | ||
| 170 | + let (swept, live) = db::offering_subject::reset_for_class_course(db, instance.get_id()).await?; | ||
| 171 | + if !live { | ||
| 172 | + return Err(AppError::NotFound); | ||
| 173 | + } | ||
| 174 | + Ok(swept) | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +/// Parse a path segment as a subject key — the nil-uuid trick the repo's | ||
| 178 | +/// other id keys use: a malformed segment matches no row and reads as a 404. | ||
| 179 | +/// Kept next to the doors so callers need no domain imports for it. | ||
| 180 | +pub fn subject_key(key: &str) -> SubjectId { | ||
| 181 | + SubjectId::from_key(key) | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +#[cfg(test)] | ||
| 185 | +mod tests { | ||
| 186 | + use super::*; | ||
| 187 | + use crate::database::init_test_db; | ||
| 188 | + use crate::db::course::a_test_instance; | ||
| 189 | + use crate::db::subject as subject_rows; | ||
| 190 | + use crate::domain::subject::{SubjectDescription, SubjectName}; | ||
| 191 | + | ||
| 192 | + async fn a_topic(db: &Database, course: &CourseId, name: &str) -> Subject { | ||
| 193 | + subject_rows::create( | ||
| 194 | + db, | ||
| 195 | + course, | ||
| 196 | + SubjectName::try_new(name).unwrap(), | ||
| 197 | + SubjectDescription::try_new("").unwrap(), | ||
| 198 | + ) | ||
| 199 | + .await | ||
| 200 | + .unwrap() | ||
| 201 | + } | ||
| 202 | + | ||
| 203 | + /// A live instance row for a freshly attached course: inheriting by | ||
| 204 | + /// default, offering auto-minted for the same course. | ||
| 205 | + async fn an_instance(db: &Database) -> (ClassCourse, CourseId) { | ||
| 206 | + let (instance, course) = a_test_instance(db).await; | ||
| 207 | + let row = service::class_course::read(db, &instance) | ||
| 208 | + .await | ||
| 209 | + .unwrap() | ||
| 210 | + .unwrap(); | ||
| 211 | + (row, course) | ||
| 212 | + } | ||
| 213 | + | ||
| 214 | + fn names(subjects: &[Subject]) -> Vec<&str> { | ||
| 215 | + subjects | ||
| 216 | + .iter() | ||
| 217 | + .map(|s| s.get_name().as_str()) | ||
| 218 | + .collect::<Vec<_>>() | ||
| 219 | + } | ||
| 220 | + | ||
| 221 | + /// Inheritance: with the flag at its attach-time TRUE and no own rows, | ||
| 222 | + /// the section resolves to exactly the offering's set, in name order — | ||
| 223 | + /// Alpha before Zeta although Zeta was created first, so dropping the | ||
| 224 | + /// ORDER BY fails this. | ||
| 225 | + #[tokio::test] | ||
| 226 | + async fn an_inheriting_section_resolves_the_offerings_set_in_name_order() { | ||
| 227 | + let (db, _leases) = init_test_db().await; | ||
| 228 | + let (instance, course) = an_instance(&db).await; | ||
| 229 | + let zeta = a_topic(&db, &course, "Zeta").await; | ||
| 230 | + let alpha = a_topic(&db, &course, "Alpha").await; | ||
| 231 | + for subject in [&zeta, &alpha] { | ||
| 232 | + db::offering_subject::add_for_offering( | ||
| 233 | + &db, | ||
| 234 | + instance.get_offering(), | ||
| 235 | + subject.get_id(), | ||
| 236 | + ) | ||
| 237 | + .await | ||
| 238 | + .unwrap(); | ||
| 239 | + } | ||
| 240 | + | ||
| 241 | + assert!(instance.subjects_inherited()); | ||
| 242 | + let resolved = resolved_for_instance(&db, &instance).await.unwrap(); | ||
| 243 | + assert_eq!(names(&resolved), vec!["Alpha", "Zeta"]); | ||
| 244 | + // The offering-side resolver agrees — one chain, two doors. | ||
| 245 | + let offering = resolved_for_offering(&db, instance.get_offering()) | ||
| 246 | + .await | ||
| 247 | + .unwrap(); | ||
| 248 | + assert_eq!(names(&offering), vec!["Alpha", "Zeta"]); | ||
| 249 | + } | ||
| 250 | + | ||
| 251 | + /// Own-set-wins, including when empty: one add flips the flag and the | ||
| 252 | + /// section resolves to its own table; after removing the only own row the | ||
| 253 | + /// flag is still FALSE and the resolved set is *empty* — the offering's | ||
| 254 | + /// topics must NOT bleed back in, or "clear the syllabus" would be | ||
| 255 | + /// impossible. | ||
| 256 | + #[tokio::test] | ||
| 257 | + async fn an_owned_set_wins_even_when_it_is_empty() { | ||
| 258 | + let (db, _leases) = init_test_db().await; | ||
| 259 | + let (instance, course) = an_instance(&db).await; | ||
| 260 | + let offering_topic = a_topic(&db, &course, "Offering-only").await; | ||
| 261 | + db::offering_subject::add_for_offering( | ||
| 262 | + &db, | ||
| 263 | + instance.get_offering(), | ||
| 264 | + offering_topic.get_id(), | ||
| 265 | + ) | ||
| 266 | + .await | ||
| 267 | + .unwrap(); | ||
| 268 | + let own = a_topic(&db, &course, "Own").await; | ||
| 269 | + | ||
| 270 | + let (_, added) = add_to_instance(&db, &instance, &own.get_id().key()) | ||
| 271 | + .await | ||
| 272 | + .unwrap(); | ||
| 273 | + assert!(added); | ||
| 274 | + | ||
| 275 | + let owned = service::class_course::read(&db, instance.get_id()) | ||
| 276 | + .await | ||
| 277 | + .unwrap() | ||
| 278 | + .unwrap(); | ||
| 279 | + assert!(!owned.subjects_inherited(), "the add must flip the flag"); | ||
| 280 | + assert_eq!( | ||
| 281 | + names(&resolved_for_instance(&db, &owned).await.unwrap()), | ||
| 282 | + vec!["Own"] | ||
| 283 | + ); | ||
| 284 | + | ||
| 285 | + remove_from_instance(&db, &owned, &own.get_id().key()) | ||
| 286 | + .await | ||
| 287 | + .unwrap(); | ||
| 288 | + let cleared = service::class_course::read(&db, instance.get_id()) | ||
| 289 | + .await | ||
| 290 | + .unwrap() | ||
| 291 | + .unwrap(); | ||
| 292 | + assert!( | ||
| 293 | + !cleared.subjects_inherited(), | ||
| 294 | + "a plain row delete must not restore inheritance" | ||
| 295 | + ); | ||
| 296 | + assert!(resolved_for_instance(&db, &cleared).await.unwrap().is_empty()); | ||
| 297 | + } | ||
| 298 | + | ||
| 299 | + /// The membership precondition at both doors: a subject of *another* | ||
| 300 | + /// course is a 400 with the tag-check's exact reason, writes no row, and | ||
| 301 | + /// leaves the flag alone. Break `ensure_course_member` (or wire a door | ||
| 302 | + /// past it) and the asserts on the error and the row counts fail. | ||
| 303 | + #[tokio::test] | ||
| 304 | + async fn a_foreign_course_subject_is_refused_at_both_doors() { | ||
| 305 | + let (db, _leases) = init_test_db().await; | ||
| 306 | + let (instance, _course) = an_instance(&db).await; | ||
| 307 | + let (foreign_instance, foreign_course) = an_instance(&db).await; | ||
| 308 | + let stranger = a_topic(&db, &foreign_course, "Stranger").await; | ||
| 309 | + | ||
| 310 | + for door in [ | ||
| 311 | + add_to_offering(&db, instance.get_offering(), &stranger.get_id().key()).await, | ||
| 312 | + add_to_instance(&db, &instance, &stranger.get_id().key()).await, | ||
| 313 | + ] { | ||
| 314 | + let err = door.unwrap_err(); | ||
| 315 | + assert!( | ||
| 316 | + matches!(err, AppError::Validation(_)), | ||
| 317 | + "expected the 400 validation refusal, got {err:?}" | ||
| 318 | + ); | ||
| 319 | + assert_eq!( | ||
| 320 | + err.to_string(), | ||
| 321 | + "subject_id: subject belongs to a different course" | ||
| 322 | + ); | ||
| 323 | + } | ||
| 324 | + | ||
| 325 | + // Nothing landed anywhere, and the section still inherits. | ||
| 326 | + assert!(resolved_for_offering(&db, instance.get_offering()) | ||
| 327 | + .await | ||
| 328 | + .unwrap() | ||
| 329 | + .is_empty()); | ||
| 330 | + assert!(resolved_for_offering(&db, foreign_instance.get_offering()) | ||
| 331 | + .await | ||
| 332 | + .unwrap() | ||
| 333 | + .is_empty()); | ||
| 334 | + assert!(db::offering_subject::list_for_class_course(&db, instance.get_id()) | ||
| 335 | + .await | ||
| 336 | + .unwrap() | ||
| 337 | + .is_empty()); | ||
| 338 | + assert!(instance.subjects_inherited()); | ||
| 339 | + } | ||
| 340 | + | ||
| 341 | + /// The reset door: after an own selection, reset sweeps the rows and | ||
| 342 | + /// flips the flag back to TRUE in the same statement — the offering's set | ||
| 343 | + /// applies again, and a second reset stays green (idempotent). | ||
| 344 | + #[tokio::test] | ||
| 345 | + async fn a_reset_restores_inheritance() { | ||
| 346 | + let (db, _leases) = init_test_db().await; | ||
| 347 | + let (instance, course) = an_instance(&db).await; | ||
| 348 | + let offering_topic = a_topic(&db, &course, "Template").await; | ||
| 349 | + db::offering_subject::add_for_offering( | ||
| 350 | + &db, | ||
| 351 | + instance.get_offering(), | ||
| 352 | + offering_topic.get_id(), | ||
| 353 | + ) | ||
| 354 | + .await | ||
| 355 | + .unwrap(); | ||
| 356 | + let own = a_topic(&db, &course, "Own").await; | ||
| 357 | + add_to_instance(&db, &instance, &own.get_id().key()) | ||
| 358 | + .await | ||
| 359 | + .unwrap(); | ||
| 360 | + | ||
| 361 | + let swept = reset_instance(&db, &instance).await.unwrap(); | ||
| 362 | + assert_eq!(swept, 1, "the one own row must be gone"); | ||
| 363 | + | ||
| 364 | + let restored = service::class_course::read(&db, instance.get_id()) | ||
| 365 | + .await | ||
| 366 | + .unwrap() | ||
| 367 | + .unwrap(); | ||
| 368 | + assert!(restored.subjects_inherited()); | ||
| 369 | + assert_eq!( | ||
| 370 | + names(&resolved_for_instance(&db, &restored).await.unwrap()), | ||
| 371 | + vec!["Template"] | ||
| 372 | + ); | ||
| 373 | + | ||
| 374 | + // Resetting a section that now holds nothing is still a clean 200-ish | ||
| 375 | + // success: the door is about the flag as much as the rows. | ||
| 376 | + assert_eq!(reset_instance(&db, &restored).await.unwrap(), 0); | ||
| 377 | + } | ||
| 378 | + | ||
| 379 | + /// Idempotent add: the second POST of the same selection succeeds without | ||
| 380 | + /// a second row — and the flag stays FALSE across both. A duplicate row | ||
| 381 | + /// (or a 409 on the repeat) fails the count/asserts. | ||
| 382 | + #[tokio::test] | ||
| 383 | + async fn re_adding_a_selection_is_a_no_op_success() { | ||
| 384 | + let (db, _leases) = init_test_db().await; | ||
| 385 | + let (instance, course) = an_instance(&db).await; | ||
| 386 | + let topic = a_topic(&db, &course, "Twice").await; | ||
| 387 | + | ||
| 388 | + let (first_subject, first_added) = | ||
| 389 | + add_to_instance(&db, &instance, &topic.get_id().key()).await.unwrap(); | ||
| 390 | + assert!(first_added); | ||
| 391 | + let (_, second_added) = | ||
| 392 | + add_to_instance(&db, &instance, &topic.get_id().key()).await.unwrap(); | ||
| 393 | + assert!(!second_added, "the repeat must be a no-op, not a second row"); | ||
| 394 | + | ||
| 395 | + assert_eq!(first_subject.get_id(), topic.get_id()); | ||
| 396 | + let own = db::offering_subject::list_for_class_course(&db, instance.get_id()) | ||
| 397 | + .await | ||
| 398 | + .unwrap(); | ||
| 399 | + assert_eq!(names(&own), vec!["Twice"]); | ||
| 400 | + | ||
| 401 | + // The offering door idempts the same way. | ||
| 402 | + let (_, offering_again) = | ||
| 403 | + add_to_offering(&db, instance.get_offering(), &topic.get_id().key()) | ||
| 404 | + .await | ||
| 405 | + .unwrap(); | ||
| 406 | + assert!(offering_again); | ||
| 407 | + let (_, offering_repeat) = | ||
| 408 | + add_to_offering(&db, instance.get_offering(), &topic.get_id().key()) | ||
| 409 | + .await | ||
| 410 | + .unwrap(); | ||
| 411 | + assert!(!offering_repeat); | ||
| 412 | + assert_eq!( | ||
| 413 | + names( | ||
| 414 | + &resolved_for_offering(&db, instance.get_offering()) | ||
| 415 | + .await | ||
| 416 | + .unwrap() | ||
| 417 | + ), | ||
| 418 | + vec!["Twice"] | ||
| 419 | + ); | ||
| 420 | + } | ||
| 421 | + | ||
| 422 | + /// The rewire's core: a same-course subject OFF the resolved set is | ||
| 423 | + /// refused by the tag gate, and accepted once the section selects it — | ||
| 424 | + /// while the plain course check (`service::subject::in_course`) would | ||
| 425 | + /// pass both. Whatever makes `ensure_resolved_member` a bare-course | ||
| 426 | + /// check again fails one of the two asserts. | ||
| 427 | + #[tokio::test] | ||
| 428 | + async fn the_tag_gate_checks_the_resolved_set_not_the_bare_course() { | ||
| 429 | + let (db, _leases) = init_test_db().await; | ||
| 430 | + let (instance, course) = an_instance(&db).await; | ||
| 431 | + let selected = a_topic(&db, &course, "Selected").await; | ||
| 432 | + let unselected = a_topic(&db, &course, "Unselected").await; | ||
| 433 | + db::offering_subject::add_for_offering( | ||
| 434 | + &db, | ||
| 435 | + instance.get_offering(), | ||
| 436 | + selected.get_id(), | ||
| 437 | + ) | ||
| 438 | + .await | ||
| 439 | + .unwrap(); | ||
| 440 | + | ||
| 441 | + // Inheriting: the offering's set is the syllabus. | ||
| 442 | + ensure_resolved_member(&db, &instance, selected.get_id()) | ||
| 443 | + .await | ||
| 444 | + .unwrap(); | ||
| 445 | + let err = ensure_resolved_member(&db, &instance, unselected.get_id()) | ||
| 446 | + .await | ||
| 447 | + .unwrap_err(); | ||
| 448 | + assert_eq!( | ||
| 449 | + err.to_string(), | ||
| 450 | + "subject_id: subject is not in this section's subject set" | ||
| 451 | + ); | ||
| 452 | + | ||
| 453 | + // Same subject, once the section owns it: accepted. The owned set is | ||
| 454 | + // authoritative *instead of* the offering's, so `selected` — in the | ||
| 455 | + // course, on the offering — is now OFF the syllabus. | ||
| 456 | + add_to_instance(&db, &instance, &unselected.get_id().key()) | ||
| 457 | + .await | ||
| 458 | + .unwrap(); | ||
| 459 | + ensure_resolved_member(&db, &instance, unselected.get_id()) | ||
| 460 | + .await | ||
| 461 | + .unwrap(); | ||
| 462 | + let err = ensure_resolved_member(&db, &instance, selected.get_id()) | ||
| 463 | + .await | ||
| 464 | + .unwrap_err(); | ||
| 465 | + assert_eq!( | ||
| 466 | + err.to_string(), | ||
| 467 | + "subject_id: subject is not in this section's subject set" | ||
| 468 | + ); | ||
| 469 | + } | ||
| 470 | +} | ||
src/service/rag_scope.rsmodified+23 -15
| @@ -132,17 +132,24 @@ pub async fn for_user( | |||
| 132 | let classes = crate::db::class_group::list_by_ids(db, &class_ids).await?; | 132 | let classes = crate::db::class_group::list_by_ids(db, &class_ids).await?; |
| 133 | let courses = crate::db::course::list_by_ids(db, &course_ids).await?; | 133 | let courses = crate::db::course::list_by_ids(db, &course_ids).await?; |
| 134 | 134 | ||
| 135 | - // Grade labels, keyed by class section. A class with no grade at all (a | 135 | + // Display labels, keyed by class section. Every section carries a ladder |
| 136 | - // club-shaped section, and the shape a fixture class carries) simply | 136 | + // rung now, so every class-keyed instance pairs with one; only the |
| 137 | - // contributes no entry, so its instances scope the subject across every | 137 | + // school-wide club/study memberships ride in with no grade at all (the |
| 138 | - // grade — the documented meaning of an absent `sinif`. | 138 | + // documented meaning of an absent `sinif`). |
| 139 | let grades: HashMap<String, String> = classes | 139 | let grades: HashMap<String, String> = classes |
| 140 | .iter() | 140 | .iter() |
| 141 | - .filter_map(|class| { | 141 | + .map(|class| (class.get_id().key(), class.get_grade_level().label().to_owned())) |
| 142 | - class | 142 | + .collect(); |
| 143 | - .get_grade() | 143 | + // The instances' **resolved** titles (override → offering → catalog): the |
| 144 | - .map(|grade| (class.get_id().key(), grade.as_str().to_owned())) | 144 | + // section's own grade content is what a scope pair names. Batched — one |
| 145 | - }) | 145 | + // offering read + one catalog read for the whole scope. The club/study |
| 146 | + // memberships below keep the catalog title: a school-wide course has no | ||
| 147 | + // offering, so the catalog row is the only label there is. | ||
| 148 | + let instance_refs: Vec<&ClassCourse> = instances.iter().collect(); | ||
| 149 | + let resolved = crate::service::instance_resolve::resolved_content(db, &instance_refs).await?; | ||
| 150 | + let ders_by_instance: HashMap<String, String> = resolved | ||
| 151 | + .into_iter() | ||
| 152 | + .map(|(key, content)| (key, content.title)) | ||
| 146 | .collect(); | 153 | .collect(); |
| 147 | let titles: HashMap<String, String> = courses | 154 | let titles: HashMap<String, String> = courses |
| 148 | .iter() | 155 | .iter() |
| @@ -152,10 +159,10 @@ pub async fn for_user( | |||
| 152 | let mut pairs: Vec<RagScopePair> = Vec::new(); | 159 | let mut pairs: Vec<RagScopePair> = Vec::new(); |
| 153 | let mut seen: HashSet<(Option<String>, String)> = HashSet::new(); | 160 | let mut seen: HashSet<(Option<String>, String)> = HashSet::new(); |
| 154 | for instance in &instances { | 161 | for instance in &instances { |
| 155 | - // A course row the batch read did not answer is unreachable — the | 162 | + // A title the batch read did not answer is unreachable — the |
| 156 | // instance's key is a foreign key — so the skip is a guard against a | 163 | // instance's key is a foreign key — so the skip is a guard against a |
| 157 | // dangling read, not a rule: a title-less pair could not be routed. | 164 | // dangling read, not a rule: a title-less pair could not be routed. |
| 158 | - let Some(ders) = titles.get(&instance.get_course().key()) else { | 165 | + let Some(ders) = ders_by_instance.get(instance.get_id().key().as_str()) else { |
| 159 | continue; | 166 | continue; |
| 160 | }; | 167 | }; |
| 161 | push_pair( | 168 | push_pair( |
| @@ -203,7 +210,8 @@ fn push_pair( | |||
| 203 | #[cfg(test)] | 210 | #[cfg(test)] |
| 204 | mod tests { | 211 | mod tests { |
| 205 | use super::*; | 212 | use super::*; |
| 206 | - use crate::domain::class_group::{ClassGrade, ClassGroupId, ClassName}; | 213 | + use crate::domain::class_group::{ClassGroupId, ClassName}; |
| 214 | + use crate::domain::grade::GradeLevel; | ||
| 207 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; | 215 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 208 | use crate::domain::user::Username; | 216 | use crate::domain::user::Username; |
| 209 | 217 | ||
| @@ -230,15 +238,15 @@ mod tests { | |||
| 230 | .unwrap() | 238 | .unwrap() |
| 231 | } | 239 | } |
| 232 | 240 | ||
| 233 | - /// A class section carrying a grade label — the half of every instance | 241 | + /// A class section at a chosen rung — the half of every instance pair |
| 234 | - /// pair, since `a_class` deliberately has none. | 242 | + /// that scopes by grade. |
| 235 | async fn graded_class(db: &Database, name: &str, grade: &str) -> ClassGroupId { | 243 | async fn graded_class(db: &Database, name: &str, grade: &str) -> ClassGroupId { |
| 236 | let office = crate::db::class_member::tests::fixture_user(db, "ragscope-office").await; | 244 | let office = crate::db::class_member::tests::fixture_user(db, "ragscope-office").await; |
| 237 | crate::service::class_group::create( | 245 | crate::service::class_group::create( |
| 238 | db, | 246 | db, |
| 239 | &office, | 247 | &office, |
| 240 | ClassName::try_new(name).unwrap(), | 248 | ClassName::try_new(name).unwrap(), |
| 241 | - Some(ClassGrade::try_new(grade).unwrap()), | 249 | + GradeLevel::new(grade.parse().unwrap()).unwrap(), |
| 242 | None, | 250 | None, |
| 243 | None, | 251 | None, |
| 244 | ) | 252 | ) |
src/service/subject.rsmodified+31 -5
| @@ -1,10 +1,14 @@ | |||
| 1 | -//! Subject workflows: the two id resolvers every question/homework tag goes | 1 | +//! Subject workflows: the id resolvers every question/homework tag goes |
| 2 | //! through — the same-course rule for curriculum content, existence-only for | 2 | //! through — the same-course rule for curriculum content, existence-only for |
| 3 | //! the bank's cross-course origin metadata — over the row writes in | 3 | //! the bank's cross-course origin metadata — over the row writes in |
| 4 | -//! [`crate::db::subject`]. | 4 | +//! [`crate::db::subject`]. Since the course-template system, the tag gate for |
| 5 | +//! instance-scoped content is [`in_instance`]: the same-course rule *plus* | ||
| 6 | +//! the section's resolved subject set (override-or-inherit), because a | ||
| 7 | +//! section teaches a selection of the course, not the whole course. | ||
| 5 | 8 | ||
| 6 | use crate::database::Database; | 9 | use crate::database::Database; |
| 7 | use crate::db::subject; | 10 | use crate::db::subject; |
| 11 | +use crate::domain::class_course::ClassCourse; | ||
| 8 | use crate::domain::course::CourseId; | 12 | use crate::domain::course::CourseId; |
| 9 | use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; | 13 | use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; |
| 10 | use crate::error::{AppError, ValidationError}; | 14 | use crate::error::{AppError, ValidationError}; |
| @@ -53,9 +57,12 @@ pub async fn delete(db: &Database, target: Subject) -> Result<Subject, AppError> | |||
| 53 | } | 57 | } |
| 54 | 58 | ||
| 55 | /// Turn a request-supplied subject id into a validated reference, provided the | 59 | /// Turn a request-supplied subject id into a validated reference, provided the |
| 56 | -/// subject belongs to `course` — a question may only be tagged with a subject | 60 | +/// subject belongs to `course`. The *course half* of the instance tag gate — |
| 57 | -/// of its own exam's course. Unknown or foreign subjects are a `400` naming | 61 | +/// a question may only be tagged with a subject of its own exam's course. |
| 58 | -/// the field. Shared by the question create/update handlers. | 62 | +/// Instance-scoped writers use [`in_instance`], which adds the section's |
| 63 | +/// resolved subject set on top; this fn stays for the callers that have only | ||
| 64 | +/// the course at hand. Unknown or foreign subjects are a `400` naming the | ||
| 65 | +/// field. Shared by the question create/update handlers. | ||
| 59 | pub async fn in_course(db: &Database, id: &str, course: &CourseId) -> Result<SubjectId, AppError> { | 66 | pub async fn in_course(db: &Database, id: &str, course: &CourseId) -> Result<SubjectId, AppError> { |
| 60 | let subject = | 67 | let subject = |
| 61 | subject::read(db, &SubjectId::from_key(id)) | 68 | subject::read(db, &SubjectId::from_key(id)) |
| @@ -73,6 +80,25 @@ pub async fn in_course(db: &Database, id: &str, course: &CourseId) -> Result<Sub | |||
| 73 | Ok(*subject.get_id()) | 80 | Ok(*subject.get_id()) |
| 74 | } | 81 | } |
| 75 | 82 | ||
| 83 | +/// The instance-scoped tag gate: the same two 400s [`in_course`] answers for | ||
| 84 | +/// the instance's course — same order, so the first 4xx a client sees is | ||
| 85 | +/// unchanged — then the course-template half: the subject must sit in what | ||
| 86 | +/// this section actually *teaches*, its resolved set | ||
| 87 | +/// ([`crate::service::offering_subject::resolved_for_instance`]), not merely | ||
| 88 | +/// in the catalog course. A right-course-but-off-syllabus subject is a `400` | ||
| 89 | +/// naming the field. The resolved-set probe is one SQL statement that reads | ||
| 90 | +/// the section's flag and the matching table as of one snapshot | ||
| 91 | +/// ([`crate::db::offering_subject::resolves_for_class_course`]). | ||
| 92 | +pub async fn in_instance( | ||
| 93 | + db: &Database, | ||
| 94 | + id: &str, | ||
| 95 | + instance: &ClassCourse, | ||
| 96 | +) -> Result<SubjectId, AppError> { | ||
| 97 | + let subject_id = in_course(db, id, instance.get_course()).await?; | ||
| 98 | + crate::service::offering_subject::ensure_resolved_member(db, instance, &subject_id).await?; | ||
| 99 | + Ok(subject_id) | ||
| 100 | +} | ||
| 101 | + | ||
| 76 | /// Turn a request-supplied subject id into a validated reference, checking only | 102 | /// Turn a request-supplied subject id into a validated reference, checking only |
| 77 | /// that the subject exists — no course tie. For the question bank, whose subject | 103 | /// that the subject exists — no course tie. For the question bank, whose subject |
| 78 | /// is cross-course origin metadata: the same-course rule applies at instantiate | 104 | /// is cross-course origin metadata: the same-course rule applies at instantiate |
src/service/weekly_slot.rsadded+479 -0
| @@ -0,0 +1,479 @@ | |||
| 1 | +//! Weekly-plan workflows: the two resolution arms (the flag decides whose | ||
| 2 | +//! rows a reader sees), the guarded adds (overlap and cap, judged inside the | ||
| 3 | +//! owner's row lock so two racers cannot both clear the pre-check), and the | ||
| 4 | +//! override doors (add/remove/reset on the section's own set, each flipping | ||
| 5 | +//! `weekly_plan_inherited` in the same statement — see | ||
| 6 | +//! [`crate::db::weekly_slot`]). | ||
| 7 | +//! | ||
| 8 | +//! **No scheduler.** Nothing here generates dated `course_session` rows from | ||
| 9 | +//! a weekly plan — `course_session` stays the per-lesson occurrence, written | ||
| 10 | +//! by its own routes. This module is template + override + resolution only; a | ||
| 11 | +//! scheduler needs its own spec. | ||
| 12 | + | ||
| 13 | +use crate::database::{Database, tx_with_retry}; | ||
| 14 | +use crate::db::weekly_slot as slot_db; | ||
| 15 | +use crate::domain::class_course::{ClassCourse, ClassCourseId}; | ||
| 16 | +use crate::domain::course_offering::CourseOfferingId; | ||
| 17 | +use crate::domain::weekly_slot::{ | ||
| 18 | + SlotAddError, SlotMinute, Weekday, WeeklySlot, WeeklySlotId, check_add, | ||
| 19 | +}; | ||
| 20 | +use crate::error::AppError; | ||
| 21 | + | ||
| 22 | +/// The weekly plan a read should present for `instance`: the offering's | ||
| 23 | +/// slots while the section follows the template | ||
| 24 | +/// (`weekly_plan_inherited`), its own rows once it overrode — **including | ||
| 25 | +/// when that own set is empty**, which is how a section clears its | ||
| 26 | +/// timetable. Weekday first, then start time; the empty plan is a valid | ||
| 27 | +/// answer, never an error. | ||
| 28 | +pub async fn resolved_for_instance( | ||
| 29 | + db: &Database, | ||
| 30 | + instance: &ClassCourse, | ||
| 31 | +) -> Result<Vec<WeeklySlot>, AppError> { | ||
| 32 | + if instance.weekly_plan_inherited() { | ||
| 33 | + resolved_for_offering(db, instance.get_offering()).await | ||
| 34 | + } else { | ||
| 35 | + resolved_own(db, instance.get_id()).await | ||
| 36 | + } | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// The offering's template week — the arm `resolved_for_instance` follows | ||
| 40 | +/// while the section inherits, and the direct read the offering-side route | ||
| 41 | +/// serves. Weekday first, then start time. | ||
| 42 | +pub async fn resolved_for_offering( | ||
| 43 | + db: &Database, | ||
| 44 | + offering_id: &CourseOfferingId, | ||
| 45 | +) -> Result<Vec<WeeklySlot>, AppError> { | ||
| 46 | + slot_db::list_for_offering(db, offering_id).await | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// The section's own rows, flag-independent — the resolver's override arm. | ||
| 50 | +async fn resolved_own( | ||
| 51 | + db: &Database, | ||
| 52 | + instance: &ClassCourseId, | ||
| 53 | +) -> Result<Vec<WeeklySlot>, AppError> { | ||
| 54 | + slot_db::list_for_class(db, instance).await | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// Add one slot to the offering's template week. Manager-gated at the route; | ||
| 58 | +/// refused with 409 `slot_overlap` when a template slot already occupies an | ||
| 59 | +/// intersecting window on that weekday (the exact duplicate overlaps too), | ||
| 60 | +/// 409 `slot_cap` when the week already holds [`MAX_WEEKLY_SLOTS`] slots, | ||
| 61 | +/// and 400 for a malformed weekday, minute, or empty window. | ||
| 62 | +pub async fn add_for_offering( | ||
| 63 | + db: &Database, | ||
| 64 | + offering: &CourseOfferingId, | ||
| 65 | + weekday: Weekday, | ||
| 66 | + starts_at: SlotMinute, | ||
| 67 | + ends_at: SlotMinute, | ||
| 68 | +) -> Result<WeeklySlot, AppError> { | ||
| 69 | + let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at)?; | ||
| 70 | + let owner = offering.clone(); | ||
| 71 | + tx_with_retry(db, false, async move |tx| { | ||
| 72 | + // The row lock serializes the pre-check and the insert: under READ | ||
| 73 | + // COMMITTED a rival's uncommitted slot would otherwise be invisible. | ||
| 74 | + slot_db::lock_offering_tx(tx, &owner).await?; | ||
| 75 | + let existing = slot_db::list_for_offering_on(&mut *tx, &owner).await?; | ||
| 76 | + check_add(&existing, &slot).map_err(slot_add_conflict)?; | ||
| 77 | + slot_db::add_for_offering_tx(tx, &slot, &owner).await | ||
| 78 | + }) | ||
| 79 | + .await | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// Add one slot to the section's own week — the override door. Writing any | ||
| 83 | +/// row flips `weekly_plan_inherited` to `FALSE` in the same statement, so the | ||
| 84 | +/// section's own set becomes authoritative from this write on. Same refusals | ||
| 85 | +/// as [`add_for_offering`], plus 404 when the instance is gone. | ||
| 86 | +pub async fn add_for_class( | ||
| 87 | + db: &Database, | ||
| 88 | + instance: &ClassCourseId, | ||
| 89 | + weekday: Weekday, | ||
| 90 | + starts_at: SlotMinute, | ||
| 91 | + ends_at: SlotMinute, | ||
| 92 | +) -> Result<WeeklySlot, AppError> { | ||
| 93 | + let slot = WeeklySlot::new(WeeklySlotId::generate(), weekday, starts_at, ends_at)?; | ||
| 94 | + let owner = instance.clone(); | ||
| 95 | + tx_with_retry(db, false, async move |tx| { | ||
| 96 | + slot_db::lock_class_tx(tx, &owner).await?; | ||
| 97 | + let existing = slot_db::list_for_class_on(&mut *tx, &owner).await?; | ||
| 98 | + check_add(&existing, &slot).map_err(slot_add_conflict)?; | ||
| 99 | + slot_db::add_for_class_tx(tx, &slot, &owner).await | ||
| 100 | + }) | ||
| 101 | + .await | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// Drop one slot of the offering's template week. A slot of another offering | ||
| 105 | +/// (or an already-gone id) is a 404. | ||
| 106 | +pub async fn remove_for_offering( | ||
| 107 | + db: &Database, | ||
| 108 | + offering: &CourseOfferingId, | ||
| 109 | + slot: &WeeklySlotId, | ||
| 110 | +) -> Result<(), AppError> { | ||
| 111 | + slot_db::remove_for_offering(db, offering, slot).await | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// Drop one slot of the section's own week — the override door. The flag | ||
| 115 | +/// flips to `FALSE` in the same statement as the delete, so dropping the | ||
| 116 | +/// last row leaves the section with an authoritative *empty* plan rather | ||
| 117 | +/// than quietly re-inheriting. A 404 (unknown id, or another instance's | ||
| 118 | +/// slot) leaves the flag untouched. | ||
| 119 | +pub async fn remove_for_class( | ||
| 120 | + db: &Database, | ||
| 121 | + instance: &ClassCourseId, | ||
| 122 | + slot: &WeeklySlotId, | ||
| 123 | +) -> Result<(), AppError> { | ||
| 124 | + slot_db::remove_for_class(db, instance, slot).await | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// Reset the section's weekly plan to inherit: delete its own slots and flip | ||
| 128 | +/// the flag back to `TRUE` in one statement. After this | ||
| 129 | +/// [`resolved_for_instance`] serves the offering's rows again. Idempotent for | ||
| 130 | +/// a section that never overrode; 404 when the instance is gone. | ||
| 131 | +pub async fn reset_for_class(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> { | ||
| 132 | + slot_db::reset_for_class(db, instance).await | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +/// Map the pure add-time refusals onto the wire's coded 409s. | ||
| 136 | +fn slot_add_conflict(error: SlotAddError) -> AppError { | ||
| 137 | + match error { | ||
| 138 | + SlotAddError::Overlap => AppError::ConflictCoded { | ||
| 139 | + code: "slot_overlap", | ||
| 140 | + message: "another slot already occupies an intersecting time on this weekday".into(), | ||
| 141 | + }, | ||
| 142 | + SlotAddError::Full => AppError::ConflictCoded { | ||
| 143 | + code: "slot_cap", | ||
| 144 | + message: format!( | ||
| 145 | + "this weekly plan already holds the maximum of {} slots", | ||
| 146 | + crate::constant::MAX_WEEKLY_SLOTS | ||
| 147 | + ), | ||
| 148 | + }, | ||
| 149 | + } | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +#[cfg(test)] | ||
| 153 | +mod tests { | ||
| 154 | + use super::*; | ||
| 155 | + use crate::db::class_member::tests::{a_class, a_course, fixture_user}; | ||
| 156 | + | ||
| 157 | + /// The instance row, re-read from the store — the flag assertions judge | ||
| 158 | + /// the stored column, not a return value. | ||
| 159 | + async fn instance_row(db: &Database, id: &ClassCourseId) -> ClassCourse { | ||
| 160 | + crate::service::class_course::read(db, id) | ||
| 161 | + .await | ||
| 162 | + .unwrap() | ||
| 163 | + .unwrap() | ||
| 164 | + } | ||
| 165 | + | ||
| 166 | + fn day(raw: i16) -> Weekday { | ||
| 167 | + Weekday::new(raw).unwrap() | ||
| 168 | + } | ||
| 169 | + | ||
| 170 | + fn mins(raw: i64) -> SlotMinute { | ||
| 171 | + SlotMinute::new(raw).unwrap() | ||
| 172 | + } | ||
| 173 | + | ||
| 174 | + /// An attached instance: its auto-minted offering id is the template the | ||
| 175 | + /// inheritance arm reads. | ||
| 176 | + async fn an_instance(db: &Database, name: &str) -> ClassCourse { | ||
| 177 | + let manager = fixture_user(db, "manager").await; | ||
| 178 | + let class = a_class(name, db).await; | ||
| 179 | + let course = a_course("Matematik", db).await; | ||
| 180 | + crate::service::class_course::attach(db, &class, &course, &manager) | ||
| 181 | + .await | ||
| 182 | + .unwrap() | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + fn coded(result: &Result<WeeklySlot, AppError>) -> String { | ||
| 186 | + match result { | ||
| 187 | + Err(AppError::ConflictCoded { code, .. }) => code.to_string(), | ||
| 188 | + other => panic!("expected a coded 409, got {other:?}"), | ||
| 189 | + } | ||
| 190 | + } | ||
| 191 | + | ||
| 192 | + /// While the section inherits, its resolved plan is the offering's — | ||
| 193 | + /// weekday first, then start time, whatever order the slots were added | ||
| 194 | + /// in. The flag stays TRUE; nothing on the section's side was written. | ||
| 195 | + #[tokio::test] | ||
| 196 | + async fn an_inheriting_section_resolves_the_offerings_slots_in_order() { | ||
| 197 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 198 | + let instance = an_instance(&db, "5-A").await; | ||
| 199 | + let offering = instance.get_offering().clone(); | ||
| 200 | + | ||
| 201 | + add_for_offering(&db, &offering, day(2), mins(600), mins(660)) | ||
| 202 | + .await | ||
| 203 | + .unwrap(); | ||
| 204 | + add_for_offering(&db, &offering, day(1), mins(600), mins(660)) | ||
| 205 | + .await | ||
| 206 | + .unwrap(); | ||
| 207 | + add_for_offering(&db, &offering, day(1), mins(480), mins(540)) | ||
| 208 | + .await | ||
| 209 | + .unwrap(); | ||
| 210 | + | ||
| 211 | + assert!( | ||
| 212 | + instance_row(&db, instance.get_id()) | ||
| 213 | + .await | ||
| 214 | + .weekly_plan_inherited() | ||
| 215 | + ); | ||
| 216 | + let resolved = resolved_for_instance(&db, &instance).await.unwrap(); | ||
| 217 | + let starts: Vec<i64> = resolved.iter().map(|s| s.get_starts_at().get()).collect(); | ||
| 218 | + let weekdays: Vec<i16> = resolved.iter().map(|s| s.get_weekday().get()).collect(); | ||
| 219 | + assert_eq!(weekdays, vec![1, 1, 2], "weekday orders first"); | ||
| 220 | + assert_eq!(starts, vec![480, 600, 600], "start time breaks the tie"); | ||
| 221 | + } | ||
| 222 | + | ||
| 223 | + /// The override arm: once the section wrote a slot of its own, its own | ||
| 224 | + /// set is authoritative — and **stays** authoritative when empty, which | ||
| 225 | + /// is exactly how a section clears its timetable instead of silently | ||
| 226 | + /// re-inheriting the template. | ||
| 227 | + #[tokio::test] | ||
| 228 | + async fn an_own_set_wins_including_when_it_is_empty() { | ||
| 229 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 230 | + let instance = an_instance(&db, "5-B").await; | ||
| 231 | + let offering = instance.get_offering().clone(); | ||
| 232 | + add_for_offering(&db, &offering, day(1), mins(480), mins(540)) | ||
| 233 | + .await | ||
| 234 | + .unwrap(); | ||
| 235 | + | ||
| 236 | + add_for_class(&db, instance.get_id(), day(3), mins(540), mins(600)) | ||
| 237 | + .await | ||
| 238 | + .unwrap(); | ||
| 239 | + // The write flipped the flag: re-read so the resolver follows the | ||
| 240 | + // override arm instead of the stale inheriting snapshot. | ||
| 241 | + let instance = instance_row(&db, instance.get_id()).await; | ||
| 242 | + assert!(!instance.weekly_plan_inherited()); | ||
| 243 | + let resolved = resolved_for_instance(&db, &instance).await.unwrap(); | ||
| 244 | + assert_eq!(resolved.len(), 1, "the own row, not the offering's"); | ||
| 245 | + | ||
| 246 | + // Dropping the last own row empties the authoritative set; the | ||
| 247 | + // offering's slot stays hidden behind the still-FALSE flag. | ||
| 248 | + let own_id = resolved[0].get_id().clone(); | ||
| 249 | + remove_for_class(&db, instance.get_id(), &own_id) | ||
| 250 | + .await | ||
| 251 | + .unwrap(); | ||
| 252 | + assert!( | ||
| 253 | + !instance_row(&db, instance.get_id()) | ||
| 254 | + .await | ||
| 255 | + .weekly_plan_inherited() | ||
| 256 | + ); | ||
| 257 | + assert!( | ||
| 258 | + resolved_for_instance(&db, &instance) | ||
| 259 | + .await | ||
| 260 | + .unwrap() | ||
| 261 | + .is_empty() | ||
| 262 | + ); | ||
| 263 | + } | ||
| 264 | + | ||
| 265 | + /// Intersecting windows on one weekday are refused — partial, exact | ||
| 266 | + /// duplicate, and containment — while touching endpoints and other | ||
| 267 | + /// weekdays pass. Malformed bodies are 400s. | ||
| 268 | + #[tokio::test] | ||
| 269 | + async fn an_overlapping_slot_is_refused() { | ||
| 270 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 271 | + let instance = an_instance(&db, "5-C").await; | ||
| 272 | + add_for_class(&db, instance.get_id(), day(1), mins(540), mins(600)) | ||
| 273 | + .await | ||
| 274 | + .unwrap(); | ||
| 275 | + | ||
| 276 | + for (starts, ends, why) in [ | ||
| 277 | + (540, 600, "the exact duplicate"), | ||
| 278 | + (570, 630, "the partial overlap"), | ||
| 279 | + (530, 610, "the containing window"), | ||
| 280 | + (530, 630, "the wider window"), | ||
| 281 | + ] { | ||
| 282 | + let attempt = | ||
| 283 | + add_for_class(&db, instance.get_id(), day(1), mins(starts), mins(ends)).await; | ||
| 284 | + assert_eq!( | ||
| 285 | + coded(&attempt), | ||
| 286 | + "slot_overlap", | ||
| 287 | + "{why} must answer 409 slot_overlap" | ||
| 288 | + ); | ||
| 289 | + } | ||
| 290 | + | ||
| 291 | + // Touching endpoints and a different weekday are not overlaps. | ||
| 292 | + add_for_class(&db, instance.get_id(), day(1), mins(600), mins(660)) | ||
| 293 | + .await | ||
| 294 | + .unwrap(); | ||
| 295 | + add_for_class(&db, instance.get_id(), day(2), mins(540), mins(600)) | ||
| 296 | + .await | ||
| 297 | + .unwrap(); | ||
| 298 | + assert_eq!( | ||
| 299 | + slot_db::list_for_class(&db, instance.get_id()) | ||
| 300 | + .await | ||
| 301 | + .unwrap() | ||
| 302 | + .len(), | ||
| 303 | + 3 | ||
| 304 | + ); | ||
| 305 | + | ||
| 306 | + // Malformed bodies are validation 400s, before any owner query runs. | ||
| 307 | + assert!(Weekday::new(0).is_err()); | ||
| 308 | + assert!(SlotMinute::new(-1).is_err()); | ||
| 309 | + let empty_window = | ||
| 310 | + add_for_class(&db, instance.get_id(), day(1), mins(600), mins(600)).await; | ||
| 311 | + assert!( | ||
| 312 | + matches!(empty_window, Err(AppError::Validation(_))), | ||
| 313 | + "{empty_window:?}" | ||
| 314 | + ); | ||
| 315 | + let inverted = add_for_class(&db, instance.get_id(), day(1), mins(1439), mins(600)).await; | ||
| 316 | + assert!( | ||
| 317 | + matches!(inverted, Err(AppError::Validation(_))), | ||
| 318 | + "{inverted:?}" | ||
| 319 | + ); | ||
| 320 | + } | ||
| 321 | + | ||
| 322 | + /// The cap bounds one owner's plan; the refusal names the cap, and the | ||
| 323 | + /// stored set never exceeds the bound. | ||
| 324 | + #[tokio::test] | ||
| 325 | + async fn the_slot_cap_holds() { | ||
| 326 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 327 | + let instance = an_instance(&db, "5-D").await; | ||
| 328 | + | ||
| 329 | + // Forty non-overlapping one-minute windows: weekday (i%7)+1, minute | ||
| 330 | + // 480+(i/7) — five or six per weekday, all touching, none crossing. | ||
| 331 | + for i in 0..crate::constant::MAX_WEEKLY_SLOTS { | ||
| 332 | + let i = i as i64; | ||
| 333 | + add_for_class( | ||
| 334 | + &db, | ||
| 335 | + instance.get_id(), | ||
| 336 | + day(((i % 7) + 1) as i16), | ||
| 337 | + mins(480 + i / 7), | ||
| 338 | + mins(481 + i / 7), | ||
| 339 | + ) | ||
| 340 | + .await | ||
| 341 | + .unwrap(); | ||
| 342 | + } | ||
| 343 | + assert_eq!( | ||
| 344 | + slot_db::list_for_class(&db, instance.get_id()) | ||
| 345 | + .await | ||
| 346 | + .unwrap() | ||
| 347 | + .len(), | ||
| 348 | + crate::constant::MAX_WEEKLY_SLOTS | ||
| 349 | + ); | ||
| 350 | + | ||
| 351 | + // Room on Sunday's timeline, but the plan is full. | ||
| 352 | + let one_more = add_for_class(&db, instance.get_id(), day(7), mins(700), mins(760)).await; | ||
| 353 | + assert_eq!(coded(&one_more), "slot_cap"); | ||
| 354 | + assert_eq!( | ||
| 355 | + slot_db::list_for_class(&db, instance.get_id()) | ||
| 356 | + .await | ||
| 357 | + .unwrap() | ||
| 358 | + .len(), | ||
| 359 | + crate::constant::MAX_WEEKLY_SLOTS | ||
| 360 | + ); | ||
| 361 | + } | ||
| 362 | + | ||
| 363 | + /// The reset door: the own slots go, the flag returns to TRUE, and the | ||
| 364 | + /// offering's rows are what the section resolves again. | ||
| 365 | + #[tokio::test] | ||
| 366 | + async fn reset_restores_inheritance() { | ||
| 367 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 368 | + let instance = an_instance(&db, "5-E").await; | ||
| 369 | + let offering = instance.get_offering().clone(); | ||
| 370 | + add_for_offering(&db, &offering, day(1), mins(480), mins(540)) | ||
| 371 | + .await | ||
| 372 | + .unwrap(); | ||
| 373 | + add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540)) | ||
| 374 | + .await | ||
| 375 | + .unwrap(); | ||
| 376 | + assert!( | ||
| 377 | + !instance_row(&db, instance.get_id()) | ||
| 378 | + .await | ||
| 379 | + .weekly_plan_inherited() | ||
| 380 | + ); | ||
| 381 | + | ||
| 382 | + reset_for_class(&db, instance.get_id()).await.unwrap(); | ||
| 383 | + let after = instance_row(&db, instance.get_id()).await; | ||
| 384 | + assert!(after.weekly_plan_inherited()); | ||
| 385 | + let resolved = resolved_for_instance(&db, &after).await.unwrap(); | ||
| 386 | + assert_eq!(resolved.len(), 1, "the offering's slot serves again"); | ||
| 387 | + assert_eq!(resolved[0].get_weekday(), day(1)); | ||
| 388 | + | ||
| 389 | + // Idempotent: resetting an inheriting section is a no-op success. | ||
| 390 | + reset_for_class(&db, instance.get_id()).await.unwrap(); | ||
| 391 | + assert!( | ||
| 392 | + instance_row(&db, instance.get_id()) | ||
| 393 | + .await | ||
| 394 | + .weekly_plan_inherited() | ||
| 395 | + ); | ||
| 396 | + } | ||
| 397 | + | ||
| 398 | + /// Removing an unknown slot — or another instance's slot — is a 404 that | ||
| 399 | + /// leaves both sections alone. An own removal keeps the rest of the set. | ||
| 400 | + #[tokio::test] | ||
| 401 | + async fn removing_a_slot_scopes_to_its_owner() { | ||
| 402 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 403 | + let instance = an_instance(&db, "5-F").await; | ||
| 404 | + let other = an_instance(&db, "5-G").await; | ||
| 405 | + | ||
| 406 | + add_for_class(&db, instance.get_id(), day(1), mins(480), mins(540)) | ||
| 407 | + .await | ||
| 408 | + .unwrap(); | ||
| 409 | + add_for_class(&db, instance.get_id(), day(2), mins(480), mins(540)) | ||
| 410 | + .await | ||
| 411 | + .unwrap(); | ||
| 412 | + let own = slot_db::list_for_class(&db, instance.get_id()) | ||
| 413 | + .await | ||
| 414 | + .unwrap(); | ||
| 415 | + | ||
| 416 | + // Another section's instance id is a 404, and the flag/id stand. | ||
| 417 | + let stranger = remove_for_class(&db, other.get_id(), own[0].get_id()).await; | ||
| 418 | + assert!(matches!(stranger, Err(AppError::NotFound)), "{stranger:?}"); | ||
| 419 | + // An unknown slot id is a 404 too. | ||
| 420 | + let missing = remove_for_class(&db, instance.get_id(), &WeeklySlotId::generate()).await; | ||
| 421 | + assert!(matches!(missing, Err(AppError::NotFound)), "{missing:?}"); | ||
| 422 | + assert_eq!( | ||
| 423 | + slot_db::list_for_class(&db, instance.get_id()) | ||
| 424 | + .await | ||
| 425 | + .unwrap() | ||
| 426 | + .len(), | ||
| 427 | + 2 | ||
| 428 | + ); | ||
| 429 | + | ||
| 430 | + remove_for_class(&db, instance.get_id(), own[0].get_id()) | ||
| 431 | + .await | ||
| 432 | + .unwrap(); | ||
| 433 | + let rest = slot_db::list_for_class(&db, instance.get_id()) | ||
| 434 | + .await | ||
| 435 | + .unwrap(); | ||
| 436 | + assert_eq!(rest.len(), 1); | ||
| 437 | + assert_eq!(rest[0].get_weekday(), day(2)); | ||
| 438 | + assert!( | ||
| 439 | + !instance_row(&db, instance.get_id()) | ||
| 440 | + .await | ||
| 441 | + .weekly_plan_inherited() | ||
| 442 | + ); | ||
| 443 | + } | ||
| 444 | + | ||
| 445 | + /// The offering-side doors mirror the class side minus the flag: overlap | ||
| 446 | + /// refused, remove scoped to the offering, resolve ordering holds. | ||
| 447 | + #[tokio::test] | ||
| 448 | + async fn the_offering_side_adds_removes_and_resolves() { | ||
| 449 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 450 | + let instance = an_instance(&db, "5-H").await; | ||
| 451 | + let offering = instance.get_offering().clone(); | ||
| 452 | + | ||
| 453 | + add_for_offering(&db, &offering, day(1), mins(540), mins(600)) | ||
| 454 | + .await | ||
| 455 | + .unwrap(); | ||
| 456 | + let clash = add_for_offering(&db, &offering, day(1), mins(570), mins(630)).await; | ||
| 457 | + assert_eq!(coded(&clash), "slot_overlap"); | ||
| 458 | + | ||
| 459 | + let slots = slot_db::list_for_offering(&db, &offering).await.unwrap(); | ||
| 460 | + assert_eq!(slots.len(), 1); | ||
| 461 | + let unknown = remove_for_offering(&db, &offering, &WeeklySlotId::generate()).await; | ||
| 462 | + assert!(matches!(unknown, Err(AppError::NotFound)), "{unknown:?}"); | ||
| 463 | + | ||
| 464 | + // Another offering's slot id is not deletable through this one. | ||
| 465 | + let other_offering = an_instance(&db, "5-I").await.get_offering().clone(); | ||
| 466 | + let foreign = remove_for_offering(&db, &other_offering, slots[0].get_id()).await; | ||
| 467 | + assert!(matches!(foreign, Err(AppError::NotFound)), "{foreign:?}"); | ||
| 468 | + | ||
| 469 | + remove_for_offering(&db, &offering, slots[0].get_id()) | ||
| 470 | + .await | ||
| 471 | + .unwrap(); | ||
| 472 | + assert!( | ||
| 473 | + resolved_for_offering(&db, &offering) | ||
| 474 | + .await | ||
| 475 | + .unwrap() | ||
| 476 | + .is_empty() | ||
| 477 | + ); | ||
| 478 | + } | ||
| 479 | +} | ||
src/web/academic_years.rsmodified+16 -11
| @@ -24,6 +24,7 @@ use utoipa_axum::routes; | |||
| 24 | use crate::domain::academic_year::{ | 24 | use crate::domain::academic_year::{ |
| 25 | AcademicYear, AcademicYearId, AcademicYearName, GradePromotion, | 25 | AcademicYear, AcademicYearId, AcademicYearName, GradePromotion, |
| 26 | }; | 26 | }; |
| 27 | +use crate::domain::grade::GradeLevel; | ||
| 27 | use crate::domain::timestamp::Timestamp; | 28 | use crate::domain::timestamp::Timestamp; |
| 28 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 29 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 29 | use crate::service; | 30 | use crate::service; |
| @@ -68,18 +69,22 @@ struct UpdateYear { | |||
| 68 | grade_promotions: Option<Vec<PromotionBody>>, | 69 | grade_promotions: Option<Vec<PromotionBody>>, |
| 69 | } | 70 | } |
| 70 | 71 | ||
| 71 | -/// One grade-promotion pair off the wire. | 72 | +/// One grade-promotion pair off the wire: two rungs on the grade ladder |
| 73 | +/// (`0` = anaokulu, `1..=12` the school years). | ||
| 72 | #[derive(Deserialize, Serialize, ToSchema)] | 74 | #[derive(Deserialize, Serialize, ToSchema)] |
| 73 | struct PromotionBody { | 75 | struct PromotionBody { |
| 74 | - #[schema(max_length = 20, example = "5")] | 76 | + #[schema(minimum = 0, maximum = 12, example = 5)] |
| 75 | - from_grade: String, | 77 | + from_grade: i16, |
| 76 | - #[schema(max_length = 20, example = "6")] | 78 | + #[schema(minimum = 0, maximum = 12, example = 6)] |
| 77 | - to_grade: String, | 79 | + to_grade: i16, |
| 78 | } | 80 | } |
| 79 | 81 | ||
| 80 | impl PromotionBody { | 82 | impl PromotionBody { |
| 81 | fn parse(&self) -> Result<GradePromotion, AppError> { | 83 | fn parse(&self) -> Result<GradePromotion, AppError> { |
| 82 | - Ok(GradePromotion::try_new(&self.from_grade, &self.to_grade)?) | 84 | + Ok(GradePromotion::new( |
| 85 | + GradeLevel::new(self.from_grade)?, | ||
| 86 | + GradeLevel::new(self.to_grade)?, | ||
| 87 | + )) | ||
| 83 | } | 88 | } |
| 84 | } | 89 | } |
| 85 | 90 | ||
| @@ -119,8 +124,8 @@ impl YearResponse { | |||
| 119 | .get_grade_promotions() | 124 | .get_grade_promotions() |
| 120 | .iter() | 125 | .iter() |
| 121 | .map(|promo| PromotionBody { | 126 | .map(|promo| PromotionBody { |
| 122 | - from_grade: promo.get_from_grade().to_string(), | 127 | + from_grade: promo.get_from_grade().get(), |
| 123 | - to_grade: promo.get_to_grade().to_string(), | 128 | + to_grade: promo.get_to_grade().get(), |
| 124 | }) | 129 | }) |
| 125 | .collect(), | 130 | .collect(), |
| 126 | class_count: year.get_class_count(), | 131 | class_count: year.get_class_count(), |
| @@ -140,9 +145,9 @@ struct RolloverResponse { | |||
| 140 | classes: usize, | 145 | classes: usize, |
| 141 | #[schema(example = 312)] | 146 | #[schema(example = 312)] |
| 142 | students: usize, | 147 | students: usize, |
| 143 | - /// The grade labels that stayed behind (graduation), in the order they | 148 | + /// The labels of the rungs that stayed behind (graduation), in the order |
| 144 | - /// were met. | 149 | + /// they were met — `"Anaokulu"` at the floor, the year number elsewhere. |
| 145 | - #[schema(example = json!(["8", "12"]))] | 150 | + #[schema(example = json!(["11", "12"]))] |
| 146 | graduated: Vec<String>, | 151 | graduated: Vec<String>, |
| 147 | } | 152 | } |
| 148 | 153 | ||
src/web/attendance.rsmodified+15 -1
| @@ -223,6 +223,12 @@ async fn build_report( | |||
| 223 | let course_by_key: HashMap<String, &Course> = | 223 | let course_by_key: HashMap<String, &Course> = |
| 224 | courses.iter().map(|c| (c.get_id().key(), c)).collect(); | 224 | courses.iter().map(|c| (c.get_id().key(), c)).collect(); |
| 225 | let people = person_map(courses.iter().flat_map(course_people), db).await?; | 225 | let people = person_map(courses.iter().flat_map(course_people), db).await?; |
| 226 | + // The per-instance blocks display the sections' **resolved** | ||
| 227 | + // titles/descriptions (override → offering → catalog), batched — the | ||
| 228 | + // `/courses` catalog list is the deliberate exception that keeps the | ||
| 229 | + // catalog row's own values, because that surface IS the catalog. | ||
| 230 | + let instance_refs: Vec<&ClassCourse> = instances.iter().collect(); | ||
| 231 | + let content = crate::service::instance_resolve::resolved_content(db, &instance_refs).await?; | ||
| 226 | 232 | ||
| 227 | let mut blocks = Vec::with_capacity(instance_ids.len()); | 233 | let mut blocks = Vec::with_capacity(instance_ids.len()); |
| 228 | let mut visible_rows: Vec<&SessionAttendance> = Vec::with_capacity(sessions.len()); | 234 | let mut visible_rows: Vec<&SessionAttendance> = Vec::with_capacity(sessions.len()); |
| @@ -242,9 +248,17 @@ async fn build_report( | |||
| 242 | }; | 248 | }; |
| 243 | let rows = &by_instance[instance_id.key().as_str()]; | 249 | let rows = &by_instance[instance_id.key().as_str()]; |
| 244 | visible_rows.extend(rows.iter().copied()); | 250 | visible_rows.extend(rows.iter().copied()); |
| 251 | + // The instance-scoped display: resolved title/description over the | ||
| 252 | + // catalog row's (which stays the id/kind/counters source). | ||
| 253 | + let resolved = content | ||
| 254 | + .get(instance.get_id().key().as_str()) | ||
| 255 | + .expect("resolved_content covers every instance it is given"); | ||
| 256 | + let mut course = CourseResponse::new(course, &people); | ||
| 257 | + course.title = resolved.title.clone(); | ||
| 258 | + course.description = resolved.description.clone(); | ||
| 245 | blocks.push(CourseAttendance { | 259 | blocks.push(CourseAttendance { |
| 246 | instance: instance.get_id().key(), | 260 | instance: instance.get_id().key(), |
| 247 | - course: CourseResponse::new(course, &people), | 261 | + course, |
| 248 | counts: StatusCounts::tally(rows.iter().map(|r| r.get_status())), | 262 | counts: StatusCounts::tally(rows.iter().map(|r| r.get_status())), |
| 249 | }); | 263 | }); |
| 250 | } | 264 | } |
src/web/classes.rsmodified+137 -132
| @@ -19,7 +19,8 @@ use utoipa_axum::routes; | |||
| 19 | use crate::database::Database; | 19 | use crate::database::Database; |
| 20 | use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId, Pumped, Skip}; | 20 | use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId, Pumped, Skip}; |
| 21 | use crate::domain::class_course::{ClassCourse, ClassCourseId}; | 21 | use crate::domain::class_course::{ClassCourse, ClassCourseId}; |
| 22 | -use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; | 22 | +use crate::domain::class_group::{ClassGroup, ClassGroupId, ClassName}; |
| 23 | +use crate::domain::grade::GradeLevel; | ||
| 23 | use crate::domain::class_member::ClassMember; | 24 | use crate::domain::class_member::ClassMember; |
| 24 | use crate::domain::course::CourseId; | 25 | use crate::domain::course::CourseId; |
| 25 | use crate::domain::role::Role; | 26 | use crate::domain::role::Role; |
| @@ -64,10 +65,11 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 64 | struct CreateClass { | 65 | struct CreateClass { |
| 65 | #[schema(max_length = 200, example = "9-A")] | 66 | #[schema(max_length = 200, example = "9-A")] |
| 66 | name: String, | 67 | name: String, |
| 67 | - /// The school's own label for the year this class sits in ("9", "10-A", | 68 | + /// The class's rung on the shared grade ladder — an integer, `0` = |
| 68 | - /// "kindergarten"). Free text; omit (or send `""`) for a class with no grade. | 69 | + /// anaokulu, `1..=12` the school years. Required: every section sits at a |
| 69 | - #[schema(max_length = 20, example = "9")] | 70 | + /// grade; it is school-wide club/study courses that belong to none. |
| 70 | - grade: Option<String>, | 71 | + #[schema(minimum = 0, maximum = 12, example = 9)] |
| 72 | + grade_level: i16, | ||
| 71 | /// The academic year this class sits in (`GET /academic-years`). Optional; | 73 | /// The academic year this class sits in (`GET /academic-years`). Optional; |
| 72 | /// a class with no year takes no exam and is never rolled over. | 74 | /// a class with no year takes no exam and is never rolled over. |
| 73 | year: Option<String>, | 75 | year: Option<String>, |
| @@ -81,11 +83,11 @@ struct CreateClass { | |||
| 81 | struct UpdateClass { | 83 | struct UpdateClass { |
| 82 | #[schema(max_length = 200)] | 84 | #[schema(max_length = 200)] |
| 83 | name: Option<String>, | 85 | name: Option<String>, |
| 84 | - /// Omit to keep the current grade, send `null` (or `""`) to clear it, or | 86 | + /// Omit to keep the current grade, or send a ladder rung (an integer, |
| 85 | - /// send a label to (re)set it. | 87 | + /// `0`..=12) to (re)set it. The grade is required on every class, so it |
| 86 | - #[serde(default, deserialize_with = "set_or_clear")] | 88 | + /// cannot be cleared. |
| 87 | - #[schema(value_type = Option<String>, max_length = 20)] | 89 | + #[schema(value_type = Option<i16>, minimum = 0, maximum = 12)] |
| 88 | - grade: Option<Option<String>>, | 90 | + grade_level: Option<i16>, |
| 89 | /// Omit to keep the current academic year, send `null` to unlink, or send | 91 | /// Omit to keep the current academic year, send `null` to unlink, or send |
| 90 | /// a year id to (re)assign. | 92 | /// a year id to (re)assign. |
| 91 | #[serde(default, deserialize_with = "set_or_clear")] | 93 | #[serde(default, deserialize_with = "set_or_clear")] |
| @@ -124,9 +126,9 @@ struct ClassResponse { | |||
| 124 | creator: Option<PersonRef>, | 126 | creator: Option<PersonRef>, |
| 125 | #[schema(example = "9-A")] | 127 | #[schema(example = "9-A")] |
| 126 | name: String, | 128 | name: String, |
| 127 | - /// The school's own free-text grade label; `null` when the class has none. | 129 | + /// The class's rung on the grade ladder (`0` = anaokulu). |
| 128 | - #[schema(example = "9")] | 130 | + #[schema(example = 9)] |
| 129 | - grade: Option<String>, | 131 | + grade_level: i16, |
| 130 | /// The academic year this class sits in (`GET /academic-years`); `null` | 132 | /// The academic year this class sits in (`GET /academic-years`); `null` |
| 131 | /// when unassigned. | 133 | /// when unassigned. |
| 132 | year: Option<String>, | 134 | year: Option<String>, |
| @@ -150,7 +152,7 @@ impl ClassResponse { | |||
| 150 | id: class.get_id().key().to_string(), | 152 | id: class.get_id().key().to_string(), |
| 151 | creator: with_creator.then(|| PersonRef::resolve(people, class.get_creator())), | 153 | creator: with_creator.then(|| PersonRef::resolve(people, class.get_creator())), |
| 152 | name: class.get_name().as_str().to_string(), | 154 | name: class.get_name().as_str().to_string(), |
| 153 | - grade: class.get_grade().map(|g| g.as_str().to_string()), | 155 | + grade_level: class.get_grade_level().get(), |
| 154 | year: class.get_year().map(|year| year.key().to_string()), | 156 | year: class.get_year().map(|year| year.key().to_string()), |
| 155 | teacher: class | 157 | teacher: class |
| 156 | .get_teacher() | 158 | .get_teacher() |
| @@ -168,7 +170,7 @@ struct CreateClassResponse { | |||
| 168 | /// The courses the template could not put on this section, empty when it | 170 | /// The courses the template could not put on this section, empty when it |
| 169 | /// took them all (and always empty when no template covered its grade). | 171 | /// took them all (and always empty when no template covered its grade). |
| 170 | skipped: Vec<SkipResponse>, | 172 | skipped: Vec<SkipResponse>, |
| 171 | - /// The grade label of the blueprint that stocked this section, or `null` | 173 | + /// The ladder rung of the blueprint that stocked this section, or `null` |
| 172 | /// when none did. `null` with an empty `skipped` is what tells "no template | 174 | /// when none did. `null` with an empty `skipped` is what tells "no template |
| 173 | /// covers this grade" apart from "the template applied cleanly" — the | 175 | /// covers this grade" apart from "the template applied cleanly" — the |
| 174 | /// distinction `matched` makes on the grade-wide pumps. | 176 | /// distinction `matched` makes on the grade-wide pumps. |
| @@ -179,7 +181,7 @@ struct CreateClassResponse { | |||
| 179 | /// remedy is the same either way — `POST /classes/{id}/blueprint`, which is | 181 | /// remedy is the same either way — `POST /classes/{id}/blueprint`, which is |
| 180 | /// idempotent and `404`s when there is genuinely no template. | 182 | /// idempotent and `404`s when there is genuinely no template. |
| 181 | #[schema(example = "9")] | 183 | #[schema(example = "9")] |
| 182 | - stocked_from: Option<String>, | 184 | + stocked_from: Option<i16>, |
| 183 | } | 185 | } |
| 184 | 186 | ||
| 185 | /// Every person a [`ClassResponse`] names: its homeroom teacher, plus its | 187 | /// Every person a [`ClassResponse`] names: its homeroom teacher, plus its |
| @@ -234,10 +236,14 @@ impl ClassMemberResponse { | |||
| 234 | struct ClassCourseResponse { | 236 | struct ClassCourseResponse { |
| 235 | id: String, | 237 | id: String, |
| 236 | class: String, | 238 | class: String, |
| 237 | - /// The catalog course the class takes (`GET /courses/{id}`) — its title | 239 | + /// The catalog course the class takes (`GET /courses/{id}`). |
| 238 | - /// lives there; what this class actually teaches is the row this response | ||
| 239 | - /// describes. | ||
| 240 | course: String, | 240 | course: String, |
| 241 | + /// The **resolved** display title of this instance: its own override, | ||
| 242 | + /// else its offering's, else the catalog course's — what every | ||
| 243 | + /// instance-scoped surface shows. | ||
| 244 | + title: String, | ||
| 245 | + /// The resolved description, the same chain as `title`. | ||
| 246 | + description: String, | ||
| 241 | /// Who attached it. | 247 | /// Who attached it. |
| 242 | attached_by: PersonRef, | 248 | attached_by: PersonRef, |
| 243 | /// Weekly lesson hours; the instance's weight in the year's report-card average. | 249 | /// Weekly lesson hours; the instance's weight in the year's report-card average. |
| @@ -254,24 +260,35 @@ struct ClassCourseResponse { | |||
| 254 | } | 260 | } |
| 255 | 261 | ||
| 256 | impl ClassCourseResponse { | 262 | impl ClassCourseResponse { |
| 257 | - fn new( | 263 | + /// The weekly hours and report-card policy shown here are the *resolved* |
| 264 | + /// ones (instance override, else its offering's default, else the | ||
| 265 | + /// catalog/constants) — the instance row itself may inherit both. So are | ||
| 266 | + /// the title and description: `content` is the | ||
| 267 | + /// [`crate::service::instance_resolve::resolved_content`] entry for this | ||
| 268 | + /// instance, batched by the caller so a page stays two queries. | ||
| 269 | + async fn new( | ||
| 270 | + db: &Database, | ||
| 258 | link: &ClassCourse, | 271 | link: &ClassCourse, |
| 272 | + content: &crate::service::instance_resolve::ResolvedContent, | ||
| 259 | teachers: &[UserId], | 273 | teachers: &[UserId], |
| 260 | people: &std::collections::HashMap<String, PersonRef>, | 274 | people: &std::collections::HashMap<String, PersonRef>, |
| 261 | - ) -> Self { | 275 | + ) -> Result<Self, AppError> { |
| 262 | - Self { | 276 | + let policy = crate::service::class_course::resolve_policy(db, link).await?; |
| 277 | + Ok(Self { | ||
| 263 | id: link.get_id().key().to_string(), | 278 | id: link.get_id().key().to_string(), |
| 264 | class: link.get_class().key().to_string(), | 279 | class: link.get_class().key().to_string(), |
| 265 | course: link.get_course().key().to_string(), | 280 | course: link.get_course().key().to_string(), |
| 281 | + title: content.title.clone(), | ||
| 282 | + description: content.description.clone(), | ||
| 266 | attached_by: PersonRef::resolve(people, link.get_attached_by()), | 283 | attached_by: PersonRef::resolve(people, link.get_attached_by()), |
| 267 | - ders_saati: link.get_ders_saati().as_i64(), | 284 | + ders_saati: policy.ders_saati.as_i64(), |
| 268 | - counts_toward_karne: link.counts_toward_karne(), | 285 | + counts_toward_karne: policy.counts_toward_karne, |
| 269 | enrollment_count: link.get_enrollment_count(), | 286 | enrollment_count: link.get_enrollment_count(), |
| 270 | teachers: teachers | 287 | teachers: teachers |
| 271 | .iter() | 288 | .iter() |
| 272 | .map(|teacher| PersonRef::resolve(people, teacher)) | 289 | .map(|teacher| PersonRef::resolve(people, teacher)) |
| 273 | .collect(), | 290 | .collect(), |
| 274 | - } | 291 | + }) |
| 275 | } | 292 | } |
| 276 | } | 293 | } |
| 277 | 294 | ||
| @@ -283,17 +300,8 @@ async fn class_or_404(id: &str, db: &Database) -> Result<ClassGroup, AppError> { | |||
| 283 | .ok_or(AppError::NotFound) | 300 | .ok_or(AppError::NotFound) |
| 284 | } | 301 | } |
| 285 | 302 | ||
| 286 | -/// An empty grade is *no* grade: the column is nullable, so a client that omits | ||
| 287 | -/// it and one that sends `""` must land on the same stored row. | ||
| 288 | -fn grade_or_none(text: Option<&str>) -> Result<Option<ClassGrade>, AppError> { | ||
| 289 | - match text { | ||
| 290 | - None | Some("") => Ok(None), | ||
| 291 | - Some(text) => Ok(Some(ClassGrade::try_new(text)?)), | ||
| 292 | - } | ||
| 293 | -} | ||
| 294 | - | ||
| 295 | /// The homeroom teacher a request names, as the row itself — an empty string is | 303 | /// The homeroom teacher a request names, as the row itself — an empty string is |
| 296 | -/// *no* teacher, exactly like `grade`, so omitting the field and clearing it | 304 | +/// *no* teacher, exactly like `year`, so omitting the field and clearing it |
| 297 | /// with `""` land on the same stored row. The named account must exist and hold | 305 | /// with `""` land on the same stored row. The named account must exist and hold |
| 298 | /// teacher-or-higher: a class's homeroom teacher is staff, and the check is the | 306 | /// teacher-or-higher: a class's homeroom teacher is staff, and the check is the |
| 299 | /// same shape `add_member` uses for a non-student. The `User` comes back so the | 307 | /// same shape `add_member` uses for a non-student. The `User` comes back so the |
| @@ -361,12 +369,12 @@ async fn classes_page( | |||
| 361 | } | 369 | } |
| 362 | 370 | ||
| 363 | /// Create a class. Requires manager+ — a class is school structure, not a | 371 | /// Create a class. Requires manager+ — a class is school structure, not a |
| 364 | -/// teacher's own room. `grade` is a free-text label for the year ("9", "10-A"), | 372 | +/// teacher's own room. `grade_level` is the class's rung on the grade ladder |
| 365 | -/// `year` links the academic year (which is what binds the class to a report | 373 | +/// (`0` = anaokulu, `1..=12`), `year` links the academic year (which is what binds the class to a report |
| 366 | /// card and to the rollover), `teacher_id` names the homeroom teacher (a | 374 | /// card and to the rollover), `teacher_id` names the homeroom teacher (a |
| 367 | /// teacher+ account); all optional. | 375 | /// teacher+ account); all optional. |
| 368 | /// | 376 | /// |
| 369 | -/// If a blueprint covers the new class's grade, the class is **stocked from it | 377 | +/// If a blueprint covers the new class's rung, the class is **stocked from it |
| 370 | /// at once** — the same best-effort pump `POST /classes/{id}/blueprint` runs, so | 378 | /// at once** — the same best-effort pump `POST /classes/{id}/blueprint` runs, so |
| 371 | /// a course that does not fit comes back in `skipped` and the class is created | 379 | /// a course that does not fit comes back in `skipped` and the class is created |
| 372 | /// either way. `stocked_from` names the template that did it, and is `null` when | 380 | /// either way. `stocked_from` names the template that did it, and is `null` when |
| @@ -379,7 +387,7 @@ async fn classes_page( | |||
| 379 | request_body = CreateClass, | 387 | request_body = CreateClass, |
| 380 | responses( | 388 | responses( |
| 381 | (status = 201, description = "Class created, stocked from its grade's blueprint when one covers it", body = CreateClassResponse), | 389 | (status = 201, description = "Class created, stocked from its grade's blueprint when one covers it", body = CreateClassResponse), |
| 382 | - (status = 400, description = "Invalid name or grade, an unknown academic year, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), | 390 | + (status = 400, description = "Invalid name or grade_level, an unknown academic year, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), |
| 383 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 391 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 384 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 392 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 385 | (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), | 393 | (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( | |||
| 392 | Json(req): Json<CreateClass>, | 400 | Json(req): Json<CreateClass>, |
| 393 | ) -> Result<(StatusCode, Json<CreateClassResponse>), AppError> { | 401 | ) -> Result<(StatusCode, Json<CreateClassResponse>), AppError> { |
| 394 | let name = ClassName::try_new(&req.name)?; | 402 | let name = ClassName::try_new(&req.name)?; |
| 395 | - let grade = grade_or_none(req.grade.as_deref())?; | 403 | + let grade_level = GradeLevel::new(req.grade_level)?; |
| 396 | // Pre-flight only: `ClassGroup::create` claims a reference on the year | 404 | // Pre-flight only: `ClassGroup::create` claims a reference on the year |
| 397 | // before it writes the link, and a year deleted in between fails that claim | 405 | // before it writes the link, and a year deleted in between fails that claim |
| 398 | // with this very error — so an unknown id reads the same whichever side wins. | 406 | // with this very error — so an unknown id reads the same whichever side wins. |
| @@ -402,7 +410,7 @@ async fn create_class( | |||
| 402 | &st.db, | 410 | &st.db, |
| 403 | user.get_id(), | 411 | user.get_id(), |
| 404 | name, | 412 | name, |
| 405 | - grade, | 413 | + grade_level, |
| 406 | year, | 414 | year, |
| 407 | teacher.as_ref().map(|t| *t.get_id()), | 415 | teacher.as_ref().map(|t| *t.get_id()), |
| 408 | ) | 416 | ) |
| @@ -453,10 +461,9 @@ async fn create_class( | |||
| 453 | )) | 461 | )) |
| 454 | } | 462 | } |
| 455 | 463 | ||
| 456 | -/// Stock a freshly created class from its grade's blueprint, if one covers it: | 464 | +/// Stock a freshly created class from its rung's blueprint, if one covers it: |
| 457 | -/// the template's grade label and the pairs it could not place, or `None` when | 465 | +/// the template's ladder rung and the pairs it could not place, or `None` when |
| 458 | -/// the class has no grade, no blueprint holds that grade, or the stocking could | 466 | +/// no blueprint holds that rung or the stocking could not be carried out. |
| 459 | -/// not be carried out. | ||
| 460 | /// | 467 | /// |
| 461 | /// Swallowing that last case is the deliberate one. Every other pump here may | 468 | /// Swallowing that last case is the deliberate one. Every other pump here may |
| 462 | /// fail its whole request, because the caller can name what it asked for again — | 469 | /// fail its whole request, because the caller can name what it asked for again — |
| @@ -470,35 +477,32 @@ async fn stock_from_blueprint( | |||
| 470 | class: &ClassGroup, | 477 | class: &ClassGroup, |
| 471 | by: &UserId, | 478 | by: &UserId, |
| 472 | db: &Database, | 479 | db: &Database, |
| 473 | -) -> Option<(String, Vec<Skip>)> { | 480 | +) -> Option<(i16, Vec<Skip>)> { |
| 474 | - let grade = class.get_grade()?; | 481 | + let blueprint = class_blueprint::read( |
| 475 | - let blueprint = class_blueprint::read(db, &ClassBlueprintId::for_grade(grade)) | 482 | + db, |
| 476 | - .await | 483 | + &ClassBlueprintId::for_grade(&class.get_grade_level()), |
| 477 | - .ok()??; | 484 | + ) |
| 485 | + .await | ||
| 486 | + .ok()??; | ||
| 478 | let skipped = class_blueprint::apply_to(db, &blueprint, class, by) | 487 | let skipped = class_blueprint::apply_to(db, &blueprint, class, by) |
| 479 | .await | 488 | .await |
| 480 | .ok()?; | 489 | .ok()?; |
| 481 | - Some((blueprint.get_grade().as_str().to_string(), skipped)) | 490 | + Some((blueprint.get_grade_level().get(), skipped)) |
| 482 | } | 491 | } |
| 483 | 492 | ||
| 484 | /// Filter for the class index. | 493 | /// Filter for the class index. |
| 485 | #[derive(Deserialize, IntoParams)] | 494 | #[derive(Deserialize, IntoParams)] |
| 486 | struct ClassFilter { | 495 | struct ClassFilter { |
| 487 | - /// Narrow to the sections carrying this exact grade label — the same | 496 | + /// Narrow to the sections carrying this exact ladder rung — the same |
| 488 | - /// spelling a blueprint is keyed by, matched verbatim (no trimming, no case | 497 | + /// equality a blueprint is keyed by. Omit for every class. |
| 489 | - /// folding: a filter that normalized would disagree with the pump it exists | 498 | + #[param(example = 9)] |
| 490 | - /// to debug). `?grade=` (empty) asks for the sections carrying *no* grade, | 499 | + grade_level: Option<i16>, |
| 491 | - /// exactly as an empty `grade` on a write means no grade. Omit for every | ||
| 492 | - /// class. | ||
| 493 | - #[param(example = "9")] | ||
| 494 | - grade: Option<String>, | ||
| 495 | } | 500 | } |
| 496 | 501 | ||
| 497 | -/// List every class, newest first. Requires teacher+. `?grade=` narrows to one | 502 | +/// List every class, newest first. Requires teacher+. `?grade_level=` narrows |
| 498 | -/// grade label, matched exactly as written — the label a blueprint is keyed by, | 503 | +/// to one ladder rung — the same equality a blueprint is keyed by, so this is |
| 499 | -/// so this is the read that shows which sections a `POST /classes/blueprints` | 504 | +/// the read that shows which sections a `POST /classes/blueprints` pump |
| 500 | -/// pump covered (and `?grade=` on its own lists the sections with no grade at | 505 | +/// covered. An unknown rung is an empty page, not a `404`. Paged via |
| 501 | -/// all). An unknown label is an empty page, not a `404`. Paged via | ||
| 502 | /// `?limit=&offset=` (omit `limit` for the full list); returns a | 506 | /// `?limit=&offset=` (omit `limit` for the full list); returns a |
| 503 | /// `{items, total, limit, offset}` envelope whose `total` counts every class | 507 | /// `{items, total, limit, offset}` envelope whose `total` counts every class |
| 504 | /// under the same filter, not just this page. | 508 | /// under the same filter, not just this page. |
| @@ -510,7 +514,7 @@ struct ClassFilter { | |||
| 510 | params(ClassFilter, PageParams), | 514 | params(ClassFilter, PageParams), |
| 511 | responses( | 515 | responses( |
| 512 | (status = 200, description = "A page of classes (the full list when unpaged)", body = Page<ClassResponse>), | 516 | (status = 200, description = "A page of classes (the full list when unpaged)", body = Page<ClassResponse>), |
| 513 | - (status = 400, description = "Invalid grade, limit or offset", body = ErrorResponse), | 517 | + (status = 400, description = "Invalid grade_level, limit or offset", body = ErrorResponse), |
| 514 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 518 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 515 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 519 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 516 | ), | 520 | ), |
| @@ -522,15 +526,13 @@ async fn list_classes( | |||
| 522 | Query(page): Query<PageParams>, | 526 | Query(page): Query<PageParams>, |
| 523 | ) -> Result<Json<Page<ClassResponse>>, AppError> { | 527 | ) -> Result<Json<Page<ClassResponse>>, AppError> { |
| 524 | let (limit, offset) = page.resolve()?; | 528 | let (limit, offset) = page.resolve()?; |
| 525 | - // The same newtype the write paths validate against, so an over-long label | 529 | + // The same newtype the write paths validate against, so an off-ladder |
| 526 | - // is the same `400` here as on a create. `grade_or_none` folds `""` into | 530 | + // rung is the same `400` here as on a create or a PATCH. |
| 527 | - // "no grade"; the outer `Option` is what keeps *omitted* apart from it. | 531 | + let grade_level = filter |
| 528 | - let grade = filter | 532 | + .grade_level |
| 529 | - .grade | 533 | + .map(GradeLevel::new) |
| 530 | - .as_deref() | ||
| 531 | - .map(|grade| grade_or_none(Some(grade))) | ||
| 532 | .transpose()?; | 534 | .transpose()?; |
| 533 | - let (classes, total) = class_group::list_all(&st.db, grade, limit, offset).await?; | 535 | + let (classes, total) = class_group::list_all(&st.db, grade_level, limit, offset).await?; |
| 534 | // Join people onto the page alone — the lookup shrinks with the window. | 536 | // Join people onto the page alone — the lookup shrinks with the window. |
| 535 | let people = person_map( | 537 | let people = person_map( |
| 536 | classes.iter().flat_map(|class| class_people(class, true)), | 538 | classes.iter().flat_map(|class| class_people(class, true)), |
| @@ -579,7 +581,7 @@ async fn get_class( | |||
| 579 | request_body = UpdateClass, | 581 | request_body = UpdateClass, |
| 580 | responses( | 582 | responses( |
| 581 | (status = 200, description = "Updated class", body = ClassResponse), | 583 | (status = 200, description = "Updated class", body = ClassResponse), |
| 582 | - (status = 400, description = "Invalid name or grade, an unknown academic year, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), | 584 | + (status = 400, description = "Invalid name or grade_level, an unknown academic year, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), |
| 583 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 585 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 584 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 586 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 585 | (status = 404, description = "Not found", body = ErrorResponse), | 587 | (status = 404, description = "Not found", body = ErrorResponse), |
| @@ -603,10 +605,7 @@ async fn update_class( | |||
| 603 | // omitted field stays `None` so the save never re-sends this snapshot's | 605 | // omitted field stays `None` so the save never re-sends this snapshot's |
| 604 | // value over a concurrent PATCH of that field. | 606 | // value over a concurrent PATCH of that field. |
| 605 | let name = req.name.as_deref().map(ClassName::try_new).transpose()?; | 607 | let name = req.name.as_deref().map(ClassName::try_new).transpose()?; |
| 606 | - let grade = match req.grade { | 608 | + let grade_level = req.grade_level.map(GradeLevel::new).transpose()?; |
| 607 | - Some(ref update) => Some(grade_or_none(update.as_deref())?), | ||
| 608 | - None => None, | ||
| 609 | - }; | ||
| 610 | let year = match req.year { | 609 | let year = match req.year { |
| 611 | // Explicit `null` clears the link; a value must name a real year. | 610 | // Explicit `null` clears the link; a value must name a real year. |
| 612 | Some(update) => Some(academic_year::resolve(&st.db, update.as_deref()).await?), | 611 | Some(update) => Some(academic_year::resolve(&st.db, update.as_deref()).await?), |
| @@ -625,7 +624,7 @@ async fn update_class( | |||
| 625 | &st.db, | 624 | &st.db, |
| 626 | class, | 625 | class, |
| 627 | name, | 626 | name, |
| 628 | - grade, | 627 | + grade_level, |
| 629 | year, | 628 | year, |
| 630 | teacher.map(|teacher| teacher.map(|teacher| *teacher.get_id())), | 629 | teacher.map(|teacher| teacher.map(|teacher| *teacher.get_id())), |
| 631 | ) | 630 | ) |
| @@ -948,9 +947,16 @@ async fn attach_course( | |||
| 948 | 947 | ||
| 949 | let link = class_course::attach(&st.db, class.get_id(), course.get_id(), user.get_id()).await?; | 948 | let link = class_course::attach(&st.db, class.get_id(), course.get_id(), user.get_id()).await?; |
| 950 | let people = PersonRef::map_of(&[&user]); | 949 | let people = PersonRef::map_of(&[&user]); |
| 950 | + let content = { | ||
| 951 | + let refs = [&link]; | ||
| 952 | + crate::service::instance_resolve::resolved_content(&st.db, &refs).await? | ||
| 953 | + }; | ||
| 954 | + let resolved = content | ||
| 955 | + .get(link.get_id().key().as_str()) | ||
| 956 | + .expect("resolved_content covers every instance it is given"); | ||
| 951 | Ok(( | 957 | Ok(( |
| 952 | StatusCode::CREATED, | 958 | StatusCode::CREATED, |
| 953 | - Json(ClassCourseResponse::new(&link, &[], &people)), | 959 | + Json(ClassCourseResponse::new(&st.db, &link, resolved, &[], &people).await?), |
| 954 | )) | 960 | )) |
| 955 | } | 961 | } |
| 956 | 962 | ||
| @@ -992,10 +998,17 @@ async fn list_class_courses( | |||
| 992 | &st.db, | 998 | &st.db, |
| 993 | ) | 999 | ) |
| 994 | .await?; | 1000 | .await?; |
| 995 | - let items = with_teachers | 1001 | + // The page's resolved titles/descriptions in one batch (one offering |
| 996 | - .iter() | 1002 | + // read + one catalog read), never per-row fallback reads. |
| 997 | - .map(|(row, teachers)| ClassCourseResponse::new(row, teachers, &people)) | 1003 | + let refs: Vec<&ClassCourse> = with_teachers.iter().map(|(row, _)| row).collect(); |
| 998 | - .collect(); | 1004 | + let content = crate::service::instance_resolve::resolved_content(&st.db, &refs).await?; |
| 1005 | + let mut items = Vec::with_capacity(with_teachers.len()); | ||
| 1006 | + for (row, teachers) in &with_teachers { | ||
| 1007 | + let resolved = content | ||
| 1008 | + .get(row.get_id().key().as_str()) | ||
| 1009 | + .expect("resolved_content covers every instance it is given"); | ||
| 1010 | + items.push(ClassCourseResponse::new(&st.db, row, resolved, teachers, &people).await?); | ||
| 1011 | + } | ||
| 999 | Ok(Json(Page::new(items, total, limit, offset))) | 1012 | Ok(Json(Page::new(items, total, limit, offset))) |
| 1000 | } | 1013 | } |
| 1001 | 1014 | ||
| @@ -1078,11 +1091,10 @@ async fn detach_course( | |||
| 1078 | 1091 | ||
| 1079 | #[derive(Deserialize, ToSchema)] | 1092 | #[derive(Deserialize, ToSchema)] |
| 1080 | struct CreateBlueprint { | 1093 | struct CreateBlueprint { |
| 1081 | - /// The grade label this template stocks — the same free text a class | 1094 | + /// The ladder rung this template stocks — 0 = anaokulu, 1..=12 school |
| 1082 | - /// carries in `grade` ("9", "10-A"). It is the blueprint's own id, so it | 1095 | + /// years. It is the blueprint's own id, so a rung off the ladder is a 400. |
| 1083 | - /// must be non-empty and free of `/ \ ? # %`. | 1096 | + #[schema(minimum = 0, maximum = 12, example = 9)] |
| 1084 | - #[schema(max_length = 20, example = "9")] | 1097 | + grade_level: i16, |
| 1085 | - grade: String, | ||
| 1086 | /// The courses every class section at that grade takes. | 1098 | /// The courses every class section at that grade takes. |
| 1087 | course_ids: Vec<String>, | 1099 | course_ids: Vec<String>, |
| 1088 | } | 1100 | } |
| @@ -1097,9 +1109,9 @@ struct UpdateBlueprint { | |||
| 1097 | 1109 | ||
| 1098 | #[derive(Serialize, ToSchema)] | 1110 | #[derive(Serialize, ToSchema)] |
| 1099 | struct BlueprintResponse { | 1111 | struct BlueprintResponse { |
| 1100 | - /// The grade label, which is also the blueprint's id in every path here. | 1112 | + /// The ladder rung, which is also the blueprint's id in every path here. |
| 1101 | - #[schema(example = "9")] | 1113 | + #[schema(example = 9)] |
| 1102 | - grade: String, | 1114 | + grade_level: i16, |
| 1103 | /// The course ids this grade's sections take. | 1115 | /// The course ids this grade's sections take. |
| 1104 | courses: Vec<String>, | 1116 | courses: Vec<String>, |
| 1105 | /// Who wrote the template. | 1117 | /// Who wrote the template. |
| @@ -1112,7 +1124,7 @@ impl BlueprintResponse { | |||
| 1112 | people: &std::collections::HashMap<String, PersonRef>, | 1124 | people: &std::collections::HashMap<String, PersonRef>, |
| 1113 | ) -> Self { | 1125 | ) -> Self { |
| 1114 | Self { | 1126 | Self { |
| 1115 | - grade: blueprint.get_grade().as_str().to_string(), | 1127 | + grade_level: blueprint.get_grade_level().get(), |
| 1116 | courses: blueprint | 1128 | courses: blueprint |
| 1117 | .get_courses() | 1129 | .get_courses() |
| 1118 | .iter() | 1130 | .iter() |
| @@ -1181,11 +1193,9 @@ impl SkipResponse { | |||
| 1181 | struct BlueprintPumpResponse { | 1193 | struct BlueprintPumpResponse { |
| 1182 | blueprint: BlueprintResponse, | 1194 | blueprint: BlueprintResponse, |
| 1183 | /// How many class sections this pump reached. **`0` means no section | 1195 | /// How many class sections this pump reached. **`0` means no section |
| 1184 | - /// carries this grade label** — the template was saved and stocked | 1196 | + /// carries this rung** — the template was saved and stocked nothing: |
| 1185 | - /// nothing. A grade is free text and matched exactly, so `"9 "`, `"9-A"` | 1197 | + /// an empty `skipped` alone reads the same whether every section took |
| 1186 | - /// and `"9"` are three different grades: check the label against the one | 1198 | + /// the list or none was found. |
| 1187 | - /// the sections actually carry, since an empty `skipped` alone reads the | ||
| 1188 | - /// same whether every section took the list or none was found. | ||
| 1189 | /// | 1199 | /// |
| 1190 | /// The sections *reached*, not the ones the grade holds: a | 1200 | /// The sections *reached*, not the ones the grade holds: a |
| 1191 | /// `blueprint_deleted` skip ends the run, and this then counts the ones | 1201 | /// `blueprint_deleted` skip ends the run, and this then counts the ones |
| @@ -1213,8 +1223,8 @@ struct SectionStatusResponse { | |||
| 1213 | 1223 | ||
| 1214 | #[derive(Serialize, ToSchema)] | 1224 | #[derive(Serialize, ToSchema)] |
| 1215 | struct BlueprintStatusResponse { | 1225 | struct BlueprintStatusResponse { |
| 1216 | - #[schema(example = "9")] | 1226 | + #[schema(example = 9)] |
| 1217 | - grade: String, | 1227 | + grade_level: i16, |
| 1218 | /// The template every section below is measured against. | 1228 | /// The template every section below is measured against. |
| 1219 | courses: Vec<String>, | 1229 | courses: Vec<String>, |
| 1220 | /// How many sections carry this grade label — the same count a pump | 1230 | /// 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<Vec<CourseId>, | |||
| 1250 | Ok(courses) | 1260 | Ok(courses) |
| 1251 | } | 1261 | } |
| 1252 | 1262 | ||
| 1253 | -/// The blueprint a path grade names, or a 404. | 1263 | +/// The blueprint `id` names, or a 404. Path handlers parse their segment |
| 1254 | -async fn blueprint_or_404(grade: &str, db: &Database) -> Result<ClassBlueprint, AppError> { | 1264 | +/// with `ClassBlueprintId::from_key`, which lands a non-numeric key on an id |
| 1255 | - class_blueprint::read(db, &ClassBlueprintId::from_key(grade)) | 1265 | +/// that matches no row — a `404`, never a decode panic. |
| 1256 | - .await? | 1266 | +async fn blueprint_or_404(id: &ClassBlueprintId, db: &Database) -> Result<ClassBlueprint, AppError> { |
| 1257 | - .ok_or(AppError::NotFound) | 1267 | + class_blueprint::read(db, id).await?.ok_or(AppError::NotFound) |
| 1258 | } | 1268 | } |
| 1259 | 1269 | ||
| 1260 | async fn blueprint_body( | 1270 | async fn blueprint_body( |
| @@ -1289,7 +1299,7 @@ async fn blueprint_body( | |||
| 1289 | request_body = CreateBlueprint, | 1299 | request_body = CreateBlueprint, |
| 1290 | responses( | 1300 | responses( |
| 1291 | (status = 201, description = "Blueprint created, with the number of sections it reached and the classes it could not stock", body = BlueprintPumpResponse), | 1301 | (status = 201, description = "Blueprint created, with the number of sections it reached and the classes it could not stock", body = BlueprintPumpResponse), |
| 1292 | - (status = 400, description = "Invalid or unaddressable grade, too many courses, or a course that does not exist", body = ErrorResponse), | 1302 | + (status = 400, description = "A grade_level off the ladder, too many courses, or a course that does not exist", body = ErrorResponse), |
| 1293 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1303 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1294 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 1304 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 1295 | (status = 409, description = "A blueprint already exists for that grade", body = ErrorResponse), | 1305 | (status = 409, description = "A blueprint already exists for that grade", body = ErrorResponse), |
| @@ -1301,9 +1311,9 @@ async fn create_blueprint( | |||
| 1301 | RequireManager(user): RequireManager, | 1311 | RequireManager(user): RequireManager, |
| 1302 | Json(req): Json<CreateBlueprint>, | 1312 | Json(req): Json<CreateBlueprint>, |
| 1303 | ) -> Result<(StatusCode, Json<BlueprintPumpResponse>), AppError> { | 1313 | ) -> Result<(StatusCode, Json<BlueprintPumpResponse>), AppError> { |
| 1304 | - let grade = ClassBlueprint::grade_key(&req.grade)?; | 1314 | + let grade_level = GradeLevel::new(req.grade_level)?; |
| 1305 | let courses = resolve_courses(&req.course_ids, &st.db).await?; | 1315 | let courses = resolve_courses(&req.course_ids, &st.db).await?; |
| 1306 | - let mut blueprint = class_blueprint::create(&st.db, user.get_id(), grade, courses).await?; | 1316 | + let mut blueprint = class_blueprint::create(&st.db, user.get_id(), grade_level, courses).await?; |
| 1307 | let pumped = class_blueprint::pump(&st.db, &mut blueprint, user.get_id()).await?; | 1317 | let pumped = class_blueprint::pump(&st.db, &mut blueprint, user.get_id()).await?; |
| 1308 | let body = blueprint_body(&blueprint, &pumped, &st.db).await?; | 1318 | let body = blueprint_body(&blueprint, &pumped, &st.db).await?; |
| 1309 | Ok((StatusCode::CREATED, Json(body))) | 1319 | Ok((StatusCode::CREATED, Json(body))) |
| @@ -1349,7 +1359,7 @@ async fn list_blueprints( | |||
| 1349 | path = "/blueprints/{grade}", | 1359 | path = "/blueprints/{grade}", |
| 1350 | tag = "classes", | 1360 | tag = "classes", |
| 1351 | security(("session_cookie" = [])), | 1361 | security(("session_cookie" = [])), |
| 1352 | - params(("grade" = String, Path, description = "Grade label")), | 1362 | + params(("grade" = String, Path, description = "Grade level (0 = anaokulu, 1..=12 school years)")), |
| 1353 | responses( | 1363 | responses( |
| 1354 | (status = 200, description = "The blueprint", body = BlueprintResponse), | 1364 | (status = 200, description = "The blueprint", body = BlueprintResponse), |
| 1355 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1365 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| @@ -1362,7 +1372,7 @@ async fn get_blueprint( | |||
| 1362 | RequireManager(_user): RequireManager, | 1372 | RequireManager(_user): RequireManager, |
| 1363 | Path(grade): Path<String>, | 1373 | Path(grade): Path<String>, |
| 1364 | ) -> Result<Json<BlueprintResponse>, AppError> { | 1374 | ) -> Result<Json<BlueprintResponse>, AppError> { |
| 1365 | - let blueprint = blueprint_or_404(&grade, &st.db).await?; | 1375 | + let blueprint = blueprint_or_404(&ClassBlueprintId::from_key(&grade), &st.db).await?; |
| 1366 | let people = person_map([*blueprint.get_creator()], &st.db).await?; | 1376 | let people = person_map([*blueprint.get_creator()], &st.db).await?; |
| 1367 | Ok(Json(BlueprintResponse::new(&blueprint, &people))) | 1377 | Ok(Json(BlueprintResponse::new(&blueprint, &people))) |
| 1368 | } | 1378 | } |
| @@ -1387,7 +1397,7 @@ async fn get_blueprint( | |||
| 1387 | path = "/blueprints/{grade}", | 1397 | path = "/blueprints/{grade}", |
| 1388 | tag = "classes", | 1398 | tag = "classes", |
| 1389 | security(("session_cookie" = [])), | 1399 | security(("session_cookie" = [])), |
| 1390 | - params(("grade" = String, Path, description = "Grade label")), | 1400 | + params(("grade" = String, Path, description = "Grade level (0 = anaokulu, 1..=12 school years)")), |
| 1391 | request_body = UpdateBlueprint, | 1401 | request_body = UpdateBlueprint, |
| 1392 | responses( | 1402 | responses( |
| 1393 | (status = 200, description = "Updated blueprint, with the number of sections it reached and the classes it could not stock", body = BlueprintPumpResponse), | 1403 | (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( | |||
| 1405 | Path(grade): Path<String>, | 1415 | Path(grade): Path<String>, |
| 1406 | Json(req): Json<UpdateBlueprint>, | 1416 | Json(req): Json<UpdateBlueprint>, |
| 1407 | ) -> Result<Json<BlueprintPumpResponse>, AppError> { | 1417 | ) -> Result<Json<BlueprintPumpResponse>, AppError> { |
| 1408 | - let blueprint = blueprint_or_404(&grade, &st.db).await?; | 1418 | + let blueprint = blueprint_or_404(&ClassBlueprintId::from_key(&grade), &st.db).await?; |
| 1409 | let courses = resolve_courses(&req.course_ids, &st.db).await?; | 1419 | let courses = resolve_courses(&req.course_ids, &st.db).await?; |
| 1410 | // The dropped templates cascade: every sourced instance they leave behind | 1420 | // The dropped templates cascade: every sourced instance they leave behind |
| 1411 | // is detached, and its subtree's files are gone from the database and the | 1421 | // is detached, and its subtree's files are gone from the database and the |
| @@ -1430,7 +1440,7 @@ async fn update_blueprint( | |||
| 1430 | path = "/blueprints/{grade}", | 1440 | path = "/blueprints/{grade}", |
| 1431 | tag = "classes", | 1441 | tag = "classes", |
| 1432 | security(("session_cookie" = [])), | 1442 | security(("session_cookie" = [])), |
| 1433 | - params(("grade" = String, Path, description = "Grade label")), | 1443 | + params(("grade" = String, Path, description = "Grade level (0 = anaokulu, 1..=12 school years)")), |
| 1434 | responses( | 1444 | responses( |
| 1435 | (status = 204, description = "Deleted"), | 1445 | (status = 204, description = "Deleted"), |
| 1436 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1446 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| @@ -1444,7 +1454,7 @@ async fn delete_blueprint( | |||
| 1444 | RequireManager(_user): RequireManager, | 1454 | RequireManager(_user): RequireManager, |
| 1445 | Path(grade): Path<String>, | 1455 | Path(grade): Path<String>, |
| 1446 | ) -> Result<StatusCode, AppError> { | 1456 | ) -> Result<StatusCode, AppError> { |
| 1447 | - let blueprint = blueprint_or_404(&grade, &st.db).await?; | 1457 | + let blueprint = blueprint_or_404(&ClassBlueprintId::from_key(&grade), &st.db).await?; |
| 1448 | // Deleting a blueprint detaches every sourced instance it started, subtree | 1458 | // Deleting a blueprint detaches every sourced instance it started, subtree |
| 1449 | // and all — the returned keys are the only record of the files those rows | 1459 | // and all — the returned keys are the only record of the files those rows |
| 1450 | // named, so they are unlinked here (the same contract the instance-detach | 1460 | // named, so they are unlinked here (the same contract the instance-detach |
| @@ -1477,7 +1487,7 @@ async fn delete_blueprint( | |||
| 1477 | path = "/blueprints/{grade}/status", | 1487 | path = "/blueprints/{grade}/status", |
| 1478 | tag = "classes", | 1488 | tag = "classes", |
| 1479 | security(("session_cookie" = [])), | 1489 | security(("session_cookie" = [])), |
| 1480 | - params(("grade" = String, Path, description = "Grade label")), | 1490 | + params(("grade" = String, Path, description = "Grade level (0 = anaokulu, 1..=12 school years)")), |
| 1481 | responses( | 1491 | responses( |
| 1482 | (status = 200, description = "Every section at the grade, with the template courses it is missing", body = BlueprintStatusResponse), | 1492 | (status = 200, description = "Every section at the grade, with the template courses it is missing", body = BlueprintStatusResponse), |
| 1483 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1493 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| @@ -1490,10 +1500,10 @@ async fn blueprint_status( | |||
| 1490 | RequireManager(_user): RequireManager, | 1500 | RequireManager(_user): RequireManager, |
| 1491 | Path(grade): Path<String>, | 1501 | Path(grade): Path<String>, |
| 1492 | ) -> Result<Json<BlueprintStatusResponse>, AppError> { | 1502 | ) -> Result<Json<BlueprintStatusResponse>, AppError> { |
| 1493 | - let blueprint = blueprint_or_404(&grade, &st.db).await?; | 1503 | + let blueprint = blueprint_or_404(&ClassBlueprintId::from_key(&grade), &st.db).await?; |
| 1494 | let sections = class_blueprint::status(&st.db, &blueprint).await?; | 1504 | let sections = class_blueprint::status(&st.db, &blueprint).await?; |
| 1495 | Ok(Json(BlueprintStatusResponse { | 1505 | Ok(Json(BlueprintStatusResponse { |
| 1496 | - grade: blueprint.get_grade().as_str().to_string(), | 1506 | + grade_level: blueprint.get_grade_level().get(), |
| 1497 | courses: blueprint | 1507 | courses: blueprint |
| 1498 | .get_courses() | 1508 | .get_courses() |
| 1499 | .iter() | 1509 | .iter() |
| @@ -1543,8 +1553,8 @@ async fn apply_blueprint( | |||
| 1543 | Path(id): Path<String>, | 1553 | Path(id): Path<String>, |
| 1544 | ) -> Result<Json<ApplyResponse>, AppError> { | 1554 | ) -> Result<Json<ApplyResponse>, AppError> { |
| 1545 | let class = class_or_404(&id, &st.db).await?; | 1555 | let class = class_or_404(&id, &st.db).await?; |
| 1546 | - let grade = class.get_grade().ok_or(AppError::NotFound)?; | 1556 | + let blueprint = |
| 1547 | - let blueprint = blueprint_or_404(grade.as_str(), &st.db).await?; | 1557 | + blueprint_or_404(&ClassBlueprintId::for_grade(&class.get_grade_level()), &st.db).await?; |
| 1548 | // The pump writes both ends, so both are guarded — the class, whose year | 1558 | // The pump writes both ends, so both are guarded — the class, whose year |
| 1549 | // every instance it mints will belong to, and every course the template | 1559 | // every instance it mints will belong to, and every course the template |
| 1550 | // names. A course the template names that is already gone is the pump's own | 1560 | // names. A course the template names that is already gone is the pump's own |
| @@ -1561,20 +1571,15 @@ async fn apply_blueprint( | |||
| 1561 | mod tests { | 1571 | mod tests { |
| 1562 | use super::*; | 1572 | use super::*; |
| 1563 | 1573 | ||
| 1564 | - /// The nullable-grade rule both write paths share: absent and `""` are the | 1574 | + /// The one validation both write paths share: the rung must sit on the |
| 1565 | - /// same *no grade*, so a PATCH clearing with `""` cannot store a blank | 1575 | + /// ladder, and the wire type is the integer itself — no `"9"`/`"10-A"` |
| 1566 | - /// label a create could never make. | 1576 | + /// string ever crosses the boundary. |
| 1567 | #[test] | 1577 | #[test] |
| 1568 | - fn an_empty_grade_is_no_grade() { | 1578 | + fn a_grade_level_is_a_ladder_rung() { |
| 1569 | - assert!(grade_or_none(None).unwrap().is_none()); | 1579 | + assert!(GradeLevel::new(0).is_ok()); |
| 1570 | - assert!(grade_or_none(Some("")).unwrap().is_none()); | 1580 | + assert!(GradeLevel::new(12).is_ok()); |
| 1571 | - assert_eq!( | 1581 | + assert!(GradeLevel::new(-1).is_err()); |
| 1572 | - grade_or_none(Some("9")) | 1582 | + assert!(GradeLevel::new(13).is_err()); |
| 1573 | - .unwrap() | ||
| 1574 | - .map(|g| g.as_str().to_string()), | ||
| 1575 | - Some("9".to_string()) | ||
| 1576 | - ); | ||
| 1577 | - assert!(grade_or_none(Some(&"x".repeat(1000))).is_err()); | ||
| 1578 | } | 1583 | } |
| 1579 | 1584 | ||
| 1580 | /// The same nullable rule on the homeroom teacher, plus the bar it holds: | 1585 | /// The same nullable rule on the homeroom teacher, plus the bar it holds: |
src/web/courses.rsmodified+5 -0
| @@ -220,6 +220,11 @@ async fn list_courses( | |||
| 220 | let window = paginate(&courses, limit, offset); | 220 | let window = paginate(&courses, limit, offset); |
| 221 | // Join creators onto the page alone — the lookup shrinks with the window. | 221 | // Join creators onto the page alone — the lookup shrinks with the window. |
| 222 | let people = person_map(window.iter().flat_map(course_people), &st.db).await?; | 222 | let people = person_map(window.iter().flat_map(course_people), &st.db).await?; |
| 223 | + // Deliberate exception to the instance-resolved display rule: this | ||
| 224 | + // surface IS the ders catalog, so it shows each row's own catalog | ||
| 225 | + // title/description. The grade templates (`/offerings`) and the | ||
| 226 | + // per-class instances (`/instances`) resolve from it — they never edit | ||
| 227 | + // it. | ||
| 223 | let items = window | 228 | let items = window |
| 224 | .iter() | 229 | .iter() |
| 225 | .map(|course| CourseResponse::new(course, &people)) | 230 | .map(|course| CourseResponse::new(course, &people)) |
src/web/exam_weights.rsadded+368 -0
| @@ -0,0 +1,368 @@ | |||
| 1 | +//! The exam-weight override routes: per-kind weights on the grade-level | ||
| 2 | +//! template (`/offerings/{id}/exam-weights`, manager+) and on the class | ||
| 3 | +//! section (`/instances/{id}/exam-weights`, the D10 instance gate), plus the | ||
| 4 | +//! section's reset. | ||
| 5 | +//! | ||
| 6 | +//! Every `GET` returns the **resolved** map — the effective weight of every | ||
| 7 | +//! kind under that level, computed here — so a client renders it verbatim and | ||
| 8 | +//! never re-implements the class → offering → settings → 1 chain. The | ||
| 9 | +//! instance map carries the `inherited` flag: while it is `true` the map is | ||
| 10 | +//! the offering's resolved set; while `false` it is exactly the section's own | ||
| 11 | +//! rows, empty included (an own set in force is authoritative even when | ||
| 12 | +//! empty). | ||
| 13 | +//! | ||
| 14 | +//! A write naming a kind the school does not run is the one refusal here with | ||
| 15 | +//! a machine code — 400 `unknown_exam_kind` — because a client can branch on | ||
| 16 | +//! "fix the kind" vs "fix the weight"; it is rendered by this module (the | ||
| 17 | +//! service's `ValidationError::Invalid { field: "kind" }` re-wrapped), since | ||
| 18 | +//! the coded-body vocabulary lives with the route that publishes it. | ||
| 19 | + | ||
| 20 | +use axum::Json; | ||
| 21 | +use axum::extract::Path; | ||
| 22 | +use axum::http::StatusCode; | ||
| 23 | +use axum::response::{IntoResponse, Response}; | ||
| 24 | +use serde::{Deserialize, Serialize}; | ||
| 25 | +use utoipa::ToSchema; | ||
| 26 | +use utoipa_axum::router::OpenApiRouter; | ||
| 27 | +use utoipa_axum::routes; | ||
| 28 | + | ||
| 29 | +use crate::database::Database; | ||
| 30 | +use crate::domain::class_course::{ClassCourse, ClassCourseId}; | ||
| 31 | +use crate::domain::course_offering::CourseOfferingId; | ||
| 32 | +use crate::domain::exam_weight::ExamWeight; | ||
| 33 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 34 | +use crate::service; | ||
| 35 | +use crate::state::AppState; | ||
| 36 | +use crate::web::instances::can_view_instance; | ||
| 37 | +use crate::web::tenant_state::State; | ||
| 38 | + | ||
| 39 | +use super::{CurrentUser, RequireManager, RequireTeacher}; | ||
| 40 | + | ||
| 41 | +/// Mounted under `/offerings` — the template's weight routes. | ||
| 42 | +pub fn offering_routes() -> OpenApiRouter<AppState> { | ||
| 43 | + OpenApiRouter::new() | ||
| 44 | + .routes(routes!(get_offering_weights, patch_offering_weight)) | ||
| 45 | + .routes(routes!(delete_offering_weight)) | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// Mounted inside `/instances` — the section's weight routes and reset. | ||
| 49 | +pub fn instance_routes() -> OpenApiRouter<AppState> { | ||
| 50 | + OpenApiRouter::new() | ||
| 51 | + .routes(routes!(get_instance_weights, patch_instance_weight)) | ||
| 52 | + .routes(routes!(delete_instance_weight)) | ||
| 53 | + .routes(routes!(reset_instance_weights)) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +#[derive(Deserialize, ToSchema)] | ||
| 57 | +struct PatchExamWeight { | ||
| 58 | + /// The exam kind exactly as the school spells it in `GET /settings` | ||
| 59 | + /// (`settings.exam_kinds`). Anything else is a 400 `unknown_exam_kind`. | ||
| 60 | + #[schema(example = "midterm")] | ||
| 61 | + kind: String, | ||
| 62 | + /// The weight this kind carries under the level being edited: 1..=100. | ||
| 63 | + #[schema(minimum = 1, maximum = 100, example = 3)] | ||
| 64 | + weight: i64, | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// One resolved entry: the kind and the weight an exam of it carries *here* | ||
| 68 | +/// after the whole fallback chain. | ||
| 69 | +#[derive(Serialize, ToSchema)] | ||
| 70 | +pub struct ExamWeightEntry { | ||
| 71 | + #[schema(example = "midterm")] | ||
| 72 | + pub kind: String, | ||
| 73 | + pub weight: i64, | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +impl ExamWeightEntry { | ||
| 77 | + pub(crate) fn of(row: &ExamWeight) -> Self { | ||
| 78 | + Self { | ||
| 79 | + kind: row.get_kind().to_string(), | ||
| 80 | + weight: row.get_weight(), | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// The template's resolved weight map. | ||
| 86 | +#[derive(Serialize, ToSchema)] | ||
| 87 | +pub struct OfferingExamWeightsResponse { | ||
| 88 | + /// Every kind the school runs (plus any kind a stored row adds), each at | ||
| 89 | + /// its effective weight: the offering's own row, else the settings | ||
| 90 | + /// weight, else 1. | ||
| 91 | + pub weights: Vec<ExamWeightEntry>, | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +/// The section's resolved weight map, with the override switch. | ||
| 95 | +#[derive(Serialize, ToSchema)] | ||
| 96 | +pub struct InstanceExamWeightsResponse { | ||
| 97 | + /// `true` = the section follows its offering's set (the map below is the | ||
| 98 | + /// offering's, resolved); `false` = the section's own table is | ||
| 99 | + /// authoritative and the map is exactly its rows — including when that is | ||
| 100 | + /// none, which is how a section zeroes the template's weights. | ||
| 101 | + pub inherited: bool, | ||
| 102 | + pub weights: Vec<ExamWeightEntry>, | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +async fn offering_or_404(key: &str, db: &Database) -> Result<CourseOfferingId, AppError> { | ||
| 106 | + let id = CourseOfferingId::from_key(key); | ||
| 107 | + if service::course_offering::read(db, &id).await?.is_none() { | ||
| 108 | + return Err(AppError::NotFound); | ||
| 109 | + } | ||
| 110 | + Ok(id) | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/// The instance row the write gates judge — a missing id is a 404 before any | ||
| 114 | +/// body is read. | ||
| 115 | +async fn instance_or_404(key: &str, db: &Database) -> Result<ClassCourse, AppError> { | ||
| 116 | + service::class_course::read(db, &ClassCourseId::from_key(key)) | ||
| 117 | + .await? | ||
| 118 | + .ok_or(AppError::NotFound) | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/// Re-renders the service's kind refusal as the coded 400 this route | ||
| 122 | +/// documents; every other error keeps its own wire shape. | ||
| 123 | +fn kind_refusal(err: AppError, kind: &str) -> Response { | ||
| 124 | + if let AppError::Validation(ValidationError::Invalid { field: "kind", .. }) = &err { | ||
| 125 | + return ( | ||
| 126 | + StatusCode::BAD_REQUEST, | ||
| 127 | + Json(serde_json::json!({ | ||
| 128 | + "error": format!("kind: `{kind}` is not a known exam kind"), | ||
| 129 | + "code": "unknown_exam_kind", | ||
| 130 | + })), | ||
| 131 | + ) | ||
| 132 | + .into_response(); | ||
| 133 | + } | ||
| 134 | + err.into_response() | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +// ---- the template's weights -------------------------------------------------- | ||
| 138 | + | ||
| 139 | +/// The grade-level template's resolved exam-kind weights. Any signed-in | ||
| 140 | +/// session. | ||
| 141 | +#[utoipa::path( | ||
| 142 | + get, | ||
| 143 | + path = "/{id}/exam-weights", | ||
| 144 | + tag = "offerings", | ||
| 145 | + security(("session_cookie" = [])), | ||
| 146 | + params(("id" = String, Path, description = "Offering id")), | ||
| 147 | + responses( | ||
| 148 | + (status = 200, description = "The offering's resolved weights", body = OfferingExamWeightsResponse), | ||
| 149 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 150 | + (status = 404, description = "Offering not found", body = ErrorResponse), | ||
| 151 | + ), | ||
| 152 | +)] | ||
| 153 | +async fn get_offering_weights( | ||
| 154 | + State(st): State<AppState>, | ||
| 155 | + CurrentUser(_user): CurrentUser, | ||
| 156 | + Path(id): Path<String>, | ||
| 157 | +) -> Result<Json<OfferingExamWeightsResponse>, AppError> { | ||
| 158 | + let offering = offering_or_404(&id, &st.db).await?; | ||
| 159 | + let weights = service::exam_weight::resolved_for_offering(&st.db, &offering).await?; | ||
| 160 | + Ok(Json(OfferingExamWeightsResponse { | ||
| 161 | + weights: weights.iter().map(ExamWeightEntry::of).collect(), | ||
| 162 | + })) | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +/// Set (or rewrite) one kind's weight on the template. Manager+. The kind must | ||
| 166 | +/// be one the school runs — a 400 carrying the machine code | ||
| 167 | +/// `unknown_exam_kind` otherwise; the weight must sit in 1..=100. Sections | ||
| 168 | +/// that still inherit the template pick the change up immediately. | ||
| 169 | +#[utoipa::path( | ||
| 170 | + patch, | ||
| 171 | + path = "/{id}/exam-weights", | ||
| 172 | + tag = "offerings", | ||
| 173 | + security(("session_cookie" = [])), | ||
| 174 | + params(("id" = String, Path, description = "Offering id")), | ||
| 175 | + request_body = PatchExamWeight, | ||
| 176 | + responses( | ||
| 177 | + (status = 200, description = "The offering's resolved weights after the write", body = OfferingExamWeightsResponse), | ||
| 178 | + (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), | ||
| 179 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 180 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 181 | + (status = 404, description = "Offering not found", body = ErrorResponse), | ||
| 182 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 183 | + ), | ||
| 184 | +)] | ||
| 185 | +async fn patch_offering_weight( | ||
| 186 | + State(st): State<AppState>, | ||
| 187 | + RequireManager(_user): RequireManager, | ||
| 188 | + Path(id): Path<String>, | ||
| 189 | + Json(req): Json<PatchExamWeight>, | ||
| 190 | +) -> Result<Response, AppError> { | ||
| 191 | + let offering = offering_or_404(&id, &st.db).await?; | ||
| 192 | + if let Err(err) = | ||
| 193 | + service::exam_weight::set_for_offering(&st.db, &offering, &req.kind, req.weight).await | ||
| 194 | + { | ||
| 195 | + return Ok(kind_refusal(err, &req.kind)); | ||
| 196 | + } | ||
| 197 | + let weights = service::exam_weight::resolved_for_offering(&st.db, &offering).await?; | ||
| 198 | + Ok(Json(OfferingExamWeightsResponse { | ||
| 199 | + weights: weights.iter().map(ExamWeightEntry::of).collect(), | ||
| 200 | + }) | ||
| 201 | + .into_response()) | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +/// Drop one kind's weight row from the template; the settings weight applies | ||
| 205 | +/// again. A kind with no row is a 404. | ||
| 206 | +#[utoipa::path( | ||
| 207 | + delete, | ||
| 208 | + path = "/{id}/exam-weights/{kind}", | ||
| 209 | + tag = "offerings", | ||
| 210 | + security(("session_cookie" = [])), | ||
| 211 | + params( | ||
| 212 | + ("id" = String, Path, description = "Offering id"), | ||
| 213 | + ("kind" = String, Path, description = "Exam kind"), | ||
| 214 | + ), | ||
| 215 | + responses( | ||
| 216 | + (status = 204, description = "Row deleted — the settings weight applies again"), | ||
| 217 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 218 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 219 | + (status = 404, description = "Offering not found, or it carries no weight row for this kind", body = ErrorResponse), | ||
| 220 | + ), | ||
| 221 | +)] | ||
| 222 | +async fn delete_offering_weight( | ||
| 223 | + State(st): State<AppState>, | ||
| 224 | + RequireManager(_user): RequireManager, | ||
| 225 | + Path((id, kind)): Path<(String, String)>, | ||
| 226 | +) -> Result<StatusCode, AppError> { | ||
| 227 | + let offering = offering_or_404(&id, &st.db).await?; | ||
| 228 | + service::exam_weight::remove_from_offering(&st.db, &offering, &kind).await?; | ||
| 229 | + Ok(StatusCode::NO_CONTENT) | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +// ---- the section's weights --------------------------------------------------- | ||
| 233 | + | ||
| 234 | +/// The section's resolved exam-kind weights and its override switch. Visible | ||
| 235 | +/// to the same eyes as the rest of the instance's reads. | ||
| 236 | +#[utoipa::path( | ||
| 237 | + get, | ||
| 238 | + path = "/{id}/exam-weights", | ||
| 239 | + tag = "instances", | ||
| 240 | + security(("session_cookie" = [])), | ||
| 241 | + params(("id" = String, Path, description = "Instance id")), | ||
| 242 | + responses( | ||
| 243 | + (status = 200, description = "The section's resolved weights, with the inherited flag", body = InstanceExamWeightsResponse), | ||
| 244 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 245 | + (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse), | ||
| 246 | + (status = 404, description = "Instance not found", body = ErrorResponse), | ||
| 247 | + ), | ||
| 248 | +)] | ||
| 249 | +async fn get_instance_weights( | ||
| 250 | + State(st): State<AppState>, | ||
| 251 | + CurrentUser(user): CurrentUser, | ||
| 252 | + Path(id): Path<String>, | ||
| 253 | +) -> Result<Json<InstanceExamWeightsResponse>, AppError> { | ||
| 254 | + let instance = instance_or_404(&id, &st.db).await?; | ||
| 255 | + if !can_view_instance(&st.db, instance.get_id(), &user).await? { | ||
| 256 | + return Err(AppError::Forbidden( | ||
| 257 | + "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its weights", | ||
| 258 | + )); | ||
| 259 | + } | ||
| 260 | + let (inherited, weights) = service::exam_weight::resolved_for_class(&st.db, &instance).await?; | ||
| 261 | + Ok(Json(InstanceExamWeightsResponse { | ||
| 262 | + inherited, | ||
| 263 | + weights: weights.iter().map(ExamWeightEntry::of).collect(), | ||
| 264 | + })) | ||
| 265 | +} | ||
| 266 | + | ||
| 267 | +/// Set (or rewrite) one kind's weight on the section — and take its weight set | ||
| 268 | +/// own: the flag flips in the same statement, so from here on the section's | ||
| 269 | +/// own rows (these included) are the whole map, even where they are absent. | ||
| 270 | +/// Requires teacher+ and a right over the instance (D10). | ||
| 271 | +#[utoipa::path( | ||
| 272 | + patch, | ||
| 273 | + path = "/{id}/exam-weights", | ||
| 274 | + tag = "instances", | ||
| 275 | + security(("session_cookie" = [])), | ||
| 276 | + params(("id" = String, Path, description = "Instance id")), | ||
| 277 | + request_body = PatchExamWeight, | ||
| 278 | + responses( | ||
| 279 | + (status = 200, description = "The section's resolved weights after the write (`inherited` now `false`)", body = InstanceExamWeightsResponse), | ||
| 280 | + (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), | ||
| 281 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 282 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 283 | + (status = 404, description = "Instance not found", body = ErrorResponse), | ||
| 284 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 285 | + ), | ||
| 286 | +)] | ||
| 287 | +async fn patch_instance_weight( | ||
| 288 | + State(st): State<AppState>, | ||
| 289 | + RequireTeacher(user): RequireTeacher, | ||
| 290 | + Path(id): Path<String>, | ||
| 291 | + Json(req): Json<PatchExamWeight>, | ||
| 292 | +) -> Result<Response, AppError> { | ||
| 293 | + let instance = instance_or_404(&id, &st.db).await?; | ||
| 294 | + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; | ||
| 295 | + if let Err(err) = | ||
| 296 | + service::exam_weight::set_for_class(&st.db, instance.get_id(), &req.kind, req.weight).await | ||
| 297 | + { | ||
| 298 | + return Ok(kind_refusal(err, &req.kind)); | ||
| 299 | + } | ||
| 300 | + // The write flipped the flag, so the map is computed off the fresh row, | ||
| 301 | + // never the one the gate read. | ||
| 302 | + let fresh = service::class_course::read(&st.db, instance.get_id()) | ||
| 303 | + .await? | ||
| 304 | + .ok_or(AppError::NotFound)?; | ||
| 305 | + let (inherited, weights) = service::exam_weight::resolved_for_class(&st.db, &fresh).await?; | ||
| 306 | + Ok(Json(InstanceExamWeightsResponse { | ||
| 307 | + inherited, | ||
| 308 | + weights: weights.iter().map(ExamWeightEntry::of).collect(), | ||
| 309 | + }) | ||
| 310 | + .into_response()) | ||
| 311 | +} | ||
| 312 | + | ||
| 313 | +/// Drop one kind's weight row from the section. Deleting still takes the set | ||
| 314 | +/// own — removing the last row *decides* on an empty set (every kind then | ||
| 315 | +/// weighs 1 here) rather than falling back. A kind with no row is a 404 that | ||
| 316 | +/// changes nothing. | ||
| 317 | +#[utoipa::path( | ||
| 318 | + delete, | ||
| 319 | + path = "/{id}/exam-weights/{kind}", | ||
| 320 | + tag = "instances", | ||
| 321 | + security(("session_cookie" = [])), | ||
| 322 | + params( | ||
| 323 | + ("id" = String, Path, description = "Instance id"), | ||
| 324 | + ("kind" = String, Path, description = "Exam kind"), | ||
| 325 | + ), | ||
| 326 | + responses( | ||
| 327 | + (status = 204, description = "Row deleted — the section's own set stays authoritative without it"), | ||
| 328 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 329 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 330 | + (status = 404, description = "Instance not found, or it carries no weight row for this kind", body = ErrorResponse), | ||
| 331 | + ), | ||
| 332 | +)] | ||
| 333 | +async fn delete_instance_weight( | ||
| 334 | + State(st): State<AppState>, | ||
| 335 | + RequireTeacher(user): RequireTeacher, | ||
| 336 | + Path((id, kind)): Path<(String, String)>, | ||
| 337 | +) -> Result<StatusCode, AppError> { | ||
| 338 | + let instance = instance_or_404(&id, &st.db).await?; | ||
| 339 | + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; | ||
| 340 | + service::exam_weight::remove_from_class(&st.db, instance.get_id(), &kind).await?; | ||
| 341 | + Ok(StatusCode::NO_CONTENT) | ||
| 342 | +} | ||
| 343 | + | ||
| 344 | +/// The reset: drop every section weight row and follow the offering's set | ||
| 345 | +/// (then the settings, then 1) again. Idempotent. | ||
| 346 | +#[utoipa::path( | ||
| 347 | + delete, | ||
| 348 | + path = "/{id}/exam-weights", | ||
| 349 | + tag = "instances", | ||
| 350 | + security(("session_cookie" = [])), | ||
| 351 | + params(("id" = String, Path, description = "Instance id")), | ||
| 352 | + responses( | ||
| 353 | + (status = 204, description = "Rows deleted — inheritance restored"), | ||
| 354 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 355 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 356 | + (status = 404, description = "Instance not found", body = ErrorResponse), | ||
| 357 | + ), | ||
| 358 | +)] | ||
| 359 | +async fn reset_instance_weights( | ||
| 360 | + State(st): State<AppState>, | ||
| 361 | + RequireTeacher(user): RequireTeacher, | ||
| 362 | + Path(id): Path<String>, | ||
| 363 | +) -> Result<StatusCode, AppError> { | ||
| 364 | + let instance = instance_or_404(&id, &st.db).await?; | ||
| 365 | + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; | ||
| 366 | + service::exam_weight::reset_class(&st.db, instance.get_id()).await?; | ||
| 367 | + Ok(StatusCode::NO_CONTENT) | ||
| 368 | +} | ||
src/web/exams/questions.rsmodified+21 -17
| @@ -12,8 +12,10 @@ use crate::service::exam_question; | |||
| 12 | 12 | ||
| 13 | #[derive(Deserialize, ToSchema)] | 13 | #[derive(Deserialize, ToSchema)] |
| 14 | pub(crate) struct CreateQuestion { | 14 | pub(crate) struct CreateQuestion { |
| 15 | - /// The subject this question belongs to — one of the subjects of the exam | 15 | + /// The subject this question belongs to — one of the subjects the exam |
| 16 | - /// instance's catalog course (`GET /courses/{id}/subjects`). Required. | 16 | + /// instance actually teaches: its resolved subject set |
| 17 | + /// (`GET /instances/{id}/subjects`), always a subject of the instance's | ||
| 18 | + /// catalog course. Required. | ||
| 17 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | 19 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 18 | subject_id: String, | 20 | subject_id: String, |
| 19 | /// The question itself. | 21 | /// The question itself. |
| @@ -139,9 +141,11 @@ impl QuestionResponse { | |||
| 139 | } | 141 | } |
| 140 | 142 | ||
| 141 | /// Add a question to an exam. Requires teacher+ and management rights over the | 143 | /// Add a question to an exam. Requires teacher+ and management rights over the |
| 142 | -/// exam's instance. `subject_id` must name one of the subjects of that | 144 | +/// exam's instance. `subject_id` must name one of the subjects the instance |
| 143 | -/// instance's catalog course (`GET /courses/{id}/subjects`) — every question | 145 | +/// actually *teaches* — its resolved subject set (the offering's selection, |
| 144 | -/// belongs to a subject. | 146 | +/// or the section's own while it overrides; `GET /instances/{id}/subjects`) — |
| 147 | +/// and in every case a subject of the instance's catalog course. Every | ||
| 148 | +/// question belongs to a subject. | ||
| 145 | /// `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` | 149 | /// `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` |
| 146 | /// questions carry neither. Locked once attempts exist. | 150 | /// questions carry neither. Locked once attempts exist. |
| 147 | #[utoipa::path( | 151 | #[utoipa::path( |
| @@ -153,7 +157,7 @@ impl QuestionResponse { | |||
| 153 | request_body = CreateQuestion, | 157 | request_body = CreateQuestion, |
| 154 | responses( | 158 | responses( |
| 155 | (status = 201, description = "Question created", body = QuestionResponse), | 159 | (status = 201, description = "Question created", body = QuestionResponse), |
| 156 | - (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), | 160 | + (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), |
| 157 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 161 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 158 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | 162 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 159 | (status = 404, description = "Exam not found", body = ErrorResponse), | 163 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| @@ -184,7 +188,7 @@ pub(crate) async fn create_question( | |||
| 184 | exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; | 188 | exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 185 | 189 | ||
| 186 | let subject = | 190 | let subject = |
| 187 | - service::subject::in_course(&st.db, &req.subject_id, instance.get_course()).await?; | 191 | + service::subject::in_instance(&st.db, &req.subject_id, &instance).await?; |
| 188 | let text = QuestionText::try_new(&req.text)?; | 192 | let text = QuestionText::try_new(&req.text)?; |
| 189 | let points = QuestionPoints::try_new(req.points)?; | 193 | let points = QuestionPoints::try_new(req.points)?; |
| 190 | // No stored choices to match against on create, so every option is new and | 194 | // No stored choices to match against on create, so every option is new and |
| @@ -294,7 +298,7 @@ pub(crate) async fn question_page( | |||
| 294 | request_body = UpdateQuestion, | 298 | request_body = UpdateQuestion, |
| 295 | responses( | 299 | responses( |
| 296 | (status = 200, description = "Updated question", body = QuestionResponse), | 300 | (status = 200, description = "Updated question", body = QuestionResponse), |
| 297 | - (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), | 301 | + (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), |
| 298 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 302 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 299 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | 303 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 300 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), | 304 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), |
| @@ -323,10 +327,8 @@ pub(crate) async fn update_question( | |||
| 323 | exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; | 327 | exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 324 | let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; | 328 | let question = exam_question::question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 325 | 329 | ||
| 326 | - let subject = match req.subject_id { | 330 | + let subject = match &req.subject_id { |
| 327 | - Some(ref subject_id) => { | 331 | + Some(subject_id) => service::subject::in_instance(&st.db, subject_id, &instance).await?, |
| 328 | - service::subject::in_course(&st.db, subject_id, instance.get_course()).await? | ||
| 329 | - } | ||
| 330 | None => *question.get_subject(), | 332 | None => *question.get_subject(), |
| 331 | }; | 333 | }; |
| 332 | let text = match req.text { | 334 | let text = match req.text { |
| @@ -462,7 +464,7 @@ pub(crate) struct InstantiateFromBank { | |||
| 462 | request_body = InstantiateFromBank, | 464 | request_body = InstantiateFromBank, |
| 463 | responses( | 465 | responses( |
| 464 | (status = 201, description = "Question created from the template", body = QuestionResponse), | 466 | (status = 201, description = "Question created from the template", body = QuestionResponse), |
| 465 | - (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), | 467 | + (status = 400, description = "A subject that is unknown, from another course, or outside the instance's resolved subject set", body = ErrorResponse), |
| 466 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 468 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 467 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | 469 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 468 | (status = 404, description = "No such exam, or no bank template the caller may see", body = ErrorResponse), | 470 | (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( | |||
| 489 | // No lease — same reasoning as `create_question`. The freeze gate rides in | 491 | // No lease — same reasoning as `create_question`. The freeze gate rides in |
| 490 | // the insert's transaction. | 492 | // the insert's transaction. |
| 491 | exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; | 493 | exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 492 | - let subject = | ||
| 493 | - service::subject::in_course(&st.db, &req.subject_id, instance.get_course()).await?; | ||
| 494 | - | ||
| 495 | let template = bank_question::read(&st.db, &BankQuestionId::from_key(&bid)) | 494 | let template = bank_question::read(&st.db, &BankQuestionId::from_key(&bid)) |
| 496 | .await? | 495 | .await? |
| 497 | .ok_or(AppError::NotFound)?; | 496 | .ok_or(AppError::NotFound)?; |
| 498 | // A template the caller may not see is a 404, exactly as it is on the bank's | 497 | // A template the caller may not see is a 404, exactly as it is on the bank's |
| 499 | // own routes — instantiating is a read of `correct`, and a 403 here would | 498 | // own routes — instantiating is a read of `correct`, and a 403 here would |
| 500 | - // confirm that someone else's private template exists under that id. | 499 | + // confirm that someone else's private template exists under that id. The |
| 500 | + // read precedes the subject gate, so an invisible template never leaks | ||
| 501 | + // existence through a body-validation 400. | ||
| 501 | if !crate::web::bank_questions::can_see(&template, &user) { | 502 | if !crate::web::bank_questions::can_see(&template, &user) { |
| 502 | return Err(AppError::NotFound); | 503 | return Err(AppError::NotFound); |
| 503 | } | 504 | } |
| 505 | + let subject = | ||
| 506 | + service::subject::in_instance(&st.db, &req.subject_id, &instance).await?; | ||
| 507 | + | ||
| 504 | let question = exam_question::create_from_bank( | 508 | let question = exam_question::create_from_bank( |
| 505 | &st.db, | 509 | &st.db, |
| 506 | exam.get_id(), | 510 | exam.get_id(), |
src/web/homework.rsmodified+6 -4
| @@ -279,8 +279,10 @@ struct UpdateHomework { | |||
| 279 | /// Edit a homework's title, description, due date, subject, or assigned subset. | 279 | /// Edit a homework's title, description, due date, subject, or assigned subset. |
| 280 | /// Requires teacher+ and management rights over its instance. Omitted fields | 280 | /// Requires teacher+ and management rights over its instance. Omitted fields |
| 281 | /// keep their value; a newly set `due_at` is re-checked against now and a new | 281 | /// keep their value; a newly set `due_at` is re-checked against now and a new |
| 282 | -/// `subject_id` re-checked against the instance's course. Narrowing `assigned` | 282 | +/// `subject_id` re-checked against the instance's resolved subject set (the |
| 283 | -/// is refused (409) while it would orphan an existing submission or result. | 283 | +/// offering's selection, or the section's own while it overrides). Narrowing |
| 284 | +/// `assigned` is refused (409) while it would orphan an existing submission or | ||
| 285 | +/// result. | ||
| 284 | #[utoipa::path( | 286 | #[utoipa::path( |
| 285 | patch, | 287 | patch, |
| 286 | path = "/{id}", | 288 | path = "/{id}", |
| @@ -290,7 +292,7 @@ struct UpdateHomework { | |||
| 290 | request_body = UpdateHomework, | 292 | request_body = UpdateHomework, |
| 291 | responses( | 293 | responses( |
| 292 | (status = 200, description = "Updated homework", body = HomeworkResponse), | 294 | (status = 200, description = "Updated homework", body = HomeworkResponse), |
| 293 | - (status = 400, description = "Invalid title, description, due date, subject (unknown or from another course), or assigned list", body = ErrorResponse), | 295 | + (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), |
| 294 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 296 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 295 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | 297 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 296 | (status = 404, description = "Not found", body = ErrorResponse), | 298 | (status = 404, description = "Not found", body = ErrorResponse), |
| @@ -336,7 +338,7 @@ async fn update_homework( | |||
| 336 | check_not_past("due_at", due_at)?; | 338 | check_not_past("due_at", due_at)?; |
| 337 | let subject = match &req.subject_id { | 339 | let subject = match &req.subject_id { |
| 338 | Some(subject_id) => Some( | 340 | Some(subject_id) => Some( |
| 339 | - crate::service::subject::in_course(&st.db, subject_id, instance.get_course()).await?, | 341 | + crate::service::subject::in_instance(&st.db, subject_id, &instance).await?, |
| 340 | ), | 342 | ), |
| 341 | None => None, | 343 | None => None, |
| 342 | }; | 344 | }; |
src/web/instances.rsmodified+186 -33
| @@ -3,9 +3,12 @@ | |||
| 3 | //! | 3 | //! |
| 4 | //! Everything a class actually runs hangs off this row: its roster, its | 4 | //! Everything a class actually runs hangs off this row: its roster, its |
| 5 | //! teachers, its exams, its lessons and its homework. Two sections teaching the | 5 | //! teachers, its exams, its lessons and its homework. Two sections teaching the |
| 6 | -//! same course are two instances and share none of it. The weekly hours | 6 | +//! same course are two instances and share none of it. Each instance points at |
| 7 | -//! (`ders_saati`) and the report-card policy (`counts_toward_karne`) are the | 7 | +//! its grade-level **offering** template and may override the content fields |
| 8 | -//! instance's own, so two sections may legitimately differ. | 8 | +//! (`title`, `description`, `ders_saati`, `counts_toward_karne`) — a `PATCH` |
| 9 | +//! sets an override, `POST /{id}/reset` clears back to inherit, and what a | ||
| 10 | +//! read presents is the resolved value (override → offering default → | ||
| 11 | +//! constant), never the raw `NULL`. | ||
| 9 | //! | 12 | //! |
| 10 | //! The catalog CRUD stays in [`super::courses`]; the exam, session and | 13 | //! The catalog CRUD stays in [`super::courses`]; the exam, session and |
| 11 | //! homework sub-routers live *here* now (they used to hang off `/courses/{id}`) | 14 | //! homework sub-routers live *here* now (they used to hang off `/courses/{id}`) |
| @@ -25,6 +28,7 @@ use utoipa_axum::routes; | |||
| 25 | 28 | ||
| 26 | use crate::database::Database; | 29 | use crate::database::Database; |
| 27 | use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; | 30 | use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; |
| 31 | +use crate::domain::course::{CourseDescription, CourseTitle}; | ||
| 28 | use crate::domain::course_session::SessionTopic; | 32 | use crate::domain::course_session::SessionTopic; |
| 29 | use crate::domain::enrollment::Enrollment; | 33 | use crate::domain::enrollment::Enrollment; |
| 30 | use crate::domain::exam::{ | 34 | use crate::domain::exam::{ |
| @@ -39,16 +43,20 @@ use crate::service; | |||
| 39 | use crate::service::instance::{can_manage_instance, visible_instances}; | 43 | use crate::service::instance::{can_manage_instance, visible_instances}; |
| 40 | use crate::state::AppState; | 44 | use crate::state::AppState; |
| 41 | 45 | ||
| 46 | +use super::exam_weights::ExamWeightEntry; | ||
| 42 | use super::homework::{description_or_none, resolve_assigned}; | 47 | use super::homework::{description_or_none, resolve_assigned}; |
| 48 | +use super::weekly_plan::WeeklySlotDto; | ||
| 43 | use super::{ | 49 | use super::{ |
| 44 | CurrentUser, ExamResponse, HomeworkResponse, Page, PageParams, PersonRef, RequireManager, | 50 | CurrentUser, ExamResponse, HomeworkResponse, Page, PageParams, PersonRef, RequireManager, |
| 45 | - RequireTeacher, SessionResponse, check_not_past, check_time_range, paginate, person_map, | 51 | + RequireTeacher, SessionResponse, SubjectResponse, check_not_past, check_time_range, paginate, |
| 52 | + person_map, | ||
| 46 | }; | 53 | }; |
| 47 | 54 | ||
| 48 | pub fn routes() -> OpenApiRouter<AppState> { | 55 | pub fn routes() -> OpenApiRouter<AppState> { |
| 49 | OpenApiRouter::new() | 56 | OpenApiRouter::new() |
| 50 | .routes(routes!(my_instances)) | 57 | .routes(routes!(my_instances)) |
| 51 | .routes(routes!(get_instance, update_instance)) | 58 | .routes(routes!(get_instance, update_instance)) |
| 59 | + .routes(routes!(reset_instance)) | ||
| 52 | .routes(routes!(assign_teacher)) | 60 | .routes(routes!(assign_teacher)) |
| 53 | .routes(routes!(unassign_teacher)) | 61 | .routes(routes!(unassign_teacher)) |
| 54 | .routes(routes!(enroll, list_roster)) | 62 | .routes(routes!(enroll, list_roster)) |
| @@ -74,15 +82,33 @@ pub fn homework_routes() -> OpenApiRouter<AppState> { | |||
| 74 | 82 | ||
| 75 | #[derive(Deserialize, ToSchema)] | 83 | #[derive(Deserialize, ToSchema)] |
| 76 | struct UpdateInstance { | 84 | struct UpdateInstance { |
| 77 | - /// Weekly lesson hours: the instance's weight in the year's report-card average. | 85 | + /// The section's own title override. Omit to keep the stored value; a |
| 78 | - /// Omit to keep the stored value; at least 1 and at most 40. | 86 | + /// PATCH **sets**, it never clears — clearing back to inherit is the |
| 87 | + /// reset door's (`POST /instances/{id}/reset`). | ||
| 88 | + #[schema(max_length = 200, example = "9-A Matematik")] | ||
| 89 | + title: Option<String>, | ||
| 90 | + /// The section's own description override. Omit to keep; never clears. | ||
| 91 | + #[schema(max_length = 2_000)] | ||
| 92 | + description: Option<String>, | ||
| 93 | + /// The section's own weekly-hours override: the weight it takes in the | ||
| 94 | + /// year's report-card average while it is set. Omit to keep the stored | ||
| 95 | + /// value (`null` to clear is the reset door's); at least 1 and at most 40. | ||
| 79 | #[schema(minimum = 1, maximum = 40, example = 5)] | 96 | #[schema(minimum = 1, maximum = 40, example = 5)] |
| 80 | ders_saati: Option<i64>, | 97 | ders_saati: Option<i64>, |
| 81 | - /// Whether this instance's marks count into the report card. Omit to keep the | 98 | + /// The section's own report-card policy override. Omit to keep; never |
| 82 | - /// stored value. | 99 | + /// clears. |
| 83 | counts_toward_karne: Option<bool>, | 100 | counts_toward_karne: Option<bool>, |
| 84 | } | 101 | } |
| 85 | 102 | ||
| 103 | +#[derive(Deserialize, ToSchema)] | ||
| 104 | +struct ResetInstanceOverrides { | ||
| 105 | + /// The overrides to clear back to **inherit**: `title`, `description`, | ||
| 106 | + /// `ders_saati`, `counts_toward_karne` — and, flipping the section's own | ||
| 107 | + /// table back to non-authoritative (the offering's set applies again), | ||
| 108 | + /// `subjects`, `exam_weights`, `weekly_plan`. Unknown names are a 400. | ||
| 109 | + fields: Vec<String>, | ||
| 110 | +} | ||
| 111 | + | ||
| 86 | #[derive(Deserialize, ToSchema)] | 112 | #[derive(Deserialize, ToSchema)] |
| 87 | struct AssignTeacher { | 113 | struct AssignTeacher { |
| 88 | /// The staff member to put in charge of this instance. Must hold the | 114 | /// The staff member to put in charge of this instance. Must hold the |
| @@ -185,8 +211,14 @@ struct CreateSessionInCourse { | |||
| 185 | ends_at: Option<i64>, | 211 | ends_at: Option<i64>, |
| 186 | } | 212 | } |
| 187 | 213 | ||
| 188 | -/// Public shape of one instance: the course as this section teaches it, with the | 214 | +/// Public shape of one instance: the course as this section teaches it. Every |
| 189 | -/// policy that is the instance's own. | 215 | +/// content field is the **resolved** view the instance resolver composes — |
| 216 | +/// scalar chains run override → offering → catalog/constant, the set axes are | ||
| 217 | +/// flag-driven — so a client renders this verbatim and renders a per-class | ||
| 218 | +/// edit screen from this one call: `*_overridden` tells its own override from | ||
| 219 | +/// an inherited value, `*_inherited` tells whose set is authoritative. The | ||
| 220 | +/// raw template values (nullable, unset = inherit) live one level up, on | ||
| 221 | +/// `GET /offerings/{id}`. | ||
| 190 | #[derive(Serialize, ToSchema)] | 222 | #[derive(Serialize, ToSchema)] |
| 191 | pub struct InstanceResponse { | 223 | pub struct InstanceResponse { |
| 192 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | 224 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| @@ -196,11 +228,51 @@ pub struct InstanceResponse { | |||
| 196 | /// The catalog course being taught (`GET /courses/{id}`) — its title lives | 228 | /// The catalog course being taught (`GET /courses/{id}`) — its title lives |
| 197 | /// there, shared by every instance of it. | 229 | /// there, shared by every instance of it. |
| 198 | pub course: String, | 230 | pub course: String, |
| 199 | - /// Weekly lesson hours; the instance's weight in the year's report-card average. | 231 | + /// The grade-level offering template this section teaches from |
| 232 | + /// (`GET /offerings/{id}`) — the thing its unset fields inherit from. | ||
| 233 | + pub offering: String, | ||
| 234 | + /// The section's **resolved** title: its own override, else its | ||
| 235 | + /// offering's, else the catalog course's. | ||
| 236 | + pub title: String, | ||
| 237 | + /// `true` when `title` is this section's own override rather than | ||
| 238 | + /// inherited from the offering or the catalog. | ||
| 239 | + pub title_overridden: bool, | ||
| 240 | + /// The section's **resolved** description, the same chain as `title`. | ||
| 241 | + pub description: String, | ||
| 242 | + /// `true` when `description` is this section's own override. | ||
| 243 | + pub description_overridden: bool, | ||
| 244 | + /// The section's **effective** weekly hours: its own override, else the | ||
| 245 | + /// offering's default, else 1 — the weight it takes in the year's | ||
| 246 | + /// report-card average. | ||
| 200 | #[schema(example = 5)] | 247 | #[schema(example = 5)] |
| 201 | pub ders_saati: i64, | 248 | pub ders_saati: i64, |
| 202 | - /// Whether this instance's marks count toward the report card. | 249 | + /// `true` when the hours are this section's own override. |
| 250 | + pub ders_saati_overridden: bool, | ||
| 251 | + /// The effective report-card policy: own override, else the offering's | ||
| 252 | + /// default, else counted. | ||
| 203 | pub counts_toward_karne: bool, | 253 | pub counts_toward_karne: bool, |
| 254 | + /// `true` when the policy is this section's own override. | ||
| 255 | + pub counts_toward_karne_overridden: bool, | ||
| 256 | + /// `false` = this section's own subject table is authoritative, including | ||
| 257 | + /// when empty; `true` = the offering's subject set applies. | ||
| 258 | + pub subjects_inherited: bool, | ||
| 259 | + /// The section's **resolved** syllabus — the same set | ||
| 260 | + /// `GET /{id}/subjects` serves, name-then-id order. | ||
| 261 | + pub subjects: Vec<SubjectResponse>, | ||
| 262 | + /// `true` = the section follows its offering's weight map; `false` = its | ||
| 263 | + /// own table is authoritative, empty included. | ||
| 264 | + pub exam_weights_inherited: bool, | ||
| 265 | + /// The section's **resolved** weight map: every kind at its effective | ||
| 266 | + /// weight (override → offering → settings → 1). | ||
| 267 | + pub exam_weights: Vec<ExamWeightEntry>, | ||
| 268 | + /// The same switch for the section's weekly plan. | ||
| 269 | + pub weekly_plan_inherited: bool, | ||
| 270 | + /// The section's **resolved** weekly plan: its own `class_course_slot` | ||
| 271 | + /// rows when the flag above is `false` — including when that set is | ||
| 272 | + /// empty — the offering's `offering_slot` template week when `true`. | ||
| 273 | + /// Weekday first, then start time. Template data a timetable renders; | ||
| 274 | + /// nothing generates dated `course_session` rows from it. | ||
| 275 | + pub weekly_plan: Vec<WeeklySlotDto>, | ||
| 204 | /// How many students are enrolled right now. | 276 | /// How many students are enrolled right now. |
| 205 | #[schema(example = 28)] | 277 | #[schema(example = 28)] |
| 206 | pub enrollment_count: i64, | 278 | pub enrollment_count: i64, |
| @@ -210,23 +282,44 @@ pub struct InstanceResponse { | |||
| 210 | } | 282 | } |
| 211 | 283 | ||
| 212 | impl InstanceResponse { | 284 | impl InstanceResponse { |
| 213 | - fn new( | 285 | + async fn new( |
| 286 | + db: &Database, | ||
| 214 | instance: &ClassCourse, | 287 | instance: &ClassCourse, |
| 215 | teachers: &[UserId], | 288 | teachers: &[UserId], |
| 216 | people: &HashMap<String, PersonRef>, | 289 | people: &HashMap<String, PersonRef>, |
| 217 | - ) -> Self { | 290 | + ) -> Result<Self, AppError> { |
| 218 | - Self { | 291 | + // One composed resolver call: title, description, the policy pair and |
| 292 | + // the three set axes — never a fallback chain re-implemented here. | ||
| 293 | + let resolved = service::instance_resolve::resolve(db, instance).await?; | ||
| 294 | + Ok(Self { | ||
| 219 | id: instance.get_id().key().to_string(), | 295 | id: instance.get_id().key().to_string(), |
| 220 | class: instance.get_class().key().to_string(), | 296 | class: instance.get_class().key().to_string(), |
| 221 | course: instance.get_course().key().to_string(), | 297 | course: instance.get_course().key().to_string(), |
| 222 | - ders_saati: instance.get_ders_saati().as_i64(), | 298 | + offering: instance.get_offering().key(), |
| 223 | - counts_toward_karne: instance.counts_toward_karne(), | 299 | + title: resolved.title, |
| 300 | + title_overridden: resolved.title_overridden, | ||
| 301 | + description: resolved.description, | ||
| 302 | + description_overridden: resolved.description_overridden, | ||
| 303 | + ders_saati: resolved.ders_saati.as_i64(), | ||
| 304 | + ders_saati_overridden: resolved.ders_saati_overridden, | ||
| 305 | + counts_toward_karne: resolved.counts_toward_karne, | ||
| 306 | + counts_toward_karne_overridden: resolved.counts_toward_karne_overridden, | ||
| 307 | + subjects_inherited: resolved.subjects_inherited, | ||
| 308 | + subjects: resolved.subjects.iter().map(SubjectResponse::new).collect(), | ||
| 309 | + exam_weights_inherited: resolved.exam_weights_inherited, | ||
| 310 | + exam_weights: resolved | ||
| 311 | + .exam_weights | ||
| 312 | + .iter() | ||
| 313 | + .map(ExamWeightEntry::of) | ||
| 314 | + .collect(), | ||
| 315 | + weekly_plan_inherited: resolved.weekly_plan_inherited, | ||
| 316 | + weekly_plan: resolved.weekly_plan.iter().map(WeeklySlotDto::new).collect(), | ||
| 224 | enrollment_count: instance.get_enrollment_count(), | 317 | enrollment_count: instance.get_enrollment_count(), |
| 225 | teachers: teachers | 318 | teachers: teachers |
| 226 | .iter() | 319 | .iter() |
| 227 | .map(|teacher| PersonRef::resolve(people, teacher)) | 320 | .map(|teacher| PersonRef::resolve(people, teacher)) |
| 228 | .collect(), | 321 | .collect(), |
| 229 | - } | 322 | + }) |
| 230 | } | 323 | } |
| 231 | } | 324 | } |
| 232 | 325 | ||
| @@ -344,10 +437,10 @@ async fn my_instances( | |||
| 344 | .collect(); | 437 | .collect(); |
| 345 | let with_teachers = crate::db::class_course_teacher::into_instances(&st.db, window).await?; | 438 | let with_teachers = crate::db::class_course_teacher::into_instances(&st.db, window).await?; |
| 346 | let people = instance_people(&with_teachers, &st.db).await?; | 439 | let people = instance_people(&with_teachers, &st.db).await?; |
| 347 | - let items = with_teachers | 440 | + let mut items = Vec::with_capacity(with_teachers.len()); |
| 348 | - .iter() | 441 | + for (instance, teachers) in &with_teachers { |
| 349 | - .map(|(instance, teachers)| InstanceResponse::new(instance, teachers, &people)) | 442 | + items.push(InstanceResponse::new(&st.db, instance, teachers, &people).await?); |
| 350 | - .collect(); | 443 | + } |
| 351 | Ok(Json(Page::new(items, total, limit, offset))) | 444 | Ok(Json(Page::new(items, total, limit, offset))) |
| 352 | } | 445 | } |
| 353 | 446 | ||
| @@ -380,12 +473,13 @@ async fn get_instance( | |||
| 380 | let teachers = | 473 | let teachers = |
| 381 | crate::db::class_course_teacher::list_for_instance(&st.db, instance.get_id()).await?; | 474 | crate::db::class_course_teacher::list_for_instance(&st.db, instance.get_id()).await?; |
| 382 | let people = person_map(teachers.iter().cloned(), &st.db).await?; | 475 | let people = person_map(teachers.iter().cloned(), &st.db).await?; |
| 383 | - Ok(Json(InstanceResponse::new(&instance, &teachers, &people))) | 476 | + Ok(Json(InstanceResponse::new(&st.db, &instance, &teachers, &people).await?)) |
| 384 | } | 477 | } |
| 385 | 478 | ||
| 386 | -/// Update one instance's own policy. Requires teacher+ and a right over this | 479 | +/// Update one instance's own policy overrides. Requires teacher+ and a right |
| 387 | -/// instance: manager+, one of its assigned teachers, or its section's homeroom | 480 | +/// over this instance: manager+, one of its assigned teachers, or its |
| 388 | -/// teacher. Omitted fields keep their value; both are non-clearable. | 481 | +/// section's homeroom teacher. Omitted fields keep their value; a PATCH |
| 482 | +/// **sets**, it never clears — `POST /{id}/reset` is the clear door. | ||
| 389 | #[utoipa::path( | 483 | #[utoipa::path( |
| 390 | patch, | 484 | patch, |
| 391 | path = "/{id}", | 485 | path = "/{id}", |
| @@ -395,7 +489,7 @@ async fn get_instance( | |||
| 395 | request_body = UpdateInstance, | 489 | request_body = UpdateInstance, |
| 396 | responses( | 490 | responses( |
| 397 | (status = 200, description = "Updated instance", body = InstanceResponse), | 491 | (status = 200, description = "Updated instance", body = InstanceResponse), |
| 398 | - (status = 400, description = "Invalid ders_saati", body = ErrorResponse), | 492 | + (status = 400, description = "Invalid title, description, or ders_saati", body = ErrorResponse), |
| 399 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 493 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 400 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | 494 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 401 | (status = 404, description = "Not found", body = ErrorResponse), | 495 | (status = 404, description = "Not found", body = ErrorResponse), |
| @@ -413,14 +507,73 @@ async fn update_instance( | |||
| 413 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; | 507 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 414 | service::class_course::require_open(&st.db, instance.get_id()).await?; | 508 | service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 415 | 509 | ||
| 510 | + let title = match &req.title { | ||
| 511 | + Some(title) => Some(CourseTitle::try_new(title)?), | ||
| 512 | + None => None, | ||
| 513 | + }; | ||
| 514 | + let description = match &req.description { | ||
| 515 | + Some(description) => Some(CourseDescription::try_new(description)?), | ||
| 516 | + None => None, | ||
| 517 | + }; | ||
| 416 | let staff = req.ders_saati.map(DersSaati::try_new).transpose()?; | 518 | let staff = req.ders_saati.map(DersSaati::try_new).transpose()?; |
| 519 | + let updated = service::class_course::update( | ||
| 520 | + &st.db, | ||
| 521 | + instance.get_id(), | ||
| 522 | + title, | ||
| 523 | + description, | ||
| 524 | + staff, | ||
| 525 | + req.counts_toward_karne, | ||
| 526 | + ) | ||
| 527 | + .await?; | ||
| 528 | + let teachers = | ||
| 529 | + crate::db::class_course_teacher::list_for_instance(&st.db, updated.get_id()).await?; | ||
| 530 | + let people = person_map(teachers.iter().cloned(), &st.db).await?; | ||
| 531 | + Ok(Json(InstanceResponse::new(&st.db, &updated, &teachers, &people).await?)) | ||
| 532 | +} | ||
| 533 | + | ||
| 534 | +/// Clear the named overrides back to inherit — the door a PATCH never is. | ||
| 535 | +/// Same gate as the PATCH: teacher+ with a right over this instance, and a | ||
| 536 | +/// live (non-archived) year. Resetting a set policy (`subjects`, | ||
| 537 | +/// `exam_weights`, `weekly_plan`) flips the section's flag back to | ||
| 538 | +/// *inherited*; deleting the section's own rows under it rides the child | ||
| 539 | +/// tables' own reset doors. | ||
| 540 | +#[utoipa::path( | ||
| 541 | + post, | ||
| 542 | + path = "/{id}/reset", | ||
| 543 | + tag = "instances", | ||
| 544 | + security(("session_cookie" = [])), | ||
| 545 | + params(("id" = String, Path, description = "Instance id")), | ||
| 546 | + request_body = ResetInstanceOverrides, | ||
| 547 | + responses( | ||
| 548 | + (status = 200, description = "The overrides cleared; the instance now inherits the named fields", body = InstanceResponse), | ||
| 549 | + (status = 400, description = "A field name is unknown, or the list is empty", body = ErrorResponse), | ||
| 550 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 551 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 552 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 553 | + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), | ||
| 554 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 555 | + ), | ||
| 556 | +)] | ||
| 557 | +async fn reset_instance( | ||
| 558 | + State(st): State<AppState>, | ||
| 559 | + RequireTeacher(user): RequireTeacher, | ||
| 560 | + Path(id): Path<String>, | ||
| 561 | + Json(req): Json<ResetInstanceOverrides>, | ||
| 562 | +) -> Result<Json<InstanceResponse>, AppError> { | ||
| 563 | + let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; | ||
| 564 | + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; | ||
| 565 | + service::class_course::require_open(&st.db, instance.get_id()).await?; | ||
| 566 | + | ||
| 567 | + let mut fields = Vec::with_capacity(req.fields.len()); | ||
| 568 | + for name in &req.fields { | ||
| 569 | + fields.push(service::class_course::parse_reset_field(name)?); | ||
| 570 | + } | ||
| 417 | let updated = | 571 | let updated = |
| 418 | - service::class_course::update(&st.db, instance.get_id(), staff, req.counts_toward_karne) | 572 | + service::class_course::reset_overrides(&st.db, instance.get_id(), &fields).await?; |
| 419 | - .await?; | ||
| 420 | let teachers = | 573 | let teachers = |
| 421 | crate::db::class_course_teacher::list_for_instance(&st.db, updated.get_id()).await?; | 574 | crate::db::class_course_teacher::list_for_instance(&st.db, updated.get_id()).await?; |
| 422 | let people = person_map(teachers.iter().cloned(), &st.db).await?; | 575 | let people = person_map(teachers.iter().cloned(), &st.db).await?; |
| 423 | - Ok(Json(InstanceResponse::new(&updated, &teachers, &people))) | 576 | + Ok(Json(InstanceResponse::new(&st.db, &updated, &teachers, &people).await?)) |
| 424 | } | 577 | } |
| 425 | 578 | ||
| 426 | /// Assign a teacher to this instance (idempotent). Manager+ only — staffing is | 579 | /// Assign a teacher to this instance (idempotent). Manager+ only — staffing is |
| @@ -461,7 +614,7 @@ async fn assign_teacher( | |||
| 461 | let teachers = | 614 | let teachers = |
| 462 | crate::db::class_course_teacher::list_for_instance(&st.db, instance.get_id()).await?; | 615 | crate::db::class_course_teacher::list_for_instance(&st.db, instance.get_id()).await?; |
| 463 | let people = person_map(teachers.iter().cloned(), &st.db).await?; | 616 | let people = person_map(teachers.iter().cloned(), &st.db).await?; |
| 464 | - Ok(Json(InstanceResponse::new(&instance, &teachers, &people))) | 617 | + Ok(Json(InstanceResponse::new(&st.db, &instance, &teachers, &people).await?)) |
| 465 | } | 618 | } |
| 466 | 619 | ||
| 467 | /// Unassign a teacher from this instance. Manager+ only. The instance, its | 620 | /// Unassign a teacher from this instance. Manager+ only. The instance, its |
| @@ -1033,7 +1186,7 @@ mod tests { | |||
| 1033 | &db, | 1186 | &db, |
| 1034 | &office, | 1187 | &office, |
| 1035 | ClassName::try_new("5-A").unwrap(), | 1188 | ClassName::try_new("5-A").unwrap(), |
| 1036 | - None, | 1189 | + crate::domain::grade::GradeLevel::new(5).unwrap(), |
| 1037 | None, | 1190 | None, |
| 1038 | Some(teacher), | 1191 | Some(teacher), |
| 1039 | ) | 1192 | ) |
| @@ -1132,7 +1285,7 @@ mod tests { | |||
| 1132 | &db, | 1285 | &db, |
| 1133 | &office, | 1286 | &office, |
| 1134 | ClassName::try_new("5-A").unwrap(), | 1287 | ClassName::try_new("5-A").unwrap(), |
| 1135 | - None, | 1288 | + crate::domain::grade::GradeLevel::new(5).unwrap(), |
| 1136 | None, | 1289 | None, |
| 1137 | Some(teacher), | 1290 | Some(teacher), |
| 1138 | ) | 1291 | ) |
src/web/limits.rsmodified+26 -3
| @@ -181,8 +181,11 @@ struct CourseLimits { | |||
| 181 | max_session_topic_len: usize, | 181 | max_session_topic_len: usize, |
| 182 | max_term_name_len: usize, | 182 | max_term_name_len: usize, |
| 183 | max_class_name_len: usize, | 183 | max_class_name_len: usize, |
| 184 | - /// A class's optional free-text grade label ("9", "10-A"). | 184 | + /// The valid `grade_level` range on a class and a blueprint: `0` is |
| 185 | - max_class_grade_len: usize, | 185 | + /// anaokulu, `1..=12` the school years. Every class carries one — there |
| 186 | + /// is no "no grade" any more. | ||
| 187 | + min_grade_level: i16, | ||
| 188 | + max_grade_level: i16, | ||
| 186 | /// Students one class may hold. Removing one frees a place. | 189 | /// Students one class may hold. Removing one frees a place. |
| 187 | max_class_members: i64, | 190 | max_class_members: i64, |
| 188 | /// Instances one class may carry. Detaching one frees a place. | 191 | /// Instances one class may carry. Detaching one frees a place. |
| @@ -194,6 +197,17 @@ struct CourseLimits { | |||
| 194 | max_academic_year_name_len: usize, | 197 | max_academic_year_name_len: usize, |
| 195 | } | 198 | } |
| 196 | 199 | ||
| 200 | +/// The weekly plan: one offering's (or one section's) timetable template. | ||
| 201 | +#[derive(Serialize, ToSchema)] | ||
| 202 | +struct WeeklyPlanLimits { | ||
| 203 | + /// Inclusive bounds for a slot's `starts_at`/`ends_at` minutes past | ||
| 204 | + /// midnight (`540` = 09:00). | ||
| 205 | + min_slot_minute: i64, | ||
| 206 | + max_slot_minute: i64, | ||
| 207 | + /// Slots one weekly plan may hold. | ||
| 208 | + max_weekly_slots: i64, | ||
| 209 | +} | ||
| 210 | + | ||
| 197 | /// Exams, their questions, answers, and marks. | 211 | /// Exams, their questions, answers, and marks. |
| 198 | #[derive(Serialize, ToSchema)] | 212 | #[derive(Serialize, ToSchema)] |
| 199 | struct ExamLimits { | 213 | struct ExamLimits { |
| @@ -515,6 +529,9 @@ struct LimitsResponse { | |||
| 515 | message: MessageLimits, | 529 | message: MessageLimits, |
| 516 | event: EventLimits, | 530 | event: EventLimits, |
| 517 | course: CourseLimits, | 531 | course: CourseLimits, |
| 532 | + /// The weekly plan's timetable bounds (`/offerings/{id}/weekly-plan` and | ||
| 533 | + /// the instance override doors). | ||
| 534 | + weekly_plan: WeeklyPlanLimits, | ||
| 518 | exam: ExamLimits, | 535 | exam: ExamLimits, |
| 519 | homework: HomeworkLimits, | 536 | homework: HomeworkLimits, |
| 520 | question_pool: QuestionPoolLimits, | 537 | question_pool: QuestionPoolLimits, |
| @@ -602,13 +619,19 @@ impl LimitsResponse { | |||
| 602 | max_session_topic_len: MAX_SESSION_TOPIC_LEN, | 619 | max_session_topic_len: MAX_SESSION_TOPIC_LEN, |
| 603 | max_term_name_len: MAX_TERM_NAME_LEN, | 620 | max_term_name_len: MAX_TERM_NAME_LEN, |
| 604 | max_class_name_len: MAX_CLASS_NAME_LEN, | 621 | max_class_name_len: MAX_CLASS_NAME_LEN, |
| 605 | - max_class_grade_len: MAX_CLASS_GRADE_LEN, | 622 | + min_grade_level: MIN_GRADE_LEVEL, |
| 623 | + max_grade_level: MAX_GRADE_LEVEL, | ||
| 606 | max_class_members: MAX_CLASS_MEMBERS, | 624 | max_class_members: MAX_CLASS_MEMBERS, |
| 607 | max_class_courses: MAX_CLASS_COURSES, | 625 | max_class_courses: MAX_CLASS_COURSES, |
| 608 | min_ders_saati: MIN_DERS_SAATI, | 626 | min_ders_saati: MIN_DERS_SAATI, |
| 609 | max_ders_saati: MAX_DERS_SAATI, | 627 | max_ders_saati: MAX_DERS_SAATI, |
| 610 | max_academic_year_name_len: MAX_ACADEMIC_YEAR_NAME_LEN, | 628 | max_academic_year_name_len: MAX_ACADEMIC_YEAR_NAME_LEN, |
| 611 | }, | 629 | }, |
| 630 | + weekly_plan: WeeklyPlanLimits { | ||
| 631 | + min_slot_minute: MIN_SLOT_MINUTE, | ||
| 632 | + max_slot_minute: MAX_SLOT_MINUTE, | ||
| 633 | + max_weekly_slots: MAX_WEEKLY_SLOTS as i64, | ||
| 634 | + }, | ||
| 612 | exam: ExamLimits { | 635 | exam: ExamLimits { |
| 613 | max_title_len: MAX_EXAM_TITLE_LEN, | 636 | max_title_len: MAX_EXAM_TITLE_LEN, |
| 614 | max_description_len: MAX_EXAM_DESCRIPTION_LEN, | 637 | max_description_len: MAX_EXAM_DESCRIPTION_LEN, |
src/web/marks.rsmodified+40 -12
| @@ -125,10 +125,12 @@ async fn enrolled_instances(user: &UserId, db: &Database) -> Result<Vec<ClassCou | |||
| 125 | } | 125 | } |
| 126 | 126 | ||
| 127 | /// Assemble the report: for each instance the student sits, join its exams with | 127 | /// Assemble the report: for each instance the student sits, join its exams with |
| 128 | -/// the student's graded results, weigh each mark by its exam kind's settings | 128 | +/// the student's graded results, weigh each mark by its kind's weight *in that |
| 129 | -/// weight, then average. A `viewer` narrows the report to the instances that | 129 | +/// section* ([`service::exam_weight::resolve`]: the section's override, else |
| 130 | -/// viewer manages (self-reports and manager+ reports pass `None` and see | 130 | +/// the offering's, else the settings weight, else 1), then average. A `viewer` |
| 131 | -/// everything); the overall average follows the narrowed set. | 131 | +/// narrows the report to the instances that viewer manages (self-reports and |
| 132 | +/// manager+ reports pass `None` and see everything); the overall average | ||
| 133 | +/// follows the narrowed set. | ||
| 132 | async fn build_report( | 134 | async fn build_report( |
| 133 | user: &UserId, | 135 | user: &UserId, |
| 134 | viewer: Option<&User>, | 136 | viewer: Option<&User>, |
| @@ -145,8 +147,9 @@ async fn build_report( | |||
| 145 | instances = kept; | 147 | instances = kept; |
| 146 | } | 148 | } |
| 147 | 149 | ||
| 148 | - // One settings read weighs and labels the whole report, and one batch read | 150 | + // One settings read grades (bands/labels) the whole report — the weights |
| 149 | - // resolves every block's catalog row (its title and kind). | 151 | + // ride each section's own chain now — and one batch read resolves every |
| 152 | + // block's catalog row (its title and kind). | ||
| 150 | let school = service::settings::load(db).await?; | 153 | let school = service::settings::load(db).await?; |
| 151 | let course_ids: Vec<crate::domain::course::CourseId> = | 154 | let course_ids: Vec<crate::domain::course::CourseId> = |
| 152 | instances.iter().map(|i| i.get_course().clone()).collect(); | 155 | instances.iter().map(|i| i.get_course().clone()).collect(); |
| @@ -156,10 +159,19 @@ async fn build_report( | |||
| 156 | .map(|course| (course.get_id().key(), course)) | 159 | .map(|course| (course.get_id().key(), course)) |
| 157 | .collect(); | 160 | .collect(); |
| 158 | let people = person_map(courses.iter().flat_map(course_people), db).await?; | 161 | let people = person_map(courses.iter().flat_map(course_people), db).await?; |
| 162 | + // The blocks display the sections' **resolved** titles/descriptions | ||
| 163 | + // (override → offering → catalog), batched — the `/courses` catalog list | ||
| 164 | + // is the deliberate exception that keeps the catalog row's own values, | ||
| 165 | + // because that surface IS the catalog. | ||
| 166 | + let instance_refs: Vec<&ClassCourse> = instances.iter().collect(); | ||
| 167 | + let content = service::instance_resolve::resolved_content(db, &instance_refs).await?; | ||
| 159 | 168 | ||
| 160 | let mut blocks = Vec::with_capacity(instances.len()); | 169 | let mut blocks = Vec::with_capacity(instances.len()); |
| 161 | let mut seen: HashSet<String> = HashSet::new(); | 170 | let mut seen: HashSet<String> = HashSet::new(); |
| 162 | for instance in &instances { | 171 | for instance in &instances { |
| 172 | + // The section's weight chain answer per kind, computed once — every | ||
| 173 | + // mark of a kind weighs the same inside one block. | ||
| 174 | + let mut line_weights: HashMap<String, i64> = HashMap::new(); | ||
| 163 | let exams = crate::service::exam::list_for_class_course(db, instance.get_id()).await?; | 175 | let exams = crate::service::exam::list_for_class_course(db, instance.get_id()).await?; |
| 164 | let by_exam: HashMap<String, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect(); | 176 | let by_exam: HashMap<String, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect(); |
| 165 | let results = | 177 | let results = |
| @@ -174,11 +186,19 @@ async fn build_report( | |||
| 174 | let Some(exam) = by_exam.get(result.get_exam().key().as_str()) else { | 186 | let Some(exam) = by_exam.get(result.get_exam().key().as_str()) else { |
| 175 | continue; | 187 | continue; |
| 176 | }; | 188 | }; |
| 177 | - // The kind's current settings weight; an exam keeps a retired | 189 | + // The kind's weight *in this section*: the section's own |
| 178 | - // kind, and its marks then count once. | 190 | + // override, else the offering's, else the settings weight, else 1 |
| 179 | - let weight = school | 191 | + // — a retired kind keeps counting once, an own set in force is |
| 180 | - .exam_kind_weight(exam.get_kind().as_str()) | 192 | + // the whole answer, empty included. |
| 181 | - .unwrap_or(1); | 193 | + let kind = exam.get_kind().as_str(); |
| 194 | + let weight = match line_weights.get(kind) { | ||
| 195 | + Some(weight) => *weight, | ||
| 196 | + None => { | ||
| 197 | + let weight = service::exam_weight::resolve(db, instance, kind).await?; | ||
| 198 | + line_weights.insert(kind.to_string(), weight); | ||
| 199 | + weight | ||
| 200 | + } | ||
| 201 | + }; | ||
| 182 | entries.push(MarkEntry { | 202 | entries.push(MarkEntry { |
| 183 | exam: exam.get_id().key().to_string(), | 203 | exam: exam.get_id().key().to_string(), |
| 184 | title: exam.get_title().as_str().to_string(), | 204 | title: exam.get_title().as_str().to_string(), |
| @@ -200,9 +220,17 @@ async fn build_report( | |||
| 200 | }; | 220 | }; |
| 201 | seen.insert(instance.get_id().key()); | 221 | seen.insert(instance.get_id().key()); |
| 202 | let average = weighted_average(&pairs); | 222 | let average = weighted_average(&pairs); |
| 223 | + // The instance-scoped display: resolved title/description over the | ||
| 224 | + // catalog row's (which stays the id/kind/counters source). | ||
| 225 | + let resolved = content | ||
| 226 | + .get(instance.get_id().key().as_str()) | ||
| 227 | + .expect("resolved_content covers every instance it is given"); | ||
| 228 | + let mut course = CourseResponse::new(course, &people); | ||
| 229 | + course.title = resolved.title.clone(); | ||
| 230 | + course.description = resolved.description.clone(); | ||
| 203 | blocks.push(CourseMarks { | 231 | blocks.push(CourseMarks { |
| 204 | instance: instance.get_id().key(), | 232 | instance: instance.get_id().key(), |
| 205 | - course: CourseResponse::new(course, &people), | 233 | + course, |
| 206 | average, | 234 | average, |
| 207 | average_grade: average.and_then(|a| school.grade_label(a).map(str::to_string)), | 235 | average_grade: average.and_then(|a| school.grade_label(a).map(str::to_string)), |
| 208 | results: entries, | 236 | results: entries, |
src/web/mod.rsmodified+5 -1
| @@ -18,6 +18,7 @@ pub mod course_notes; | |||
| 18 | pub mod courses; | 18 | pub mod courses; |
| 19 | pub mod etag; | 19 | pub mod etag; |
| 20 | pub mod events; | 20 | pub mod events; |
| 21 | +pub mod exam_weights; | ||
| 21 | pub mod exam_ws; | 22 | pub mod exam_ws; |
| 22 | pub mod exams; | 23 | pub mod exams; |
| 23 | pub mod homework; | 24 | pub mod homework; |
| @@ -30,6 +31,8 @@ pub mod messages; | |||
| 30 | pub mod module_gate; | 31 | pub mod module_gate; |
| 31 | pub mod modules; | 32 | pub mod modules; |
| 32 | pub mod notes; | 33 | pub mod notes; |
| 34 | +pub mod offering_subjects; | ||
| 35 | +pub mod offerings; | ||
| 33 | pub mod payments; | 36 | pub mod payments; |
| 34 | pub mod podcast; | 37 | pub mod podcast; |
| 35 | pub mod pomodoro; | 38 | pub mod pomodoro; |
| @@ -42,6 +45,7 @@ pub mod settings; | |||
| 42 | pub mod subjects; | 45 | pub mod subjects; |
| 43 | pub mod terms; | 46 | pub mod terms; |
| 44 | pub mod users; | 47 | pub mod users; |
| 48 | +pub mod weekly_plan; | ||
| 45 | pub mod work; | 49 | pub mod work; |
| 46 | 50 | ||
| 47 | pub mod tenant_state; | 51 | pub mod tenant_state; |
| @@ -526,7 +530,7 @@ mod tests { | |||
| 526 | db, | 530 | db, |
| 527 | &office, | 531 | &office, |
| 528 | ClassName::try_new("9-A").unwrap(), | 532 | ClassName::try_new("9-A").unwrap(), |
| 529 | - None, | 533 | + crate::domain::grade::GradeLevel::new(9).unwrap(), |
| 530 | None, | 534 | None, |
| 531 | Some(*teacher.get_id()), | 535 | Some(*teacher.get_id()), |
| 532 | ) | 536 | ) |
src/web/offering_subjects.rsadded+317 -0
| @@ -0,0 +1,317 @@ | |||
| 1 | +//! Syllabus topic selection on the course-template system: the topics an | ||
| 2 | +//! offering ([`crate::domain::course_offering::CourseOffering`]) selects for | ||
| 3 | +//! its grade, and the per-section override | ||
| 4 | +//! ([`crate::domain::class_course::ClassCourse`]). The override rule is | ||
| 5 | +//! override-or-inherit, never merge, and it is **flag-driven**: | ||
| 6 | +//! `subjects_inherited` `TRUE` follows the offering's set, `FALSE` makes the | ||
| 7 | +//! section's own table authoritative *including when it is empty* — the | ||
| 8 | +//! section-level deletes and the reset door flip it in the same statement as | ||
| 9 | +//! the row change ([`crate::db::offering_subject`]). | ||
| 10 | +//! | ||
| 11 | +//! This module exports two routers: [`offering_routes`] (mounted under | ||
| 12 | +//! `/offerings` by the offerings router) and [`instance_routes`] (mounted | ||
| 13 | +//! inside `/instances` like the exam/session/homework children). Reads are | ||
| 14 | +//! open to any signed-in session; offering writes are the office's | ||
| 15 | +//! (`manager`+); instance writes pay the D10 gate every other | ||
| 16 | +//! instance-scoped write pays (`service::class_course::ensure_instance_teacher`) | ||
| 17 | +//! and refuse on an archived year. | ||
| 18 | +//! | ||
| 19 | +//! Selection always names a subject of the offering's own course — a foreign | ||
| 20 | +//! topic is the same 400 the question/homework tag check answers. | ||
| 21 | + | ||
| 22 | +use axum::Json; | ||
| 23 | +use axum::extract::Path; | ||
| 24 | +use axum::http::StatusCode; | ||
| 25 | +use serde::{Deserialize, Serialize}; | ||
| 26 | +use utoipa::ToSchema; | ||
| 27 | +use utoipa_axum::router::OpenApiRouter; | ||
| 28 | +use utoipa_axum::routes; | ||
| 29 | + | ||
| 30 | +use crate::database::Database; | ||
| 31 | +use crate::domain::class_course::{ClassCourse, ClassCourseId}; | ||
| 32 | +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; | ||
| 33 | +use crate::domain::user::User; | ||
| 34 | +use crate::error::{AppError, ErrorResponse}; | ||
| 35 | +use crate::service; | ||
| 36 | +use crate::state::AppState; | ||
| 37 | +use crate::web::dto::SubjectResponse; | ||
| 38 | +use crate::web::tenant_state::State; | ||
| 39 | + | ||
| 40 | +use super::{CurrentUser, RequireManager, RequireTeacher}; | ||
| 41 | + | ||
| 42 | +/// The offering-side half: mounted under `/offerings`. | ||
| 43 | +pub fn offering_routes() -> OpenApiRouter<AppState> { | ||
| 44 | + OpenApiRouter::new() | ||
| 45 | + .routes(routes!(list_offering_subjects, add_offering_subject)) | ||
| 46 | + .routes(routes!(remove_offering_subject)) | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// The instance-side half: mounted inside `/instances`, next to the exam, | ||
| 50 | +/// session and homework children. The two `DELETE`s stay in separate | ||
| 51 | +/// `routes!` calls — one call may register each HTTP method only once. | ||
| 52 | +pub fn instance_routes() -> OpenApiRouter<AppState> { | ||
| 53 | + OpenApiRouter::new() | ||
| 54 | + .routes(routes!(list_instance_subjects, add_instance_subject)) | ||
| 55 | + .routes(routes!(remove_instance_subject)) | ||
| 56 | + .routes(routes!(reset_instance_subjects)) | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +#[derive(Deserialize, ToSchema)] | ||
| 60 | +struct AddSubject { | ||
| 61 | + /// The subject id to select (`GET /courses/{id}/subjects`). Must belong | ||
| 62 | + /// to the offering's own course — a foreign topic is a 400. | ||
| 63 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | ||
| 64 | + subject: String, | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// The topics one section teaches, resolved override-or-inherit — plus the | ||
| 68 | +/// switch, so a client can tell "the template's set" from "its own (possibly | ||
| 69 | +/// empty) set". | ||
| 70 | +#[derive(Serialize, ToSchema)] | ||
| 71 | +struct ResolvedSubjects { | ||
| 72 | + /// The resolved set, by subject name then id. | ||
| 73 | + subjects: Vec<SubjectResponse>, | ||
| 74 | + /// `true` = the section follows its offering's set; `false` = its own | ||
| 75 | + /// selection is authoritative, even when the list above is empty. | ||
| 76 | + subjects_inherited: bool, | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +async fn offering_or_404(key: &str, db: &Database) -> Result<CourseOffering, AppError> { | ||
| 80 | + service::course_offering::read(db, &CourseOfferingId::from_key(key)) | ||
| 81 | + .await? | ||
| 82 | + .ok_or(AppError::NotFound) | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +async fn instance_or_404(key: &str, db: &Database) -> Result<ClassCourse, AppError> { | ||
| 86 | + service::class_course::read(db, &ClassCourseId::from_key(key)) | ||
| 87 | + .await? | ||
| 88 | + .ok_or(AppError::NotFound) | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// The instance-side write gate: D10 (manager+, this instance's teachers, its | ||
| 92 | +/// şube's homeroom teacher) over a live year — the same pair every other | ||
| 93 | +/// instance-scoped write pays. | ||
| 94 | +async fn gated_instance(key: &str, user: &User, db: &Database) -> Result<ClassCourse, AppError> { | ||
| 95 | + let instance = instance_or_404(key, db).await?; | ||
| 96 | + service::class_course::ensure_instance_teacher(db, user, instance.get_id()).await?; | ||
| 97 | + service::class_course::require_open(db, instance.get_id()).await?; | ||
| 98 | + Ok(instance) | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +/// The offering's selected topics — the set every inheriting section at that | ||
| 102 | +/// grade teaches — by subject name then id. Any signed-in session. | ||
| 103 | +#[utoipa::path( | ||
| 104 | + get, | ||
| 105 | + path = "/{id}/subjects", | ||
| 106 | + tag = "offerings", | ||
| 107 | + security(("session_cookie" = [])), | ||
| 108 | + params(("id" = String, Path, description = "Offering id")), | ||
| 109 | + responses( | ||
| 110 | + (status = 200, description = "The offering's selected subjects", body = [SubjectResponse]), | ||
| 111 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 112 | + (status = 404, description = "Offering not found", body = ErrorResponse), | ||
| 113 | + ), | ||
| 114 | +)] | ||
| 115 | +async fn list_offering_subjects( | ||
| 116 | + State(st): State<AppState>, | ||
| 117 | + CurrentUser(_user): CurrentUser, | ||
| 118 | + Path(id): Path<String>, | ||
| 119 | +) -> Result<Json<Vec<SubjectResponse>>, AppError> { | ||
| 120 | + let offering = offering_or_404(&id, &st.db).await?; | ||
| 121 | + let subjects = service::offering_subject::resolved_for_offering(&st.db, offering.get_id()) | ||
| 122 | + .await?; | ||
| 123 | + Ok(Json(subjects.iter().map(SubjectResponse::new).collect())) | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +/// Select a topic for the offering. Manager+. Re-selecting an already | ||
| 127 | +/// selected topic is a no-op success (`200`, not a second row). | ||
| 128 | +#[utoipa::path( | ||
| 129 | + post, | ||
| 130 | + path = "/{id}/subjects", | ||
| 131 | + tag = "offerings", | ||
| 132 | + security(("session_cookie" = [])), | ||
| 133 | + params(("id" = String, Path, description = "Offering id")), | ||
| 134 | + request_body = AddSubject, | ||
| 135 | + responses( | ||
| 136 | + (status = 201, description = "Subject selected", body = SubjectResponse), | ||
| 137 | + (status = 200, description = "Already selected — no-op success", body = SubjectResponse), | ||
| 138 | + (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), | ||
| 139 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 140 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 141 | + (status = 404, description = "Offering not found", body = ErrorResponse), | ||
| 142 | + (status = 422, description = "The body does not fit this request: `subject` is missing or malformed"), | ||
| 143 | + ), | ||
| 144 | +)] | ||
| 145 | +async fn add_offering_subject( | ||
| 146 | + State(st): State<AppState>, | ||
| 147 | + RequireManager(_user): RequireManager, | ||
| 148 | + Path(id): Path<String>, | ||
| 149 | + Json(req): Json<AddSubject>, | ||
| 150 | +) -> Result<(StatusCode, Json<SubjectResponse>), AppError> { | ||
| 151 | + let offering = offering_or_404(&id, &st.db).await?; | ||
| 152 | + let (subject, added) = | ||
| 153 | + service::offering_subject::add_to_offering(&st.db, offering.get_id(), &req.subject) | ||
| 154 | + .await?; | ||
| 155 | + let code = if added { | ||
| 156 | + StatusCode::CREATED | ||
| 157 | + } else { | ||
| 158 | + StatusCode::OK | ||
| 159 | + }; | ||
| 160 | + Ok((code, Json(SubjectResponse::new(&subject)))) | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +/// Drop a topic from the offering's selection. Manager+. Dropping a topic the | ||
| 164 | +/// offering never selected is a 404. | ||
| 165 | +#[utoipa::path( | ||
| 166 | + delete, | ||
| 167 | + path = "/{id}/subjects/{subject}", | ||
| 168 | + tag = "offerings", | ||
| 169 | + security(("session_cookie" = [])), | ||
| 170 | + params( | ||
| 171 | + ("id" = String, Path, description = "Offering id"), | ||
| 172 | + ("subject" = String, Path, description = "Subject id"), | ||
| 173 | + ), | ||
| 174 | + responses( | ||
| 175 | + (status = 204, description = "Dropped"), | ||
| 176 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 177 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 178 | + (status = 404, description = "Offering not found, or subject not selected", body = ErrorResponse), | ||
| 179 | + ), | ||
| 180 | +)] | ||
| 181 | +async fn remove_offering_subject( | ||
| 182 | + State(st): State<AppState>, | ||
| 183 | + RequireManager(_user): RequireManager, | ||
| 184 | + Path((id, subject)): Path<(String, String)>, | ||
| 185 | +) -> Result<StatusCode, AppError> { | ||
| 186 | + let offering = offering_or_404(&id, &st.db).await?; | ||
| 187 | + service::offering_subject::remove_from_offering(&st.db, offering.get_id(), &subject).await?; | ||
| 188 | + Ok(StatusCode::NO_CONTENT) | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +/// The topics this section teaches, resolved override-or-inherit, with the | ||
| 192 | +/// switch: `subjects_inherited: false` means the listed set (even when | ||
| 193 | +/// empty) is the section's own and the offering's is ignored. Any signed-in | ||
| 194 | +/// session. | ||
| 195 | +#[utoipa::path( | ||
| 196 | + get, | ||
| 197 | + path = "/{id}/subjects", | ||
| 198 | + tag = "instances", | ||
| 199 | + security(("session_cookie" = [])), | ||
| 200 | + params(("id" = String, Path, description = "Instance (class×course) id")), | ||
| 201 | + responses( | ||
| 202 | + (status = 200, description = "The resolved subject set and whether it is inherited", body = ResolvedSubjects), | ||
| 203 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 204 | + (status = 404, description = "Instance not found", body = ErrorResponse), | ||
| 205 | + ), | ||
| 206 | +)] | ||
| 207 | +async fn list_instance_subjects( | ||
| 208 | + State(st): State<AppState>, | ||
| 209 | + CurrentUser(_user): CurrentUser, | ||
| 210 | + Path(id): Path<String>, | ||
| 211 | +) -> Result<Json<ResolvedSubjects>, AppError> { | ||
| 212 | + let instance = instance_or_404(&id, &st.db).await?; | ||
| 213 | + let subjects = service::offering_subject::resolved_for_instance(&st.db, &instance).await?; | ||
| 214 | + Ok(Json(ResolvedSubjects { | ||
| 215 | + subjects: subjects.iter().map(SubjectResponse::new).collect(), | ||
| 216 | + subjects_inherited: instance.subjects_inherited(), | ||
| 217 | + })) | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +/// Select a topic for this section's own set — the override. The switch | ||
| 221 | +/// flips to "own" in the same write, so the section's table (not the | ||
| 222 | +/// offering's set) becomes authoritative from this call on. Re-selecting an | ||
| 223 | +/// already selected topic is a no-op success. D10 gate; refuses on an | ||
| 224 | +/// archived year. | ||
| 225 | +#[utoipa::path( | ||
| 226 | + post, | ||
| 227 | + path = "/{id}/subjects", | ||
| 228 | + tag = "instances", | ||
| 229 | + security(("session_cookie" = [])), | ||
| 230 | + params(("id" = String, Path, description = "Instance (class×course) id")), | ||
| 231 | + request_body = AddSubject, | ||
| 232 | + responses( | ||
| 233 | + (status = 201, description = "Subject selected — the section now owns its set", body = SubjectResponse), | ||
| 234 | + (status = 200, description = "Already selected — no-op success", body = SubjectResponse), | ||
| 235 | + (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), | ||
| 236 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 237 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 238 | + (status = 404, description = "Instance not found", body = ErrorResponse), | ||
| 239 | + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), | ||
| 240 | + (status = 422, description = "The body does not fit this request: `subject` is missing or malformed"), | ||
| 241 | + ), | ||
| 242 | +)] | ||
| 243 | +async fn add_instance_subject( | ||
| 244 | + State(st): State<AppState>, | ||
| 245 | + RequireTeacher(user): RequireTeacher, | ||
| 246 | + Path(id): Path<String>, | ||
| 247 | + Json(req): Json<AddSubject>, | ||
| 248 | +) -> Result<(StatusCode, Json<SubjectResponse>), AppError> { | ||
| 249 | + let instance = gated_instance(&id, &user, &st.db).await?; | ||
| 250 | + let (subject, added) = | ||
| 251 | + service::offering_subject::add_to_instance(&st.db, &instance, &req.subject).await?; | ||
| 252 | + let code = if added { | ||
| 253 | + StatusCode::CREATED | ||
| 254 | + } else { | ||
| 255 | + StatusCode::OK | ||
| 256 | + }; | ||
| 257 | + Ok((code, Json(SubjectResponse::new(&subject)))) | ||
| 258 | +} | ||
| 259 | + | ||
| 260 | +/// Drop one topic from this section's own set (keeping the set its own — | ||
| 261 | +/// clearing the syllabus needs the reset below, or deleting the last rows | ||
| 262 | +/// one by one). Dropping a topic the section never selected is a 404 and | ||
| 263 | +/// flips nothing. D10 gate; refuses on an archived year. | ||
| 264 | +#[utoipa::path( | ||
| 265 | + delete, | ||
| 266 | + path = "/{id}/subjects/{subject}", | ||
| 267 | + tag = "instances", | ||
| 268 | + security(("session_cookie" = [])), | ||
| 269 | + params( | ||
| 270 | + ("id" = String, Path, description = "Instance (class×course) id"), | ||
| 271 | + ("subject" = String, Path, description = "Subject id"), | ||
| 272 | + ), | ||
| 273 | + responses( | ||
| 274 | + (status = 204, description = "Dropped — the section keeps its own set"), | ||
| 275 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 276 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 277 | + (status = 404, description = "Instance not found, or subject not in the section's own set", body = ErrorResponse), | ||
| 278 | + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), | ||
| 279 | + ), | ||
| 280 | +)] | ||
| 281 | +async fn remove_instance_subject( | ||
| 282 | + State(st): State<AppState>, | ||
| 283 | + RequireTeacher(user): RequireTeacher, | ||
| 284 | + Path((id, subject)): Path<(String, String)>, | ||
| 285 | +) -> Result<StatusCode, AppError> { | ||
| 286 | + let instance = gated_instance(&id, &user, &st.db).await?; | ||
| 287 | + service::offering_subject::remove_from_instance(&st.db, &instance, &subject).await?; | ||
| 288 | + Ok(StatusCode::NO_CONTENT) | ||
| 289 | +} | ||
| 290 | + | ||
| 291 | +/// Restore inheritance: sweep the section's own rows and flip | ||
| 292 | +/// `subjects_inherited` back to TRUE in the same statement — the offering's | ||
| 293 | +/// set applies again. A section whose own set was already empty resets | ||
| 294 | +/// cleanly. D10 gate; refuses on an archived year. | ||
| 295 | +#[utoipa::path( | ||
| 296 | + delete, | ||
| 297 | + path = "/{id}/subjects", | ||
| 298 | + tag = "instances", | ||
| 299 | + security(("session_cookie" = [])), | ||
| 300 | + params(("id" = String, Path, description = "Instance (class×course) id")), | ||
| 301 | + responses( | ||
| 302 | + (status = 204, description = "Own set swept — the offering's set applies again"), | ||
| 303 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 304 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 305 | + (status = 404, description = "Instance not found", body = ErrorResponse), | ||
| 306 | + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), | ||
| 307 | + ), | ||
| 308 | +)] | ||
| 309 | +async fn reset_instance_subjects( | ||
| 310 | + State(st): State<AppState>, | ||
| 311 | + RequireTeacher(user): RequireTeacher, | ||
| 312 | + Path(id): Path<String>, | ||
| 313 | +) -> Result<StatusCode, AppError> { | ||
| 314 | + let instance = gated_instance(&id, &user, &st.db).await?; | ||
| 315 | + service::offering_subject::reset_instance(&st.db, &instance).await?; | ||
| 316 | + Ok(StatusCode::NO_CONTENT) | ||
| 317 | +} | ||
src/web/offerings.rsadded+376 -0
| @@ -0,0 +1,376 @@ | |||
| 1 | +//! The course **offerings**: the grade-level templates (`course_offering`) | ||
| 2 | +//! every class×course instance inherits from — one row per | ||
| 3 | +//! (course × grade_level) carrying the title, description and the | ||
| 4 | +//! weekly-hours / report-card defaults for that grade, with the per-class | ||
| 5 | +//! overrides living on the instances themselves | ||
| 6 | +//! ([`crate::web::instances`]). | ||
| 7 | +//! | ||
| 8 | +//! Reads are open to any signed-in session; writes are the office's | ||
| 9 | +//! (`manager`+), the same bar as the catalog itself. Every write door keeps | ||
| 10 | +//! the override-or-inherit rule visible: a `PATCH` field sent as `null` | ||
| 11 | +//! clears back to inherit, and the delete refuses with `offering_in_use` | ||
| 12 | +//! while any instance still teaches from the template. | ||
| 13 | + | ||
| 14 | +use std::collections::HashMap; | ||
| 15 | + | ||
| 16 | +use axum::Json; | ||
| 17 | +use axum::extract::{Path, Query}; | ||
| 18 | +use axum::http::StatusCode; | ||
| 19 | +use serde::{Deserialize, Serialize}; | ||
| 20 | +use utoipa::{IntoParams, ToSchema}; | ||
| 21 | +use utoipa_axum::router::OpenApiRouter; | ||
| 22 | +use utoipa_axum::routes; | ||
| 23 | + | ||
| 24 | +use crate::database::Database; | ||
| 25 | +use crate::domain::class_course::DersSaati; | ||
| 26 | +use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; | ||
| 27 | +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; | ||
| 28 | +use crate::domain::grade::GradeLevel; | ||
| 29 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 30 | +use crate::service; | ||
| 31 | +use crate::state::AppState; | ||
| 32 | +use crate::web::tenant_state::State; | ||
| 33 | + | ||
| 34 | +use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, person_map, set_or_clear}; | ||
| 35 | + | ||
| 36 | +pub fn routes() -> OpenApiRouter<AppState> { | ||
| 37 | + OpenApiRouter::new() | ||
| 38 | + .routes(routes!(create_offering, list_offerings)) | ||
| 39 | + .routes(routes!(get_offering, update_offering, delete_offering)) | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +#[derive(Deserialize, ToSchema)] | ||
| 43 | +struct CreateOffering { | ||
| 44 | + /// The catalog course this template teaches from (`POST /courses`). | ||
| 45 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | ||
| 46 | + course: String, | ||
| 47 | + /// The ladder rung: `0` is anaokulu, `1..=12` the school years. | ||
| 48 | + #[schema(minimum = 0, maximum = 12, example = 9)] | ||
| 49 | + grade_level: i16, | ||
| 50 | + /// The grade's own title; omit to inherit the catalog course's. | ||
| 51 | + #[schema(max_length = 200)] | ||
| 52 | + title: Option<String>, | ||
| 53 | + /// The grade's own description; omit to inherit the catalog's. | ||
| 54 | + #[schema(max_length = 2_000)] | ||
| 55 | + description: Option<String>, | ||
| 56 | + /// The grade's default weekly hours; omit for the constant 1. | ||
| 57 | + #[schema(minimum = 1, maximum = 40, example = 5)] | ||
| 58 | + default_ders_saati: Option<i64>, | ||
| 59 | + /// The grade's default report-card policy; omit for counted (`true`). | ||
| 60 | + default_counts_toward_karne: Option<bool>, | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +#[derive(Deserialize, ToSchema)] | ||
| 64 | +struct UpdateOffering { | ||
| 65 | + /// Omit to keep; send `null` to clear (inherit the catalog course's | ||
| 66 | + /// title); send a value to set the grade's own. | ||
| 67 | + #[serde(default, deserialize_with = "set_or_clear")] | ||
| 68 | + #[schema(value_type = Option<String>, max_length = 200)] | ||
| 69 | + title: Option<Option<String>>, | ||
| 70 | + /// Omit to keep; `null` to clear (inherit the catalog's); a value to set. | ||
| 71 | + #[serde(default, deserialize_with = "set_or_clear")] | ||
| 72 | + #[schema(value_type = Option<String>, max_length = 2_000)] | ||
| 73 | + description: Option<Option<String>>, | ||
| 74 | + /// Omit to keep; `null` to clear (inherit the constant 1); 1..=40 to set. | ||
| 75 | + #[serde(default, deserialize_with = "set_or_clear")] | ||
| 76 | + #[schema(value_type = Option<i64>, minimum = 1, maximum = 40)] | ||
| 77 | + default_ders_saati: Option<Option<i64>>, | ||
| 78 | + /// Omit to keep; `null` to clear (inherit counted); a value to set. | ||
| 79 | + #[serde(default, deserialize_with = "set_or_clear")] | ||
| 80 | + #[schema(value_type = Option<bool>)] | ||
| 81 | + default_counts_toward_karne: Option<Option<bool>>, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// The list filters, both optional and combinable. | ||
| 85 | +#[derive(Deserialize, IntoParams)] | ||
| 86 | +struct OfferingFilter { | ||
| 87 | + /// Only this course's offerings. | ||
| 88 | + #[param(example = "019732e3-7b00-7000-8000-00000000dead")] | ||
| 89 | + course: Option<String>, | ||
| 90 | + /// Only this ladder rung (`0` = anaokulu). | ||
| 91 | + #[param(minimum = 0, maximum = 12)] | ||
| 92 | + grade_level: Option<i16>, | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +impl OfferingFilter { | ||
| 96 | + /// Validate + canonicalize: a malformed course key is a 400, not an empty | ||
| 97 | + /// page — the caller asked for something, the key just does not name it. | ||
| 98 | + fn resolve(&self) -> Result<(Option<CourseId>, Option<GradeLevel>), AppError> { | ||
| 99 | + let course = match &self.course { | ||
| 100 | + Some(key) => { | ||
| 101 | + let id = CourseId::from_key(key); | ||
| 102 | + if id.uuid().is_nil() { | ||
| 103 | + return Err(ValidationError::Invalid { | ||
| 104 | + field: "course", | ||
| 105 | + reason: "must be a hyphenated uuid", | ||
| 106 | + } | ||
| 107 | + .into()); | ||
| 108 | + } | ||
| 109 | + Some(id) | ||
| 110 | + } | ||
| 111 | + None => None, | ||
| 112 | + }; | ||
| 113 | + let grade = self.grade_level.map(GradeLevel::new).transpose()?; | ||
| 114 | + Ok((course, grade)) | ||
| 115 | + } | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +/// Public shape of one offering: the grade-level template, with `null` | ||
| 119 | +/// meaning *inherit* on every content field. These are the **raw template | ||
| 120 | +/// values** — this row IS the grade's template, so a manager reads and edits | ||
| 121 | +/// exactly what is stored here. The per-instance **resolved** view (override | ||
| 122 | +/// → offering → catalog/constant, no nulls, with the source flags) is what | ||
| 123 | +/// `GET /instances/{id}` serves. | ||
| 124 | +#[derive(Serialize, ToSchema)] | ||
| 125 | +pub struct OfferingResponse { | ||
| 126 | + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] | ||
| 127 | + pub id: String, | ||
| 128 | + /// The catalog course taught from this template (`GET /courses/{id}`). | ||
| 129 | + pub course: String, | ||
| 130 | + /// The ladder rung: `0` = anaokulu, `1..=12` the school years. | ||
| 131 | + pub grade_level: i16, | ||
| 132 | + /// The grade's own title; `null` = the catalog course's title. | ||
| 133 | + pub title: Option<String>, | ||
| 134 | + /// The grade's own description; `null` = the catalog course's. | ||
| 135 | + pub description: Option<String>, | ||
| 136 | + /// The grade's default weekly hours; `null` = the constant 1. | ||
| 137 | + pub default_ders_saati: Option<i64>, | ||
| 138 | + /// The grade's default report-card policy; `null` = counted (`true`). | ||
| 139 | + pub default_counts_toward_karne: Option<bool>, | ||
| 140 | + /// Who minted the template (deliberately, or by first attaching the | ||
| 141 | + /// course to a class at this grade). | ||
| 142 | + pub created_by: PersonRef, | ||
| 143 | + /// Mint instant, UTC unix-milliseconds. | ||
| 144 | + pub created_at: i64, | ||
| 145 | + /// Last content edit, UTC unix-milliseconds. | ||
| 146 | + pub updated_at: i64, | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +impl OfferingResponse { | ||
| 150 | + fn new(offering: &CourseOffering, people: &HashMap<String, PersonRef>) -> Self { | ||
| 151 | + Self { | ||
| 152 | + id: offering.get_id().key(), | ||
| 153 | + course: offering.get_course().key(), | ||
| 154 | + grade_level: offering.get_grade_level().get(), | ||
| 155 | + title: offering.get_title().map(|t| t.as_str().to_string()), | ||
| 156 | + description: offering.get_description().map(|d| d.as_str().to_string()), | ||
| 157 | + default_ders_saati: offering.get_default_ders_saati().map(DersSaati::as_i64), | ||
| 158 | + default_counts_toward_karne: offering.get_default_counts_toward_karne(), | ||
| 159 | + created_by: PersonRef::resolve(people, offering.get_created_by()), | ||
| 160 | + created_at: offering.get_created_at().as_millis(), | ||
| 161 | + updated_at: offering.get_updated_at().as_millis(), | ||
| 162 | + } | ||
| 163 | + } | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +async fn offering_or_404(key: &str, db: &Database) -> Result<CourseOffering, AppError> { | ||
| 167 | + service::course_offering::read(db, &CourseOfferingId::from_key(key)) | ||
| 168 | + .await? | ||
| 169 | + .ok_or(AppError::NotFound) | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +/// Create the grade-level template for a course. Manager+. A course that is | ||
| 173 | +/// not a class-delivered ders has no grade axis and is refused (a club or | ||
| 174 | +/// etüt is joined individually, never attached); a template that already | ||
| 175 | +/// exists for the (course, grade) pair is a 409 `offering_exists`. | ||
| 176 | +#[utoipa::path( | ||
| 177 | + post, | ||
| 178 | + path = "/", | ||
| 179 | + tag = "offerings", | ||
| 180 | + security(("session_cookie" = [])), | ||
| 181 | + request_body = CreateOffering, | ||
| 182 | + responses( | ||
| 183 | + (status = 201, description = "Offering created", body = OfferingResponse), | ||
| 184 | + (status = 400, description = "Invalid fields, or the course is not a class-delivered ders (kind `course`)", body = ErrorResponse), | ||
| 185 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 186 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 187 | + (status = 404, description = "Course not found", body = ErrorResponse), | ||
| 188 | + (status = 409, description = "The course already has an offering for this grade — the body carries the machine code `offering_exists`", body = ErrorResponse), | ||
| 189 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 190 | + ), | ||
| 191 | +)] | ||
| 192 | +async fn create_offering( | ||
| 193 | + State(st): State<AppState>, | ||
| 194 | + RequireManager(user): RequireManager, | ||
| 195 | + Json(req): Json<CreateOffering>, | ||
| 196 | +) -> Result<(StatusCode, Json<OfferingResponse>), AppError> { | ||
| 197 | + let course = CourseId::from_key(&req.course); | ||
| 198 | + if course.uuid().is_nil() { | ||
| 199 | + return Err(ValidationError::Invalid { | ||
| 200 | + field: "course", | ||
| 201 | + reason: "must be a hyphenated uuid", | ||
| 202 | + } | ||
| 203 | + .into()); | ||
| 204 | + } | ||
| 205 | + let grade = GradeLevel::new(req.grade_level)?; | ||
| 206 | + let title = match &req.title { | ||
| 207 | + Some(title) => Some(CourseTitle::try_new(title)?), | ||
| 208 | + None => None, | ||
| 209 | + }; | ||
| 210 | + let description = match &req.description { | ||
| 211 | + Some(description) => Some(CourseDescription::try_new(description)?), | ||
| 212 | + None => None, | ||
| 213 | + }; | ||
| 214 | + let staff = req.default_ders_saati.map(DersSaati::try_new).transpose()?; | ||
| 215 | + let offering = service::course_offering::create( | ||
| 216 | + &st.db, | ||
| 217 | + user.get_id(), | ||
| 218 | + &course, | ||
| 219 | + grade, | ||
| 220 | + title, | ||
| 221 | + description, | ||
| 222 | + staff, | ||
| 223 | + req.default_counts_toward_karne, | ||
| 224 | + ) | ||
| 225 | + .await?; | ||
| 226 | + let people = PersonRef::map_of(&[&user]); | ||
| 227 | + Ok((StatusCode::CREATED, Json(OfferingResponse::new(&offering, &people)))) | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +/// List the offerings, paged via `?limit=&offset=` (omit `limit` for all of | ||
| 231 | +/// them); optionally narrowed by `?course=` and/or `?grade_level=`. Returns a | ||
| 232 | +/// `{items, total, limit, offset}` envelope. | ||
| 233 | +#[utoipa::path( | ||
| 234 | + get, | ||
| 235 | + path = "/", | ||
| 236 | + tag = "offerings", | ||
| 237 | + security(("session_cookie" = [])), | ||
| 238 | + params(PageParams, OfferingFilter), | ||
| 239 | + responses( | ||
| 240 | + (status = 200, description = "A page of offerings (all of them when unpaged)", body = Page<OfferingResponse>), | ||
| 241 | + (status = 400, description = "Invalid limit, offset, course key, or grade_level", body = ErrorResponse), | ||
| 242 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 243 | + ), | ||
| 244 | +)] | ||
| 245 | +async fn list_offerings( | ||
| 246 | + State(st): State<AppState>, | ||
| 247 | + CurrentUser(_user): CurrentUser, | ||
| 248 | + Query(page): Query<PageParams>, | ||
| 249 | + Query(filter): Query<OfferingFilter>, | ||
| 250 | +) -> Result<Json<Page<OfferingResponse>>, AppError> { | ||
| 251 | + let (limit, offset) = page.resolve()?; | ||
| 252 | + let (course, grade) = filter.resolve()?; | ||
| 253 | + let (rows, total) = | ||
| 254 | + service::course_offering::list(&st.db, course.as_ref(), grade, limit, offset).await?; | ||
| 255 | + let people = person_map(rows.iter().map(|o| *o.get_created_by()), &st.db).await?; | ||
| 256 | + let items = rows | ||
| 257 | + .iter() | ||
| 258 | + .map(|offering| OfferingResponse::new(offering, &people)) | ||
| 259 | + .collect(); | ||
| 260 | + Ok(Json(Page::new(items, total, limit, offset))) | ||
| 261 | +} | ||
| 262 | + | ||
| 263 | +/// Fetch one offering by id. Any signed-in session. The body is the raw | ||
| 264 | +/// template row (nullable = inherit) — not the per-instance resolved view | ||
| 265 | +/// `GET /instances/{id}` serves. | ||
| 266 | +#[utoipa::path( | ||
| 267 | + get, | ||
| 268 | + path = "/{id}", | ||
| 269 | + tag = "offerings", | ||
| 270 | + security(("session_cookie" = [])), | ||
| 271 | + params(("id" = String, Path, description = "Offering id")), | ||
| 272 | + responses( | ||
| 273 | + (status = 200, description = "The offering's raw template values (null = inherit); the per-class resolved view lives on GET /instances/{id}", body = OfferingResponse), | ||
| 274 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 275 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 276 | + ), | ||
| 277 | +)] | ||
| 278 | +async fn get_offering( | ||
| 279 | + State(st): State<AppState>, | ||
| 280 | + CurrentUser(_user): CurrentUser, | ||
| 281 | + Path(id): Path<String>, | ||
| 282 | +) -> Result<Json<OfferingResponse>, AppError> { | ||
| 283 | + let offering = offering_or_404(&id, &st.db).await?; | ||
| 284 | + let people = person_map(std::iter::once(*offering.get_created_by()), &st.db).await?; | ||
| 285 | + Ok(Json(OfferingResponse::new(&offering, &people))) | ||
| 286 | +} | ||
| 287 | + | ||
| 288 | +/// Field-scoped edit. Manager+. Omitted fields keep their value; an explicit | ||
| 289 | +/// `null` clears the override back to inherit (the catalog course's title or | ||
| 290 | +/// description, the constant 1 weekly hour, counted toward the karne); a | ||
| 291 | +/// value sets the grade's own. Instances that carry no override of their own | ||
| 292 | +/// follow the change immediately — that is what inherit means. | ||
| 293 | +#[utoipa::path( | ||
| 294 | + patch, | ||
| 295 | + path = "/{id}", | ||
| 296 | + tag = "offerings", | ||
| 297 | + security(("session_cookie" = [])), | ||
| 298 | + params(("id" = String, Path, description = "Offering id")), | ||
| 299 | + request_body = UpdateOffering, | ||
| 300 | + responses( | ||
| 301 | + (status = 200, description = "Updated offering", body = OfferingResponse), | ||
| 302 | + (status = 400, description = "Invalid field values", body = ErrorResponse), | ||
| 303 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 304 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 305 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 306 | + (status = 422, description = "The body does not fit this request: a field has the wrong type"), | ||
| 307 | + ), | ||
| 308 | +)] | ||
| 309 | +async fn update_offering( | ||
| 310 | + State(st): State<AppState>, | ||
| 311 | + RequireManager(_user): RequireManager, | ||
| 312 | + Path(id): Path<String>, | ||
| 313 | + Json(req): Json<UpdateOffering>, | ||
| 314 | +) -> Result<Json<OfferingResponse>, AppError> { | ||
| 315 | + // Tri-state per field: absent = keep, null = clear to inherit, value = set. | ||
| 316 | + let title = match req.title { | ||
| 317 | + None => None, | ||
| 318 | + Some(inner) => Some(match inner { | ||
| 319 | + None => None, | ||
| 320 | + Some(text) => Some(CourseTitle::try_new(&text)?), | ||
| 321 | + }), | ||
| 322 | + }; | ||
| 323 | + let description = match req.description { | ||
| 324 | + None => None, | ||
| 325 | + Some(inner) => Some(match inner { | ||
| 326 | + None => None, | ||
| 327 | + Some(text) => Some(CourseDescription::try_new(&text)?), | ||
| 328 | + }), | ||
| 329 | + }; | ||
| 330 | + let staff = match req.default_ders_saati { | ||
| 331 | + None => None, | ||
| 332 | + Some(inner) => Some(match inner { | ||
| 333 | + None => None, | ||
| 334 | + Some(hours) => Some(DersSaati::try_new(hours)?), | ||
| 335 | + }), | ||
| 336 | + }; | ||
| 337 | + let offering = service::course_offering::update( | ||
| 338 | + &st.db, | ||
| 339 | + &CourseOfferingId::from_key(&id), | ||
| 340 | + title, | ||
| 341 | + description, | ||
| 342 | + staff, | ||
| 343 | + req.default_counts_toward_karne, | ||
| 344 | + ) | ||
| 345 | + .await?; | ||
| 346 | + let people = person_map(std::iter::once(*offering.get_created_by()), &st.db).await?; | ||
| 347 | + Ok(Json(OfferingResponse::new(&offering, &people))) | ||
| 348 | +} | ||
| 349 | + | ||
| 350 | +/// Delete the template. Manager+. Refused with 409 `offering_in_use` while | ||
| 351 | +/// any class×course instance still teaches from it — detach the course from | ||
| 352 | +/// those classes first. Deleting a template no section uses erases only the | ||
| 353 | +/// grade's overrides; the instances keep existing (their next attach | ||
| 354 | +/// re-mints an empty template). | ||
| 355 | +#[utoipa::path( | ||
| 356 | + delete, | ||
| 357 | + path = "/{id}", | ||
| 358 | + tag = "offerings", | ||
| 359 | + security(("session_cookie" = [])), | ||
| 360 | + params(("id" = String, Path, description = "Offering id")), | ||
| 361 | + responses( | ||
| 362 | + (status = 204, description = "Deleted"), | ||
| 363 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 364 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 365 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 366 | + (status = 409, description = "An instance still teaches from this offering — the body carries the machine code `offering_in_use`", body = ErrorResponse), | ||
| 367 | + ), | ||
| 368 | +)] | ||
| 369 | +async fn delete_offering( | ||
| 370 | + State(st): State<AppState>, | ||
| 371 | + RequireManager(_user): RequireManager, | ||
| 372 | + Path(id): Path<String>, | ||
| 373 | +) -> Result<StatusCode, AppError> { | ||
| 374 | + service::course_offering::delete(&st.db, &CourseOfferingId::from_key(&id)).await?; | ||
| 375 | + Ok(StatusCode::NO_CONTENT) | ||
| 376 | +} | ||
src/web/users.rsmodified+8 -3
| @@ -1008,8 +1008,9 @@ struct ProfileClassRef { | |||
| 1008 | id: String, | 1008 | id: String, |
| 1009 | #[schema(example = "9-A")] | 1009 | #[schema(example = "9-A")] |
| 1010 | name: String, | 1010 | name: String, |
| 1011 | - #[schema(example = "9")] | 1011 | + /// The class's rung on the grade ladder (`0` = anaokulu). |
| 1012 | - grade: Option<String>, | 1012 | + #[schema(example = 9)] |
| 1013 | + grade_level: i16, | ||
| 1013 | } | 1014 | } |
| 1014 | 1015 | ||
| 1015 | /// A course as a profile shows it — a label, nothing more. | 1016 | /// A course as a profile shows it — a label, nothing more. |
| @@ -1207,13 +1208,17 @@ async fn profile_of( | |||
| 1207 | .map(|class| ProfileClassRef { | 1208 | .map(|class| ProfileClassRef { |
| 1208 | id: class.get_id().key().to_string(), | 1209 | id: class.get_id().key().to_string(), |
| 1209 | name: class.get_name().as_str().to_string(), | 1210 | name: class.get_name().as_str().to_string(), |
| 1210 | - grade: class.get_grade().map(|grade| grade.as_str().to_string()), | 1211 | + grade_level: class.get_grade_level().get(), |
| 1211 | }) | 1212 | }) |
| 1212 | .collect(), | 1213 | .collect(), |
| 1213 | courses: courses | 1214 | courses: courses |
| 1214 | .iter() | 1215 | .iter() |
| 1215 | .map(|course| ProfileCourseRef { | 1216 | .map(|course| ProfileCourseRef { |
| 1216 | id: course.get_id().key().to_string(), | 1217 | id: course.get_id().key().to_string(), |
| 1218 | + // Catalog-tier surface, like `GET /courses`: a profile lists | ||
| 1219 | + // the person's courses by their catalog identity (a person | ||
| 1220 | + // may sit two sections of one ders), so the catalog title is | ||
| 1221 | + // the deliberate exception to the instance-resolved display. | ||
| 1217 | title: course.get_title().as_str().to_string(), | 1222 | title: course.get_title().as_str().to_string(), |
| 1218 | kind: course.get_kind().as_str().to_string(), | 1223 | kind: course.get_kind().as_str().to_string(), |
| 1219 | }) | 1224 | }) |
src/web/weekly_plan.rsadded+371 -0
| @@ -0,0 +1,371 @@ | |||
| 1 | +//! The weekly plan surface: the timetable template's routes on both owners — | ||
| 2 | +//! the grade-level offering (`/offerings/{id}/weekly-plan`, the office's | ||
| 3 | +//! door) and the class×course instance (`/instances/{id}/weekly-plan`, the | ||
| 4 | +//! D10 door), split into the two mount functions the router composes | ||
| 5 | +//! (`offering_routes` under `/offerings`, `instance_routes` inside | ||
| 6 | +//! `/instances`) so each carries its own module's gate. | ||
| 7 | +//! | ||
| 8 | +//! A slot is one weekday plus a minutes-past-midnight window (`1` = Monday | ||
| 9 | +//! through `7` = Sunday, `540` = 09:00). Two slots of one owner may touch but | ||
| 10 | +//! never overlap (409 `slot_overlap`); a plan holds at most | ||
| 11 | +//! [`crate::constant::MAX_WEEKLY_SLOTS`] slots (409 `slot_cap`). | ||
| 12 | +//! Writing any instance-side row flips `weekly_plan_inherited` to `false` in | ||
| 13 | +//! the same statement, and `DELETE /instances/{id}/weekly-plan` (no slot id) | ||
| 14 | +//! is the reset back to inherit — the resolved reads never merge the two | ||
| 15 | +//! sets. | ||
| 16 | +//! | ||
| 17 | +//! **No scheduler.** Nothing generates dated `course_session` rows from a | ||
| 18 | +//! weekly plan — `course_session` stays the per-lesson occurrence, written by | ||
| 19 | +//! its own routes. These routes serve template + override + resolution only. | ||
| 20 | + | ||
| 21 | +use axum::Json; | ||
| 22 | +use axum::extract::Path; | ||
| 23 | +use axum::http::StatusCode; | ||
| 24 | +use serde::{Deserialize, Serialize}; | ||
| 25 | +use utoipa::ToSchema; | ||
| 26 | +use utoipa_axum::router::OpenApiRouter; | ||
| 27 | +use utoipa_axum::routes; | ||
| 28 | + | ||
| 29 | +use crate::database::Database; | ||
| 30 | +use crate::domain::class_course::{ClassCourse, ClassCourseId}; | ||
| 31 | +use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; | ||
| 32 | +use crate::domain::weekly_slot::{SlotMinute, Weekday, WeeklySlot, WeeklySlotId}; | ||
| 33 | +use crate::error::{AppError, ErrorResponse}; | ||
| 34 | +use crate::service; | ||
| 35 | +use crate::state::AppState; | ||
| 36 | +use crate::web::tenant_state::State; | ||
| 37 | + | ||
| 38 | +use super::instances::can_view_instance; | ||
| 39 | +use super::{CurrentUser, RequireManager, RequireTeacher}; | ||
| 40 | + | ||
| 41 | +/// The route set mounted under `/offerings` (relative paths): the template | ||
| 42 | +/// week's reads and the office's writes. | ||
| 43 | +pub fn offering_routes() -> OpenApiRouter<AppState> { | ||
| 44 | + OpenApiRouter::new() | ||
| 45 | + .routes(routes!(list_offering_weekly_plan, add_offering_slot)) | ||
| 46 | + .routes(routes!(remove_offering_slot)) | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// The instance-side half: mounted inside `/instances` — the section's | ||
| 50 | +/// resolved plan, its override writes, and the reset. The two `DELETE`s stay | ||
| 51 | +/// in separate `routes!` calls — one call may register each HTTP method only | ||
| 52 | +/// once. | ||
| 53 | +pub fn instance_routes() -> OpenApiRouter<AppState> { | ||
| 54 | + OpenApiRouter::new() | ||
| 55 | + .routes(routes!(list_instance_weekly_plan, add_instance_slot)) | ||
| 56 | + .routes(routes!(remove_instance_slot)) | ||
| 57 | + .routes(routes!(reset_instance_weekly_plan)) | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +/// A weekly plan line the caller sent: the ISO weekday and the two | ||
| 61 | +/// minutes-past-midnight bounds of the lesson window. | ||
| 62 | +#[derive(Deserialize, ToSchema)] | ||
| 63 | +struct CreateSlot { | ||
| 64 | + /// `1` = Monday through `7` = Sunday. | ||
| 65 | + weekday: i16, | ||
| 66 | + /// Minutes past midnight (`540` = 09:00) — the window opens here. | ||
| 67 | + starts_at: i64, | ||
| 68 | + /// Minutes past midnight — strictly after `starts_at`. | ||
| 69 | + ends_at: i64, | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +/// Public shape of one weekly plan slot. Times stay the minutes-past-midnight | ||
| 73 | +/// form the request sent; `weekday` stays the integer (`1` = Monday). | ||
| 74 | +#[derive(Serialize, ToSchema)] | ||
| 75 | +pub struct WeeklySlotDto { | ||
| 76 | + pub id: String, | ||
| 77 | + /// `1` = Monday through `7` = Sunday. | ||
| 78 | + pub weekday: i16, | ||
| 79 | + /// Minutes past midnight — the window opens here. | ||
| 80 | + pub starts_at: i64, | ||
| 81 | + /// Minutes past midnight, strictly after `starts_at`. | ||
| 82 | + pub ends_at: i64, | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +impl WeeklySlotDto { | ||
| 86 | + pub fn new(slot: &WeeklySlot) -> Self { | ||
| 87 | + Self { | ||
| 88 | + id: slot.get_id().key(), | ||
| 89 | + weekday: slot.get_weekday().get(), | ||
| 90 | + starts_at: slot.get_starts_at().get(), | ||
| 91 | + ends_at: slot.get_ends_at().get(), | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// The section's **resolved** weekly plan: whose rows are authoritative and | ||
| 97 | +/// what they are — the offering's template week while | ||
| 98 | +/// `weekly_plan_inherited` stands, the section's own rows (possibly empty) | ||
| 99 | +/// once it overrode. Ordered weekday first, then start time. | ||
| 100 | +#[derive(Serialize, ToSchema)] | ||
| 101 | +pub struct InstanceWeeklyPlan { | ||
| 102 | + pub weekly_plan: Vec<WeeklySlotDto>, | ||
| 103 | + /// `true` = the offering's template week is authoritative; `false` = the | ||
| 104 | + /// section's own rows below, including when that list is empty. | ||
| 105 | + pub weekly_plan_inherited: bool, | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +async fn offering_or_404(key: &str, db: &Database) -> Result<CourseOffering, AppError> { | ||
| 109 | + service::course_offering::read(db, &CourseOfferingId::from_key(key)) | ||
| 110 | + .await? | ||
| 111 | + .ok_or(AppError::NotFound) | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// The instance a path id names, or a 404 — the read arm mirrors | ||
| 115 | +/// [`super::instances`]'s. | ||
| 116 | +async fn instance_or_404(key: &str, db: &Database) -> Result<ClassCourse, AppError> { | ||
| 117 | + service::class_course::read(db, &ClassCourseId::from_key(key)) | ||
| 118 | + .await? | ||
| 119 | + .ok_or(AppError::NotFound) | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// The body's slot, range-checked before anything is written: weekday and | ||
| 123 | +/// minute bounds here, the non-empty window inside the domain `WeeklySlot`. | ||
| 124 | +fn parse_slot( | ||
| 125 | + req: &CreateSlot, | ||
| 126 | +) -> Result<(Weekday, SlotMinute, SlotMinute), crate::error::ValidationError> { | ||
| 127 | + Ok(( | ||
| 128 | + Weekday::new(req.weekday)?, | ||
| 129 | + SlotMinute::new(req.starts_at)?, | ||
| 130 | + SlotMinute::new(req.ends_at)?, | ||
| 131 | + )) | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// List the offering's template week — weekday first, then start time. Any | ||
| 135 | +/// signed-in session, the same visibility as the offering read itself. | ||
| 136 | +#[utoipa::path( | ||
| 137 | + get, | ||
| 138 | + path = "/{id}/weekly-plan", | ||
| 139 | + tag = "offerings", | ||
| 140 | + security(("session_cookie" = [])), | ||
| 141 | + params(("id" = String, Path, description = "Offering id")), | ||
| 142 | + responses( | ||
| 143 | + (status = 200, description = "The template week, ordered weekday then start time", body = [WeeklySlotDto]), | ||
| 144 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 145 | + (status = 404, description = "Offering not found", body = ErrorResponse), | ||
| 146 | + ), | ||
| 147 | +)] | ||
| 148 | +async fn list_offering_weekly_plan( | ||
| 149 | + State(st): State<AppState>, | ||
| 150 | + CurrentUser(_user): CurrentUser, | ||
| 151 | + Path(id): Path<String>, | ||
| 152 | +) -> Result<Json<Vec<WeeklySlotDto>>, AppError> { | ||
| 153 | + let offering = offering_or_404(&id, &st.db).await?; | ||
| 154 | + let slots = service::weekly_slot::resolved_for_offering(&st.db, offering.get_id()).await?; | ||
| 155 | + Ok(Json(slots.iter().map(WeeklySlotDto::new).collect())) | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +/// Add one slot to the offering's template week. Manager+. Refused with 409 | ||
| 159 | +/// `slot_overlap` when a template slot already occupies an intersecting | ||
| 160 | +/// window on that weekday (an exact duplicate overlaps too), 409 `slot_cap` | ||
| 161 | +/// when the week already holds the maximum. | ||
| 162 | +#[utoipa::path( | ||
| 163 | + post, | ||
| 164 | + path = "/{id}/weekly-plan", | ||
| 165 | + tag = "offerings", | ||
| 166 | + security(("session_cookie" = [])), | ||
| 167 | + params(("id" = String, Path, description = "Offering id")), | ||
| 168 | + request_body = CreateSlot, | ||
| 169 | + responses( | ||
| 170 | + (status = 201, description = "Slot added", body = WeeklySlotDto), | ||
| 171 | + (status = 400, description = "Invalid weekday or minutes, or an empty window", body = ErrorResponse), | ||
| 172 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 173 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 174 | + (status = 404, description = "Offering not found", body = ErrorResponse), | ||
| 175 | + (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), | ||
| 176 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 177 | + ), | ||
| 178 | +)] | ||
| 179 | +async fn add_offering_slot( | ||
| 180 | + State(st): State<AppState>, | ||
| 181 | + RequireManager(_user): RequireManager, | ||
| 182 | + Path(id): Path<String>, | ||
| 183 | + Json(req): Json<CreateSlot>, | ||
| 184 | +) -> Result<(StatusCode, Json<WeeklySlotDto>), AppError> { | ||
| 185 | + let offering = offering_or_404(&id, &st.db).await?; | ||
| 186 | + let (weekday, starts_at, ends_at) = parse_slot(&req)?; | ||
| 187 | + let slot = service::weekly_slot::add_for_offering( | ||
| 188 | + &st.db, | ||
| 189 | + offering.get_id(), | ||
| 190 | + weekday, | ||
| 191 | + starts_at, | ||
| 192 | + ends_at, | ||
| 193 | + ) | ||
| 194 | + .await?; | ||
| 195 | + Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot)))) | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +/// Drop one slot of the offering's template week. Manager+. A slot of another | ||
| 199 | +/// offering, or one already gone, is a 404. | ||
| 200 | +#[utoipa::path( | ||
| 201 | + delete, | ||
| 202 | + path = "/{id}/weekly-plan/{slot}", | ||
| 203 | + tag = "offerings", | ||
| 204 | + security(("session_cookie" = [])), | ||
| 205 | + params( | ||
| 206 | + ("id" = String, Path, description = "Offering id"), | ||
| 207 | + ("slot" = String, Path, description = "Slot id"), | ||
| 208 | + ), | ||
| 209 | + responses( | ||
| 210 | + (status = 204, description = "Slot removed"), | ||
| 211 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 212 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 213 | + (status = 404, description = "Offering or slot not found", body = ErrorResponse), | ||
| 214 | + ), | ||
| 215 | +)] | ||
| 216 | +async fn remove_offering_slot( | ||
| 217 | + State(st): State<AppState>, | ||
| 218 | + RequireManager(_user): RequireManager, | ||
| 219 | + Path((id, slot)): Path<(String, String)>, | ||
| 220 | +) -> Result<StatusCode, AppError> { | ||
| 221 | + let offering = offering_or_404(&id, &st.db).await?; | ||
| 222 | + service::weekly_slot::remove_for_offering( | ||
| 223 | + &st.db, | ||
| 224 | + offering.get_id(), | ||
| 225 | + &WeeklySlotId::from_key(&slot), | ||
| 226 | + ) | ||
| 227 | + .await?; | ||
| 228 | + Ok(StatusCode::NO_CONTENT) | ||
| 229 | +} | ||
| 230 | + | ||
| 231 | +/// The section's resolved weekly plan plus whose rows it is. Visible to the | ||
| 232 | +/// same eyes as the instance read: enrolled students, its teachers, its | ||
| 233 | +/// şube's homeroom teacher, and managers/admins. | ||
| 234 | +#[utoipa::path( | ||
| 235 | + get, | ||
| 236 | + path = "/{id}/weekly-plan", | ||
| 237 | + tag = "instances", | ||
| 238 | + security(("session_cookie" = [])), | ||
| 239 | + params(("id" = String, Path, description = "Instance id")), | ||
| 240 | + responses( | ||
| 241 | + (status = 200, description = "The resolved plan and the flag that picked it", body = InstanceWeeklyPlan), | ||
| 242 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 243 | + (status = 403, description = "Not enrolled, and not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 244 | + (status = 404, description = "Instance not found", body = ErrorResponse), | ||
| 245 | + ), | ||
| 246 | +)] | ||
| 247 | +async fn list_instance_weekly_plan( | ||
| 248 | + State(st): State<AppState>, | ||
| 249 | + CurrentUser(user): CurrentUser, | ||
| 250 | + Path(id): Path<String>, | ||
| 251 | +) -> Result<Json<InstanceWeeklyPlan>, AppError> { | ||
| 252 | + let instance = instance_or_404(&id, &st.db).await?; | ||
| 253 | + if !can_view_instance(&st.db, instance.get_id(), &user).await? { | ||
| 254 | + return Err(AppError::Forbidden( | ||
| 255 | + "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view it", | ||
| 256 | + )); | ||
| 257 | + } | ||
| 258 | + let weekly_plan = service::weekly_slot::resolved_for_instance(&st.db, &instance).await?; | ||
| 259 | + Ok(Json(InstanceWeeklyPlan { | ||
| 260 | + weekly_plan: weekly_plan.iter().map(WeeklySlotDto::new).collect(), | ||
| 261 | + weekly_plan_inherited: instance.weekly_plan_inherited(), | ||
| 262 | + })) | ||
| 263 | +} | ||
| 264 | + | ||
| 265 | +/// Add one slot to the section's own week. Requires teacher+ and a right over | ||
| 266 | +/// the instance; the write flips `weekly_plan_inherited` to `false` in the | ||
| 267 | +/// same statement, so from here the section's own rows — not the offering's | ||
| 268 | +/// template — are what every read resolves. Same overlap and cap refusals as | ||
| 269 | +/// the offering side. | ||
| 270 | +#[utoipa::path( | ||
| 271 | + post, | ||
| 272 | + path = "/{id}/weekly-plan", | ||
| 273 | + tag = "instances", | ||
| 274 | + security(("session_cookie" = [])), | ||
| 275 | + params(("id" = String, Path, description = "Instance id")), | ||
| 276 | + request_body = CreateSlot, | ||
| 277 | + responses( | ||
| 278 | + (status = 201, description = "Slot added; the section now overrides the template", body = WeeklySlotDto), | ||
| 279 | + (status = 400, description = "Invalid weekday or minutes, or an empty window", body = ErrorResponse), | ||
| 280 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 281 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 282 | + (status = 404, description = "Instance not found", body = ErrorResponse), | ||
| 283 | + (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), | ||
| 284 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | ||
| 285 | + ), | ||
| 286 | +)] | ||
| 287 | +async fn add_instance_slot( | ||
| 288 | + State(st): State<AppState>, | ||
| 289 | + RequireTeacher(user): RequireTeacher, | ||
| 290 | + Path(id): Path<String>, | ||
| 291 | + Json(req): Json<CreateSlot>, | ||
| 292 | +) -> Result<(StatusCode, Json<WeeklySlotDto>), AppError> { | ||
| 293 | + let instance = instance_or_404(&id, &st.db).await?; | ||
| 294 | + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; | ||
| 295 | + service::class_course::require_open(&st.db, instance.get_id()).await?; | ||
| 296 | + let (weekday, starts_at, ends_at) = parse_slot(&req)?; | ||
| 297 | + let slot = | ||
| 298 | + service::weekly_slot::add_for_class(&st.db, instance.get_id(), weekday, starts_at, ends_at) | ||
| 299 | + .await?; | ||
| 300 | + Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot)))) | ||
| 301 | +} | ||
| 302 | + | ||
| 303 | +/// Drop one slot of the section's own week. Requires teacher+ and a right | ||
| 304 | +/// over the instance. The flag flip to `false` rides the delete in the same | ||
| 305 | +/// statement — dropping the last own row leaves the section with an | ||
| 306 | +/// authoritative *empty* plan, not a quiet return to the template | ||
| 307 | +/// (`DELETE /{id}/weekly-plan` is the way back to inherit). A slot of another | ||
| 308 | +/// instance, or one already gone, is a 404 that leaves the flag untouched. | ||
| 309 | +#[utoipa::path( | ||
| 310 | + delete, | ||
| 311 | + path = "/{id}/weekly-plan/{slot}", | ||
| 312 | + tag = "instances", | ||
| 313 | + security(("session_cookie" = [])), | ||
| 314 | + params( | ||
| 315 | + ("id" = String, Path, description = "Instance id"), | ||
| 316 | + ("slot" = String, Path, description = "Slot id"), | ||
| 317 | + ), | ||
| 318 | + responses( | ||
| 319 | + (status = 204, description = "Slot removed"), | ||
| 320 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 321 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 322 | + (status = 404, description = "Instance or slot not found", body = ErrorResponse), | ||
| 323 | + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), | ||
| 324 | + ), | ||
| 325 | +)] | ||
| 326 | +async fn remove_instance_slot( | ||
| 327 | + State(st): State<AppState>, | ||
| 328 | + RequireTeacher(user): RequireTeacher, | ||
| 329 | + Path((id, slot)): Path<(String, String)>, | ||
| 330 | +) -> Result<StatusCode, AppError> { | ||
| 331 | + let instance = instance_or_404(&id, &st.db).await?; | ||
| 332 | + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; | ||
| 333 | + service::class_course::require_open(&st.db, instance.get_id()).await?; | ||
| 334 | + service::weekly_slot::remove_for_class( | ||
| 335 | + &st.db, | ||
| 336 | + instance.get_id(), | ||
| 337 | + &WeeklySlotId::from_key(&slot), | ||
| 338 | + ) | ||
| 339 | + .await?; | ||
| 340 | + Ok(StatusCode::NO_CONTENT) | ||
| 341 | +} | ||
| 342 | + | ||
| 343 | +/// Reset the section's weekly plan to inherit — delete every slot of its own | ||
| 344 | +/// week and flip `weekly_plan_inherited` back to `true` in one statement, so | ||
| 345 | +/// the offering's template week is what every read resolves again. | ||
| 346 | +/// Idempotent for a section that never overrode. | ||
| 347 | +#[utoipa::path( | ||
| 348 | + delete, | ||
| 349 | + path = "/{id}/weekly-plan", | ||
| 350 | + tag = "instances", | ||
| 351 | + security(("session_cookie" = [])), | ||
| 352 | + params(("id" = String, Path, description = "Instance id")), | ||
| 353 | + responses( | ||
| 354 | + (status = 204, description = "The section's own week is gone; the offering's template is authoritative again"), | ||
| 355 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 356 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | ||
| 357 | + (status = 404, description = "Instance not found", body = ErrorResponse), | ||
| 358 | + (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), | ||
| 359 | + ), | ||
| 360 | +)] | ||
| 361 | +async fn reset_instance_weekly_plan( | ||
| 362 | + State(st): State<AppState>, | ||
| 363 | + RequireTeacher(user): RequireTeacher, | ||
| 364 | + Path(id): Path<String>, | ||
| 365 | +) -> Result<StatusCode, AppError> { | ||
| 366 | + let instance = instance_or_404(&id, &st.db).await?; | ||
| 367 | + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; | ||
| 368 | + service::class_course::require_open(&st.db, instance.get_id()).await?; | ||
| 369 | + service::weekly_slot::reset_for_class(&st.db, instance.get_id()).await?; | ||
| 370 | + Ok(StatusCode::NO_CONTENT) | ||
| 371 | +} | ||
tests/ai_bridge.rsmodified+4 -2
| @@ -3672,8 +3672,10 @@ async fn a_manager_study_request_carries_the_school_wide_scope_pairs() { | |||
| 3672 | .as_array() | 3672 | .as_array() |
| 3673 | .expect("scope_pairs is an array"); | 3673 | .expect("scope_pairs is an array"); |
| 3674 | assert_eq!(pairs.len(), 2, "manager receives every school pair"); | 3674 | assert_eq!(pairs.len(), 2, "manager receives every school pair"); |
| 3675 | - assert!(pairs.contains(&json!([null, "Matematik"]))); | 3675 | + // Every şube sits at a ladder rung now, so the pairs name the rung label, |
| 3676 | - assert!(pairs.contains(&json!([null, "Fizik"]))); | 3676 | + // not a null grade. |
| 3677 | + assert!(pairs.contains(&json!(["9", "Matematik"]))); | ||
| 3678 | + assert!(pairs.contains(&json!(["9", "Fizik"]))); | ||
| 3677 | } | 3679 | } |
| 3678 | 3680 | ||
| 3679 | /// A connected worker that does not carry the capability is not a worker for | 3681 | /// A connected worker that does not carry the capability is not a worker for |
tests/board_invite.rsmodified+1 -1
| @@ -66,7 +66,7 @@ async fn a_class(app: &axum::Router, manager: &str, name: &str, members: &[&str] | |||
| 66 | "POST", | 66 | "POST", |
| 67 | "/classes", | 67 | "/classes", |
| 68 | Some(manager), | 68 | Some(manager), |
| 69 | - Some(json!({ "name": name })), | 69 | + Some(json!({ "name": name, "grade_level": 9 })), |
| 70 | ) | 70 | ) |
| 71 | .await; | 71 | .await; |
| 72 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 72 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
tests/common/mod.rsmodified+119 -16
| @@ -517,7 +517,43 @@ pub async fn create_subject(app: &Router, cookie: &str, course: &str, name: &str | |||
| 517 | ) | 517 | ) |
| 518 | .await; | 518 | .await; |
| 519 | assert_eq!(res.status, StatusCode::CREATED, "create subject {name}"); | 519 | assert_eq!(res.status, StatusCode::CREATED, "create subject {name}"); |
| 520 | - id_of(&res.body) | 520 | + let subject = id_of(&res.body); |
| 521 | + | ||
| 522 | + // The subject-tag gates (homework, exam questions) read the section's | ||
| 523 | + // resolved syllabus, so a topic a suite creates is only usable once the | ||
| 524 | + // offering selects it. When the course has been attached somewhere, the | ||
| 525 | + // offering exists — select the fresh topic there (idempotent; a | ||
| 526 | + // non-manager cookie cannot curate the offering and skips this, which | ||
| 527 | + // the tag gates then surface as their own 400). | ||
| 528 | + let res = send( | ||
| 529 | + app, | ||
| 530 | + "GET", | ||
| 531 | + &format!("/offerings?course={course}"), | ||
| 532 | + Some(cookie), | ||
| 533 | + None, | ||
| 534 | + ) | ||
| 535 | + .await; | ||
| 536 | + if res.status == StatusCode::OK | ||
| 537 | + && let Some(offering) = res.body["items"][0]["id"].as_str() | ||
| 538 | + { | ||
| 539 | + let res = send( | ||
| 540 | + app, | ||
| 541 | + "POST", | ||
| 542 | + &format!("/offerings/{offering}/subjects"), | ||
| 543 | + Some(cookie), | ||
| 544 | + Some(json!({ "subject": subject })), | ||
| 545 | + ) | ||
| 546 | + .await; | ||
| 547 | + // A non-manager cookie cannot curate the offering; the tag gates | ||
| 548 | + // then answer their own 400 and the caller selects another way | ||
| 549 | + // (see `create_homework`'s instance-door retry). | ||
| 550 | + assert!( | ||
| 551 | + matches!(res.status, StatusCode::CREATED | StatusCode::OK | StatusCode::FORBIDDEN), | ||
| 552 | + "select subject {name} on offering {offering}: {}", | ||
| 553 | + res.body | ||
| 554 | + ); | ||
| 555 | + } | ||
| 556 | + subject | ||
| 521 | } | 557 | } |
| 522 | 558 | ||
| 523 | // ---- the academic fixture --------------------------------------------------- | 559 | // ---- the academic fixture --------------------------------------------------- |
| @@ -595,10 +631,14 @@ pub async fn create_term(app: &Router, staff: &str, year: &str, name: &str) -> S | |||
| 595 | } | 631 | } |
| 596 | 632 | ||
| 597 | /// Create a class (şube) as `staff` (asserts 201); returns its id. `body` | 633 | /// Create a class (şube) as `staff` (asserts 201); returns its id. `body` |
| 598 | -/// carries everything but the name: `year`, `teacher_id`, `grade`. | 634 | +/// carries everything but the name: `year`, `teacher_id`, `grade_level` |
| 635 | +/// (defaulting to rung 9 when the caller does not name one). | ||
| 599 | pub async fn create_class(app: &Router, staff: &str, name: &str, body: Value) -> String { | 636 | pub async fn create_class(app: &Router, staff: &str, name: &str, body: Value) -> String { |
| 600 | let mut body = body; | 637 | let mut body = body; |
| 601 | body["name"] = json!(name); | 638 | body["name"] = json!(name); |
| 639 | + if body.get("grade_level").is_none() { | ||
| 640 | + body["grade_level"] = json!(9); | ||
| 641 | + } | ||
| 602 | let res = send(app, "POST", "/classes", Some(staff), Some(body)).await; | 642 | let res = send(app, "POST", "/classes", Some(staff), Some(body)).await; |
| 603 | assert_eq!( | 643 | assert_eq!( |
| 604 | res.status, | 644 | res.status, |
| @@ -749,6 +789,75 @@ pub async fn create_exam_with(app: &Router, cookie: &str, instance: &str, body: | |||
| 749 | .await | 789 | .await |
| 750 | } | 790 | } |
| 751 | 791 | ||
| 792 | +/// One homework-create send with the subject-gate retry: a `subject_id` the | ||
| 793 | +/// section's resolved syllabus does not carry is refused, and the writer — | ||
| 794 | +/// who holds a right over the instance (the very gate the homework write | ||
| 795 | +/// passed) — takes the topic onto the section's own set through the instance | ||
| 796 | +/// door and retries once. Every other refusal comes back untouched. | ||
| 797 | +async fn send_homework_create( | ||
| 798 | + app: &Router, | ||
| 799 | + cookie: &str, | ||
| 800 | + instance: &str, | ||
| 801 | + body: Value, | ||
| 802 | +) -> Res { | ||
| 803 | + let res = send( | ||
| 804 | + app, | ||
| 805 | + "POST", | ||
| 806 | + &format!("/instances/{instance}/homework"), | ||
| 807 | + Some(cookie), | ||
| 808 | + Some(body.clone()), | ||
| 809 | + ) | ||
| 810 | + .await; | ||
| 811 | + if res.status == StatusCode::BAD_REQUEST | ||
| 812 | + && res.body["error"] | ||
| 813 | + .as_str() | ||
| 814 | + .is_some_and(|e| e.contains("subject is not in this section's subject set")) | ||
| 815 | + { | ||
| 816 | + let subject = body["subject_id"].as_str().expect("subject_id").to_string(); | ||
| 817 | + let res = send( | ||
| 818 | + app, | ||
| 819 | + "POST", | ||
| 820 | + &format!("/instances/{instance}/subjects"), | ||
| 821 | + Some(cookie), | ||
| 822 | + Some(json!({ "subject": subject })), | ||
| 823 | + ) | ||
| 824 | + .await; | ||
| 825 | + assert!( | ||
| 826 | + matches!(res.status, StatusCode::CREATED | StatusCode::OK), | ||
| 827 | + "select subject {subject} on instance {instance}: {}", | ||
| 828 | + res.body | ||
| 829 | + ); | ||
| 830 | + return send( | ||
| 831 | + app, | ||
| 832 | + "POST", | ||
| 833 | + &format!("/instances/{instance}/homework"), | ||
| 834 | + Some(cookie), | ||
| 835 | + Some(body), | ||
| 836 | + ) | ||
| 837 | + .await; | ||
| 838 | + } | ||
| 839 | + res | ||
| 840 | +} | ||
| 841 | + | ||
| 842 | +/// Take `subject` onto the section's own syllabus through the instance door — | ||
| 843 | +/// the D10 gate, the same right the question and homework writers hold. | ||
| 844 | +/// Idempotent: a subject already in the set re-answers 200. | ||
| 845 | +pub async fn select_instance_subject(app: &Router, cookie: &str, instance: &str, subject: &str) { | ||
| 846 | + let res = send( | ||
| 847 | + app, | ||
| 848 | + "POST", | ||
| 849 | + &format!("/instances/{instance}/subjects"), | ||
| 850 | + Some(cookie), | ||
| 851 | + Some(json!({ "subject": subject })), | ||
| 852 | + ) | ||
| 853 | + .await; | ||
| 854 | + assert!( | ||
| 855 | + matches!(res.status, StatusCode::CREATED | StatusCode::OK), | ||
| 856 | + "select subject {subject} on instance {instance}: {}", | ||
| 857 | + res.body | ||
| 858 | + ); | ||
| 859 | +} | ||
| 860 | + | ||
| 752 | /// Create a homework inside `instance` as `cookie` (asserts 201); returns its | 861 | /// Create a homework inside `instance` as `cookie` (asserts 201); returns its |
| 753 | /// id. Tagged with `subject` (required — every homework carries one of its | 862 | /// id. Tagged with `subject` (required — every homework carries one of its |
| 754 | /// course's subjects) and due at `due_at` (unix-millis; must not lie past the | 863 | /// course's subjects) and due at `due_at` (unix-millis; must not lie past the |
| @@ -762,12 +871,11 @@ pub async fn create_homework( | |||
| 762 | title: &str, | 871 | title: &str, |
| 763 | due_at: i64, | 872 | due_at: i64, |
| 764 | ) -> String { | 873 | ) -> String { |
| 765 | - let res = send( | 874 | + let res = send_homework_create( |
| 766 | app, | 875 | app, |
| 767 | - "POST", | 876 | + cookie, |
| 768 | - &format!("/instances/{instance}/homework"), | 877 | + instance, |
| 769 | - Some(cookie), | 878 | + json!({ "title": title, "subject_id": subject, "due_at": due_at }), |
| 770 | - Some(json!({ "title": title, "subject_id": subject, "due_at": due_at })), | ||
| 771 | ) | 879 | ) |
| 772 | .await; | 880 | .await; |
| 773 | assert_eq!( | 881 | assert_eq!( |
| @@ -780,16 +888,11 @@ pub async fn create_homework( | |||
| 780 | } | 888 | } |
| 781 | 889 | ||
| 782 | /// Create a homework inside `instance` from a full JSON body (no assertion) — | 890 | /// Create a homework inside `instance` from a full JSON body (no assertion) — |
| 783 | -/// for exercising the `assigned` subset and the validation rejects. | 891 | +/// for exercising the `assigned` subset and the validation rejects. The |
| 892 | +/// subject-gate retry applies here too; every other refusal comes back as | ||
| 893 | +/// the server answered it. | ||
| 784 | pub async fn create_homework_with(app: &Router, cookie: &str, instance: &str, body: Value) -> Res { | 894 | pub async fn create_homework_with(app: &Router, cookie: &str, instance: &str, body: Value) -> Res { |
| 785 | - send( | 895 | + send_homework_create(app, cookie, instance, body).await |
| 786 | - app, | ||
| 787 | - "POST", | ||
| 788 | - &format!("/instances/{instance}/homework"), | ||
| 789 | - Some(cookie), | ||
| 790 | - Some(body), | ||
| 791 | - ) | ||
| 792 | - .await | ||
| 793 | } | 896 | } |
| 794 | 897 | ||
| 795 | /// Create a lesson session inside `instance` as `cookie` (asserts 201); returns | 898 | /// Create a lesson session inside `instance` as `cookie` (asserts 201); returns |
tests/e2e.rsmodified+47 -5
| @@ -674,7 +674,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { | |||
| 674 | // a plain teacher run the instance's roster and write its exams. | 674 | // a plain teacher run the instance's roster and write its exams. |
| 675 | let class: Value = manager | 675 | let class: Value = manager |
| 676 | .post(format!("{base}/classes")) | 676 | .post(format!("{base}/classes")) |
| 677 | - .json(&json!({ "name": "9-A", "year": year, "teacher_id": teacher_id })) | 677 | + .json(&json!({ "name": "9-A", "grade_level": 9, "year": year, "teacher_id": teacher_id })) |
| 678 | .send() | 678 | .send() |
| 679 | .await | 679 | .await |
| 680 | .unwrap() | 680 | .unwrap() |
| @@ -693,6 +693,26 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { | |||
| 693 | .unwrap(); | 693 | .unwrap(); |
| 694 | let instance_id = instance["id"].as_str().unwrap().to_string(); | 694 | let instance_id = instance["id"].as_str().unwrap().to_string(); |
| 695 | 695 | ||
| 696 | + // The attach auto-minted the grade-level offering with an empty syllabus; | ||
| 697 | + // the manager selects the fresh topic onto it, because a question may | ||
| 698 | + // only name a subject the section teaches. | ||
| 699 | + let offering: Value = manager | ||
| 700 | + .get(format!("{base}/instances/{instance_id}")) | ||
| 701 | + .send() | ||
| 702 | + .await | ||
| 703 | + .unwrap() | ||
| 704 | + .json() | ||
| 705 | + .await | ||
| 706 | + .unwrap(); | ||
| 707 | + let offering_id = offering["offering"].as_str().unwrap().to_string(); | ||
| 708 | + let res = manager | ||
| 709 | + .post(format!("{base}/offerings/{offering_id}/subjects")) | ||
| 710 | + .json(&json!({ "subject": subject_id })) | ||
| 711 | + .send() | ||
| 712 | + .await | ||
| 713 | + .unwrap(); | ||
| 714 | + assert_eq!(res.status(), StatusCode::CREATED); | ||
| 715 | + | ||
| 696 | let res = teacher | 716 | let res = teacher |
| 697 | .post(format!("{base}/instances/{instance_id}/enrollments")) | 717 | .post(format!("{base}/instances/{instance_id}/enrollments")) |
| 698 | .json(&json!({ "user_id": student_id })) | 718 | .json(&json!({ "user_id": student_id })) |
| @@ -3288,7 +3308,7 @@ async fn a_class_seats_its_roster_and_gives_the_seat_back() { | |||
| 3288 | ); | 3308 | ); |
| 3289 | let res = manager | 3309 | let res = manager |
| 3290 | .post(format!("{base}/classes")) | 3310 | .post(format!("{base}/classes")) |
| 3291 | - .json(&json!({ "name": "9-A", "grade": "9", "teacher_id": teacher_id })) | 3311 | + .json(&json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id })) |
| 3292 | .send() | 3312 | .send() |
| 3293 | .await | 3313 | .await |
| 3294 | .unwrap(); | 3314 | .unwrap(); |
| @@ -3541,7 +3561,7 @@ async fn a_manager_archived_year_refuses_every_write_and_answers_every_read() { | |||
| 3541 | // instance is what every one of the writes below hangs off. | 3561 | // instance is what every one of the writes below hangs off. |
| 3542 | let res = mudur | 3562 | let res = mudur |
| 3543 | .post(format!("{base}/classes")) | 3563 | .post(format!("{base}/classes")) |
| 3544 | - .json(&json!({ "name": "9-A", "grade": "9", "year": year_id })) | 3564 | + .json(&json!({ "name": "9-A", "grade_level": 9, "year": year_id })) |
| 3545 | .send() | 3565 | .send() |
| 3546 | .await | 3566 | .await |
| 3547 | .unwrap(); | 3567 | .unwrap(); |
| @@ -3560,6 +3580,28 @@ async fn a_manager_archived_year_refuses_every_write_and_answers_every_read() { | |||
| 3560 | assert_eq!(res.status(), StatusCode::CREATED); | 3580 | assert_eq!(res.status(), StatusCode::CREATED); |
| 3561 | let instance_id = json_of(res).await["id"].as_str().unwrap().to_string(); | 3581 | let instance_id = json_of(res).await["id"].as_str().unwrap().to_string(); |
| 3562 | 3582 | ||
| 3583 | + // The attach auto-minted the grade-level offering with an empty syllabus; | ||
| 3584 | + // select the fresh topic onto it so the question and the homework below | ||
| 3585 | + // may tag it. | ||
| 3586 | + let offering_id = json_of( | ||
| 3587 | + mudur | ||
| 3588 | + .get(format!("{base}/instances/{instance_id}")) | ||
| 3589 | + .send() | ||
| 3590 | + .await | ||
| 3591 | + .unwrap(), | ||
| 3592 | + ) | ||
| 3593 | + .await["offering"] | ||
| 3594 | + .as_str() | ||
| 3595 | + .unwrap() | ||
| 3596 | + .to_string(); | ||
| 3597 | + let res = mudur | ||
| 3598 | + .post(format!("{base}/offerings/{offering_id}/subjects")) | ||
| 3599 | + .json(&json!({ "subject": subject_id })) | ||
| 3600 | + .send() | ||
| 3601 | + .await | ||
| 3602 | + .unwrap(); | ||
| 3603 | + assert_eq!(res.status(), StatusCode::CREATED); | ||
| 3604 | + | ||
| 3563 | let exam: Value = json_of( | 3605 | let exam: Value = json_of( |
| 3564 | mudur | 3606 | mudur |
| 3565 | .post(format!("{base}/instances/{instance_id}/exams")) | 3607 | .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() { | |||
| 4162 | // --- two şubeler, one catalog course ------------------------------------ | 4204 | // --- two şubeler, one catalog course ------------------------------------ |
| 4163 | let res = mudur | 4205 | let res = mudur |
| 4164 | .post(format!("{base}/classes")) | 4206 | .post(format!("{base}/classes")) |
| 4165 | - .json(&json!({ "name": "5-A", "grade": "5", "year": year, "teacher_id": hoca_id })) | 4207 | + .json(&json!({ "name": "5-A", "grade_level": 5, "year": year, "teacher_id": hoca_id })) |
| 4166 | .send() | 4208 | .send() |
| 4167 | .await | 4209 | .await |
| 4168 | .unwrap(); | 4210 | .unwrap(); |
| @@ -4170,7 +4212,7 @@ async fn a_course_taught_by_two_subeler_is_two_instances_end_to_end() { | |||
| 4170 | let five_a = id_of(&res.json::<Value>().await.unwrap()["class"]); | 4212 | let five_a = id_of(&res.json::<Value>().await.unwrap()["class"]); |
| 4171 | let res = mudur | 4213 | let res = mudur |
| 4172 | .post(format!("{base}/classes")) | 4214 | .post(format!("{base}/classes")) |
| 4173 | - .json(&json!({ "name": "5-B", "grade": "5", "year": year })) | 4215 | + .json(&json!({ "name": "5-B", "grade_level": 5, "year": year })) |
| 4174 | .send() | 4216 | .send() |
| 4175 | .await | 4217 | .await |
| 4176 | .unwrap(); | 4218 | .unwrap(); |
tests/integration.rsmodified+487 -14
| @@ -8,8 +8,8 @@ use axum::http::{Request, StatusCode}; | |||
| 8 | use common::{ | 8 | use common::{ |
| 9 | add_member, app_and_db, app_and_tenants, attach_instance, create_class, create_course, | 9 | add_member, app_and_db, app_and_tenants, attach_instance, create_class, create_course, |
| 10 | create_exam, create_exam_with, create_homework, create_session, create_subject, create_term, | 10 | create_exam, create_exam_with, create_homework, create_session, create_subject, create_term, |
| 11 | - create_year, enroll, ensure_year, id_of, login, login_as, me_id, mem_app, send, set_role, | 11 | + create_year, enroll, ensure_year, id_of, login, login_as, me_id, mem_app, select_instance_subject, |
| 12 | - taught_under, unenroll, upload_course_note_file, | 12 | + send, set_role, taught, taught_under, unenroll, upload_course_note_file, |
| 13 | }; | 13 | }; |
| 14 | use hezarfen_backend::build_router; | 14 | use hezarfen_backend::build_router; |
| 15 | use hezarfen_backend::constant::{ | 15 | use hezarfen_backend::constant::{ |
| @@ -4671,6 +4671,8 @@ async fn subject_reference_counts_track_every_writer() { | |||
| 4671 | let t = taught_under(&app, &mudur, &teacher, "physics").await; | 4671 | let t = taught_under(&app, &mudur, &teacher, "physics").await; |
| 4672 | let from = create_subject(&app, &teacher, &t.course, "optics").await; | 4672 | let from = create_subject(&app, &teacher, &t.course, "optics").await; |
| 4673 | let to = create_subject(&app, &teacher, &t.course, "waves").await; | 4673 | let to = create_subject(&app, &teacher, &t.course, "waves").await; |
| 4674 | + select_instance_subject(&app, &teacher, &t.instance, &from).await; | ||
| 4675 | + select_instance_subject(&app, &teacher, &t.instance, &to).await; | ||
| 4674 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "yazili").await; | 4676 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "yazili").await; |
| 4675 | let due = Timestamp::now().as_millis() + 86_400_000; | 4677 | let due = Timestamp::now().as_millis() + 86_400_000; |
| 4676 | 4678 | ||
| @@ -9093,6 +9095,8 @@ async fn subject_delete_blocks_while_questions_reference_it() { | |||
| 9093 | let t = taught_under(&app, &mudur, &teacher, "history").await; | 9095 | let t = taught_under(&app, &mudur, &teacher, "history").await; |
| 9094 | let tagged = create_subject(&app, &teacher, &t.course, "antiquity").await; | 9096 | let tagged = create_subject(&app, &teacher, &t.course, "antiquity").await; |
| 9095 | let spare = create_subject(&app, &teacher, &t.course, "middle ages").await; | 9097 | let spare = create_subject(&app, &teacher, &t.course, "middle ages").await; |
| 9098 | + select_instance_subject(&app, &teacher, &t.instance, &tagged).await; | ||
| 9099 | + select_instance_subject(&app, &teacher, &t.instance, &spare).await; | ||
| 9096 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; | 9100 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; |
| 9097 | let question_body = create_question_body( | 9101 | let question_body = create_question_body( |
| 9098 | &app, | 9102 | &app, |
| @@ -9189,7 +9193,7 @@ async fn create_question( | |||
| 9189 | id_of(&create_question_body(app, cookie, exam, subject, body).await) | 9193 | id_of(&create_question_body(app, cookie, exam, subject, body).await) |
| 9190 | } | 9194 | } |
| 9191 | 9195 | ||
| 9192 | -/// Like [`create_question`], but hands back the whole response: choice ids are | 9196 | +/// Like [`create_question_body`], but hands back the whole response: choice ids are |
| 9193 | /// minted by the server, so a test that answers a question — or pictures one of | 9197 | /// minted by the server, so a test that answers a question — or pictures one of |
| 9194 | /// its options — has to read them off the response rather than count positions. | 9198 | /// its options — has to read them off the response rather than count positions. |
| 9195 | async fn create_question_body( | 9199 | async fn create_question_body( |
| @@ -9205,9 +9209,33 @@ async fn create_question_body( | |||
| 9205 | "POST", | 9209 | "POST", |
| 9206 | &format!("/exams/{exam}/questions"), | 9210 | &format!("/exams/{exam}/questions"), |
| 9207 | Some(cookie), | 9211 | Some(cookie), |
| 9208 | - Some(body), | 9212 | + Some(body.clone()), |
| 9209 | ) | 9213 | ) |
| 9210 | .await; | 9214 | .await; |
| 9215 | + // The subject-tag gate reads the section's resolved syllabus: a topic the | ||
| 9216 | + // offering never selected is refused. The writer holds a right over the | ||
| 9217 | + // instance (the very gate the question write passed), so take the topic | ||
| 9218 | + // onto the section's own set through the instance door and retry once. | ||
| 9219 | + let res = if res.status == StatusCode::BAD_REQUEST | ||
| 9220 | + && res.body["error"] | ||
| 9221 | + .as_str() | ||
| 9222 | + .is_some_and(|e| e.contains("subject is not in this section's subject set")) | ||
| 9223 | + { | ||
| 9224 | + let exam_row = send(app, "GET", &format!("/exams/{exam}"), Some(cookie), None).await; | ||
| 9225 | + assert_eq!(exam_row.status, StatusCode::OK, "{}", exam_row.body); | ||
| 9226 | + let instance = exam_row.body["class_course"].as_str().expect("class_course"); | ||
| 9227 | + select_instance_subject(app, cookie, instance, subject).await; | ||
| 9228 | + send( | ||
| 9229 | + app, | ||
| 9230 | + "POST", | ||
| 9231 | + &format!("/exams/{exam}/questions"), | ||
| 9232 | + Some(cookie), | ||
| 9233 | + Some(body), | ||
| 9234 | + ) | ||
| 9235 | + .await | ||
| 9236 | + } else { | ||
| 9237 | + res | ||
| 9238 | + }; | ||
| 9211 | assert_eq!( | 9239 | assert_eq!( |
| 9212 | res.status, | 9240 | res.status, |
| 9213 | StatusCode::CREATED, | 9241 | StatusCode::CREATED, |
| @@ -9266,6 +9294,7 @@ async fn question_crud_validation_and_rbac() { | |||
| 9266 | scheduling_kinds(&app, &mudur).await; | 9294 | scheduling_kinds(&app, &mudur).await; |
| 9267 | let t = taught_under(&app, &mudur, &teacher, "logic").await; | 9295 | let t = taught_under(&app, &mudur, &teacher, "logic").await; |
| 9268 | let subject = create_subject(&app, &teacher, &t.course, "propositions").await; | 9296 | let subject = create_subject(&app, &teacher, &t.course, "propositions").await; |
| 9297 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 9269 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; | 9298 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; |
| 9270 | 9299 | ||
| 9271 | // A choice question echoes its full authoring view, correct included. | 9300 | // A choice question echoes its full authoring view, correct included. |
| @@ -9470,6 +9499,7 @@ async fn question_crud_validation_and_rbac() { | |||
| 9470 | // Re-tagging stays inside the course: another of its subjects is fine, a | 9499 | // Re-tagging stays inside the course: another of its subjects is fine, a |
| 9471 | // foreign course's subject is a 400. | 9500 | // foreign course's subject is a 400. |
| 9472 | let second_subject = create_subject(&app, &teacher, &t.course, "predicates").await; | 9501 | let second_subject = create_subject(&app, &teacher, &t.course, "predicates").await; |
| 9502 | + select_instance_subject(&app, &teacher, &t.instance, &second_subject).await; | ||
| 9473 | let res = send( | 9503 | let res = send( |
| 9474 | &app, | 9504 | &app, |
| 9475 | "PATCH", | 9505 | "PATCH", |
| @@ -15759,6 +15789,7 @@ async fn hw_world(app: &axum::Router, db: &hezarfen_backend::database::Database) | |||
| 15759 | let veli_id = me_id(app, &veli).await; | 15789 | let veli_id = me_id(app, &veli).await; |
| 15760 | let t = taught_under(app, &mudur, &teacher, "math").await; | 15790 | let t = taught_under(app, &mudur, &teacher, "math").await; |
| 15761 | let subject = create_subject(app, &teacher, &t.course, "algebra").await; | 15791 | let subject = create_subject(app, &teacher, &t.course, "algebra").await; |
| 15792 | + select_instance_subject(app, &teacher, &t.instance, &subject).await; | ||
| 15762 | // The students sit in the şube: the pump enrolls them into the instance. | 15793 | // The students sit in the şube: the pump enrolls them into the instance. |
| 15763 | add_member(app, &mudur, &t.class, &ali_id).await; | 15794 | add_member(app, &mudur, &t.class, &ali_id).await; |
| 15764 | add_member(app, &mudur, &t.class, &veli_id).await; | 15795 | add_member(app, &mudur, &t.class, &veli_id).await; |
| @@ -16092,6 +16123,7 @@ async fn homework_patch_rechecks_and_blocks_orphaning() { | |||
| 16092 | .await; | 16123 | .await; |
| 16093 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); | 16124 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 16094 | let algebra2 = create_subject(&app, &w.teacher, &w.course, "algebra II").await; | 16125 | let algebra2 = create_subject(&app, &w.teacher, &w.course, "algebra II").await; |
| 16126 | + select_instance_subject(&app, &w.teacher, &w.instance, &algebra2).await; | ||
| 16095 | let res = send( | 16127 | let res = send( |
| 16096 | &app, | 16128 | &app, |
| 16097 | "PATCH", | 16129 | "PATCH", |
| @@ -17172,6 +17204,7 @@ async fn homework_blocks_subject_delete_until_retagged() { | |||
| 17172 | 17204 | ||
| 17173 | // Re-tagging frees the old subject and guards the new one. | 17205 | // Re-tagging frees the old subject and guards the new one. |
| 17174 | let second = create_subject(&app, &w.teacher, &w.course, "geometry").await; | 17206 | let second = create_subject(&app, &w.teacher, &w.course, "geometry").await; |
| 17207 | + select_instance_subject(&app, &w.teacher, &w.instance, &second).await; | ||
| 17175 | let res = send( | 17208 | let res = send( |
| 17176 | &app, | 17209 | &app, |
| 17177 | "PATCH", | 17210 | "PATCH", |
| @@ -19837,6 +19870,7 @@ async fn bank_question_create_get_list_and_instantiate() { | |||
| 19837 | let mudur = login_as(&app, &db, "algebra_m", "manager").await; | 19870 | let mudur = login_as(&app, &db, "algebra_m", "manager").await; |
| 19838 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; | 19871 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 19839 | let subject = create_subject(&app, &teacher, &t.course, "linear").await; | 19872 | let subject = create_subject(&app, &teacher, &t.course, "linear").await; |
| 19873 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 19840 | 19874 | ||
| 19841 | // Create a template — subject is origin metadata, not held to a course. | 19875 | // Create a template — subject is origin metadata, not held to a course. |
| 19842 | let res = send( | 19876 | let res = send( |
| @@ -19936,6 +19970,7 @@ async fn bank_question_list_pages_filters_and_names() { | |||
| 19936 | let mudur = login_as(&app, &db, "algebra_m", "manager").await; | 19970 | let mudur = login_as(&app, &db, "algebra_m", "manager").await; |
| 19937 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; | 19971 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 19938 | let subject = create_subject(&app, &teacher, &t.course, "linear").await; | 19972 | let subject = create_subject(&app, &teacher, &t.course, "linear").await; |
| 19973 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 19939 | let other_subject = create_subject(&app, &teacher, &t.course, "quadratic").await; | 19974 | let other_subject = create_subject(&app, &teacher, &t.course, "quadratic").await; |
| 19940 | 19975 | ||
| 19941 | // 120 templates — more than the clients' `limit=100`. | 19976 | // 120 templates — more than the clients' `limit=100`. |
| @@ -20413,6 +20448,7 @@ async fn bank_private_template_is_invisible_until_published() { | |||
| 20413 | scheduling_kinds(&app, &mudur).await; | 20448 | scheduling_kinds(&app, &mudur).await; |
| 20414 | let t = taught_under(&app, &mudur, &owner, "bio").await; | 20449 | let t = taught_under(&app, &mudur, &owner, "bio").await; |
| 20415 | let subject = create_subject(&app, &owner, &t.course, "cells").await; | 20450 | let subject = create_subject(&app, &owner, &t.course, "cells").await; |
| 20451 | + select_instance_subject(&app, &owner, &t.instance, &subject).await; | ||
| 20416 | 20452 | ||
| 20417 | // Two templates; only the second is ever published. | 20453 | // Two templates; only the second is ever published. |
| 20418 | let res = send( | 20454 | let res = send( |
| @@ -20463,6 +20499,7 @@ async fn bank_private_template_is_invisible_until_published() { | |||
| 20463 | // The other teacher's own exam, to attempt an instantiate from. | 20499 | // The other teacher's own exam, to attempt an instantiate from. |
| 20464 | let t2 = taught_under(&app, &mudur, &other, "bio2").await; | 20500 | let t2 = taught_under(&app, &mudur, &other, "bio2").await; |
| 20465 | let subject2 = create_subject(&app, &other, &t2.course, "cells2").await; | 20501 | let subject2 = create_subject(&app, &other, &t2.course, "cells2").await; |
| 20502 | + select_instance_subject(&app, &other, &t2.instance, &subject2).await; | ||
| 20466 | let exam2 = create_exam(&app, &other, &t2.instance, &t2.term, "quiz", "final").await; | 20503 | let exam2 = create_exam(&app, &other, &t2.instance, &t2.term, "quiz", "final").await; |
| 20467 | let owner_id = me_id(&app, &owner).await; | 20504 | let owner_id = me_id(&app, &owner).await; |
| 20468 | 20505 | ||
| @@ -20740,6 +20777,7 @@ async fn bank_instantiate_copies_images() { | |||
| 20740 | scheduling_kinds(&app, &mudur).await; | 20777 | scheduling_kinds(&app, &mudur).await; |
| 20741 | let t = taught_under(&app, &mudur, &teacher, "geo1").await; | 20778 | let t = taught_under(&app, &mudur, &teacher, "geo1").await; |
| 20742 | let subject = create_subject(&app, &teacher, &t.course, "maps1").await; | 20779 | let subject = create_subject(&app, &teacher, &t.course, "maps1").await; |
| 20780 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 20743 | 20781 | ||
| 20744 | // A choice template with an illustration and one option picture. | 20782 | // A choice template with an illustration and one option picture. |
| 20745 | let res = send( | 20783 | let res = send( |
| @@ -21042,6 +21080,7 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() { | |||
| 21042 | scheduling_kinds(&app, &mudur).await; | 21080 | scheduling_kinds(&app, &mudur).await; |
| 21043 | let t = taught_under(&app, &mudur, &teacher, "geo2").await; | 21081 | let t = taught_under(&app, &mudur, &teacher, "geo2").await; |
| 21044 | let subject = create_subject(&app, &teacher, &t.course, "maps2").await; | 21082 | let subject = create_subject(&app, &teacher, &t.course, "maps2").await; |
| 21083 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 21045 | 21084 | ||
| 21046 | // Two images so the copy loop has multiple steps. | 21085 | // Two images so the copy loop has multiple steps. |
| 21047 | let res = send( | 21086 | let res = send( |
| @@ -21411,6 +21450,7 @@ async fn bank_provenance_both_directions() { | |||
| 21411 | scheduling_kinds(&app, &mudur).await; | 21450 | scheduling_kinds(&app, &mudur).await; |
| 21412 | let t = taught_under(&app, &mudur, &teacher, "bprov_c").await; | 21451 | let t = taught_under(&app, &mudur, &teacher, "bprov_c").await; |
| 21413 | let subject = create_subject(&app, &teacher, &t.course, "bprov_s").await; | 21452 | let subject = create_subject(&app, &teacher, &t.course, "bprov_s").await; |
| 21453 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 21414 | 21454 | ||
| 21415 | // Bank -> exam: from_bank is the template id, banked_as stays null. | 21455 | // Bank -> exam: from_bank is the template id, banked_as stays null. |
| 21416 | let res = send( | 21456 | let res = send( |
| @@ -21921,6 +21961,7 @@ async fn bank_list_counts_the_copies_made_from_each_template() { | |||
| 21921 | scheduling_kinds(&app, &mudur).await; | 21961 | scheduling_kinds(&app, &mudur).await; |
| 21922 | let t = taught_under(&app, &mudur, &teacher, "buse_c").await; | 21962 | let t = taught_under(&app, &mudur, &teacher, "buse_c").await; |
| 21923 | let subject = create_subject(&app, &teacher, &t.course, "buse_s").await; | 21963 | let subject = create_subject(&app, &teacher, &t.course, "buse_s").await; |
| 21964 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 21924 | 21965 | ||
| 21925 | let template = |text: &'static str| { | 21966 | let template = |text: &'static str| { |
| 21926 | send( | 21967 | send( |
| @@ -22042,6 +22083,7 @@ async fn refreshing_a_question_recopies_its_template() { | |||
| 22042 | scheduling_kinds(&app, &mudur).await; | 22083 | scheduling_kinds(&app, &mudur).await; |
| 22043 | let t = taught_under(&app, &mudur, &teacher, "bref_c").await; | 22084 | let t = taught_under(&app, &mudur, &teacher, "bref_c").await; |
| 22044 | let subject = create_subject(&app, &teacher, &t.course, "bref_s").await; | 22085 | let subject = create_subject(&app, &teacher, &t.course, "bref_s").await; |
| 22086 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 22045 | 22087 | ||
| 22046 | // A template with an illustration and a picture on its first option. | 22088 | // A template with an illustration and a picture on its first option. |
| 22047 | let res = send( | 22089 | let res = send( |
| @@ -26993,7 +27035,7 @@ async fn a_class_pumps_enrollments_and_guards_each_axis_separately() { | |||
| 26993 | "POST", | 27035 | "POST", |
| 26994 | "/classes", | 27036 | "/classes", |
| 26995 | Some(&teacher), | 27037 | Some(&teacher), |
| 26996 | - Some(json!({"name": "9-A"})), | 27038 | + Some(json!({"name": "9-A", "grade_level": 9})), |
| 26997 | ) | 27039 | ) |
| 26998 | .await; | 27040 | .await; |
| 26999 | assert_eq!( | 27041 | assert_eq!( |
| @@ -27006,13 +27048,13 @@ async fn a_class_pumps_enrollments_and_guards_each_axis_separately() { | |||
| 27006 | "POST", | 27048 | "POST", |
| 27007 | "/classes", | 27049 | "/classes", |
| 27008 | Some(&manager), | 27050 | Some(&manager), |
| 27009 | - Some(json!({"name": "9-A", "grade": ""})), | 27051 | + Some(json!({"name": "9-A", "grade_level": 9})), |
| 27010 | ) | 27052 | ) |
| 27011 | .await; | 27053 | .await; |
| 27012 | assert_eq!(res.status, StatusCode::CREATED); | 27054 | assert_eq!(res.status, StatusCode::CREATED); |
| 27013 | - assert!( | 27055 | + assert_eq!( |
| 27014 | - res.body["class"]["grade"].is_null(), | 27056 | + res.body["class"]["grade_level"], 9, |
| 27015 | - "an empty grade is no grade" | 27057 | + "the class carries the rung it was created at" |
| 27016 | ); | 27058 | ); |
| 27017 | let class = id_of(&res.body["class"]); | 27059 | let class = id_of(&res.body["class"]); |
| 27018 | assert_eq!( | 27060 | assert_eq!( |
| @@ -27206,7 +27248,7 @@ async fn class_reads_are_staff_only_and_a_manager_manages_every_course() { | |||
| 27206 | "POST", | 27248 | "POST", |
| 27207 | "/classes", | 27249 | "/classes", |
| 27208 | Some(&manager), | 27250 | Some(&manager), |
| 27209 | - Some(json!({ "name": "9-A" })), | 27251 | + Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 27210 | ) | 27252 | ) |
| 27211 | .await; | 27253 | .await; |
| 27212 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 27254 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| @@ -27309,7 +27351,7 @@ async fn a_demotion_sweeps_the_class_membership_and_what_it_pumped() { | |||
| 27309 | "POST", | 27351 | "POST", |
| 27310 | "/classes", | 27352 | "/classes", |
| 27311 | Some(&manager), | 27353 | Some(&manager), |
| 27312 | - Some(json!({ "name": "9-A" })), | 27354 | + Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 27313 | ) | 27355 | ) |
| 27314 | .await; | 27356 | .await; |
| 27315 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 27357 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| @@ -27467,7 +27509,7 @@ async fn a_year_a_class_points_at_refuses_to_delete() { | |||
| 27467 | "POST", | 27509 | "POST", |
| 27468 | "/classes", | 27510 | "/classes", |
| 27469 | Some(&manager), | 27511 | Some(&manager), |
| 27470 | - Some(json!({ "name": "9-A", "year": year })), | 27512 | + Some(json!({ "name": "9-A", "grade_level": 9, "year": year })), |
| 27471 | ) | 27513 | ) |
| 27472 | .await; | 27514 | .await; |
| 27473 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 27515 | 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() { | |||
| 27552 | "POST", | 27594 | "POST", |
| 27553 | "/classes", | 27595 | "/classes", |
| 27554 | Some(&manager), | 27596 | Some(&manager), |
| 27555 | - Some(json!({ "name": "9-A" })), | 27597 | + Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 27556 | ) | 27598 | ) |
| 27557 | .await; | 27599 | .await; |
| 27558 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 27600 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| @@ -30269,7 +30311,7 @@ const CORE_PREFIXES: [(&str, &str); 14] = [ | |||
| 30269 | /// A module may own more than one prefix: `courses` also answers under | 30311 | /// A module may own more than one prefix: `courses` also answers under |
| 30270 | /// `/instances` (the instance anchor), and `chatbot` — the whole `ai` package — | 30312 | /// `/instances` (the instance anchor), and `chatbot` — the whole `ai` package — |
| 30271 | /// also answers under `/rag`, `/insights` and `/podcast`. | 30313 | /// also answers under `/rag`, `/insights` and `/podcast`. |
| 30272 | -const MODULE_PREFIXES: [(Module, &str); 25] = [ | 30314 | +const MODULE_PREFIXES: [(Module, &str); 26] = [ |
| 30273 | (Module::Chatbot, "/chatbot"), | 30315 | (Module::Chatbot, "/chatbot"), |
| 30274 | (Module::Chatbot, "/rag"), | 30316 | (Module::Chatbot, "/rag"), |
| 30275 | (Module::Chatbot, "/insights"), | 30317 | (Module::Chatbot, "/insights"), |
| @@ -30280,6 +30322,7 @@ const MODULE_PREFIXES: [(Module, &str); 25] = [ | |||
| 30280 | (Module::Appointments, "/appointments"), | 30322 | (Module::Appointments, "/appointments"), |
| 30281 | (Module::Courses, "/courses"), | 30323 | (Module::Courses, "/courses"), |
| 30282 | (Module::Courses, "/instances"), | 30324 | (Module::Courses, "/instances"), |
| 30325 | + (Module::Courses, "/offerings"), | ||
| 30283 | (Module::CourseNotes, "/course-notes"), | 30326 | (Module::CourseNotes, "/course-notes"), |
| 30284 | (Module::Classes, "/classes"), | 30327 | (Module::Classes, "/classes"), |
| 30285 | (Module::Sessions, "/sessions"), | 30328 | (Module::Sessions, "/sessions"), |
| @@ -30895,3 +30938,433 @@ async fn the_insight_run_ledger_is_manager_only() { | |||
| 30895 | let res = send(&app, "GET", "/insights/runs", Some(&teacher), None).await; | 30938 | let res = send(&app, "GET", "/insights/runs", Some(&teacher), None).await; |
| 30896 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | 30939 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 30897 | } | 30940 | } |
| 30941 | + | ||
| 30942 | +// --- course template: the six template/instance children are wired -------- | ||
| 30943 | + | ||
| 30944 | +/// The six foreign-module route pairs wave 2 mounted — subject selection, | ||
| 30945 | +/// exam weights and the weekly plan under both `/offerings` and | ||
| 30946 | +/// `/instances` — all answer through the built router with one manager | ||
| 30947 | +/// session. A missed merge or a double prefix would 404 here; the module | ||
| 30948 | +/// gates stay out of the way because the school runs every module. | ||
| 30949 | +#[tokio::test] | ||
| 30950 | +async fn offering_and_instance_template_children_answer_through_the_router() { | ||
| 30951 | + let (app, db) = app_and_db().await; | ||
| 30952 | + let mudur = login_as(&app, &db, "mudur_template", "manager").await; | ||
| 30953 | + | ||
| 30954 | + // One class-delivered ders attached to one şube: the attach auto-mints | ||
| 30955 | + // the grade-level offering the section inherits from, and the instance | ||
| 30956 | + // read names it. | ||
| 30957 | + let t = taught(&app, &mudur, "resim").await; | ||
| 30958 | + let read = send( | ||
| 30959 | + &app, | ||
| 30960 | + "GET", | ||
| 30961 | + &format!("/instances/{}", t.instance), | ||
| 30962 | + Some(&mudur), | ||
| 30963 | + None, | ||
| 30964 | + ) | ||
| 30965 | + .await; | ||
| 30966 | + assert_eq!(read.status, StatusCode::OK, "{}", read.body); | ||
| 30967 | + let offering = read.body["offering"] | ||
| 30968 | + .as_str() | ||
| 30969 | + .expect("instance carries its offering") | ||
| 30970 | + .to_string(); | ||
| 30971 | + | ||
| 30972 | + // The catalog POST itself: a second grade level of the same ders is a | ||
| 30973 | + // fresh template — 201, not a 404 from a double-prefixed mount. | ||
| 30974 | + let created = send( | ||
| 30975 | + &app, | ||
| 30976 | + "POST", | ||
| 30977 | + "/offerings", | ||
| 30978 | + Some(&mudur), | ||
| 30979 | + Some(json!({ "course": t.course, "grade_level": 0 })), | ||
| 30980 | + ) | ||
| 30981 | + .await; | ||
| 30982 | + assert_eq!(created.status, StatusCode::CREATED, "{}", created.body); | ||
| 30983 | + | ||
| 30984 | + for (path, why) in [ | ||
| 30985 | + ( | ||
| 30986 | + format!("/offerings/{offering}/subjects"), | ||
| 30987 | + "offering subjects", | ||
| 30988 | + ), | ||
| 30989 | + ( | ||
| 30990 | + format!("/offerings/{offering}/exam-weights"), | ||
| 30991 | + "offering exam weights", | ||
| 30992 | + ), | ||
| 30993 | + ( | ||
| 30994 | + format!("/offerings/{offering}/weekly-plan"), | ||
| 30995 | + "offering weekly plan", | ||
| 30996 | + ), | ||
| 30997 | + ( | ||
| 30998 | + format!("/instances/{}/subjects", t.instance), | ||
| 30999 | + "instance subjects", | ||
| 31000 | + ), | ||
| 31001 | + ( | ||
| 31002 | + format!("/instances/{}/exam-weights", t.instance), | ||
| 31003 | + "instance exam weights", | ||
| 31004 | + ), | ||
| 31005 | + ( | ||
| 31006 | + format!("/instances/{}/weekly-plan", t.instance), | ||
| 31007 | + "instance weekly plan", | ||
| 31008 | + ), | ||
| 31009 | + ] { | ||
| 31010 | + let res = send(&app, "GET", &path, Some(&mudur), None).await; | ||
| 31011 | + assert_eq!(res.status, StatusCode::OK, "{why}: {}", res.body); | ||
| 31012 | + } | ||
| 31013 | +} | ||
| 31014 | + | ||
| 31015 | +// --- course template: the user's per-class scenario, end to end ------------- | ||
| 31016 | + | ||
| 31017 | +/// The user's scenario (2026-09-23): a 9th-grade and a 12th-grade section both | ||
| 31018 | +/// teach Biology — same catalog course, two instances — and each resolves to | ||
| 31019 | +/// the template of its own grade, with per-class overrides deviating exactly | ||
| 31020 | +/// one axis at a time (override-or-inherit, never merge). Driven over the HTTP | ||
| 31021 | +/// surface only: | ||
| 31022 | +/// | ||
| 31023 | +/// (a) both instances share the course id but resolve to different offerings; | ||
| 31024 | +/// (b) the grade-9 offering's template (title suffix, description, hours, a | ||
| 31025 | +/// topic, a weight, a slot) shows on the grade-9 instance and nowhere on | ||
| 31026 | +/// grade 12; | ||
| 31027 | +/// (c) a `ders_saati` override on one instance deviates exactly that axis; | ||
| 31028 | +/// (d) an own-but-empty subject set beats the offering's set; | ||
| 31029 | +/// (e) the reset doors restore inheritance (a scalar, and the set axes); | ||
| 31030 | +/// (f) a topic of the grade-9 template tags a question there and is refused | ||
| 31031 | +/// in the grade-12 instance; | ||
| 31032 | +/// (g) the marks and karne reports show each section its own resolved title. | ||
| 31033 | +#[tokio::test] | ||
| 31034 | +async fn course_template_resolution_is_per_class_end_to_end() { | ||
| 31035 | + let (app, db) = app_and_db().await; | ||
| 31036 | + let staff = login_as(&app, &db, "mudur_scenario", "manager").await; | ||
| 31037 | + | ||
| 31038 | + // One ders, two topics, two şubeler at different rungs of the ladder. | ||
| 31039 | + let course = create_course(&app, &staff, "Biyoloji").await; | ||
| 31040 | + let s1 = create_subject(&app, &staff, &course, "Hücre").await; | ||
| 31041 | + let s2 = create_subject(&app, &staff, &course, "Genetik").await; | ||
| 31042 | + let year = ensure_year(&app, &staff).await; | ||
| 31043 | + let term = create_term(&app, &staff, &year, "1. Dönem").await; | ||
| 31044 | + let class_a = create_class( | ||
| 31045 | + &app, | ||
| 31046 | + &staff, | ||
| 31047 | + "9-A", | ||
| 31048 | + json!({ "year": year, "grade_level": 9 }), | ||
| 31049 | + ) | ||
| 31050 | + .await; | ||
| 31051 | + let class_b = create_class( | ||
| 31052 | + &app, | ||
| 31053 | + &staff, | ||
| 31054 | + "12-B", | ||
| 31055 | + json!({ "year": year, "grade_level": 12 }), | ||
| 31056 | + ) | ||
| 31057 | + .await; | ||
| 31058 | + let inst_a = attach_instance(&app, &staff, &class_a, &course).await; | ||
| 31059 | + let inst_b = attach_instance(&app, &staff, &class_b, &course).await; | ||
| 31060 | + let read_instance = |uri: String| { | ||
| 31061 | + let app = app.clone(); | ||
| 31062 | + let staff = staff.clone(); | ||
| 31063 | + async move { send(&app, "GET", &uri, Some(&staff), None).await } | ||
| 31064 | + }; | ||
| 31065 | + | ||
| 31066 | + // (a) Same ders, two instances — and each teaches from its own grade's | ||
| 31067 | + // template: shared course id, distinct offering ids, both scalars still | ||
| 31068 | + // inheriting the catalog/constant floor. | ||
| 31069 | + let a = read_instance(format!("/instances/{inst_a}")).await; | ||
| 31070 | + let b = read_instance(format!("/instances/{inst_b}")).await; | ||
| 31071 | + assert_eq!(a.status, StatusCode::OK, "{}", a.body); | ||
| 31072 | + assert_eq!(b.status, StatusCode::OK, "{}", b.body); | ||
| 31073 | + assert_eq!(a.body["course"], course, "(a) same catalog course"); | ||
| 31074 | + assert_eq!(b.body["course"], course, "(a) same catalog course"); | ||
| 31075 | + let offering_a = a.body["offering"].as_str().expect("(a) offering id"); | ||
| 31076 | + let offering_b = b.body["offering"].as_str().expect("(a) offering id"); | ||
| 31077 | + assert_ne!(offering_a, offering_b, "(a) each grade has its own template"); | ||
| 31078 | + assert_eq!(a.body["title"], "Biyoloji", "(a) pre-template title inherits"); | ||
| 31079 | + assert_eq!(a.body["title_overridden"], false); | ||
| 31080 | + assert_eq!(b.body["ders_saati"], 1, "(a) the constant floor, not a value"); | ||
| 31081 | + assert_eq!(b.body["ders_saati_overridden"], false); | ||
| 31082 | + | ||
| 31083 | + // (b) Fill the grade-9 template; the grade-12 one stays empty. | ||
| 31084 | + let patched = send( | ||
| 31085 | + &app, | ||
| 31086 | + "PATCH", | ||
| 31087 | + &format!("/offerings/{offering_a}"), | ||
| 31088 | + Some(&staff), | ||
| 31089 | + Some(json!({ | ||
| 31090 | + "title": "Biyoloji (9. sınıf)", | ||
| 31091 | + "description": "9. sınıf müfredatı", | ||
| 31092 | + "default_ders_saati": 4 | ||
| 31093 | + })), | ||
| 31094 | + ) | ||
| 31095 | + .await; | ||
| 31096 | + assert_eq!(patched.status, StatusCode::OK, "{}", patched.body); | ||
| 31097 | + for (offering, subject) in [(offering_a, &s1), (offering_b, &s2)] { | ||
| 31098 | + let res = send( | ||
| 31099 | + &app, | ||
| 31100 | + "POST", | ||
| 31101 | + &format!("/offerings/{offering}/subjects"), | ||
| 31102 | + Some(&staff), | ||
| 31103 | + Some(json!({ "subject": subject })), | ||
| 31104 | + ) | ||
| 31105 | + .await; | ||
| 31106 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 31107 | + } | ||
| 31108 | + let weighted = send( | ||
| 31109 | + &app, | ||
| 31110 | + "PATCH", | ||
| 31111 | + &format!("/offerings/{offering_a}/exam-weights"), | ||
| 31112 | + Some(&staff), | ||
| 31113 | + Some(json!({ "kind": "yazili", "weight": 3 })), | ||
| 31114 | + ) | ||
| 31115 | + .await; | ||
| 31116 | + assert_eq!(weighted.status, StatusCode::OK, "{}", weighted.body); | ||
| 31117 | + let slotted = send( | ||
| 31118 | + &app, | ||
| 31119 | + "POST", | ||
| 31120 | + &format!("/offerings/{offering_a}/weekly-plan"), | ||
| 31121 | + Some(&staff), | ||
| 31122 | + Some(json!({ "weekday": 1, "starts_at": 540, "ends_at": 570 })), | ||
| 31123 | + ) | ||
| 31124 | + .await; | ||
| 31125 | + assert_eq!(slotted.status, StatusCode::CREATED, "{}", slotted.body); | ||
| 31126 | + | ||
| 31127 | + let a = read_instance(format!("/instances/{inst_a}")).await; | ||
| 31128 | + assert_eq!(a.body["title"], "Biyoloji (9. sınıf)", "(b) grade-9 title"); | ||
| 31129 | + assert_eq!(a.body["title_overridden"], false, "(b) inherited, not owned"); | ||
| 31130 | + assert_eq!(a.body["description"], "9. sınıf müfredatı"); | ||
| 31131 | + assert_eq!(a.body["ders_saati"], 4, "(b) the grade-9 default"); | ||
| 31132 | + assert_eq!(a.body["subjects_inherited"], true); | ||
| 31133 | + assert_eq!(a.body["subjects"][0]["id"], s1, "(b) the grade-9 syllabus"); | ||
| 31134 | + let a_weights = a.body["exam_weights"] | ||
| 31135 | + .as_array() | ||
| 31136 | + .expect("(b) resolved weight map"); | ||
| 31137 | + let a_yazili = a_weights | ||
| 31138 | + .iter() | ||
| 31139 | + .find(|w| w["kind"] == "yazili") | ||
| 31140 | + .expect("(b) settings kinds are always mapped"); | ||
| 31141 | + assert_eq!(a_yazili["weight"], 3, "(b) the template's weight"); | ||
| 31142 | + assert_eq!(a.body["weekly_plan"][0]["weekday"], 1, "(b) template week"); | ||
| 31143 | + | ||
| 31144 | + let b = read_instance(format!("/instances/{inst_b}")).await; | ||
| 31145 | + assert_eq!(b.body["title"], "Biyoloji", "(b) grade 12 stays on the catalog"); | ||
| 31146 | + assert_eq!(b.body["ders_saati"], 1, "(b) the empty template inherits all"); | ||
| 31147 | + assert_eq!(b.body["subjects"][0]["id"], s2, "(b) grade 12's own template"); | ||
| 31148 | + assert!( | ||
| 31149 | + !b.body["subjects"] | ||
| 31150 | + .as_array() | ||
| 31151 | + .expect("(b) subjects array") | ||
| 31152 | + .iter() | ||
| 31153 | + .any(|s| s["id"] == s1), | ||
| 31154 | + "(b) no bleed of the grade-9 topic into grade 12" | ||
| 31155 | + ); | ||
| 31156 | + let b_weights = b.body["exam_weights"] | ||
| 31157 | + .as_array() | ||
| 31158 | + .expect("(b) resolved weight map"); | ||
| 31159 | + let b_yazili = b_weights | ||
| 31160 | + .iter() | ||
| 31161 | + .find(|w| w["kind"] == "yazili") | ||
| 31162 | + .expect("(b) settings kinds are always mapped"); | ||
| 31163 | + assert_eq!(b_yazili["weight"], 1, "(b) grade 12 keeps the settings weight"); | ||
| 31164 | + assert_eq!( | ||
| 31165 | + b.body["weekly_plan"] | ||
| 31166 | + .as_array() | ||
| 31167 | + .expect("(b) weekly plan array") | ||
| 31168 | + .len(), | ||
| 31169 | + 0, | ||
| 31170 | + "(b) the empty grade-12 template week" | ||
| 31171 | + ); | ||
| 31172 | + | ||
| 31173 | + // (c) Override exactly one axis on the grade-9 section: its hours move, | ||
| 31174 | + // everything else keeps flowing from the template, and grade 12 is | ||
| 31175 | + // untouched. | ||
| 31176 | + let patched = send( | ||
| 31177 | + &app, | ||
| 31178 | + "PATCH", | ||
| 31179 | + &format!("/instances/{inst_a}"), | ||
| 31180 | + Some(&staff), | ||
| 31181 | + Some(json!({ "ders_saati": 6 })), | ||
| 31182 | + ) | ||
| 31183 | + .await; | ||
| 31184 | + assert_eq!(patched.status, StatusCode::OK, "{}", patched.body); | ||
| 31185 | + let a = read_instance(format!("/instances/{inst_a}")).await; | ||
| 31186 | + assert_eq!(a.body["ders_saati"], 6, "(c) the override wins"); | ||
| 31187 | + assert_eq!(a.body["ders_saati_overridden"], true, "(c) flagged as owned"); | ||
| 31188 | + assert_eq!( | ||
| 31189 | + a.body["title"], "Biyoloji (9. sınıf)", | ||
| 31190 | + "(c) no merge: the title still inherits" | ||
| 31191 | + ); | ||
| 31192 | + assert_eq!(a.body["title_overridden"], false, "(c) still not owned"); | ||
| 31193 | + assert_eq!( | ||
| 31194 | + a.body["subjects_inherited"], true, | ||
| 31195 | + "(c) the set axis is untouched" | ||
| 31196 | + ); | ||
| 31197 | + let b = read_instance(format!("/instances/{inst_b}")).await; | ||
| 31198 | + assert_eq!(b.body["ders_saati"], 1, "(c) grade 12 unaffected"); | ||
| 31199 | + | ||
| 31200 | + // (f) Topic tagging while grade 9 still inherits: its template's topic is | ||
| 31201 | + // accepted there, refused next door. | ||
| 31202 | + let exam_a = create_exam(&app, &staff, &inst_a, &term, "A sınavı", "yazili").await; | ||
| 31203 | + let exam_b = create_exam(&app, &staff, &inst_b, &term, "B sınavı", "yazili").await; | ||
| 31204 | + let tagged = send( | ||
| 31205 | + &app, | ||
| 31206 | + "POST", | ||
| 31207 | + &format!("/exams/{exam_a}/questions"), | ||
| 31208 | + Some(&staff), | ||
| 31209 | + Some(json!({ "subject_id": s1, "text": "Mitokondri?", "kind": "text", "points": 10 })), | ||
| 31210 | + ) | ||
| 31211 | + .await; | ||
| 31212 | + assert_eq!(tagged.status, StatusCode::CREATED, "(f) {}", tagged.body); | ||
| 31213 | + let refused = send( | ||
| 31214 | + &app, | ||
| 31215 | + "POST", | ||
| 31216 | + &format!("/exams/{exam_b}/questions"), | ||
| 31217 | + Some(&staff), | ||
| 31218 | + Some(json!({ "subject_id": s1, "text": "Mitokondri?", "kind": "text", "points": 10 })), | ||
| 31219 | + ) | ||
| 31220 | + .await; | ||
| 31221 | + assert_eq!(refused.status, StatusCode::BAD_REQUEST, "(f) {}", refused.body); | ||
| 31222 | + let own = send( | ||
| 31223 | + &app, | ||
| 31224 | + "POST", | ||
| 31225 | + &format!("/exams/{exam_b}/questions"), | ||
| 31226 | + Some(&staff), | ||
| 31227 | + Some(json!({ "subject_id": s2, "text": "DNA?", "kind": "text", "points": 10 })), | ||
| 31228 | + ) | ||
| 31229 | + .await; | ||
| 31230 | + assert_eq!( | ||
| 31231 | + own.status, | ||
| 31232 | + StatusCode::CREATED, | ||
| 31233 | + "(f) the refusal is syllabus scope, not course scope: {}", | ||
| 31234 | + own.body | ||
| 31235 | + ); | ||
| 31236 | + | ||
| 31237 | + // (d) An own set that is EMPTY wins: take a topic onto the section and | ||
| 31238 | + // drop it — the flag stays "own", the resolved set is empty, and the | ||
| 31239 | + // sibling still sees its own template's topic. | ||
| 31240 | + let took = send( | ||
| 31241 | + &app, | ||
| 31242 | + "POST", | ||
| 31243 | + &format!("/instances/{inst_a}/subjects"), | ||
| 31244 | + Some(&staff), | ||
| 31245 | + Some(json!({ "subject": s1 })), | ||
| 31246 | + ) | ||
| 31247 | + .await; | ||
| 31248 | + assert_eq!(took.status, StatusCode::CREATED, "(d) {}", took.body); | ||
| 31249 | + let dropped = send( | ||
| 31250 | + &app, | ||
| 31251 | + "DELETE", | ||
| 31252 | + &format!("/instances/{inst_a}/subjects/{s1}"), | ||
| 31253 | + Some(&staff), | ||
| 31254 | + None, | ||
| 31255 | + ) | ||
| 31256 | + .await; | ||
| 31257 | + assert_eq!(dropped.status, StatusCode::NO_CONTENT, "(d) {}", dropped.body); | ||
| 31258 | + let a = read_instance(format!("/instances/{inst_a}")).await; | ||
| 31259 | + assert_eq!(a.body["subjects_inherited"], false, "(d) the set is its own"); | ||
| 31260 | + assert_eq!( | ||
| 31261 | + a.body["subjects"] | ||
| 31262 | + .as_array() | ||
| 31263 | + .expect("(d) subjects array") | ||
| 31264 | + .len(), | ||
| 31265 | + 0, | ||
| 31266 | + "(d) empty own set beats the template's" | ||
| 31267 | + ); | ||
| 31268 | + let b = read_instance(format!("/instances/{inst_b}")).await; | ||
| 31269 | + assert_eq!( | ||
| 31270 | + b.body["subjects"][0]["id"], s2, | ||
| 31271 | + "(d) the sibling still inherits its template" | ||
| 31272 | + ); | ||
| 31273 | + | ||
| 31274 | + // (e) The reset doors restore inheritance: the scalar goes back to the | ||
| 31275 | + // offering's default, the weekly plan back to the template week, and the | ||
| 31276 | + // subjects flag back to the template's set. | ||
| 31277 | + let reset = send( | ||
| 31278 | + &app, | ||
| 31279 | + "POST", | ||
| 31280 | + &format!("/instances/{inst_a}/reset"), | ||
| 31281 | + Some(&staff), | ||
| 31282 | + Some(json!({ "fields": ["ders_saati"] })), | ||
| 31283 | + ) | ||
| 31284 | + .await; | ||
| 31285 | + assert_eq!(reset.status, StatusCode::OK, "(e) {}", reset.body); | ||
| 31286 | + assert_eq!(reset.body["ders_saati"], 4, "(e) the offering default again"); | ||
| 31287 | + assert_eq!(reset.body["ders_saati_overridden"], false, "(e) inheriting"); | ||
| 31288 | + | ||
| 31289 | + let own_slot = send( | ||
| 31290 | + &app, | ||
| 31291 | + "POST", | ||
| 31292 | + &format!("/instances/{inst_a}/weekly-plan"), | ||
| 31293 | + Some(&staff), | ||
| 31294 | + Some(json!({ "weekday": 2, "starts_at": 600, "ends_at": 630 })), | ||
| 31295 | + ) | ||
| 31296 | + .await; | ||
| 31297 | + assert_eq!(own_slot.status, StatusCode::CREATED, "(e) {}", own_slot.body); | ||
| 31298 | + let a = read_instance(format!("/instances/{inst_a}")).await; | ||
| 31299 | + assert_eq!(a.body["weekly_plan_inherited"], false, "(e) own week wins"); | ||
| 31300 | + assert_eq!(a.body["weekly_plan"][0]["weekday"], 2); | ||
| 31301 | + let plan_reset = send( | ||
| 31302 | + &app, | ||
| 31303 | + "DELETE", | ||
| 31304 | + &format!("/instances/{inst_a}/weekly-plan"), | ||
| 31305 | + Some(&staff), | ||
| 31306 | + None, | ||
| 31307 | + ) | ||
| 31308 | + .await; | ||
| 31309 | + assert_eq!(plan_reset.status, StatusCode::NO_CONTENT, "(e)"); | ||
| 31310 | + let a = read_instance(format!("/instances/{inst_a}")).await; | ||
| 31311 | + assert_eq!(a.body["weekly_plan_inherited"], true, "(e) inheriting again"); | ||
| 31312 | + assert_eq!( | ||
| 31313 | + a.body["weekly_plan"][0]["weekday"], 1, | ||
| 31314 | + "(e) the template week again" | ||
| 31315 | + ); | ||
| 31316 | + | ||
| 31317 | + let subjects_reset = send( | ||
| 31318 | + &app, | ||
| 31319 | + "POST", | ||
| 31320 | + &format!("/instances/{inst_a}/reset"), | ||
| 31321 | + Some(&staff), | ||
| 31322 | + Some(json!({ "fields": ["subjects"] })), | ||
| 31323 | + ) | ||
| 31324 | + .await; | ||
| 31325 | + assert_eq!(subjects_reset.status, StatusCode::OK, "(e)"); | ||
| 31326 | + let a = read_instance(format!("/instances/{inst_a}")).await; | ||
| 31327 | + assert_eq!(a.body["subjects_inherited"], true, "(e) the flag is back"); | ||
| 31328 | + assert_eq!(a.body["subjects"][0]["id"], s1, "(e) the template set again"); | ||
| 31329 | + | ||
| 31330 | + // (g) The batched report reads show each section its own resolved title. | ||
| 31331 | + let ogrenci = login(&app, "scenario_ogrenci").await; | ||
| 31332 | + let student_id = me_id(&app, &ogrenci).await; | ||
| 31333 | + add_member(&app, &staff, &class_a, &student_id).await; | ||
| 31334 | + add_member(&app, &staff, &class_b, &student_id).await; | ||
| 31335 | + | ||
| 31336 | + let marks = send(&app, "GET", &format!("/marks/{student_id}"), Some(&staff), None).await; | ||
| 31337 | + assert_eq!(marks.status, StatusCode::OK, "(g) {}", marks.body); | ||
| 31338 | + let blocks = marks.body["courses"].as_array().expect("(g) marks blocks"); | ||
| 31339 | + assert_eq!(blocks.len(), 2, "(g) one block per section: {}", marks.body); | ||
| 31340 | + for block in blocks { | ||
| 31341 | + let expected = if block["instance"] == inst_a { | ||
| 31342 | + "Biyoloji (9. sınıf)" | ||
| 31343 | + } else { | ||
| 31344 | + "Biyoloji" | ||
| 31345 | + }; | ||
| 31346 | + assert_eq!(block["course"]["title"], expected, "(g) {}", marks.body); | ||
| 31347 | + } | ||
| 31348 | + | ||
| 31349 | + let karne = send( | ||
| 31350 | + &app, | ||
| 31351 | + "GET", | ||
| 31352 | + &format!("/marks/karne/{student_id}?term={term}"), | ||
| 31353 | + Some(&staff), | ||
| 31354 | + None, | ||
| 31355 | + ) | ||
| 31356 | + .await; | ||
| 31357 | + assert_eq!(karne.status, StatusCode::OK, "(g) {}", karne.body); | ||
| 31358 | + let lines = karne.body["instances"] | ||
| 31359 | + .as_array() | ||
| 31360 | + .expect("(g) karne lines"); | ||
| 31361 | + assert_eq!(lines.len(), 2, "(g) one line per section: {}", karne.body); | ||
| 31362 | + for line in lines { | ||
| 31363 | + let expected = if line["class_course"] == inst_a { | ||
| 31364 | + "Biyoloji (9. sınıf)" | ||
| 31365 | + } else { | ||
| 31366 | + "Biyoloji" | ||
| 31367 | + }; | ||
| 31368 | + assert_eq!(line["course"], expected, "(g) {}", karne.body); | ||
| 31369 | + } | ||
| 31370 | +} | ||
tests/pagination.rsmodified+1 -1
| @@ -594,7 +594,7 @@ async fn class_lists_are_paged() { | |||
| 594 | "POST", | 594 | "POST", |
| 595 | "/classes", | 595 | "/classes", |
| 596 | Some(&manager), | 596 | Some(&manager), |
| 597 | - Some(json!({ "name": format!("9-{n}") })), | 597 | + Some(json!({ "name": format!("9-{n}"), "grade_level": 9 })), |
| 598 | ) | 598 | ) |
| 599 | .await; | 599 | .await; |
| 600 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 600 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
tests/partial_patch_terms.rsmodified+1 -1
| @@ -209,7 +209,7 @@ async fn an_archived_term_is_frozen_for_writes_and_open_for_reads() { | |||
| 209 | "POST", | 209 | "POST", |
| 210 | "/classes", | 210 | "/classes", |
| 211 | Some(&manager), | 211 | Some(&manager), |
| 212 | - Some(json!({ "name": "9-A", "year": year })), | 212 | + Some(json!({ "name": "9-A", "year": year, "grade_level": 9 })), |
| 213 | ) | 213 | ) |
| 214 | .await; | 214 | .await; |
| 215 | assert_eq!( | 215 | assert_eq!( |
tests/persistence.rsmodified+6 -1
| @@ -9,7 +9,9 @@ mod common; | |||
| 9 | 9 | ||
| 10 | use axum::Router; | 10 | use axum::Router; |
| 11 | use axum::http::StatusCode; | 11 | use axum::http::StatusCode; |
| 12 | -use common::{create_subject, enroll, login_as, me_id, send, set_role, taught_under}; | 12 | +use common::{ |
| 13 | + create_subject, enroll, login_as, me_id, select_instance_subject, send, set_role, taught_under, | ||
| 14 | +}; | ||
| 13 | use hezarfen_backend::database::Database; | 15 | use hezarfen_backend::database::Database; |
| 14 | use hezarfen_backend::module::ModuleSet; | 16 | use hezarfen_backend::module::ModuleSet; |
| 15 | use hezarfen_backend::rate_limit::RateLimitConfig; | 17 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| @@ -314,6 +316,9 @@ async fn attempt_history_survives_remigration() { | |||
| 314 | let mudur = login_as(&app, &db, "mudur", "manager").await; | 316 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 315 | let t = taught_under(&app, &mudur, &teacher, "biology").await; | 317 | let t = taught_under(&app, &mudur, &teacher, "biology").await; |
| 316 | let subject = create_subject(&app, &teacher, &t.course, "cells").await; | 318 | let subject = create_subject(&app, &teacher, &t.course, "cells").await; |
| 319 | + // The tag check reads the resolved syllabus — the topic rides the | ||
| 320 | + // section's own set before any question may carry it. | ||
| 321 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 317 | enroll(&app, &teacher, &t.instance, &student_id).await; | 322 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 318 | let res = send( | 323 | let res = send( |
| 319 | &app, | 324 | &app, |
tests/regress_blueprints.rsmodified+105 -80
| @@ -19,7 +19,7 @@ use common::{ | |||
| 19 | upload_file_at, | 19 | upload_file_at, |
| 20 | }; | 20 | }; |
| 21 | use hezarfen_backend::database::Database; | 21 | use hezarfen_backend::database::Database; |
| 22 | -use hezarfen_backend::domain::class_blueprint::ClassBlueprint; | 22 | +use hezarfen_backend::domain::grade::GradeLevel; |
| 23 | use hezarfen_backend::domain::course::CourseId; | 23 | use hezarfen_backend::domain::course::CourseId; |
| 24 | use hezarfen_backend::domain::monotonic_id::next_uuid; | 24 | use hezarfen_backend::domain::monotonic_id::next_uuid; |
| 25 | use hezarfen_backend::domain::timestamp::Timestamp; | 25 | use hezarfen_backend::domain::timestamp::Timestamp; |
| @@ -76,22 +76,24 @@ async fn source_of(class: &str, course: &str, db: &Database) -> Option<uuid::Uui | |||
| 76 | .unwrap() | 76 | .unwrap() |
| 77 | } | 77 | } |
| 78 | 78 | ||
| 79 | -async fn blueprint_id(grade: &str, db: &Database) -> uuid::Uuid { | 79 | +async fn blueprint_id(grade_level: i16, db: &Database) -> uuid::Uuid { |
| 80 | - sqlx::query_scalar::<_, uuid::Uuid>("SELECT id FROM class_blueprint WHERE grade = $1") | 80 | + sqlx::query_scalar::<_, uuid::Uuid>( |
| 81 | - .bind(grade) | 81 | + "SELECT id FROM class_blueprint WHERE grade_level = $1", |
| 82 | + ) | ||
| 83 | + .bind(grade_level) | ||
| 82 | .fetch_one(db) | 84 | .fetch_one(db) |
| 83 | .await | 85 | .await |
| 84 | .unwrap() | 86 | .unwrap() |
| 85 | } | 87 | } |
| 86 | 88 | ||
| 87 | /// Does that grade's template still name that course, in the store? | 89 | /// Does that grade's template still name that course, in the store? |
| 88 | -async fn templated(grade: &str, course: &str, db: &Database) -> bool { | 90 | +async fn templated(grade_level: i16, course: &str, db: &Database) -> bool { |
| 89 | sqlx::query_scalar::<_, i64>( | 91 | sqlx::query_scalar::<_, i64>( |
| 90 | "SELECT count(*) FROM blueprint_course bc \ | 92 | "SELECT count(*) FROM blueprint_course bc \ |
| 91 | JOIN class_blueprint b ON b.id = bc.blueprint \ | 93 | JOIN class_blueprint b ON b.id = bc.blueprint \ |
| 92 | - WHERE b.grade = $1 AND bc.course = $2", | 94 | + WHERE b.grade_level = $1 AND bc.course = $2", |
| 93 | ) | 95 | ) |
| 94 | - .bind(grade) | 96 | + .bind(grade_level) |
| 95 | .bind(CourseId::from_key(course)) | 97 | .bind(CourseId::from_key(course)) |
| 96 | .fetch_one(db) | 98 | .fetch_one(db) |
| 97 | .await | 99 | .await |
| @@ -115,13 +117,18 @@ async fn held(app: &axum::Router, cookie: &str, grade: &str) -> Vec<Value> { | |||
| 115 | } | 117 | } |
| 116 | 118 | ||
| 117 | /// Create a class section as `cookie`; returns its id. | 119 | /// Create a class section as `cookie`; returns its id. |
| 118 | -async fn create_class(app: &axum::Router, cookie: &str, name: &str, grade: &str) -> String { | 120 | +async fn create_class( |
| 121 | + app: &axum::Router, | ||
| 122 | + cookie: &str, | ||
| 123 | + name: &str, | ||
| 124 | + grade_level: i16, | ||
| 125 | +) -> String { | ||
| 119 | let res = send( | 126 | let res = send( |
| 120 | app, | 127 | app, |
| 121 | "POST", | 128 | "POST", |
| 122 | "/classes", | 129 | "/classes", |
| 123 | Some(cookie), | 130 | Some(cookie), |
| 124 | - Some(json!({ "name": name, "grade": grade })), | 131 | + Some(json!({ "name": name, "grade_level": grade_level })), |
| 125 | ) | 132 | ) |
| 126 | .await; | 133 | .await; |
| 127 | assert_eq!(res.status, StatusCode::CREATED, "create class {name}"); | 134 | assert_eq!(res.status, StatusCode::CREATED, "create class {name}"); |
| @@ -210,11 +217,11 @@ async fn a_blueprint_is_created_read_updated_and_deleted() { | |||
| 210 | "POST", | 217 | "POST", |
| 211 | "/classes/blueprints", | 218 | "/classes/blueprints", |
| 212 | Some(&manager), | 219 | Some(&manager), |
| 213 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | 220 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), |
| 214 | ) | 221 | ) |
| 215 | .await; | 222 | .await; |
| 216 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 223 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); |
| 217 | - assert_eq!(made.body["blueprint"]["grade"], "9"); | 224 | + assert_eq!(made.body["blueprint"]["grade_level"], 9); |
| 218 | assert_eq!(made.body["blueprint"]["courses"][0], algebra.as_str()); | 225 | assert_eq!(made.body["blueprint"]["courses"][0], algebra.as_str()); |
| 219 | assert!(skips(&made).is_empty(), "no class exists to skip"); | 226 | assert!(skips(&made).is_empty(), "no class exists to skip"); |
| 220 | 227 | ||
| @@ -225,7 +232,7 @@ async fn a_blueprint_is_created_read_updated_and_deleted() { | |||
| 225 | "POST", | 232 | "POST", |
| 226 | "/classes/blueprints", | 233 | "/classes/blueprints", |
| 227 | Some(&manager), | 234 | Some(&manager), |
| 228 | - Some(json!({ "grade": "9", "course_ids": [] })), | 235 | + Some(json!({ "grade_level": 9, "course_ids": [] })), |
| 229 | ) | 236 | ) |
| 230 | .await; | 237 | .await; |
| 231 | assert_eq!(again.status, StatusCode::CONFLICT, "{:?}", again.body); | 238 | assert_eq!(again.status, StatusCode::CONFLICT, "{:?}", again.body); |
| @@ -270,20 +277,20 @@ async fn a_blueprint_is_created_read_updated_and_deleted() { | |||
| 270 | let gone = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await; | 277 | let gone = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await; |
| 271 | assert_eq!(gone.status, StatusCode::NOT_FOUND); | 278 | assert_eq!(gone.status, StatusCode::NOT_FOUND); |
| 272 | 279 | ||
| 273 | - // An unaddressable grade is a 400, not a record nobody can ever read back. | 280 | + // An off-ladder rung is a 400, not a record nobody can ever read back. |
| 274 | - for bad in ["", "9/A"] { | 281 | + for bad in [-1, 13, 99] { |
| 275 | let refused = send( | 282 | let refused = send( |
| 276 | &app, | 283 | &app, |
| 277 | "POST", | 284 | "POST", |
| 278 | "/classes/blueprints", | 285 | "/classes/blueprints", |
| 279 | Some(&manager), | 286 | Some(&manager), |
| 280 | - Some(json!({ "grade": bad, "course_ids": [] })), | 287 | + Some(json!({ "grade_level": bad, "course_ids": [] })), |
| 281 | ) | 288 | ) |
| 282 | .await; | 289 | .await; |
| 283 | assert_eq!( | 290 | assert_eq!( |
| 284 | refused.status, | 291 | refused.status, |
| 285 | StatusCode::BAD_REQUEST, | 292 | StatusCode::BAD_REQUEST, |
| 286 | - "grade {bad:?}: {:?}", | 293 | + "grade_level {bad}: {:?}", |
| 287 | refused.body | 294 | refused.body |
| 288 | ); | 295 | ); |
| 289 | } | 296 | } |
| @@ -302,12 +309,12 @@ async fn a_fresh_class_takes_its_grades_blueprint() { | |||
| 302 | "POST", | 309 | "POST", |
| 303 | "/classes/blueprints", | 310 | "/classes/blueprints", |
| 304 | Some(&manager), | 311 | Some(&manager), |
| 305 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })), | 312 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone(), physics.clone()] })), |
| 306 | ) | 313 | ) |
| 307 | .await; | 314 | .await; |
| 308 | assert_eq!(made.status, StatusCode::CREATED); | 315 | assert_eq!(made.status, StatusCode::CREATED); |
| 309 | 316 | ||
| 310 | - let class = create_class(&app, &manager, "9-A", "9").await; | 317 | + let class = create_class(&app, &manager, "9-A", 9).await; |
| 311 | let student = student_in(&app, &db, &class, &manager, "ali").await; | 318 | let student = student_in(&app, &db, &class, &manager, "ali").await; |
| 312 | 319 | ||
| 313 | let applied = send( | 320 | let applied = send( |
| @@ -325,7 +332,7 @@ async fn a_fresh_class_takes_its_grades_blueprint() { | |||
| 325 | assert!(attached(&class, course, &db).await); | 332 | assert!(attached(&class, course, &db).await); |
| 326 | assert_eq!( | 333 | assert_eq!( |
| 327 | source_of(&class, course, &db).await, | 334 | source_of(&class, course, &db).await, |
| 328 | - Some(blueprint_id("9", &db).await), | 335 | + Some(blueprint_id(9, &db).await), |
| 329 | "the blueprint must own what it attached" | 336 | "the blueprint must own what it attached" |
| 330 | ); | 337 | ); |
| 331 | let instance = instance_of(&class, course, &db).await; | 338 | let instance = instance_of(&class, course, &db).await; |
| @@ -361,7 +368,7 @@ async fn a_fresh_class_takes_its_grades_blueprint() { | |||
| 361 | assert_eq!(rows("SELECT count(*) FROM class_course", &db).await, 2); | 368 | assert_eq!(rows("SELECT count(*) FROM class_course", &db).await, 2); |
| 362 | 369 | ||
| 363 | // A class whose grade no blueprint covers is a 404, not an empty success. | 370 | // A class whose grade no blueprint covers is a 404, not an empty success. |
| 364 | - let other = create_class(&app, &manager, "10-A", "10").await; | 371 | + let other = create_class(&app, &manager, "10-A", 10).await; |
| 365 | let none = send( | 372 | let none = send( |
| 366 | &app, | 373 | &app, |
| 367 | "POST", | 374 | "POST", |
| @@ -388,7 +395,7 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { | |||
| 388 | "POST", | 395 | "POST", |
| 389 | "/classes/blueprints", | 396 | "/classes/blueprints", |
| 390 | Some(&manager), | 397 | Some(&manager), |
| 391 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })), | 398 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone(), physics.clone()] })), |
| 392 | ) | 399 | ) |
| 393 | .await; | 400 | .await; |
| 394 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 401 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); |
| @@ -398,12 +405,12 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { | |||
| 398 | "POST", | 405 | "POST", |
| 399 | "/classes", | 406 | "/classes", |
| 400 | Some(&manager), | 407 | Some(&manager), |
| 401 | - Some(json!({ "name": "9-A", "grade": "9" })), | 408 | + Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 402 | ) | 409 | ) |
| 403 | .await; | 410 | .await; |
| 404 | assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); | 411 | assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); |
| 405 | assert_eq!( | 412 | assert_eq!( |
| 406 | - res.body["stocked_from"], "9", | 413 | + res.body["stocked_from"], 9, |
| 407 | "the create must name the template that stocked it: {:?}", | 414 | "the create must name the template that stocked it: {:?}", |
| 408 | res.body | 415 | res.body |
| 409 | ); | 416 | ); |
| @@ -419,7 +426,7 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { | |||
| 419 | assert!(attached(&class, course, &db).await, "{course} is attached"); | 426 | assert!(attached(&class, course, &db).await, "{course} is attached"); |
| 420 | assert_eq!( | 427 | assert_eq!( |
| 421 | source_of(&class, course, &db).await, | 428 | source_of(&class, course, &db).await, |
| 422 | - Some(blueprint_id("9", &db).await), | 429 | + Some(blueprint_id(9, &db).await), |
| 423 | "the blueprint must own what a create attached, exactly as a pump does" | 430 | "the blueprint must own what a create attached, exactly as a pump does" |
| 424 | ); | 431 | ); |
| 425 | } | 432 | } |
| @@ -451,8 +458,9 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { | |||
| 451 | // A grade no template covers, and a class with no grade at all: `null`, | 458 | // A grade no template covers, and a class with no grade at all: `null`, |
| 452 | // which is the one thing an empty `skipped` could never say. | 459 | // which is the one thing an empty `skipped` could never say. |
| 453 | for body in [ | 460 | for body in [ |
| 454 | - json!({ "name": "10-A", "grade": "10" }), | 461 | + json!({ "name": "10-A", "grade_level": 10 }), |
| 455 | - json!({ "name": "satranç", "grade": "" }), | 462 | + // A club-shaped section sits at the ladder's floor, like any class. |
| 463 | + json!({ "name": "satranç", "grade_level": 0 }), | ||
| 456 | ] { | 464 | ] { |
| 457 | let res = send(&app, "POST", "/classes", Some(&manager), Some(body)).await; | 465 | let res = send(&app, "POST", "/classes", Some(&manager), Some(body)).await; |
| 458 | assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); | 466 | assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); |
| @@ -497,7 +505,7 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { | |||
| 497 | "POST", | 505 | "POST", |
| 498 | "/classes/blueprints", | 506 | "/classes/blueprints", |
| 499 | Some(&manager), | 507 | Some(&manager), |
| 500 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })), | 508 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone(), physics.clone()] })), |
| 501 | ) | 509 | ) |
| 502 | .await; | 510 | .await; |
| 503 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 511 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); |
| @@ -522,7 +530,7 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { | |||
| 522 | .unwrap(); | 530 | .unwrap(); |
| 523 | tx.commit().await.unwrap(); | 531 | tx.commit().await.unwrap(); |
| 524 | assert!( | 532 | assert!( |
| 525 | - templated("9", &physics, &db).await, | 533 | + templated(9, &physics, &db).await, |
| 526 | "the id is still listed" | 534 | "the id is still listed" |
| 527 | ); | 535 | ); |
| 528 | 536 | ||
| @@ -531,7 +539,7 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { | |||
| 531 | "POST", | 539 | "POST", |
| 532 | "/classes", | 540 | "/classes", |
| 533 | Some(&manager), | 541 | Some(&manager), |
| 534 | - Some(json!({ "name": "9-A", "grade": "9" })), | 542 | + Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 535 | ) | 543 | ) |
| 536 | .await; | 544 | .await; |
| 537 | assert_eq!( | 545 | assert_eq!( |
| @@ -540,7 +548,7 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { | |||
| 540 | "a pair that will not fit may not cost the class: {:?}", | 548 | "a pair that will not fit may not cost the class: {:?}", |
| 541 | res.body | 549 | res.body |
| 542 | ); | 550 | ); |
| 543 | - assert_eq!(res.body["stocked_from"], "9"); | 551 | + assert_eq!(res.body["stocked_from"], 9); |
| 544 | assert_eq!(skips(&res).len(), 1, "{:?}", res.body); | 552 | assert_eq!(skips(&res).len(), 1, "{:?}", res.body); |
| 545 | assert_eq!(skips(&res)[0]["reason"], "course_deleted"); | 553 | assert_eq!(skips(&res)[0]["reason"], "course_deleted"); |
| 546 | assert_eq!(skips(&res)[0]["course"], physics.as_str()); | 554 | assert_eq!(skips(&res)[0]["course"], physics.as_str()); |
| @@ -584,9 +592,9 @@ async fn an_edit_retro_pumps_every_class_at_the_grade() { | |||
| 584 | let (app, db) = app_and_db().await; | 592 | let (app, db) = app_and_db().await; |
| 585 | let manager = login_as(&app, &db, "mgr", "manager").await; | 593 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 586 | let algebra = create_course(&app, &manager, "algebra").await; | 594 | let algebra = create_course(&app, &manager, "algebra").await; |
| 587 | - let a = create_class(&app, &manager, "9-A", "9").await; | 595 | + let a = create_class(&app, &manager, "9-A", 9).await; |
| 588 | - let b = create_class(&app, &manager, "9-B", "9").await; | 596 | + let b = create_class(&app, &manager, "9-B", 9).await; |
| 589 | - let ten = create_class(&app, &manager, "10-A", "10").await; | 597 | + let ten = create_class(&app, &manager, "10-A", 10).await; |
| 590 | let ali = student_in(&app, &db, &a, &manager, "ali").await; | 598 | let ali = student_in(&app, &db, &a, &manager, "ali").await; |
| 591 | student_in(&app, &db, &ten, &manager, "veli").await; | 599 | student_in(&app, &db, &ten, &manager, "veli").await; |
| 592 | 600 | ||
| @@ -596,7 +604,7 @@ async fn an_edit_retro_pumps_every_class_at_the_grade() { | |||
| 596 | "POST", | 604 | "POST", |
| 597 | "/classes/blueprints", | 605 | "/classes/blueprints", |
| 598 | Some(&manager), | 606 | Some(&manager), |
| 599 | - Some(json!({ "grade": "9", "course_ids": [] })), | 607 | + Some(json!({ "grade_level": 9, "course_ids": [] })), |
| 600 | ) | 608 | ) |
| 601 | .await; | 609 | .await; |
| 602 | assert_eq!(made.status, StatusCode::CREATED); | 610 | assert_eq!(made.status, StatusCode::CREATED); |
| @@ -658,7 +666,7 @@ async fn a_duplicate_attach_answers_its_machine_code() { | |||
| 658 | let (app, db) = app_and_db().await; | 666 | let (app, db) = app_and_db().await; |
| 659 | let manager = login_as(&app, &db, "mgr", "manager").await; | 667 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 660 | let roomy = create_course(&app, &manager, "algebra").await; | 668 | let roomy = create_course(&app, &manager, "algebra").await; |
| 661 | - let class = create_class(&app, &manager, "9-A", "9").await; | 669 | + let class = create_class(&app, &manager, "9-A", 9).await; |
| 662 | student_in(&app, &db, &class, &manager, "ali").await; | 670 | student_in(&app, &db, &class, &manager, "ali").await; |
| 663 | 671 | ||
| 664 | let attached = send( | 672 | let attached = send( |
| @@ -701,8 +709,8 @@ async fn a_removal_spares_a_hand_attached_course() { | |||
| 701 | let (app, db) = app_and_db().await; | 709 | let (app, db) = app_and_db().await; |
| 702 | let manager = login_as(&app, &db, "mgr", "manager").await; | 710 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 703 | let algebra = create_course(&app, &manager, "algebra").await; | 711 | let algebra = create_course(&app, &manager, "algebra").await; |
| 704 | - let pumped = create_class(&app, &manager, "9-A", "9").await; | 712 | + let pumped = create_class(&app, &manager, "9-A", 9).await; |
| 705 | - let byhand = create_class(&app, &manager, "9-B", "9").await; | 713 | + let byhand = create_class(&app, &manager, "9-B", 9).await; |
| 706 | let ali = student_in(&app, &db, &pumped, &manager, "ali").await; | 714 | let ali = student_in(&app, &db, &pumped, &manager, "ali").await; |
| 707 | student_in(&app, &db, &byhand, &manager, "veli").await; | 715 | student_in(&app, &db, &byhand, &manager, "veli").await; |
| 708 | 716 | ||
| @@ -727,7 +735,7 @@ async fn a_removal_spares_a_hand_attached_course() { | |||
| 727 | "POST", | 735 | "POST", |
| 728 | "/classes/blueprints", | 736 | "/classes/blueprints", |
| 729 | Some(&manager), | 737 | Some(&manager), |
| 730 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | 738 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), |
| 731 | ) | 739 | ) |
| 732 | .await; | 740 | .await; |
| 733 | assert_eq!(made.status, StatusCode::CREATED); | 741 | assert_eq!(made.status, StatusCode::CREATED); |
| @@ -739,7 +747,7 @@ async fn a_removal_spares_a_hand_attached_course() { | |||
| 739 | ); | 747 | ); |
| 740 | assert_eq!( | 748 | assert_eq!( |
| 741 | source_of(&pumped, &algebra, &db).await, | 749 | source_of(&pumped, &algebra, &db).await, |
| 742 | - Some(blueprint_id("9", &db).await), | 750 | + Some(blueprint_id(9, &db).await), |
| 743 | ); | 751 | ); |
| 744 | 752 | ||
| 745 | // Drop it from the template. | 753 | // Drop it from the template. |
| @@ -799,7 +807,7 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() { | |||
| 799 | let (app, db) = app_and_db().await; | 807 | let (app, db) = app_and_db().await; |
| 800 | let manager = login_as(&app, &db, "mgr", "manager").await; | 808 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 801 | let algebra = create_course(&app, &manager, "algebra").await; | 809 | let algebra = create_course(&app, &manager, "algebra").await; |
| 802 | - let class = create_class(&app, &manager, "9-A", "9").await; | 810 | + let class = create_class(&app, &manager, "9-A", 9).await; |
| 803 | student_in(&app, &db, &class, &manager, "ali").await; | 811 | student_in(&app, &db, &class, &manager, "ali").await; |
| 804 | let attached_by_hand = send( | 812 | let attached_by_hand = send( |
| 805 | &app, | 813 | &app, |
| @@ -836,7 +844,7 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() { | |||
| 836 | "POST", | 844 | "POST", |
| 837 | "/classes/blueprints", | 845 | "/classes/blueprints", |
| 838 | Some(&manager), | 846 | Some(&manager), |
| 839 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | 847 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), |
| 840 | ) | 848 | ) |
| 841 | .await; | 849 | .await; |
| 842 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 850 | 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() { | |||
| 896 | "POST", | 904 | "POST", |
| 897 | "/classes/blueprints", | 905 | "/classes/blueprints", |
| 898 | Some(&manager), | 906 | Some(&manager), |
| 899 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | 907 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), |
| 900 | ) | 908 | ) |
| 901 | .await; | 909 | .await; |
| 902 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 910 | 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() { | |||
| 905 | // is stocked by its own create, and one that existed already was stocked by | 913 | // is stocked by its own create, and one that existed already was stocked by |
| 906 | // the template's. Moving it there afterwards is neither — a grade change is | 914 | // the template's. Moving it there afterwards is neither — a grade change is |
| 907 | // deliberately a blueprint no-op. | 915 | // deliberately a blueprint no-op. |
| 908 | - let class = create_class(&app, &manager, "9-A", "10").await; | 916 | + let class = create_class(&app, &manager, "9-A", 10).await; |
| 909 | let moved = send( | 917 | let moved = send( |
| 910 | &app, | 918 | &app, |
| 911 | "PATCH", | 919 | "PATCH", |
| 912 | &format!("/classes/{class}"), | 920 | &format!("/classes/{class}"), |
| 913 | Some(&manager), | 921 | Some(&manager), |
| 914 | - Some(json!({ "grade": "9" })), | 922 | + Some(json!({ "grade_level": 9 })), |
| 915 | ) | 923 | ) |
| 916 | .await; | 924 | .await; |
| 917 | assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body); | 925 | 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() { | |||
| 923 | // the strand consists of. Capture the uuid before the delete: the grade | 931 | // the strand consists of. Capture the uuid before the delete: the grade |
| 924 | // label is UNIQUE, not the FK. | 932 | // label is UNIQUE, not the FK. |
| 925 | let manager_id = UserId::from_key(&me_id(&app, &manager).await); | 933 | let manager_id = UserId::from_key(&me_id(&app, &manager).await); |
| 926 | - let stranded = blueprint_id("9", &db).await; | 934 | + let stranded = blueprint_id(9, &db).await; |
| 927 | let mut tx = db.begin().await.unwrap(); | 935 | let mut tx = db.begin().await.unwrap(); |
| 928 | sqlx::query("SET LOCAL session_replication_role = replica") | 936 | sqlx::query("SET LOCAL session_replication_role = replica") |
| 929 | .execute(&mut *tx) | 937 | .execute(&mut *tx) |
| 930 | .await | 938 | .await |
| 931 | .unwrap(); | 939 | .unwrap(); |
| 932 | - sqlx::query("DELETE FROM class_blueprint WHERE grade = '9'") | 940 | + sqlx::query("DELETE FROM class_blueprint WHERE grade_level = 9") |
| 933 | .execute(&mut *tx) | 941 | .execute(&mut *tx) |
| 934 | .await | 942 | .await |
| 935 | .unwrap(); | 943 | .unwrap(); |
| 944 | + // The strand names an offering too (the column is NOT NULL): the pump run | ||
| 945 | + // above already minted one for (algebra, 9) — reuse it, minting a twin | ||
| 946 | + // only if none survived, exactly like `ensure_tx` would. | ||
| 947 | + let offering: (uuid::Uuid,) = sqlx::query_as( | ||
| 948 | + "INSERT INTO course_offering (id, course, grade_level, created_by, created_at, updated_at) \ | ||
| 949 | + VALUES ($1, $2, 9, $3, $4, $4) \ | ||
| 950 | + ON CONFLICT (course, grade_level) DO UPDATE SET updated_at = EXCLUDED.updated_at \ | ||
| 951 | + RETURNING id", | ||
| 952 | + ) | ||
| 953 | + .bind(next_uuid()) | ||
| 954 | + .bind(CourseId::from_key(&algebra)) | ||
| 955 | + .bind(manager_id) | ||
| 956 | + .bind(Timestamp::now().as_millis()) | ||
| 957 | + .fetch_one(&mut *tx) | ||
| 958 | + .await | ||
| 959 | + .unwrap(); | ||
| 936 | sqlx::query( | 960 | sqlx::query( |
| 937 | - "INSERT INTO class_course (id, class, course, attached_by, attached_at, source) \ | 961 | + "INSERT INTO class_course (id, class, course, attached_by, attached_at, source, offering) \ |
| 938 | - VALUES ($1, $2, $3, $4, $5, $6)", | 962 | + VALUES ($1, $2, $3, $4, $5, $6, $7)", |
| 939 | ) | 963 | ) |
| 940 | .bind(next_uuid()) | 964 | .bind(next_uuid()) |
| 941 | .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id")) | 965 | .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() { | |||
| 943 | .bind(manager_id) | 967 | .bind(manager_id) |
| 944 | .bind(Timestamp::now().as_millis()) | 968 | .bind(Timestamp::now().as_millis()) |
| 945 | .bind(stranded) | 969 | .bind(stranded) |
| 970 | + .bind(offering.0) | ||
| 946 | .execute(&mut *tx) | 971 | .execute(&mut *tx) |
| 947 | .await | 972 | .await |
| 948 | .unwrap(); | 973 | .unwrap(); |
| @@ -990,30 +1015,30 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() { | |||
| 990 | ); | 1015 | ); |
| 991 | } | 1016 | } |
| 992 | 1017 | ||
| 993 | -/// The silent miss `matched` exists for: a grade label is free text and matched | 1018 | +/// The silent miss `matched` exists for: sections are matched by their ladder |
| 994 | -/// exactly, so a template keyed `"9 "` reaches none of the sections keyed `"9"` | 1019 | +/// rung, so a template keyed at a rung no section carries reaches none of them |
| 995 | /// — and it says so with an empty `skipped`, which is the same body a template | 1020 | /// — and it says so with an empty `skipped`, which is the same body a template |
| 996 | /// that stocked every section returns. | 1021 | /// that stocked every section returns. |
| 997 | /// | 1022 | /// |
| 998 | -/// Both halves are asserted from the same section, one label apart, because the | 1023 | +/// Both halves are asserted from the same section, one rung apart, because the |
| 999 | /// count only means anything against the case that *does* reach it: a `matched` | 1024 | /// count only means anything against the case that *does* reach it: a `matched` |
| 1000 | -/// wired to the course list would claim 1 on the typo, and one wired to the | 1025 | +/// wired to the course list would claim 1 on the empty rung, and one wired to |
| 1001 | -/// skip count would answer 0 on the label that works. | 1026 | +/// the skip count would answer 0 on the rung that works. |
| 1002 | #[tokio::test] | 1027 | #[tokio::test] |
| 1003 | -async fn a_grade_label_nothing_carries_reports_matched_zero() { | 1028 | +async fn a_rung_nothing_carries_reports_matched_zero() { |
| 1004 | let (app, db) = app_and_db().await; | 1029 | let (app, db) = app_and_db().await; |
| 1005 | let manager = login_as(&app, &db, "mgr", "manager").await; | 1030 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 1006 | let algebra = create_course(&app, &manager, "algebra").await; | 1031 | let algebra = create_course(&app, &manager, "algebra").await; |
| 1007 | // The section exists first, so a template that finds it stocks it on | 1032 | // The section exists first, so a template that finds it stocks it on |
| 1008 | // create. | 1033 | // create. |
| 1009 | - let class = create_class(&app, &manager, "9-A", "9").await; | 1034 | + let class = create_class(&app, &manager, "9-A", 9).await; |
| 1010 | 1035 | ||
| 1011 | let typo = send( | 1036 | let typo = send( |
| 1012 | &app, | 1037 | &app, |
| 1013 | "POST", | 1038 | "POST", |
| 1014 | "/classes/blueprints", | 1039 | "/classes/blueprints", |
| 1015 | Some(&manager), | 1040 | Some(&manager), |
| 1016 | - Some(json!({ "grade": "9 ", "course_ids": [algebra.clone()] })), | 1041 | + Some(json!({ "grade_level": 11, "course_ids": [algebra.clone()] })), |
| 1017 | ) | 1042 | ) |
| 1018 | .await; | 1043 | .await; |
| 1019 | assert_eq!(typo.status, StatusCode::CREATED, "{:?}", typo.body); | 1044 | assert_eq!(typo.status, StatusCode::CREATED, "{:?}", typo.body); |
| @@ -1024,12 +1049,12 @@ async fn a_grade_label_nothing_carries_reports_matched_zero() { | |||
| 1024 | ); | 1049 | ); |
| 1025 | assert_eq!( | 1050 | assert_eq!( |
| 1026 | typo.body["matched"], 0, | 1051 | typo.body["matched"], 0, |
| 1027 | - "no section carries \"9 \", and that must not read as success: {:?}", | 1052 | + "no section sits at 11, and that must not read as success: {:?}", |
| 1028 | typo.body | 1053 | typo.body |
| 1029 | ); | 1054 | ); |
| 1030 | assert!( | 1055 | assert!( |
| 1031 | !attached(&class, &algebra, &db).await, | 1056 | !attached(&class, &algebra, &db).await, |
| 1032 | - "a trailing space really is a different grade" | 1057 | + "a rung above the section's really is a different grade" |
| 1033 | ); | 1058 | ); |
| 1034 | 1059 | ||
| 1035 | let right = send( | 1060 | let right = send( |
| @@ -1037,7 +1062,7 @@ async fn a_grade_label_nothing_carries_reports_matched_zero() { | |||
| 1037 | "POST", | 1062 | "POST", |
| 1038 | "/classes/blueprints", | 1063 | "/classes/blueprints", |
| 1039 | Some(&manager), | 1064 | Some(&manager), |
| 1040 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | 1065 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), |
| 1041 | ) | 1066 | ) |
| 1042 | .await; | 1067 | .await; |
| 1043 | assert_eq!(right.status, StatusCode::CREATED, "{:?}", right.body); | 1068 | assert_eq!(right.status, StatusCode::CREATED, "{:?}", right.body); |
| @@ -1074,7 +1099,7 @@ async fn a_status_read_names_the_course_a_section_is_short() { | |||
| 1074 | let algebra = create_course(&app, &manager, "algebra").await; | 1099 | let algebra = create_course(&app, &manager, "algebra").await; |
| 1075 | // The section starts at grade 10, where nothing stocks it, so the template | 1100 | // The section starts at grade 10, where nothing stocks it, so the template |
| 1076 | // below is never what attached anything to it. | 1101 | // below is never what attached anything to it. |
| 1077 | - let short = create_class(&app, &manager, "9-A", "10").await; | 1102 | + let short = create_class(&app, &manager, "9-A", 10).await; |
| 1078 | 1103 | ||
| 1079 | // No template covers the grade yet, and that is a 404 rather than an empty | 1104 | // No template covers the grade yet, and that is a 404 rather than an empty |
| 1080 | // report — there is nothing to be out of sync with. | 1105 | // 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() { | |||
| 1093 | "POST", | 1118 | "POST", |
| 1094 | "/classes/blueprints", | 1119 | "/classes/blueprints", |
| 1095 | Some(&manager), | 1120 | Some(&manager), |
| 1096 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | 1121 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), |
| 1097 | ) | 1122 | ) |
| 1098 | .await; | 1123 | .await; |
| 1099 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 1124 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); |
| @@ -1101,7 +1126,7 @@ async fn a_status_read_names_the_course_a_section_is_short() { | |||
| 1101 | assert_eq!(made.body["matched"], 0, "no section carries the label yet"); | 1126 | assert_eq!(made.body["matched"], 0, "no section carries the label yet"); |
| 1102 | 1127 | ||
| 1103 | // A section created at the grade is stocked by its own create, in sync. | 1128 | // A section created at the grade is stocked by its own create, in sync. |
| 1104 | - let full = create_class(&app, &manager, "9-B", "9").await; | 1129 | + let full = create_class(&app, &manager, "9-B", 9).await; |
| 1105 | assert!(attached(&full, &algebra, &db).await); | 1130 | assert!(attached(&full, &algebra, &db).await); |
| 1106 | 1131 | ||
| 1107 | // The other section reaches the grade by a rename, which is deliberately | 1132 | // 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() { | |||
| 1111 | "PATCH", | 1136 | "PATCH", |
| 1112 | &format!("/classes/{short}"), | 1137 | &format!("/classes/{short}"), |
| 1113 | Some(&manager), | 1138 | Some(&manager), |
| 1114 | - Some(json!({ "grade": "9" })), | 1139 | + Some(json!({ "grade_level": 9 })), |
| 1115 | ) | 1140 | ) |
| 1116 | .await; | 1141 | .await; |
| 1117 | assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body); | 1142 | assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body); |
| @@ -1126,7 +1151,7 @@ async fn a_status_read_names_the_course_a_section_is_short() { | |||
| 1126 | ) | 1151 | ) |
| 1127 | .await; | 1152 | .await; |
| 1128 | assert_eq!(drifted.status, StatusCode::OK, "{:?}", drifted.body); | 1153 | assert_eq!(drifted.status, StatusCode::OK, "{:?}", drifted.body); |
| 1129 | - assert_eq!(drifted.body["grade"], "9"); | 1154 | + assert_eq!(drifted.body["grade_level"], 9); |
| 1130 | assert_eq!(drifted.body["matched"], 2, "both sections carry the label"); | 1155 | assert_eq!(drifted.body["matched"], 2, "both sections carry the label"); |
| 1131 | assert_eq!( | 1156 | assert_eq!( |
| 1132 | missing(&drifted, &short), | 1157 | missing(&drifted, &short), |
| @@ -1213,14 +1238,14 @@ async fn deleting_a_course_takes_it_out_of_every_blueprint() { | |||
| 1213 | // a section that lets its link go is what lets the course be deleted at | 1238 | // a section that lets its link go is what lets the course be deleted at |
| 1214 | // all (the guard reads the course's own instance counter, so one still | 1239 | // all (the guard reads the course's own instance counter, so one still |
| 1215 | // teaching it is a 409). | 1240 | // teaching it is a 409). |
| 1216 | - let class = create_class(&app, &manager, "9-A", "9").await; | 1241 | + let class = create_class(&app, &manager, "9-A", 9).await; |
| 1217 | 1242 | ||
| 1218 | let made = send( | 1243 | let made = send( |
| 1219 | &app, | 1244 | &app, |
| 1220 | "POST", | 1245 | "POST", |
| 1221 | "/classes/blueprints", | 1246 | "/classes/blueprints", |
| 1222 | Some(&manager), | 1247 | Some(&manager), |
| 1223 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone(), history.clone()] })), | 1248 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone(), history.clone()] })), |
| 1224 | ) | 1249 | ) |
| 1225 | .await; | 1250 | .await; |
| 1226 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 1251 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); |
| @@ -1268,11 +1293,11 @@ async fn deleting_a_course_takes_it_out_of_every_blueprint() { | |||
| 1268 | assert_eq!(deleted.status, StatusCode::NO_CONTENT, "{:?}", deleted.body); | 1293 | assert_eq!(deleted.status, StatusCode::NO_CONTENT, "{:?}", deleted.body); |
| 1269 | 1294 | ||
| 1270 | assert!( | 1295 | assert!( |
| 1271 | - !templated("9", &history, &db).await, | 1296 | + !templated(9, &history, &db).await, |
| 1272 | "the deleted course is out of the template" | 1297 | "the deleted course is out of the template" |
| 1273 | ); | 1298 | ); |
| 1274 | assert!( | 1299 | assert!( |
| 1275 | - templated("9", &algebra, &db).await, | 1300 | + templated(9, &algebra, &db).await, |
| 1276 | "…and nothing else is — the sweep names one course" | 1301 | "…and nothing else is — the sweep names one course" |
| 1277 | ); | 1302 | ); |
| 1278 | assert!( | 1303 | assert!( |
| @@ -1336,7 +1361,7 @@ async fn a_grade_with_no_sections_still_loses_its_deleted_course() { | |||
| 1336 | "POST", | 1361 | "POST", |
| 1337 | "/classes/blueprints", | 1362 | "/classes/blueprints", |
| 1338 | Some(&manager), | 1363 | Some(&manager), |
| 1339 | - Some(json!({ "grade": "11", "course_ids": [algebra.clone()] })), | 1364 | + Some(json!({ "grade_level": 11, "course_ids": [algebra.clone()] })), |
| 1340 | ) | 1365 | ) |
| 1341 | .await; | 1366 | .await; |
| 1342 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 1367 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); |
| @@ -1353,7 +1378,7 @@ async fn a_grade_with_no_sections_still_loses_its_deleted_course() { | |||
| 1353 | assert_eq!(deleted.status, StatusCode::NO_CONTENT, "{:?}", deleted.body); | 1378 | assert_eq!(deleted.status, StatusCode::NO_CONTENT, "{:?}", deleted.body); |
| 1354 | 1379 | ||
| 1355 | assert!( | 1380 | assert!( |
| 1356 | - !templated("11", &algebra, &db).await, | 1381 | + !templated(11, &algebra, &db).await, |
| 1357 | "no section to walk, and the id is gone anyway" | 1382 | "no section to walk, and the id is gone anyway" |
| 1358 | ); | 1383 | ); |
| 1359 | assert!( | 1384 | assert!( |
| @@ -1396,7 +1421,7 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() { | |||
| 1396 | let manager = login_as(&app, &db, "mgr", "manager").await; | 1421 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 1397 | let algebra = create_course(&app, &manager, "algebra").await; | 1422 | let algebra = create_course(&app, &manager, "algebra").await; |
| 1398 | let history = create_course(&app, &manager, "history").await; | 1423 | let history = create_course(&app, &manager, "history").await; |
| 1399 | - let class = create_class(&app, &manager, "9-A", "9").await; | 1424 | + let class = create_class(&app, &manager, "9-A", 9).await; |
| 1400 | let ali = student_in(&app, &db, &class, &manager, "ali").await; | 1425 | let ali = student_in(&app, &db, &class, &manager, "ali").await; |
| 1401 | 1426 | ||
| 1402 | let made = send( | 1427 | let made = send( |
| @@ -1404,7 +1429,7 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() { | |||
| 1404 | "POST", | 1429 | "POST", |
| 1405 | "/classes/blueprints", | 1430 | "/classes/blueprints", |
| 1406 | Some(&manager), | 1431 | Some(&manager), |
| 1407 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone(), history.clone()] })), | 1432 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone(), history.clone()] })), |
| 1408 | ) | 1433 | ) |
| 1409 | .await; | 1434 | .await; |
| 1410 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 1435 | 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() { | |||
| 1415 | sqlx::query( | 1440 | sqlx::query( |
| 1416 | "DELETE FROM blueprint_course \ | 1441 | "DELETE FROM blueprint_course \ |
| 1417 | WHERE course = $1 \ | 1442 | WHERE course = $1 \ |
| 1418 | - AND blueprint = (SELECT id FROM class_blueprint WHERE grade = '9')", | 1443 | + AND blueprint = (SELECT id FROM class_blueprint WHERE grade_level = 9)", |
| 1419 | ) | 1444 | ) |
| 1420 | .bind(CourseId::from_key(&history)) | 1445 | .bind(CourseId::from_key(&history)) |
| 1421 | .execute(&db) | 1446 | .execute(&db) |
| @@ -1506,7 +1531,7 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() { | |||
| 1506 | let manager = login_as(&app, &db, "mgr", "manager").await; | 1531 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 1507 | let algebra = create_course(&app, &manager, "algebra").await; | 1532 | let algebra = create_course(&app, &manager, "algebra").await; |
| 1508 | let history = create_course(&app, &manager, "history").await; | 1533 | let history = create_course(&app, &manager, "history").await; |
| 1509 | - let class = create_class(&app, &manager, "9-A", "9").await; | 1534 | + let class = create_class(&app, &manager, "9-A", 9).await; |
| 1510 | 1535 | ||
| 1511 | let mut conn = db.acquire().await.expect("acquire for the trigger"); | 1536 | let mut conn = db.acquire().await.expect("acquire for the trigger"); |
| 1512 | sqlx::raw_sql(sqlx::AssertSqlSafe(format!( | 1537 | 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() { | |||
| 1527 | "POST", | 1552 | "POST", |
| 1528 | "/classes/blueprints", | 1553 | "/classes/blueprints", |
| 1529 | Some(&manager), | 1554 | Some(&manager), |
| 1530 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | 1555 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), |
| 1531 | ) | 1556 | ) |
| 1532 | .await; | 1557 | .await; |
| 1533 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 1558 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); |
| @@ -1610,7 +1635,7 @@ async fn a_template_write_refuses_a_course_that_is_gone() { | |||
| 1610 | let refused = class_blueprint::create( | 1635 | let refused = class_blueprint::create( |
| 1611 | &db, | 1636 | &db, |
| 1612 | &by, | 1637 | &by, |
| 1613 | - ClassBlueprint::grade_key("9").unwrap(), | 1638 | + GradeLevel::new(9).unwrap(), |
| 1614 | vec![ghost.clone()], | 1639 | vec![ghost.clone()], |
| 1615 | ) | 1640 | ) |
| 1616 | .await; | 1641 | .await; |
| @@ -1627,7 +1652,7 @@ async fn a_template_write_refuses_a_course_that_is_gone() { | |||
| 1627 | let blueprint = class_blueprint::create( | 1652 | let blueprint = class_blueprint::create( |
| 1628 | &db, | 1653 | &db, |
| 1629 | &by, | 1654 | &by, |
| 1630 | - ClassBlueprint::grade_key("9").unwrap(), | 1655 | + GradeLevel::new(9).unwrap(), |
| 1631 | vec![algebra.clone()], | 1656 | vec![algebra.clone()], |
| 1632 | ) | 1657 | ) |
| 1633 | .await | 1658 | .await |
| @@ -1670,15 +1695,15 @@ async fn a_blueprint_removal_unlinks_the_swept_instances_blob_bytes() { | |||
| 1670 | "POST", | 1695 | "POST", |
| 1671 | "/classes/blueprints", | 1696 | "/classes/blueprints", |
| 1672 | Some(&manager), | 1697 | Some(&manager), |
| 1673 | - Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), | 1698 | + Some(json!({ "grade_level": 9, "course_ids": [algebra.clone()] })), |
| 1674 | ) | 1699 | ) |
| 1675 | .await; | 1700 | .await; |
| 1676 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 1701 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); |
| 1677 | let class = | 1702 | let class = |
| 1678 | - common::create_class(&app, &manager, "9-A", json!({ "grade": "9", "year": year })).await; | 1703 | + common::create_class(&app, &manager, "9-A", json!({ "grade_level": 9, "year": year })).await; |
| 1679 | assert_eq!( | 1704 | assert_eq!( |
| 1680 | source_of(&class, &algebra, &db).await, | 1705 | source_of(&class, &algebra, &db).await, |
| 1681 | - Some(blueprint_id("9", &db).await), | 1706 | + Some(blueprint_id(9, &db).await), |
| 1682 | "the create must stock the section from the template" | 1707 | "the create must stock the section from the template" |
| 1683 | ); | 1708 | ); |
| 1684 | let instance = instance_of(&class, &algebra, &db).await; | 1709 | let instance = instance_of(&class, &algebra, &db).await; |
tests/regress_classes.rsmodified+62 -54
| @@ -13,6 +13,7 @@ use common::{ | |||
| 13 | use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; | 13 | use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; |
| 14 | use hezarfen_backend::database::Database; | 14 | use hezarfen_backend::database::Database; |
| 15 | use hezarfen_backend::domain::class_group::ClassName; | 15 | use hezarfen_backend::domain::class_group::ClassName; |
| 16 | +use hezarfen_backend::domain::grade::GradeLevel; | ||
| 16 | use hezarfen_backend::domain::course::CourseId; | 17 | use hezarfen_backend::domain::course::CourseId; |
| 17 | use hezarfen_backend::domain::user::UserId; | 18 | use hezarfen_backend::domain::user::UserId; |
| 18 | use hezarfen_backend::error::AppError; | 19 | use hezarfen_backend::error::AppError; |
| @@ -108,7 +109,7 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() { | |||
| 108 | &db, | 109 | &db, |
| 109 | &manager, | 110 | &manager, |
| 110 | ClassName::try_new("9-A").unwrap(), | 111 | ClassName::try_new("9-A").unwrap(), |
| 111 | - None, | 112 | + GradeLevel::new(9).unwrap(), |
| 112 | None, | 113 | None, |
| 113 | None, | 114 | None, |
| 114 | ) | 115 | ) |
| @@ -155,7 +156,7 @@ async fn a_stale_link_detaches_and_frees_its_class() { | |||
| 155 | "POST", | 156 | "POST", |
| 156 | "/classes", | 157 | "/classes", |
| 157 | Some(&manager), | 158 | Some(&manager), |
| 158 | - Some(json!({ "name": "9-A" })), | 159 | + Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 159 | ) | 160 | ) |
| 160 | .await; | 161 | .await; |
| 161 | assert_eq!(res.status, StatusCode::CREATED); | 162 | assert_eq!(res.status, StatusCode::CREATED); |
| @@ -237,7 +238,7 @@ async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() { | |||
| 237 | "POST", | 238 | "POST", |
| 238 | "/classes", | 239 | "/classes", |
| 239 | Some(&manager), | 240 | Some(&manager), |
| 240 | - Some(json!({ "name": "9-A" })), | 241 | + Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 241 | ) | 242 | ) |
| 242 | .await; | 243 | .await; |
| 243 | res.body["class"]["id"].as_str().unwrap().to_string() | 244 | res.body["class"]["id"].as_str().unwrap().to_string() |
| @@ -365,7 +366,7 @@ async fn a_hand_enroll_takes_the_row_off_the_class() { | |||
| 365 | "POST", | 366 | "POST", |
| 366 | "/classes", | 367 | "/classes", |
| 367 | Some(&manager), | 368 | Some(&manager), |
| 368 | - Some(json!({ "name": "9-A" })), | 369 | + Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 369 | ) | 370 | ) |
| 370 | .await; | 371 | .await; |
| 371 | res.body["class"]["id"].as_str().unwrap().to_string() | 372 | res.body["class"]["id"].as_str().unwrap().to_string() |
| @@ -472,7 +473,7 @@ async fn a_role_change_sweeps_memberships_and_enrollments_together() { | |||
| 472 | "POST", | 473 | "POST", |
| 473 | "/classes", | 474 | "/classes", |
| 474 | Some(&manager), | 475 | Some(&manager), |
| 475 | - Some(json!({ "name": "9-A" })), | 476 | + Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 476 | ) | 477 | ) |
| 477 | .await; | 478 | .await; |
| 478 | res.body["class"]["id"].as_str().unwrap().to_string() | 479 | 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() { | |||
| 573 | &db, | 574 | &db, |
| 574 | &manager, | 575 | &manager, |
| 575 | ClassName::try_new("9-A").unwrap(), | 576 | ClassName::try_new("9-A").unwrap(), |
| 576 | - None, | 577 | + GradeLevel::new(9).unwrap(), |
| 577 | None, | 578 | None, |
| 578 | None, | 579 | None, |
| 579 | ) | 580 | ) |
| @@ -654,7 +655,7 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() { | |||
| 654 | &db, | 655 | &db, |
| 655 | &manager, | 656 | &manager, |
| 656 | ClassName::try_new("9-A").unwrap(), | 657 | ClassName::try_new("9-A").unwrap(), |
| 657 | - None, | 658 | + GradeLevel::new(9).unwrap(), |
| 658 | None, | 659 | None, |
| 659 | None, | 660 | None, |
| 660 | ) | 661 | ) |
| @@ -708,7 +709,7 @@ async fn a_class_refuses_the_member_past_its_ceiling() { | |||
| 708 | &db, | 709 | &db, |
| 709 | &manager, | 710 | &manager, |
| 710 | ClassName::try_new("9-A").unwrap(), | 711 | ClassName::try_new("9-A").unwrap(), |
| 711 | - None, | 712 | + GradeLevel::new(9).unwrap(), |
| 712 | None, | 713 | None, |
| 713 | None, | 714 | None, |
| 714 | ) | 715 | ) |
| @@ -778,7 +779,7 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() { | |||
| 778 | &db, | 779 | &db, |
| 779 | &manager, | 780 | &manager, |
| 780 | ClassName::try_new("9-A").unwrap(), | 781 | ClassName::try_new("9-A").unwrap(), |
| 781 | - None, | 782 | + GradeLevel::new(9).unwrap(), |
| 782 | None, | 783 | None, |
| 783 | None, | 784 | None, |
| 784 | ) | 785 | ) |
| @@ -839,7 +840,7 @@ async fn a_class_over_the_course_ceiling_takes_no_member() { | |||
| 839 | &db, | 840 | &db, |
| 840 | &manager, | 841 | &manager, |
| 841 | ClassName::try_new("9-B").unwrap(), | 842 | ClassName::try_new("9-B").unwrap(), |
| 842 | - None, | 843 | + GradeLevel::new(9).unwrap(), |
| 843 | None, | 844 | None, |
| 844 | None, | 845 | None, |
| 845 | ) | 846 | ) |
| @@ -881,7 +882,10 @@ async fn a_class_over_the_course_ceiling_takes_no_member() { | |||
| 881 | /// `{class, skipped, stocked_from}` since a create stocks from its grade's | 882 | /// `{class, skipped, stocked_from}` since a create stocks from its grade's |
| 882 | /// blueprint, and the tests below are about the class itself. The two outer | 883 | /// blueprint, and the tests below are about the class itself. The two outer |
| 883 | /// fields have their own tests (`regress_blueprints`). | 884 | /// fields have their own tests (`regress_blueprints`). |
| 884 | -async fn create_class(app: &axum::Router, cookie: &str, body: serde_json::Value) -> Res { | 885 | +async fn create_class(app: &axum::Router, cookie: &str, mut body: serde_json::Value) -> Res { |
| 886 | + if body.get("grade_level").is_none() { | ||
| 887 | + body["grade_level"] = serde_json::json!(9); | ||
| 888 | + } | ||
| 885 | let mut res = send(app, "POST", "/classes", Some(cookie), Some(body)).await; | 889 | let mut res = send(app, "POST", "/classes", Some(cookie), Some(body)).await; |
| 886 | assert_eq!(res.status, StatusCode::CREATED, "create class"); | 890 | assert_eq!(res.status, StatusCode::CREATED, "create class"); |
| 887 | res.body = res.body["class"].clone(); | 891 | res.body = res.body["class"].clone(); |
| @@ -912,7 +916,7 @@ async fn the_homeroom_teacher_round_trips_through_create_and_patch() { | |||
| 912 | let created = create_class( | 916 | let created = create_class( |
| 913 | &app, | 917 | &app, |
| 914 | &manager, | 918 | &manager, |
| 915 | - json!({ "name": "9-A", "teacher_id": teacher_id }), | 919 | + json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id }), |
| 916 | ) | 920 | ) |
| 917 | .await; | 921 | .await; |
| 918 | let class = created.body["id"].as_str().unwrap().to_string(); | 922 | 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() { | |||
| 933 | "PATCH", | 937 | "PATCH", |
| 934 | &format!("/classes/{class}"), | 938 | &format!("/classes/{class}"), |
| 935 | Some(&manager), | 939 | Some(&manager), |
| 936 | - Some(json!({ "name": "9-B" })), | 940 | + Some(json!({ "name": "9-B", "grade_level": 9 })), |
| 937 | ) | 941 | ) |
| 938 | .await; | 942 | .await; |
| 939 | assert_eq!(renamed.status, StatusCode::OK); | 943 | assert_eq!(renamed.status, StatusCode::OK); |
| @@ -1000,7 +1004,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() { | |||
| 1000 | "POST", | 1004 | "POST", |
| 1001 | "/classes", | 1005 | "/classes", |
| 1002 | Some(&manager), | 1006 | Some(&manager), |
| 1003 | - Some(json!({ "name": "9-A", "teacher_id": bad })), | 1007 | + Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": bad })), |
| 1004 | ) | 1008 | ) |
| 1005 | .await; | 1009 | .await; |
| 1006 | assert_eq!(refused.status, StatusCode::BAD_REQUEST, "create with {bad}"); | 1010 | 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() { | |||
| 1011 | "a refused create may write no class" | 1015 | "a refused create may write no class" |
| 1012 | ); | 1016 | ); |
| 1013 | 1017 | ||
| 1014 | - let class = create_class(&app, &manager, json!({ "name": "9-A" })) | 1018 | + let class = create_class(&app, &manager, json!({ "name": "9-A", "grade_level": 9 })) |
| 1015 | .await | 1019 | .await |
| 1016 | .body["id"] | 1020 | .body["id"] |
| 1017 | .as_str() | 1021 | .as_str() |
| @@ -1023,7 +1027,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() { | |||
| 1023 | "PATCH", | 1027 | "PATCH", |
| 1024 | &format!("/classes/{class}"), | 1028 | &format!("/classes/{class}"), |
| 1025 | Some(&manager), | 1029 | Some(&manager), |
| 1026 | - Some(json!({ "name": "9-B", "teacher_id": bad })), | 1030 | + Some(json!({ "name": "9-B", "grade_level": 9, "teacher_id": bad })), |
| 1027 | ) | 1031 | ) |
| 1028 | .await; | 1032 | .await; |
| 1029 | assert_eq!(refused.status, StatusCode::BAD_REQUEST, "patch with {bad}"); | 1033 | 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() { | |||
| 1255 | let class = create_class( | 1259 | let class = create_class( |
| 1256 | &app, | 1260 | &app, |
| 1257 | &admin, | 1261 | &admin, |
| 1258 | - json!({ "name": "9-A", "teacher_id": teacher_id }), | 1262 | + json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id }), |
| 1259 | ) | 1263 | ) |
| 1260 | .await | 1264 | .await |
| 1261 | .body["id"] | 1265 | .body["id"] |
| @@ -1476,7 +1480,7 @@ async fn a_create_whose_teacher_is_demoted_mid_write_rolls_back_whole() { | |||
| 1476 | "POST", | 1480 | "POST", |
| 1477 | "/classes", | 1481 | "/classes", |
| 1478 | Some(&manager), | 1482 | Some(&manager), |
| 1479 | - Some(json!({ "name": "9-A", "teacher_id": teacher_id, "year": year })), | 1483 | + Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id, "year": year })), |
| 1480 | ) | 1484 | ) |
| 1481 | .await; | 1485 | .await; |
| 1482 | 1486 | ||
| @@ -1539,7 +1543,7 @@ async fn a_rolled_back_create_at_a_blueprinted_grade_leaves_nothing_behind() { | |||
| 1539 | "POST", | 1543 | "POST", |
| 1540 | "/classes/blueprints", | 1544 | "/classes/blueprints", |
| 1541 | Some(&manager), | 1545 | Some(&manager), |
| 1542 | - Some(json!({ "grade": "9", "course_ids": [course] })), | 1546 | + Some(json!({ "grade_level": 9, "course_ids": [course] })), |
| 1543 | ) | 1547 | ) |
| 1544 | .await; | 1548 | .await; |
| 1545 | assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); | 1549 | 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() { | |||
| 1550 | "POST", | 1554 | "POST", |
| 1551 | "/classes", | 1555 | "/classes", |
| 1552 | Some(&manager), | 1556 | Some(&manager), |
| 1553 | - Some(json!({ "name": "9-A", "grade": "9", "teacher_id": teacher_id })), | 1557 | + Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id })), |
| 1554 | ) | 1558 | ) |
| 1555 | .await; | 1559 | .await; |
| 1556 | 1560 | ||
| @@ -1580,7 +1584,7 @@ async fn a_patch_whose_teacher_is_demoted_mid_write_undoes_the_column() { | |||
| 1580 | let manager = login_as(&app, &db, "manager", "manager").await; | 1584 | let manager = login_as(&app, &db, "manager", "manager").await; |
| 1581 | let teacher = login_as(&app, &db, "teacher", "teacher").await; | 1585 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 1582 | let teacher_id = me_id(&app, &teacher).await; | 1586 | let teacher_id = me_id(&app, &teacher).await; |
| 1583 | - let class = create_class(&app, &manager, json!({ "name": "9-A" })) | 1587 | + let class = create_class(&app, &manager, json!({ "name": "9-A", "grade_level": 9 })) |
| 1584 | .await | 1588 | .await |
| 1585 | .body["id"] | 1589 | .body["id"] |
| 1586 | .as_str() | 1590 | .as_str() |
| @@ -1701,7 +1705,7 @@ async fn a_rollback_the_guard_refuses_is_a_500_not_a_lying_409() { | |||
| 1701 | "POST", | 1705 | "POST", |
| 1702 | "/classes", | 1706 | "/classes", |
| 1703 | Some(&manager), | 1707 | Some(&manager), |
| 1704 | - Some(json!({ "name": "9-A", "teacher_id": teacher_id })), | 1708 | + Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id })), |
| 1705 | ) | 1709 | ) |
| 1706 | .await; | 1710 | .await; |
| 1707 | 1711 | ||
| @@ -1737,23 +1741,25 @@ fn names(res: &Res) -> Vec<String> { | |||
| 1737 | .collect() | 1741 | .collect() |
| 1738 | } | 1742 | } |
| 1739 | 1743 | ||
| 1740 | -/// `?grade=` is the read a manager holding a blueprint's skip list needs: which | 1744 | +/// `?grade_level=` is the read a manager holding a blueprint's skip list |
| 1741 | -/// sections carry the label the pump keyed on. It is the *query's* `WHERE`, so | 1745 | +/// needs: which sections carry the rung the pump keyed on. It is the *query's* |
| 1742 | -/// `total` counts the filtered set and a window walks that set alone — drop the | 1746 | +/// `WHERE`, so `total` counts the filtered set and a window walks that set |
| 1743 | -/// predicate and every assertion below sees the unfiltered four instead. | 1747 | +/// alone — drop the predicate and every assertion below sees the unfiltered |
| 1748 | +/// four instead. | ||
| 1744 | #[tokio::test] | 1749 | #[tokio::test] |
| 1745 | async fn the_class_index_filters_by_grade() { | 1750 | async fn the_class_index_filters_by_grade() { |
| 1746 | let (app, db) = app_and_db().await; | 1751 | let (app, db) = app_and_db().await; |
| 1747 | let manager = login_as(&app, &db, "mgr", "manager").await; | 1752 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 1748 | - for (name, grade) in [ | 1753 | + for (name, grade_level) in [ |
| 1749 | - ("9-A", "9"), | 1754 | + ("9-A", 9), |
| 1750 | - ("9-B", "9"), | 1755 | + ("9-B", 9), |
| 1751 | - ("10-A", "10"), | 1756 | + ("10-A", 10), |
| 1752 | - // A club-shaped section: created with no grade at all, so its row | 1757 | + // A club-shaped section: created at the ladder's floor, like every |
| 1753 | - // carries no `grade` key. | 1758 | + // class — it just never shares a rung with an ordinary section here. |
| 1754 | - ("satranc", ""), | 1759 | + ("satranc", 0), |
| 1755 | ] { | 1760 | ] { |
| 1756 | - create_class(&app, &manager, json!({ "name": name, "grade": grade })).await; | 1761 | + create_class(&app, &manager, json!({ "name": name, "grade_level": grade_level })) |
| 1762 | + .await; | ||
| 1757 | } | 1763 | } |
| 1758 | let list = async |query: &str| -> Res { | 1764 | let list = async |query: &str| -> Res { |
| 1759 | let res = send( | 1765 | let res = send( |
| @@ -1778,14 +1784,16 @@ async fn the_class_index_filters_by_grade() { | |||
| 1778 | assert_eq!(total(&res.body), 4); | 1784 | assert_eq!(total(&res.body), 4); |
| 1779 | assert_eq!(names(&res).len(), 4); | 1785 | assert_eq!(names(&res).len(), 4); |
| 1780 | 1786 | ||
| 1781 | - // One label, matched exactly: both sections at it, and a `total` that | 1787 | + // One rung, matched exactly: both sections at it, and a `total` that |
| 1782 | // counts only them. | 1788 | // counts only them. |
| 1783 | - let res = list("?grade=9").await; | 1789 | + let res = list("?grade_level=9").await; |
| 1784 | assert_eq!(total(&res.body), 2, "total counts the filtered set"); | 1790 | assert_eq!(total(&res.body), 2, "total counts the filtered set"); |
| 1785 | assert_eq!(names(&res), ["9-B", "9-A"], "newest first, 9 only"); | 1791 | assert_eq!(names(&res), ["9-B", "9-A"], "newest first, 9 only"); |
| 1786 | - // "9" is not a prefix match, a fold, or a trim. | 1792 | + assert_eq!(names(&list("?grade_level=10").await), ["10-A"]); |
| 1787 | - assert_eq!(names(&list("?grade=10").await), ["10-A"]); | 1793 | + // Rungs nobody carries are empty pages, not errors — the integers leave |
| 1788 | - for miss in ["?grade=11", "?grade=%209", "?grade=9-A"] { | 1794 | + // no spelling games to play (an unparseable value like `anaokulu` never |
| 1795 | + // reaches the handler: the query decoder refuses it with a `400`). | ||
| 1796 | + for miss in ["?grade_level=11", "?grade_level=12"] { | ||
| 1789 | let res = list(miss).await; | 1797 | let res = list(miss).await; |
| 1790 | assert_eq!(total(&res.body), 0, "GET /classes{miss} total"); | 1798 | assert_eq!(total(&res.body), 0, "GET /classes{miss} total"); |
| 1791 | assert!( | 1799 | assert!( |
| @@ -1794,22 +1802,22 @@ async fn the_class_index_filters_by_grade() { | |||
| 1794 | ); | 1802 | ); |
| 1795 | } | 1803 | } |
| 1796 | 1804 | ||
| 1797 | - // Empty `?grade=` is *no* grade, the same reading `grade_or_none` gives a | 1805 | + // The floor is a rung like any other: it filters, it does not mean |
| 1798 | - // write — the sections a blueprint can never cover. | 1806 | + // "no grade" — no such class exists any more. |
| 1799 | - let res = list("?grade=").await; | 1807 | + let res = list("?grade_level=0").await; |
| 1800 | assert_eq!((total(&res.body), names(&res)), (1, vec!["satranc".into()])); | 1808 | assert_eq!((total(&res.body), names(&res)), (1, vec!["satranc".into()])); |
| 1801 | 1809 | ||
| 1802 | // Filter and window compose: the window is cut from the filtered set, and | 1810 | // Filter and window compose: the window is cut from the filtered set, and |
| 1803 | // `total` stays that set's size on every page of it. | 1811 | // `total` stays that set's size on every page of it. |
| 1804 | - let first = list("?grade=9&limit=1&offset=0").await; | 1812 | + let first = list("?grade_level=9&limit=1&offset=0").await; |
| 1805 | assert_eq!(total(&first.body), 2); | 1813 | assert_eq!(total(&first.body), 2); |
| 1806 | assert_eq!(names(&first), ["9-B"]); | 1814 | assert_eq!(names(&first), ["9-B"]); |
| 1807 | assert_eq!(first.body["limit"], 1); | 1815 | assert_eq!(first.body["limit"], 1); |
| 1808 | - let second = list("?grade=9&limit=1&offset=1").await; | 1816 | + let second = list("?grade_level=9&limit=1&offset=1").await; |
| 1809 | assert_eq!(total(&second.body), 2); | 1817 | assert_eq!(total(&second.body), 2); |
| 1810 | assert_eq!(names(&second), ["9-A"], "consecutive pages are disjoint"); | 1818 | assert_eq!(names(&second), ["9-A"], "consecutive pages are disjoint"); |
| 1811 | assert_eq!(second.body["offset"], 1); | 1819 | assert_eq!(second.body["offset"], 1); |
| 1812 | - let past = list("?grade=9&limit=1&offset=9").await; | 1820 | + let past = list("?grade_level=9&limit=1&offset=9").await; |
| 1813 | assert!(names(&past).is_empty(), "past the end is an empty page"); | 1821 | assert!(names(&past).is_empty(), "past the end is an empty page"); |
| 1814 | assert_eq!( | 1822 | assert_eq!( |
| 1815 | total(&past.body), | 1823 | total(&past.body), |
| @@ -1817,12 +1825,12 @@ async fn the_class_index_filters_by_grade() { | |||
| 1817 | "…with the filtered total still honest" | 1825 | "…with the filtered total still honest" |
| 1818 | ); | 1826 | ); |
| 1819 | 1827 | ||
| 1820 | - // A label the write paths would refuse is refused here too, rather than | 1828 | + // A rung the write paths would refuse is refused here too, rather than |
| 1821 | // reading as "no such grade". | 1829 | // reading as "no such grade". |
| 1822 | let res = send( | 1830 | let res = send( |
| 1823 | &app, | 1831 | &app, |
| 1824 | "GET", | 1832 | "GET", |
| 1825 | - &format!("/classes?grade={}", "9".repeat(21)), | 1833 | + "/classes?grade_level=13", |
| 1826 | Some(&manager), | 1834 | Some(&manager), |
| 1827 | None, | 1835 | None, |
| 1828 | ) | 1836 | ) |
| @@ -1862,7 +1870,7 @@ async fn a_member_exit_never_hands_a_row_to_a_class_that_is_gone() { | |||
| 1862 | &db, | 1870 | &db, |
| 1863 | &manager, | 1871 | &manager, |
| 1864 | ClassName::try_new(name).unwrap(), | 1872 | ClassName::try_new(name).unwrap(), |
| 1865 | - None, | 1873 | + GradeLevel::new(9).unwrap(), |
| 1866 | None, | 1874 | None, |
| 1867 | None, | 1875 | None, |
| 1868 | ) | 1876 | ) |
| @@ -1947,7 +1955,7 @@ async fn an_archived_year_freezes_every_class_write_and_no_read() { | |||
| 1947 | let class = create_class( | 1955 | let class = create_class( |
| 1948 | &app, | 1956 | &app, |
| 1949 | &manager, | 1957 | &manager, |
| 1950 | - json!({ "name": "9-A", "grade": "9", "year": year }), | 1958 | + json!({ "name": "9-A", "grade_level": 9, "year": year }), |
| 1951 | ) | 1959 | ) |
| 1952 | .await; | 1960 | .await; |
| 1953 | let class = common::id_of(&class.body); | 1961 | let class = common::id_of(&class.body); |
| @@ -1978,7 +1986,7 @@ async fn an_archived_year_freezes_every_class_write_and_no_read() { | |||
| 1978 | "POST", | 1986 | "POST", |
| 1979 | "/classes/blueprints", | 1987 | "/classes/blueprints", |
| 1980 | Some(&manager), | 1988 | Some(&manager), |
| 1981 | - Some(json!({ "grade": "9", "course_ids": [dated] })), | 1989 | + Some(json!({ "grade_level": 9, "course_ids": [dated] })), |
| 1982 | ) | 1990 | ) |
| 1983 | .await; | 1991 | .await; |
| 1984 | assert_eq!(blueprint.status, StatusCode::CREATED, "blueprint"); | 1992 | assert_eq!(blueprint.status, StatusCode::CREATED, "blueprint"); |
| @@ -1998,7 +2006,7 @@ async fn an_archived_year_freezes_every_class_write_and_no_read() { | |||
| 1998 | ( | 2006 | ( |
| 1999 | "PATCH", | 2007 | "PATCH", |
| 2000 | format!("/classes/{class}"), | 2008 | format!("/classes/{class}"), |
| 2001 | - Some(json!({ "name": "9-B" })), | 2009 | + Some(json!({ "name": "9-B", "grade_level": 9 })), |
| 2002 | ), | 2010 | ), |
| 2003 | ( | 2011 | ( |
| 2004 | "POST", | 2012 | "POST", |
| @@ -2082,7 +2090,7 @@ async fn an_archived_year_freezes_every_class_write_and_no_read() { | |||
| 2082 | "PATCH", | 2090 | "PATCH", |
| 2083 | &format!("/classes/{class}"), | 2091 | &format!("/classes/{class}"), |
| 2084 | Some(&manager), | 2092 | Some(&manager), |
| 2085 | - Some(json!({ "name": "9-B" })), | 2093 | + Some(json!({ "name": "9-B", "grade_level": 9 })), |
| 2086 | ) | 2094 | ) |
| 2087 | .await; | 2095 | .await; |
| 2088 | assert_eq!(patched.status, StatusCode::OK, "thawed: {:?}", patched.body); | 2096 | assert_eq!(patched.status, StatusCode::OK, "thawed: {:?}", patched.body); |
| @@ -2110,14 +2118,14 @@ async fn two_subeler_teaching_one_course_are_two_instances() { | |||
| 2110 | let a = create_class( | 2118 | let a = create_class( |
| 2111 | &app, | 2119 | &app, |
| 2112 | &manager, | 2120 | &manager, |
| 2113 | - json!({ "name": "5-A", "grade": "5", "year": year }), | 2121 | + json!({ "name": "5-A", "grade_level": 5, "year": year }), |
| 2114 | ) | 2122 | ) |
| 2115 | .await; | 2123 | .await; |
| 2116 | let a = common::id_of(&a.body); | 2124 | let a = common::id_of(&a.body); |
| 2117 | let b = create_class( | 2125 | let b = create_class( |
| 2118 | &app, | 2126 | &app, |
| 2119 | &manager, | 2127 | &manager, |
| 2120 | - json!({ "name": "5-B", "grade": "5", "year": year }), | 2128 | + json!({ "name": "5-B", "grade_level": 5, "year": year }), |
| 2121 | ) | 2129 | ) |
| 2122 | .await; | 2130 | .await; |
| 2123 | let b = common::id_of(&b.body); | 2131 | let b = common::id_of(&b.body); |
tests/regress_course_child_orphans.rsmodified+2 -1
| @@ -38,6 +38,7 @@ use hezarfen_backend::db::{ | |||
| 38 | use hezarfen_backend::domain::academic_year::AcademicYearName; | 38 | use hezarfen_backend::domain::academic_year::AcademicYearName; |
| 39 | use hezarfen_backend::domain::class_course::ClassCourseId; | 39 | use hezarfen_backend::domain::class_course::ClassCourseId; |
| 40 | use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName}; | 40 | use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName}; |
| 41 | +use hezarfen_backend::domain::grade::GradeLevel; | ||
| 41 | use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; | 42 | use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 42 | use hezarfen_backend::domain::course_note::{CourseNoteContent, CourseNoteTitle}; | 43 | use hezarfen_backend::domain::course_note::{CourseNoteContent, CourseNoteTitle}; |
| 43 | use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; | 44 | use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; |
| @@ -155,7 +156,7 @@ async fn fixture(db: &Database) -> Fixture { | |||
| 155 | db, | 156 | db, |
| 156 | &teacher, | 157 | &teacher, |
| 157 | ClassName::try_new("9-A").unwrap(), | 158 | ClassName::try_new("9-A").unwrap(), |
| 158 | - None, | 159 | + GradeLevel::new(9).unwrap(), |
| 159 | Some(year), | 160 | Some(year), |
| 160 | None, | 161 | None, |
| 161 | ) | 162 | ) |
tests/regress_event_class_audience.rsmodified+1 -1
| @@ -20,7 +20,7 @@ async fn create_class(app: &Router, cookie: &str, name: &str) -> String { | |||
| 20 | "POST", | 20 | "POST", |
| 21 | "/classes", | 21 | "/classes", |
| 22 | Some(cookie), | 22 | Some(cookie), |
| 23 | - Some(json!({"name": name})), | 23 | + Some(json!({"name": name, "grade_level": 9})), |
| 24 | ) | 24 | ) |
| 25 | .await; | 25 | .await; |
| 26 | assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); | 26 | assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); |
tests/regress_profile.rsmodified+4 -4
| @@ -932,7 +932,7 @@ async fn section() -> Section { | |||
| 932 | let student = login(&app, "kid").await; | 932 | let student = login(&app, "kid").await; |
| 933 | let student_id = me_id(&app, &student).await; | 933 | let student_id = me_id(&app, &student).await; |
| 934 | 934 | ||
| 935 | - let class = create_class(&app, &manager, "9-A", "9").await; | 935 | + let class = create_class(&app, &manager, "9-A", 9).await; |
| 936 | add_member(&app, &manager, &class, &student_id).await; | 936 | add_member(&app, &manager, &class, &student_id).await; |
| 937 | link_student(&app, &admin, &parent_id, &student_id).await; | 937 | link_student(&app, &admin, &parent_id, &student_id).await; |
| 938 | 938 | ||
| @@ -947,13 +947,13 @@ async fn section() -> Section { | |||
| 947 | } | 947 | } |
| 948 | } | 948 | } |
| 949 | 949 | ||
| 950 | -async fn create_class(app: &Router, manager: &str, name: &str, grade: &str) -> String { | 950 | +async fn create_class(app: &Router, manager: &str, name: &str, grade_level: i16) -> String { |
| 951 | let res = send( | 951 | let res = send( |
| 952 | app, | 952 | app, |
| 953 | "POST", | 953 | "POST", |
| 954 | "/classes", | 954 | "/classes", |
| 955 | Some(manager), | 955 | Some(manager), |
| 956 | - Some(json!({ "name": name, "grade": grade })), | 956 | + Some(json!({ "name": name, "grade_level": grade_level })), |
| 957 | ) | 957 | ) |
| 958 | .await; | 958 | .await; |
| 959 | assert_eq!( | 959 | assert_eq!( |
| @@ -1072,7 +1072,7 @@ async fn teacher_parent_manager_and_the_owner_still_read_the_class_block() { | |||
| 1072 | let mine = send(&s.app, "GET", "/users/me/profile", Some(&s.student), None).await; | 1072 | let mine = send(&s.app, "GET", "/users/me/profile", Some(&s.student), None).await; |
| 1073 | assert_eq!(mine.status, StatusCode::OK, "{}", mine.body); | 1073 | assert_eq!(mine.status, StatusCode::OK, "{}", mine.body); |
| 1074 | assert_eq!(mine.body["classes"][0]["name"], "9-A"); | 1074 | assert_eq!(mine.body["classes"][0]["name"], "9-A"); |
| 1075 | - assert_eq!(mine.body["classes"][0]["grade"], "9"); | 1075 | + assert_eq!(mine.body["classes"][0]["grade_level"], 9); |
| 1076 | } | 1076 | } |
| 1077 | 1077 | ||
| 1078 | /// `stats.classes` is the owner's true total, deliberately *not* the length of | 1078 | /// `stats.classes` is the owner's true total, deliberately *not* the length of |
tests/regress_review.rsmodified+10 -1
| @@ -21,7 +21,7 @@ mod common; | |||
| 21 | use axum::http::StatusCode; | 21 | use axum::http::StatusCode; |
| 22 | use common::{ | 22 | use common::{ |
| 23 | app_and_db, create_exam_with, create_subject, enroll, id_of, login, login_as, me_id, send, | 23 | app_and_db, create_exam_with, create_subject, enroll, id_of, login, login_as, me_id, send, |
| 24 | - taught_under, ABSENT_ID, | 24 | + select_instance_subject, taught_under, ABSENT_ID, |
| 25 | }; | 25 | }; |
| 26 | use serde_json::json; | 26 | use serde_json::json; |
| 27 | 27 | ||
| @@ -38,6 +38,10 @@ async fn review_hides_the_key_of_a_bank_question_live_under_another_sitting() { | |||
| 38 | 38 | ||
| 39 | let t = taught_under(&app, &mudur, &teacher, "maths").await; | 39 | let t = taught_under(&app, &mudur, &teacher, "maths").await; |
| 40 | let subject = create_subject(&app, &teacher, &t.course, "arithmetic").await; | 40 | let subject = create_subject(&app, &teacher, &t.course, "arithmetic").await; |
| 41 | + // The section only tags questions with topics it actually *teaches* — | ||
| 42 | + // the resolved set, not the bare course — so the fixture takes the topic | ||
| 43 | + // onto this section first. | ||
| 44 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 41 | enroll(&app, &teacher, &t.instance, &student_id).await; | 45 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 42 | 46 | ||
| 43 | // One template, instantiated into both exams below. | 47 | // One template, instantiated into both exams below. |
| @@ -226,6 +230,9 @@ async fn review_hides_a_question_banked_out_of_it_and_live_elsewhere() { | |||
| 226 | 230 | ||
| 227 | let t = taught_under(&app, &mudur, &teacher, "physics").await; | 231 | let t = taught_under(&app, &mudur, &teacher, "physics").await; |
| 228 | let subject = create_subject(&app, &teacher, &t.course, "optics").await; | 232 | let subject = create_subject(&app, &teacher, &t.course, "optics").await; |
| 233 | + // Same as above: the tag check reads the resolved syllabus, so the | ||
| 234 | + // fixture teaches the topic before tagging with it. | ||
| 235 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 229 | enroll(&app, &teacher, &t.instance, &student_id).await; | 236 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 230 | 237 | ||
| 231 | let exam = async |title: &str, review: bool| { | 238 | let exam = async |title: &str, review: bool| { |
| @@ -397,6 +404,7 @@ async fn a_retake_in_progress_closes_the_students_own_review_reads() { | |||
| 397 | 404 | ||
| 398 | let t = taught_under(&app, &mudur, &teacher, "biology").await; | 405 | let t = taught_under(&app, &mudur, &teacher, "biology").await; |
| 399 | let subject = create_subject(&app, &teacher, &t.course, "cells").await; | 406 | let subject = create_subject(&app, &teacher, &t.course, "cells").await; |
| 407 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 400 | enroll(&app, &teacher, &t.instance, &student_id).await; | 408 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 401 | let res = create_exam_with( | 409 | let res = create_exam_with( |
| 402 | &app, | 410 | &app, |
| @@ -494,6 +502,7 @@ async fn review_stays_shut_while_another_sitting_is_still_available() { | |||
| 494 | 502 | ||
| 495 | let t = taught_under(&app, &mudur, &teacher, "chemistry").await; | 503 | let t = taught_under(&app, &mudur, &teacher, "chemistry").await; |
| 496 | let subject = create_subject(&app, &teacher, &t.course, "bonds").await; | 504 | let subject = create_subject(&app, &teacher, &t.course, "bonds").await; |
| 505 | + select_instance_subject(&app, &teacher, &t.instance, &subject).await; | ||
| 497 | enroll(&app, &teacher, &t.instance, &student_id).await; | 506 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 498 | // Unlimited sittings: no amount of finishing exhausts them. | 507 | // Unlimited sittings: no amount of finishing exhausts them. |
| 499 | let res = create_exam_with( | 508 | let res = create_exam_with( |
tests/regress_role_sweep.rsmodified+2 -1
| @@ -24,6 +24,7 @@ use hezarfen_backend::database::Database; | |||
| 24 | use hezarfen_backend::db::enrollment; | 24 | use hezarfen_backend::db::enrollment; |
| 25 | use hezarfen_backend::domain::class_course::ClassCourseId; | 25 | use hezarfen_backend::domain::class_course::ClassCourseId; |
| 26 | use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName}; | 26 | use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName}; |
| 27 | +use hezarfen_backend::domain::grade::GradeLevel; | ||
| 27 | use hezarfen_backend::domain::event::EventId; | 28 | use hezarfen_backend::domain::event::EventId; |
| 28 | use hezarfen_backend::domain::role::Role; | 29 | use hezarfen_backend::domain::role::Role; |
| 29 | use hezarfen_backend::domain::timestamp::Timestamp; | 30 | use hezarfen_backend::domain::timestamp::Timestamp; |
| @@ -385,7 +386,7 @@ async fn a_class_named(name: &str, db: &Database) -> ClassGroupId { | |||
| 385 | db, | 386 | db, |
| 386 | &manager, | 387 | &manager, |
| 387 | ClassName::try_new(name).unwrap(), | 388 | ClassName::try_new(name).unwrap(), |
| 388 | - None, | 389 | + GradeLevel::new(9).unwrap(), |
| 389 | None, | 390 | None, |
| 390 | None, | 391 | None, |
| 391 | ) | 392 | ) |
tests/spec_bounds.rsmodified+87 -15
| @@ -422,15 +422,27 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | |||
| 422 | ), | 422 | ), |
| 423 | ( | 423 | ( |
| 424 | "CreateClass", | 424 | "CreateClass", |
| 425 | - "grade", | 425 | + "grade_level", |
| 426 | - "maxLength", | 426 | + "minimum", |
| 427 | - MAX_CLASS_GRADE_LEN as i64, | 427 | + MIN_GRADE_LEVEL as i64, |
| 428 | + ), | ||
| 429 | + ( | ||
| 430 | + "CreateClass", | ||
| 431 | + "grade_level", | ||
| 432 | + "maximum", | ||
| 433 | + MAX_GRADE_LEVEL as i64, | ||
| 428 | ), | 434 | ), |
| 429 | ( | 435 | ( |
| 430 | "CreateBlueprint", | 436 | "CreateBlueprint", |
| 431 | - "grade", | 437 | + "grade_level", |
| 432 | - "maxLength", | 438 | + "minimum", |
| 433 | - MAX_CLASS_GRADE_LEN as i64, | 439 | + MIN_GRADE_LEVEL as i64, |
| 440 | + ), | ||
| 441 | + ( | ||
| 442 | + "CreateBlueprint", | ||
| 443 | + "grade_level", | ||
| 444 | + "maximum", | ||
| 445 | + MAX_GRADE_LEVEL as i64, | ||
| 434 | ), | 446 | ), |
| 435 | ( | 447 | ( |
| 436 | "UpdateClass", | 448 | "UpdateClass", |
| @@ -440,9 +452,15 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | |||
| 440 | ), | 452 | ), |
| 441 | ( | 453 | ( |
| 442 | "UpdateClass", | 454 | "UpdateClass", |
| 443 | - "grade", | 455 | + "grade_level", |
| 444 | - "maxLength", | 456 | + "minimum", |
| 445 | - MAX_CLASS_GRADE_LEN as i64, | 457 | + MIN_GRADE_LEVEL as i64, |
| 458 | + ), | ||
| 459 | + ( | ||
| 460 | + "UpdateClass", | ||
| 461 | + "grade_level", | ||
| 462 | + "maximum", | ||
| 463 | + MAX_GRADE_LEVEL as i64, | ||
| 446 | ), | 464 | ), |
| 447 | ( | 465 | ( |
| 448 | "CreateExamInCourse", | 466 | "CreateExamInCourse", |
| @@ -735,6 +753,18 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | |||
| 735 | ), | 753 | ), |
| 736 | ("ExamKindDto", "weight", "minimum", MIN_EXAM_KIND_WEIGHT), | 754 | ("ExamKindDto", "weight", "minimum", MIN_EXAM_KIND_WEIGHT), |
| 737 | ("ExamKindDto", "weight", "maximum", MAX_EXAM_KIND_WEIGHT), | 755 | ("ExamKindDto", "weight", "maximum", MAX_EXAM_KIND_WEIGHT), |
| 756 | + ( | ||
| 757 | + "PatchExamWeight", | ||
| 758 | + "weight", | ||
| 759 | + "minimum", | ||
| 760 | + MIN_EXAM_KIND_WEIGHT, | ||
| 761 | + ), | ||
| 762 | + ( | ||
| 763 | + "PatchExamWeight", | ||
| 764 | + "weight", | ||
| 765 | + "maximum", | ||
| 766 | + MAX_EXAM_KIND_WEIGHT, | ||
| 767 | + ), | ||
| 738 | ("GradeBandDto", "min", "minimum", MIN_MARK), | 768 | ("GradeBandDto", "min", "minimum", MIN_MARK), |
| 739 | ("GradeBandDto", "min", "maximum", MAX_MARK), | 769 | ("GradeBandDto", "min", "maximum", MAX_MARK), |
| 740 | ( | 770 | ( |
| @@ -1121,8 +1151,8 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | |||
| 1121 | ), | 1151 | ), |
| 1122 | // --- academic years and the class×course instance (the K12 anchor) --- | 1152 | // --- academic years and the class×course instance (the K12 anchor) --- |
| 1123 | // A year is named like a term ("2026-2027"), so it shares the term | 1153 | // A year is named like a term ("2026-2027"), so it shares the term |
| 1124 | - // name's bound; its two grade labels are şube grades, bounded like | 1154 | + // name's bound; its two grade fields are şube rungs on the grade |
| 1125 | - // `CreateClass.grade`. | 1155 | + // ladder, bounded like `CreateClass.grade_level`. |
| 1126 | ( | 1156 | ( |
| 1127 | "CreateYear", | 1157 | "CreateYear", |
| 1128 | "name", | 1158 | "name", |
| @@ -1138,19 +1168,61 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | |||
| 1138 | ( | 1168 | ( |
| 1139 | "PromotionBody", | 1169 | "PromotionBody", |
| 1140 | "from_grade", | 1170 | "from_grade", |
| 1141 | - "maxLength", | 1171 | + "minimum", |
| 1142 | - MAX_CLASS_GRADE_LEN as i64, | 1172 | + MIN_GRADE_LEVEL as i64, |
| 1173 | + ), | ||
| 1174 | + ( | ||
| 1175 | + "PromotionBody", | ||
| 1176 | + "from_grade", | ||
| 1177 | + "maximum", | ||
| 1178 | + MAX_GRADE_LEVEL as i64, | ||
| 1143 | ), | 1179 | ), |
| 1144 | ( | 1180 | ( |
| 1145 | "PromotionBody", | 1181 | "PromotionBody", |
| 1146 | "to_grade", | 1182 | "to_grade", |
| 1147 | - "maxLength", | 1183 | + "minimum", |
| 1148 | - MAX_CLASS_GRADE_LEN as i64, | 1184 | + MIN_GRADE_LEVEL as i64, |
| 1185 | + ), | ||
| 1186 | + ( | ||
| 1187 | + "PromotionBody", | ||
| 1188 | + "to_grade", | ||
| 1189 | + "maximum", | ||
| 1190 | + MAX_GRADE_LEVEL as i64, | ||
| 1149 | ), | 1191 | ), |
| 1150 | // The instance's weekly hours: the karne weight, bounded so one | 1192 | // The instance's weekly hours: the karne weight, bounded so one |
| 1151 | // instance cannot be made to dominate the year average by a typo. | 1193 | // instance cannot be made to dominate the year average by a typo. |
| 1152 | ("UpdateInstance", "ders_saati", "minimum", MIN_DERS_SAATI), | 1194 | ("UpdateInstance", "ders_saati", "minimum", MIN_DERS_SAATI), |
| 1153 | ("UpdateInstance", "ders_saati", "maximum", MAX_DERS_SAATI), | 1195 | ("UpdateInstance", "ders_saati", "maximum", MAX_DERS_SAATI), |
| 1196 | + // The offering spine (course × grade_level templates) and the | ||
| 1197 | + // per-class instance overrides: same bounds as the catalog course | ||
| 1198 | + // they inherit from. | ||
| 1199 | + ("CreateOffering", "grade_level", "minimum", MIN_GRADE_LEVEL as i64), | ||
| 1200 | + ("CreateOffering", "grade_level", "maximum", MAX_GRADE_LEVEL as i64), | ||
| 1201 | + ("CreateOffering", "title", "maxLength", MAX_COURSE_TITLE_LEN as i64), | ||
| 1202 | + ( | ||
| 1203 | + "CreateOffering", | ||
| 1204 | + "description", | ||
| 1205 | + "maxLength", | ||
| 1206 | + MAX_COURSE_DESCRIPTION_LEN as i64, | ||
| 1207 | + ), | ||
| 1208 | + ("CreateOffering", "default_ders_saati", "minimum", MIN_DERS_SAATI), | ||
| 1209 | + ("CreateOffering", "default_ders_saati", "maximum", MAX_DERS_SAATI), | ||
| 1210 | + ("UpdateOffering", "title", "maxLength", MAX_COURSE_TITLE_LEN as i64), | ||
| 1211 | + ( | ||
| 1212 | + "UpdateOffering", | ||
| 1213 | + "description", | ||
| 1214 | + "maxLength", | ||
| 1215 | + MAX_COURSE_DESCRIPTION_LEN as i64, | ||
| 1216 | + ), | ||
| 1217 | + ("UpdateOffering", "default_ders_saati", "minimum", MIN_DERS_SAATI), | ||
| 1218 | + ("UpdateOffering", "default_ders_saati", "maximum", MAX_DERS_SAATI), | ||
| 1219 | + ("UpdateInstance", "title", "maxLength", MAX_COURSE_TITLE_LEN as i64), | ||
| 1220 | + ( | ||
| 1221 | + "UpdateInstance", | ||
| 1222 | + "description", | ||
| 1223 | + "maxLength", | ||
| 1224 | + MAX_COURSE_DESCRIPTION_LEN as i64, | ||
| 1225 | + ), | ||
| 1154 | ] | 1226 | ] |
| 1155 | } | 1227 | } |
| 1156 | 1228 | ||