forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

offering_subject.rs470 lines, 17.9 KiBHistoryRawDownload
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
15use crate::database::Database;
16use crate::domain::class_course::ClassCourse;
17use crate::domain::course::CourseId;
18use crate::domain::course_offering::CourseOfferingId;
19use crate::domain::offering_subject::ensure_course_member;
20use crate::domain::subject::{Subject, SubjectId};
21use crate::error::{AppError, ValidationError};
22use crate::{db, service};
23
24/// The topics the grade-level template selects, name-then-id order — the
25/// inheritance side of [`resolved_for_instance`].
26pub 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.
36pub 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.
52pub 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.
73async 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).
91pub 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.
107pub 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).
128pub 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.
148pub 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).
169pub 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.
180pub fn subject_key(key: &str) -> SubjectId {
181 SubjectId::from_key(key)
182}
183
184#[cfg(test)]
185mod 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}