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

class_course.rs863 lines, 35.5 KiBHistoryRawDownload
1//! Class-course workflows: the attach that maps the pump's refusals to this
2//! route's answers, the detach that turns a zero-row sweep into a 404, and the
3//! instance-scoped gates every route under `/instances` pays — the archived
4//! year and the D10 "who may act on this instance" rule. The transactions live
5//! in [`crate::db::class_pump`] and [`crate::db::class_course`].
6
7use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
8use crate::database::Database;
9use crate::db::class_course;
10use crate::db::class_pump::{self, Axis};
11use crate::domain::academic_year::AcademicYearId;
12use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati, OverrideField};
13use crate::domain::class_group::ClassGroupId;
14use crate::domain::course::{CourseDescription, CourseId, CourseTitle};
15use crate::domain::role::Role;
16use crate::domain::user::{User, UserId};
17use crate::error::{AppError, ValidationError};
18
19/// Attach `course` to `class` and enroll the class's whole roster into it,
20/// in one transaction.
21///
22/// Students already in the course keep the rows they have — no second
23/// enrollment written, `source` untouched — and the attach is one
24/// `class_course` row per (class, course): the instance every exam, session,
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.
29pub async fn attach(
30 db: &Database,
31 class: &ClassGroupId,
32 course: &CourseId,
33 attached_by: &UserId,
34) -> Result<ClassCourse, AppError> {
35 let landed = class_course::attach_sourced(db, class, course, attached_by, None).await?;
36 // Read off the refusal, never respelled here: this route and a
37 // blueprint pump answer one vocabulary. `Made` is the only `None`, and
38 // it takes the `Ok` arm below.
39 let code = landed.refusal_code(&Axis::Course).unwrap_or_default();
40 match landed {
41 class_pump::Attached::Made(saved) => Ok(saved),
42 class_pump::Attached::Duplicate => Err(AppError::ConflictCoded {
43 code,
44 message: "the course is already on this class".into(),
45 }),
46 // The class or the course: either end of the link being gone is a
47 // 404 on this route, and only a blueprint's skip list needs them
48 // told apart.
49 class_pump::Attached::Gone | class_pump::Attached::PivotGone => Err(AppError::NotFound),
50 class_pump::Attached::ClassFull => Err(AppError::ConflictCoded {
51 code,
52 message: format!("this class already holds {MAX_CLASS_COURSES} courses"),
53 }),
54 // The other axis: attaching one course enrolls the whole roster, so
55 // a class over *that* ceiling cannot take a course however few it
56 // carries. Only a class predating the ceiling can be here.
57 class_pump::Attached::ClassOverloaded => Err(AppError::ConflictCoded {
58 code,
59 message: format!(
60 "this class holds more than {MAX_CLASS_MEMBERS} students — \
61 remove some before attaching a course"
62 ),
63 }),
64 // Unreachable on this axis, and kept because the match is
65 // exhaustive: the pair loop enrolls the roster into `$pivot` and
66 // nothing else, and the pivot claim already proved *that* course
67 // alive inside the same transaction. Only a member add walks a
68 // class's existing course links, so `linked_course_missing` is that
69 // route's alone — which is why this route's `409` does not publish
70 // it. Left mapped rather than folded into an `Internal`, so a future
71 // axis change is a wrong-looking 409, not a 500.
72 class_pump::Attached::CourseGone(course) => Err(AppError::ConflictCoded {
73 code,
74 message: format!("{course} no longer exists — detach it from this class first"),
75 }),
76 // This path passes no source, so the claim that answers this is
77 // never in the transaction it ran.
78 class_pump::Attached::SourceGone => Err(AppError::Internal(
79 "a hand attach has no blueprint to lose".into(),
80 )),
81 }
82}
83
84/// Detach `course` from `class` and sweep the enrollments the class pumped
85/// into it. A course that was not attached is a [`AppError::NotFound`],
86/// raised here rather than left to each caller to re-derive from a boolean.
87///
88/// The instance is the anchor, so this takes everything the class taught under
89/// it — exams, sessions, homework, the roster and the teacher links (see
90/// [`class_pump::detach_course`]) — and answers the blob keys of the image and
91/// homework-file rows that cascade removed, so the route can unlink those files
92/// after the commit (the shape [`crate::service::course::delete`] already has).
93/// The rows are gone by the time this returns: a caller that drops the list
94/// leaves the bytes on disk with nothing pointing at them.
95///
96/// An empty list is *not* the refusal — an instance that carried no uploads
97/// detaches fine and simply has no files to unlink. Only a pair holding no
98/// instance at all is the 404.
99pub async fn detach(
100 db: &Database,
101 class: &ClassGroupId,
102 course: &CourseId,
103) -> Result<Vec<String>, AppError> {
104 class_pump::detach_course(db, class, course, None)
105 .await?
106 .ok_or(AppError::NotFound)
107}
108
109/// The courses a class is attached to, newest first, paged — the read behind
110/// `GET /classes/{id}/instances`.
111pub async fn list_for_class(
112 db: &Database,
113 class: &ClassGroupId,
114 limit: Option<i64>,
115 offset: i64,
116) -> Result<(Vec<ClassCourse>, i64), AppError> {
117 class_course::list_for_class(db, class, limit, offset).await
118}
119
120/// One instance, or `None` when the id names no row — the read behind
121/// `GET /instances/{id}`.
122pub async fn read(db: &Database, id: &ClassCourseId) -> Result<Option<ClassCourse>, AppError> {
123 class_course::read(db, id).await
124}
125
126/// PATCH one instance's own content overrides: title, description, the
127/// weekly hours and the report-card policy. Each `Some(_)` **sets** the
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`).
131pub async fn update(
132 db: &Database,
133 id: &ClassCourseId,
134 title: Option<CourseTitle>,
135 description: Option<CourseDescription>,
136 staff: Option<DersSaati>,
137 counts: Option<bool>,
138) -> Result<ClassCourse, AppError> {
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)]
154pub struct InstancePolicy {
155 pub ders_saati: DersSaati,
156 pub counts_toward_karne: bool,
157}
158
159pub 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.
189pub 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.
206pub 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 }
221}
222
223/// The academic year this instance sits under, if any — the seam every
224/// instance-scoped write reads the archive gate off (instance → section →
225/// year).
226pub async fn year_of(
227 db: &Database,
228 instance: &ClassCourseId,
229) -> Result<Option<AcademicYearId>, AppError> {
230 let Some(class) = class_course::class_of(db, instance).await? else {
231 return Ok(None);
232 };
233 Ok(crate::db::class_group::read(db, &class)
234 .await?
235 .and_then(|class| class.get_year().copied()))
236}
237
238/// Refuse the write when the instance's year is archived — past years are
239/// read-only. A pre-flight guard, accepted race (see README concurrency
240/// model): a year archived after this read still lets the write through.
241///
242/// A class section with no year, or one whose year row is gone, passes: a
243/// dangling link is not this guard's error, and the caller that cares answers
244/// it.
245pub async fn require_open(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> {
246 if let Some(year) = year_of(db, instance).await? {
247 crate::service::academic_year::require_open(db, &year).await?;
248 }
249 Ok(())
250}
251
252/// Assign `target` to teach this instance, on `by`'s orders.
253///
254/// The target must already hold the `teacher` role or higher — assignment
255/// hands out the rights every instance-scoped gate re-checks against that bar,
256/// so assigning anyone below it would write a row that can never be used —
257/// and the caller `by` must hold `manager`+: staffing is the office's call,
258/// stated here so it holds for every caller of this workflow and not only for
259/// the route that remembers to extract it. Assignment is idempotent, and a
260/// past year is read-only: staffing an archived year's instance is refused
261/// like every other write against it.
262pub async fn assign_teacher(
263 db: &Database,
264 instance: &ClassCourseId,
265 target: &UserId,
266 by: &UserId,
267) -> Result<(), AppError> {
268 let Some(actor) = crate::db::user::read(db, by).await? else {
269 return Err(AppError::Unauthorized);
270 };
271 if !actor.get_role().at_least(Role::Manager) {
272 return Err(AppError::Forbidden(
273 "assigning a teacher is the office's call — manager role or higher",
274 ));
275 }
276 let Some(target_user) = crate::db::user::read(db, target).await? else {
277 return Err(AppError::Validation(ValidationError::Invalid {
278 field: "user_id",
279 reason: "target user does not exist",
280 }));
281 };
282 if !target_user.get_role().at_least(Role::Teacher) {
283 return Err(AppError::Validation(ValidationError::Invalid {
284 field: "user_id",
285 reason: "target user must hold the teacher role or higher",
286 }));
287 }
288 require_open(db, instance).await?;
289 crate::db::class_course_teacher::assign(db, instance, target).await?;
290 Ok(())
291}
292
293/// Drop `target` from this instance's teachers: read-only in a past year, like
294/// every other write against archived structure. `false` when they were not
295/// assigned to it, so the web layer can answer 404 instead of pretending it
296/// removed someone.
297pub async fn unassign_teacher(
298 db: &Database,
299 instance: &ClassCourseId,
300 target: &UserId,
301) -> Result<bool, AppError> {
302 require_open(db, instance).await?;
303 crate::db::class_course_teacher::unassign(db, instance, target).await
304}
305
306/// A 403 unless `user` may act on this instance — D10, the one gate every
307/// instance-scoped route shares in place of a `class_course_teacher` lookup of
308/// its own. It passes when the user is `manager`+ (the office), when they are
309/// one of the instance's assigned teachers, or when they are the section's
310/// homeroom teacher — the three ways a person legitimately runs a section's
311/// course.
312///
313/// A gone instance is a `404`, never a 403: the route the user asked about
314/// does not exist.
315pub async fn ensure_instance_teacher(
316 db: &Database,
317 user: &User,
318 instance: &ClassCourseId,
319) -> Result<(), AppError> {
320 if user.get_role().at_least(Role::Manager) {
321 return Ok(());
322 }
323 let Some(class) = class_course::class_of(db, instance).await? else {
324 return Err(AppError::NotFound);
325 };
326 // Both ways in below are an *assignment*, and an assignment is history:
327 // the caller's live role decides, exactly as it does on the catalog path
328 // ([`crate::web::courses::can_manage_course`]). The demotion cascade
329 // sweeps the assignment table and the homeroom column only when it runs
330 // with the role write, so a flip that skipped it would otherwise leave a
331 // student running the section they were stripped of.
332 if user.get_role().at_least(Role::Teacher)
333 && (crate::db::class_course_teacher::list_for_instance(db, instance)
334 .await?
335 .contains(user.get_id())
336 || crate::db::class_group::read(db, &class)
337 .await?
338 .and_then(|class| class.get_teacher().copied())
339 .as_ref()
340 == Some(user.get_id()))
341 {
342 return Ok(());
343 }
344 Err(AppError::Forbidden(
345 "only this instance's teachers, its class's homeroom teacher, or a manager may act here",
346 ))
347}
348
349#[cfg(test)]
350mod tests {
351 use super::*;
352 use crate::constant::MIN_DERS_SAATI;
353 use crate::db::class_group;
354 use crate::db::class_member::tests::{
355 a_class, a_course, counter, course_exists, link_exists, rows, source_of,
356 };
357 use crate::domain::user::Username;
358 use crate::service::class_member;
359
360 /// The stored user row, for the gates that judge a live role.
361 async fn user_of(db: &Database, id: &UserId) -> User {
362 crate::db::user::read(db, id).await.unwrap().unwrap()
363 }
364
365 /// A real account at a role — the D10 gates judge the live row, so a
366 /// fixture id would not do.
367 async fn staff(db: &Database, username: &str, role: Role) -> UserId {
368 let account = crate::db::user::create(db, Username::try_new(username).unwrap(), None)
369 .await
370 .unwrap();
371 crate::service::user::set_role(db, account.get_id(), role)
372 .await
373 .unwrap();
374 *account.get_id()
375 }
376
377 /// Attaching mints the instance, seeds it from the roster the class already
378 /// holds, and refuses a second attach of the same pair.
379 #[tokio::test]
380 async fn an_attach_enrolls_the_whole_roster_into_the_new_instance() {
381 let (db, _leases) = crate::database::init_test_db().await;
382 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
383 let class = a_class("9-A", &db).await;
384 let algebra = a_course("algebra", &db).await;
385 let students = [
386 crate::db::class_member::tests::fixture_user(&db, "a").await,
387 crate::db::class_member::tests::fixture_user(&db, "b").await,
388 ];
389 for student in &students {
390 class_member::add(&db, &class, student, &manager)
391 .await
392 .unwrap();
393 }
394
395 let instance = attach(&db, &class, &algebra, &manager).await.unwrap();
396 for student in &students {
397 assert_eq!(
398 source_of(instance.get_id(), student, &db).await,
399 Some(Some(class.clone()))
400 );
401 }
402 assert_eq!(
403 counter("enrollment_count", instance.get_id().uuid(), &db).await,
404 2
405 );
406 assert_eq!(counter("class_course_count", class.uuid(), &db).await, 1);
407
408 let again = attach(&db, &class, &algebra, &manager).await;
409 assert!(
410 matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"),
411 "a second attach is a 409 coded `duplicate`: {again:?}"
412 );
413 }
414
415 /// Two class sections teaching one catalog course are two instances — that
416 /// is the whole remodel — and each keeps its own roster.
417 #[tokio::test]
418 async fn two_classes_teaching_one_course_keep_their_own_rosters() {
419 let (db, _leases) = crate::database::init_test_db().await;
420 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
421 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
422 let algebra = a_course("algebra", &db).await;
423 let fifth_a = a_class("5-A", &db).await;
424 let fifth_b = a_class("5-B", &db).await;
425
426 let first = attach(&db, &fifth_a, &algebra, &manager).await.unwrap();
427 let second = attach(&db, &fifth_b, &algebra, &manager).await.unwrap();
428 assert_ne!(
429 first.get_id(),
430 second.get_id(),
431 "one catalog course, one instance per şube"
432 );
433
434 class_member::add(&db, &fifth_a, &student, &manager)
435 .await
436 .unwrap();
437 assert_eq!(
438 source_of(first.get_id(), &student, &db).await,
439 Some(Some(fifth_a.clone())),
440 "5-A's student lands in 5-A's instance"
441 );
442 assert_eq!(
443 source_of(second.get_id(), &student, &db).await,
444 None,
445 "…and nowhere near 5-B's"
446 );
447
448 // Detaching one class section takes its instance and its roster; the
449 // other section's instance and roster stand.
450 detach(&db, &fifth_a, &algebra).await.unwrap();
451 assert_eq!(source_of(first.get_id(), &student, &db).await, None);
452 assert_eq!(
453 source_of(second.get_id(), &student, &db).await,
454 None,
455 "5-B's instance was never enrolled either"
456 );
457 assert_eq!(
458 counter("class_course_count", fifth_b.uuid(), &db).await,
459 1,
460 "the other şube keeps its instance"
461 );
462 assert_eq!(
463 counter("class_member_count", fifth_a.uuid(), &db).await,
464 1,
465 "the two axes are independent: dropping the course keeps the roster"
466 );
467 }
468
469 /// A hand-placed row is never adopted: the pump skips it, and a member
470 /// exit leaves it standing because it carries no class `source`. The
471 /// detach is the other story: it takes the whole instance subtree, and a
472 /// hand row lives on that instance like any other.
473 #[tokio::test]
474 async fn a_hand_placed_row_is_never_adopted_by_the_class() {
475 let (db, _leases) = crate::database::init_test_db().await;
476 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
477 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
478 let class = a_class("9-A", &db).await;
479 let algebra = a_course("algebra", &db).await;
480 let instance = attach(&db, &class, &algebra, &manager).await.unwrap();
481 crate::db::enrollment::enroll(&db, instance.get_id(), &student, &manager, None)
482 .await
483 .unwrap();
484 class_member::add(&db, &class, &student, &manager)
485 .await
486 .unwrap();
487
488 assert_eq!(
489 source_of(instance.get_id(), &student, &db).await,
490 Some(None),
491 "the pump may not adopt a hand-placed row"
492 );
493 assert_eq!(
494 counter("enrollment_count", instance.get_id().uuid(), &db).await,
495 1,
496 "…nor count it twice"
497 );
498
499 class_member::leave(&db, &class, &student).await.unwrap();
500 assert_eq!(
501 source_of(instance.get_id(), &student, &db).await,
502 Some(None),
503 "the member sweep may only take back the rows the class wrote"
504 );
505 assert_eq!(
506 counter("enrollment_count", instance.get_id().uuid(), &db).await,
507 1
508 );
509
510 detach(&db, &class, &algebra).await.unwrap();
511 assert_eq!(
512 source_of(instance.get_id(), &student, &db).await,
513 None,
514 "the detach takes the instance and every row on it"
515 );
516 let again = detach(&db, &class, &algebra).await;
517 assert!(
518 matches!(again, Err(AppError::NotFound)),
519 "a second detach is a 404: {again:?}"
520 );
521 }
522
523 /// Detaching sweeps the rows the class pumped, and only those: the
524 /// membership row is a separate axis and stays.
525 #[tokio::test]
526 async fn a_detach_sweeps_the_rows_it_pumped() {
527 let (db, _leases) = crate::database::init_test_db().await;
528 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
529 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
530 let class = a_class("9-A", &db).await;
531 let algebra = a_course("algebra", &db).await;
532 class_member::add(&db, &class, &student, &manager)
533 .await
534 .unwrap();
535 let instance = attach(&db, &class, &algebra, &manager).await.unwrap();
536
537 detach(&db, &class, &algebra).await.unwrap();
538 assert_eq!(source_of(instance.get_id(), &student, &db).await, None);
539 assert_eq!(rows("enrollment", &db).await, 0);
540 assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0);
541 assert_eq!(
542 rows("class_member", &db).await,
543 1,
544 "the two axes are independent: dropping the course may not drop \
545 the student out of the class as well"
546 );
547 }
548
549 /// The attach of an empty class leaves the new instance's counter at zero —
550 /// nothing to enroll, nothing charged.
551 #[tokio::test]
552 async fn the_attach_of_an_empty_roster_charges_no_seat() {
553 let (db, _leases) = crate::database::init_test_db().await;
554 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
555 let class = a_class("9-A", &db).await;
556 let algebra = a_course("algebra", &db).await;
557 let instance = attach(&db, &class, &algebra, &manager).await.unwrap();
558 assert_eq!(
559 counter("enrollment_count", instance.get_id().uuid(), &db).await,
560 0,
561 "a fresh instance's roster counter is zero"
562 );
563 }
564
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.
568 #[tokio::test]
569 async fn an_update_writes_only_the_fields_it_carried() {
570 let (db, _leases) = crate::database::init_test_db().await;
571 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
572 let class = a_class("9-A", &db).await;
573 let algebra = a_course("algebra", &db).await;
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);
582
583 let updated = update(
584 &db,
585 instance.get_id(),
586 Some(CourseTitle::try_new("9-A Matematik").unwrap()),
587 None,
588 Some(DersSaati::try_new(5).unwrap()),
589 None,
590 )
591 .await
592 .unwrap();
593 assert_eq!(
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!(
599 updated.counts_toward_karne(),
600 None,
601 "the omitted field keeps its stored value"
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);
606
607 let again = update(
608 &db,
609 instance.get_id(),
610 None,
611 None,
612 None,
613 Some(false),
614 )
615 .await
616 .unwrap();
617 assert_eq!(again.counts_toward_karne(), Some(false));
618 assert_eq!(
619 again.get_ders_saati().map(DersSaati::as_i64),
620 Some(5),
621 "…and the other direction holds too"
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 );
647 }
648
649 /// D10: the instance's own teacher, the section's homeroom teacher and a
650 /// manager may act on it; another instance's teacher and a plain student
651 /// may not. Assignment itself is the office's call and the assignee must
652 /// hold the teacher bar.
653 #[tokio::test]
654 async fn the_instance_gate_admits_its_teachers_homeroom_and_managers() {
655 let (db, _leases) = crate::database::init_test_db().await;
656 let manager = staff(&db, "mudur", Role::Manager).await;
657 let assigned = staff(&db, "ayse", Role::Teacher).await;
658 let outsider = staff(&db, "mehmet", Role::Teacher).await;
659 let homeroom = staff(&db, "zeynep", Role::Teacher).await;
660 let student = crate::db::class_member::tests::fixture_user(&db, "ogrenci").await;
661 let algebra = a_course("algebra", &db).await;
662 let class = class_group::create(
663 &db,
664 &manager,
665 crate::domain::class_group::ClassName::try_new("9-A").unwrap(),
666 crate::domain::grade::GradeLevel::new(9).unwrap(),
667 None,
668 Some(homeroom),
669 )
670 .await
671 .unwrap();
672 let instance = attach(&db, &class.get_id().clone(), &algebra, &manager)
673 .await
674 .unwrap();
675
676 assign_teacher(&db, instance.get_id(), &assigned, &manager)
677 .await
678 .unwrap();
679 // Idempotent, like every other assignment.
680 assign_teacher(&db, instance.get_id(), &assigned, &manager)
681 .await
682 .unwrap();
683
684 assert!(
685 ensure_instance_teacher(&db, &user_of(&db, &manager).await, instance.get_id())
686 .await
687 .is_ok()
688 );
689 assert!(
690 ensure_instance_teacher(&db, &user_of(&db, &assigned).await, instance.get_id())
691 .await
692 .is_ok()
693 );
694 assert!(
695 ensure_instance_teacher(&db, &user_of(&db, &homeroom).await, instance.get_id())
696 .await
697 .is_ok()
698 );
699 assert!(
700 ensure_instance_teacher(&db, &user_of(&db, &outsider).await, instance.get_id())
701 .await
702 .is_err(),
703 "a teacher of another instance is not this one's"
704 );
705 assert!(
706 ensure_instance_teacher(&db, &user_of(&db, &student).await, instance.get_id())
707 .await
708 .is_err()
709 );
710
711 // A student cannot be made an instance's teacher, and a non-manager
712 // cannot assign one.
713 let refused = assign_teacher(&db, instance.get_id(), &student, &manager).await;
714 assert!(
715 matches!(refused, Err(AppError::Validation(_))),
716 "a student is not a teacher: {refused:?}"
717 );
718 let refused = assign_teacher(&db, instance.get_id(), &assigned, &outsider).await;
719 assert!(
720 matches!(refused, Err(AppError::Forbidden(_))),
721 "staffing is the office's call: {refused:?}"
722 );
723 }
724
725 /// The `Menu::delete` defect on the class layer: a `class_course` row must
726 /// not outlive the course it names. The attach's proof that the course is
727 /// still there lands on the very row `Course::delete`'s guard locks, so
728 /// whatever the interleaving, a link row and a deleted course can never
729 /// both stand.
730 ///
731 /// Both orders are forced. Delete-first awaits the delete, then the
732 /// attach: the course is gone and no link may appear. Attach-first awaits
733 /// the attach, then the delete: a course a class still teaches must
734 /// refuse, not 500, and the course stays. A 2ms head start does not force
735 /// that under pool contention. Overlapped rounds may all lose the delete;
736 /// that is not a failure.
737 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
738 async fn a_class_course_link_never_outlives_the_course() {
739 let (db, _leases) = crate::database::init_test_db().await;
740 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
741
742 // Delete-first: nothing may attach to a course that is already gone.
743 {
744 let class = a_class("9-df", &db).await;
745 let algebra = a_course("algebra-df", &db).await;
746 let course = crate::db::course::read(&db, &algebra)
747 .await
748 .unwrap()
749 .unwrap();
750 let dropped = crate::db::course::delete(&db, course).await;
751 assert!(
752 matches!(dropped, Ok(true)),
753 "delete-first: an empty course must delete, not {dropped:?}"
754 );
755 assert!(
756 !course_exists(&algebra, &db).await,
757 "delete-first: the course is still there"
758 );
759 let child = attach(&db, &class, &algebra, &manager).await;
760 assert!(
761 !matches!(child, Err(AppError::Db(_))),
762 "delete-first: an attach must be answered, not 500: {child:?}"
763 );
764 assert!(
765 !link_exists(&class, &algebra, &db).await,
766 "a class_course link outlived its course"
767 );
768 assert_eq!(
769 counter("class_course_count", class.uuid(), &db).await,
770 0,
771 "a class counts a course that is gone"
772 );
773 }
774
775 // Attach-first: the guard must refuse. Parent stays; that is the
776 // verdict, not a missed sweep.
777 {
778 let class = a_class("9-wf", &db).await;
779 let algebra = a_course("algebra-wf", &db).await;
780 let course = crate::db::course::read(&db, &algebra)
781 .await
782 .unwrap()
783 .unwrap();
784 let child = attach(&db, &class, &algebra, &manager).await;
785 assert!(
786 child.is_ok(),
787 "attach-first: the attach must land before the delete: {child:?}"
788 );
789 let dropped = crate::db::course::delete(&db, course).await;
790 assert!(
791 !matches!(dropped, Err(AppError::Db(_))),
792 "attach-first: a delete must be answered, not 500: {dropped:?}"
793 );
794 assert!(
795 matches!(dropped, Ok(false)),
796 "attach-first: a course a class still teaches must refuse, not {dropped:?}"
797 );
798 assert!(
799 course_exists(&algebra, &db).await,
800 "attach-first: the refused delete removed the course"
801 );
802 assert!(
803 link_exists(&class, &algebra, &db).await,
804 "attach-first: the landed link is gone"
805 );
806 }
807
808 // Overlapped rounds. Delete may lose every one of them.
809 let mut swept = 0;
810 for round in 0..4 {
811 let class = a_class(&format!("9-{round}"), &db).await;
812 let algebra = a_course(&format!("algebra{round}"), &db).await;
813 let course = crate::db::course::read(&db, &algebra)
814 .await
815 .unwrap()
816 .unwrap();
817
818 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
819 let drop_it = {
820 let (db, gate, course) = (db.clone(), gate.clone(), course);
821 tokio::spawn(async move {
822 gate.wait().await;
823 crate::db::course::delete(&db, course).await
824 })
825 };
826 let child = {
827 let (db, class, algebra, manager, gate) =
828 (db.clone(), class.clone(), algebra.clone(), manager, gate);
829 tokio::spawn(async move {
830 gate.wait().await;
831 attach(&db, &class, &algebra, &manager).await
832 })
833 };
834 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
835 assert!(
836 !matches!(child, Err(AppError::Db(_))),
837 "round {round}: a raced attach must be answered, not 500: {child:?}"
838 );
839 assert!(
840 !matches!(drop_it, Err(AppError::Db(_))),
841 "round {round}: a raced delete must be answered, not 500: {drop_it:?}"
842 );
843
844 if !course_exists(&algebra, &db).await {
845 swept += 1;
846 assert!(
847 !link_exists(&class, &algebra, &db).await,
848 "round {round}: a class_course link outlived its course"
849 );
850 assert_eq!(
851 counter("class_course_count", class.uuid(), &db).await,
852 0,
853 "round {round}: a class counts a course that is gone"
854 );
855 } else if matches!(drop_it, Ok(true)) {
856 panic!("round {round}: the delete reported success but the course is still there");
857 }
858 }
859 eprintln!(
860 "Course::delete raced by an attach: {swept}/4 concurrent rounds deleted the course"
861 );
862 }
863}