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

regress_classes.rs2449 lines, 83.2 KiBHistoryRawDownload
1//! Regressions for the class section (şube) layer, its enrollment side, and the sweep a
2//! role change runs. Every test here pins a defect that shipped: a link left
3//! pointing at a deleted course, the refusal that misnamed it, a hand enroll a
4//! class could still undo, and the two-transaction role sweep.
5
6mod common;
7
8use axum::http::StatusCode;
9use common::{
10 ABSENT_ID, GHOST_ID, Res, add_member, app_and_db, attach_instance, create_course, create_exam,
11 create_term, create_year, items, login_as, me_id, send, taught, total,
12};
13use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
14use hezarfen_backend::database::Database;
15use hezarfen_backend::domain::class_group::ClassName;
16use hezarfen_backend::domain::grade::GradeLevel;
17use hezarfen_backend::domain::course::CourseId;
18use hezarfen_backend::domain::user::UserId;
19use hezarfen_backend::error::AppError;
20use hezarfen_backend::service::{class_course, class_group, class_member};
21use serde_json::json;
22use sqlx::Row as _;
23
24/// The instance id out of a `POST /classes/{id}/instances` response — the
25/// anchor every roster, exam and detach under that attachment keys on.
26fn instance_of(res: &Res) -> String {
27 res.body["id"].as_str().expect("instance id").to_string()
28}
29
30/// One counter, re-read out of the store — never off a response body. `sql`
31/// is a whole scalar query; each call spells the aggregate it asserts on.
32async fn counter(sql: &'static str, db: &Database) -> i64 {
33 sqlx::query_scalar(sql).fetch_one(db).await.unwrap()
34}
35
36/// How many rows `sql` counts.
37async fn rows(sql: &'static str, db: &Database) -> i64 {
38 counter(sql, db).await
39}
40
41/// A real `app_user` row for the fixture actor or member a domain call must
42/// name: the actor and member columns are foreign keys now, so they are rows,
43/// not fabricated ids. The username is unique, so every call for the same name
44/// shares one row, whichever call minted it. These rows never log in, so the
45/// hash is a stub.
46async fn fixture_user(db: &Database, username: &str) -> UserId {
47 sqlx::query(
48 "INSERT INTO app_user (id, username, created_at, role) \
49 VALUES ($1, $2, 0, 'student') ON CONFLICT DO NOTHING",
50 )
51 .bind(UserId::generate().uuid())
52 .bind(username)
53 .execute(db)
54 .await
55 .unwrap();
56 let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1")
57 .bind(username)
58 .fetch_one(db)
59 .await
60 .unwrap()
61 .try_get(0)
62 .unwrap();
63 UserId::from_key(&id.to_string())
64}
65
66/// Delete a row the way a racing write that lost would have left it: the row
67/// gone, its referring rows untouched. Real FKs refuse that state, so the
68/// delete is forced the one way Postgres allows: FK triggers suspended for the
69/// one transaction.
70async fn wipe_row(table: &str, id: uuid::Uuid, db: &Database) {
71 let mut tx = db.begin().await.unwrap();
72 sqlx::query("SET LOCAL session_replication_role = replica")
73 .execute(&mut *tx)
74 .await
75 .unwrap();
76 sqlx::query(sqlx::AssertSqlSafe(format!(
77 "DELETE FROM {table} WHERE id = $1"
78 )))
79 .bind(id)
80 .execute(&mut *tx)
81 .await
82 .unwrap();
83 tx.commit().await.unwrap();
84}
85
86/// Delete a course row the way a *concurrent* `DELETE /courses/{id}` racing an
87/// attach leaves the store: the row goes, the `class_course` link it never saw
88/// stays. The real cascade sweeps those links, so this is the only way to reach
89/// the state from a test — and the state the pump's in-transaction claim exists
90/// to make unreachable in the first place.
91async fn wipe_course_row(course: &str, db: &Database) {
92 wipe_row(
93 "course",
94 uuid::Uuid::parse_str(course).expect("a uuid course id"),
95 db,
96 )
97 .await;
98}
99
100/// B1(a). A class with *zero* members makes the pump's pair loop empty, so the
101/// attach transaction touched no row a concurrent course delete wrote and
102/// SurrealDB's write-skew let both commit — a `class_course` row pointing at a
103/// course that does not exist. The pivot claim is what makes that impossible.
104#[tokio::test]
105async fn an_attach_onto_a_deleted_course_writes_no_link() {
106 let (_app, db) = app_and_db().await;
107 let manager = fixture_user(&db, "manager").await;
108 let class = class_group::create(
109 &db,
110 &manager,
111 ClassName::try_new("9-A").unwrap(),
112 GradeLevel::new(9).unwrap(),
113 None,
114 None,
115 )
116 .await
117 .unwrap();
118 // A course id nothing ever created: the same row a delete that won the race
119 // leaves behind.
120 let ghost = CourseId::from_key(GHOST_ID);
121
122 let refused = class_course::attach(&db, class.get_id(), &ghost, &manager).await;
123 assert!(
124 refused.is_err(),
125 "attaching a course that is gone must be refused: {refused:?}"
126 );
127 assert_eq!(
128 rows("SELECT count(*) FROM class_course", &db).await,
129 0,
130 "no link row may point at a course that does not exist"
131 );
132 assert_eq!(
133 counter(
134 "SELECT COALESCE(sum(class_course_count), 0)::bigint FROM class_group",
135 &db
136 )
137 .await,
138 0,
139 "…and the class must not count one either, or it is undeletable forever"
140 );
141}
142
143/// B1(b). The other half: a link that *did* land that way must still be
144/// removable. The detach keys on the link row itself (`DELETE
145/// /classes/{c}/instances/{instance}`), so a course that vanished under it is
146/// still swept — a route that read the course first would answer 404 forever
147/// and leave the class 409 forever, over an attachment nothing could sweep.
148#[tokio::test]
149async fn a_stale_link_detaches_and_frees_its_class() {
150 let (app, db) = app_and_db().await;
151 let manager = login_as(&app, &db, "manager", "manager").await;
152 let course = create_course(&app, &manager, "algebra").await;
153 let class = {
154 let res = send(
155 &app,
156 "POST",
157 "/classes",
158 Some(&manager),
159 Some(json!({ "name": "9-A", "grade_level": 9 })),
160 )
161 .await;
162 assert_eq!(res.status, StatusCode::CREATED);
163 res.body["class"]["id"].as_str().unwrap().to_string()
164 };
165 let attached = send(
166 &app,
167 "POST",
168 &format!("/classes/{class}/instances"),
169 Some(&manager),
170 Some(json!({ "course_id": course })),
171 )
172 .await;
173 assert_eq!(attached.status, StatusCode::CREATED);
174 let instance = instance_of(&attached);
175 // The course row goes the way a concurrent `DELETE /courses/{id}` racing
176 // the attach would leave it: gone, the link it never saw still standing.
177 wipe_course_row(&course, &db).await;
178
179 let detached = send(
180 &app,
181 "DELETE",
182 &format!("/classes/{class}/instances/{instance}"),
183 Some(&manager),
184 None,
185 )
186 .await;
187 assert_eq!(
188 detached.status,
189 StatusCode::NO_CONTENT,
190 "a link whose course is gone must still detach: {:?}",
191 detached.body
192 );
193 let deleted = send(
194 &app,
195 "DELETE",
196 &format!("/classes/{class}"),
197 Some(&manager),
198 None,
199 )
200 .await;
201 assert_eq!(
202 deleted.status,
203 StatusCode::NO_CONTENT,
204 "…and the class it blocked must be deletable again: {:?}",
205 deleted.body
206 );
207
208 // An instance that is no longer attached is still a 404 — the guard that
209 // turns "sweep the stale link" into "delete anything" is the link row, not
210 // the course row.
211 let again = send(
212 &app,
213 "DELETE",
214 &format!("/classes/{class}/instances/{instance}"),
215 Some(&manager),
216 None,
217 )
218 .await;
219 assert_eq!(again.status, StatusCode::NOT_FOUND);
220}
221
222/// B2. A class whose link names a catalog row that is gone — the state a
223/// `DELETE /courses/{id}` racing the attach leaves behind — must not lock the
224/// operator out. The pump's pairs are `(instance, user)` and never read the
225/// catalog row, so the add lands and the student is enrolled; the stale link
226/// then sweeps through its *own* route (the link row is the guard, never the
227/// course row), and the class is deletable again once its roster has left.
228#[tokio::test]
229async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() {
230 let (app, db) = app_and_db().await;
231 let manager = login_as(&app, &db, "manager", "manager").await;
232 let student = login_as(&app, &db, "student", "student").await;
233 let student_id = me_id(&app, &student).await;
234 let course = create_course(&app, &manager, "algebra").await;
235 let class = {
236 let res = send(
237 &app,
238 "POST",
239 "/classes",
240 Some(&manager),
241 Some(json!({ "name": "9-A", "grade_level": 9 })),
242 )
243 .await;
244 res.body["class"]["id"].as_str().unwrap().to_string()
245 };
246 let attached = send(
247 &app,
248 "POST",
249 &format!("/classes/{class}/instances"),
250 Some(&manager),
251 Some(json!({ "course_id": course })),
252 )
253 .await;
254 assert_eq!(attached.status, StatusCode::CREATED);
255 let instance = instance_of(&attached);
256 wipe_course_row(&course, &db).await;
257
258 let added = send(
259 &app,
260 "POST",
261 &format!("/classes/{class}/members"),
262 Some(&manager),
263 Some(json!({ "user_id": student_id })),
264 )
265 .await;
266 assert_eq!(
267 added.status,
268 StatusCode::CREATED,
269 "a link whose course is gone must not lock the roster: {:?}",
270 added.body
271 );
272 // The student is on the instance's roster, tagged with the şube that
273 // pumped them: what the pump names is the instance, and the catalog row
274 // the link points at is not part of that pair.
275 let roster = send(
276 &app,
277 "GET",
278 &format!("/instances/{instance}/enrollments"),
279 Some(&manager),
280 None,
281 )
282 .await;
283 assert_eq!(roster.status, StatusCode::OK, "{:?}", roster.body);
284 assert_eq!(
285 total(&roster.body),
286 1,
287 "the pump enrolled the student: {:?}",
288 roster.body
289 );
290 assert_eq!(items(&roster.body)[0]["user"]["id"], json!(student_id));
291 assert_eq!(items(&roster.body)[0]["source"], json!(class));
292
293 // The stale link detaches through its own route, and the class is free
294 // once the roster has left it.
295 let detached = send(
296 &app,
297 "DELETE",
298 &format!("/classes/{class}/instances/{instance}"),
299 Some(&manager),
300 None,
301 )
302 .await;
303 assert_eq!(
304 detached.status,
305 StatusCode::NO_CONTENT,
306 "{:?}",
307 detached.body
308 );
309 let left = send(
310 &app,
311 "DELETE",
312 &format!("/classes/{class}/members/{student_id}"),
313 Some(&manager),
314 None,
315 )
316 .await;
317 assert_eq!(left.status, StatusCode::NO_CONTENT, "{:?}", left.body);
318 let deleted = send(
319 &app,
320 "DELETE",
321 &format!("/classes/{class}"),
322 Some(&manager),
323 None,
324 )
325 .await;
326 assert_eq!(
327 deleted.status,
328 StatusCode::NO_CONTENT,
329 "…and the class the stale link blocked is deletable again: {:?}",
330 deleted.body
331 );
332 assert_eq!(
333 rows("SELECT count(*) FROM class_member", &db).await,
334 0,
335 "the şube delete takes its roster history with it"
336 );
337 assert_eq!(
338 rows("SELECT count(*) FROM enrollment", &db).await,
339 0,
340 "…and the instance's roster went with the detach"
341 );
342 assert_eq!(
343 counter(
344 "SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM class_course",
345 &db
346 )
347 .await,
348 0,
349 "…with each instance's seat counter"
350 );
351}
352
353/// B3. A hand enroll over a row a class pumped must take the row off the class,
354/// or the next sweep unenrolls a student an operator placed on purpose —
355/// the mirror of the manual unenroll that a class may never undo.
356#[tokio::test]
357async fn a_hand_enroll_takes_the_row_off_the_class() {
358 let (app, db) = app_and_db().await;
359 let manager = login_as(&app, &db, "manager", "manager").await;
360 let student = login_as(&app, &db, "student", "student").await;
361 let student_id = me_id(&app, &student).await;
362 let course = create_course(&app, &manager, "algebra").await;
363 let class = {
364 let res = send(
365 &app,
366 "POST",
367 "/classes",
368 Some(&manager),
369 Some(json!({ "name": "9-A", "grade_level": 9 })),
370 )
371 .await;
372 res.body["class"]["id"].as_str().unwrap().to_string()
373 };
374 let attached = send(
375 &app,
376 "POST",
377 &format!("/classes/{class}/instances"),
378 Some(&manager),
379 Some(json!({ "course_id": course })),
380 )
381 .await;
382 assert_eq!(attached.status, StatusCode::CREATED);
383 let instance = instance_of(&attached);
384 let added = send(
385 &app,
386 "POST",
387 &format!("/classes/{class}/members"),
388 Some(&manager),
389 Some(json!({ "user_id": student_id })),
390 )
391 .await;
392 assert_eq!(added.status, StatusCode::CREATED);
393
394 // The pumped row names its class, and says so on the wire — a client that
395 // cannot see `source` cannot tell which of its roster rows is sweepable.
396 let roster = send(
397 &app,
398 "GET",
399 &format!("/instances/{instance}/enrollments"),
400 Some(&manager),
401 None,
402 )
403 .await;
404 assert_eq!(roster.body["items"][0]["source"], json!(class));
405
406 let by_hand = send(
407 &app,
408 "POST",
409 &format!("/instances/{instance}/enrollments"),
410 Some(&manager),
411 Some(json!({ "user_id": student_id })),
412 )
413 .await;
414 assert_eq!(by_hand.status, StatusCode::OK);
415 assert_eq!(
416 by_hand.body["source"],
417 json!(null),
418 "a hand enroll must take the row off the class"
419 );
420 assert_eq!(
421 rows(
422 "SELECT count(*) FROM enrollment WHERE source IS NOT NULL",
423 &db
424 )
425 .await,
426 0,
427 "…in the stored row, not just the response"
428 );
429
430 // Which is the whole point: the class letting the student go now leaves the
431 // hand-placed row standing, with its seat still counted.
432 let removed = send(
433 &app,
434 "DELETE",
435 &format!("/classes/{class}/members/{student_id}"),
436 Some(&manager),
437 None,
438 )
439 .await;
440 assert_eq!(removed.status, StatusCode::NO_CONTENT);
441 assert_eq!(
442 rows("SELECT count(*) FROM enrollment", &db).await,
443 1,
444 "the class may not unenroll a student an operator enrolled by hand"
445 );
446 assert_eq!(
447 counter(
448 "SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM class_course",
449 &db
450 )
451 .await,
452 1,
453 "…and the seat it never paid for may not be released"
454 );
455}
456
457/// B5. The role sweep is one transaction over both tables. Pinned end to end:
458/// a promotion leaves no membership, no enrollment and no counter behind, so
459/// the class is deletable and no row is left tagged with it. (The half-apply
460/// itself needs a crash between two statements, which no test can schedule —
461/// this pins the state the fold must always land in.)
462#[tokio::test]
463async fn a_role_change_sweeps_memberships_and_enrollments_together() {
464 let (app, db) = app_and_db().await;
465 let admin = login_as(&app, &db, "patron", "admin").await;
466 let manager = login_as(&app, &db, "manager", "manager").await;
467 let student = login_as(&app, &db, "student", "student").await;
468 let student_id = me_id(&app, &student).await;
469 let course = create_course(&app, &manager, "algebra").await;
470 let class = {
471 let res = send(
472 &app,
473 "POST",
474 "/classes",
475 Some(&manager),
476 Some(json!({ "name": "9-A", "grade_level": 9 })),
477 )
478 .await;
479 res.body["class"]["id"].as_str().unwrap().to_string()
480 };
481 let attached = send(
482 &app,
483 "POST",
484 &format!("/classes/{class}/instances"),
485 Some(&manager),
486 Some(json!({ "course_id": course })),
487 )
488 .await;
489 assert_eq!(attached.status, StatusCode::CREATED);
490 let instance = instance_of(&attached);
491 send(
492 &app,
493 "POST",
494 &format!("/classes/{class}/members"),
495 Some(&manager),
496 Some(json!({ "user_id": student_id })),
497 )
498 .await;
499 assert_eq!(rows("SELECT count(*) FROM enrollment", &db).await, 1);
500
501 let promoted = send(
502 &app,
503 "PATCH",
504 &format!("/users/{student_id}/role"),
505 Some(&admin),
506 Some(json!({ "role": "teacher" })),
507 )
508 .await;
509 assert_eq!(promoted.status, StatusCode::OK);
510
511 assert_eq!(
512 rows(
513 "SELECT count(*) FROM class_member WHERE left_at IS NULL",
514 &db
515 )
516 .await,
517 0,
518 "a non-student holds no live stint; the history row is what a soft \
519 leave keeps"
520 );
521 assert_eq!(
522 rows("SELECT count(*) FROM enrollment", &db).await,
523 0,
524 "a non-student holds no roster row, whoever wrote it"
525 );
526 assert_eq!(
527 counter(
528 "SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM class_course",
529 &db
530 )
531 .await,
532 0,
533 "the seat comes back exactly once"
534 );
535 assert_eq!(
536 counter(
537 "SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group",
538 &db
539 )
540 .await,
541 0
542 );
543 // Nothing is left tagged with the class, so letting it go strands nothing.
544 let detached = send(
545 &app,
546 "DELETE",
547 &format!("/classes/{class}/instances/{instance}"),
548 Some(&manager),
549 None,
550 )
551 .await;
552 assert_eq!(detached.status, StatusCode::NO_CONTENT);
553 let deleted = send(
554 &app,
555 "DELETE",
556 &format!("/classes/{class}"),
557 Some(&manager),
558 None,
559 )
560 .await;
561 assert_eq!(deleted.status, StatusCode::NO_CONTENT);
562}
563
564/// D1. Both link tables key on the *pair* (`<class>_<user>`), so the
565/// documented "newest first" was implemented as `ORDER BY id DESC` — which
566/// sorts the roster by the member's account ULID, an order that has nothing to
567/// do with when anyone was added. The three students here are added in an order
568/// their ids do not reproduce, so id-ordering and stamp-ordering disagree.
569#[tokio::test]
570async fn a_roster_is_ordered_by_when_a_student_was_added() {
571 let (_app, db) = app_and_db().await;
572 let manager = fixture_user(&db, "manager").await;
573 let class = class_group::create(
574 &db,
575 &manager,
576 ClassName::try_new("9-A").unwrap(),
577 GradeLevel::new(9).unwrap(),
578 None,
579 None,
580 )
581 .await
582 .unwrap()
583 .get_id()
584 .clone();
585
586 // Members added in an order no id ordering reproduces: only a real stamp
587 // can tell the two apart. The waits are what keep the stamps distinct —
588 // a tie falls back to the id, which is the very order under test. The
589 // minted rows carry uuid ids, so the assertions read back through the
590 // name -> id map.
591 let mut names: Vec<(&str, UserId)> = Vec::new();
592 for key in ["a", "c", "b"] {
593 let member = fixture_user(&db, key).await;
594 class_member::add(&db, &class, &member, &manager)
595 .await
596 .unwrap();
597 names.push((key, member));
598 tokio::time::sleep(std::time::Duration::from_millis(2)).await;
599 }
600 let name_of = |id: &UserId| {
601 names
602 .iter()
603 .find(|(_, mid)| mid == id)
604 .map(|(k, _)| *k)
605 .unwrap()
606 };
607
608 let (roster, _) = class_member::list_for_class(&db, &class, None, 0)
609 .await
610 .unwrap();
611 let order: Vec<&str> = roster
612 .iter()
613 .map(|member| name_of(member.get_user()))
614 .collect();
615 assert_eq!(
616 order,
617 vec!["b", "c", "a"],
618 "the roster must come back newest-added first, not sorted by account id"
619 );
620
621 // A row whose age nobody knows: the shipped `joined_at` is `NOT NULL`
622 // since the K12 remodel (a stint is minted with a stamp, always), so
623 // "no stamp at all" is unrepresentable — the oldest stamp there is *is*
624 // the unknown age. It sorts last under DESC, which is what makes such a
625 // row read as the oldest rather than an invented number putting it
626 // anywhere else.
627 sqlx::query(
628 "UPDATE class_member SET joined_at = 0
629 WHERE app_user = (SELECT id FROM app_user WHERE username = 'c')",
630 )
631 .execute(&db)
632 .await
633 .unwrap();
634 let (roster, _) = class_member::list_for_class(&db, &class, None, 0)
635 .await
636 .unwrap();
637 assert_eq!(
638 roster
639 .iter()
640 .map(|member| name_of(member.get_user()))
641 .collect::<Vec<_>>(),
642 vec!["b", "a", "c"],
643 "a row of unknown age must sort oldest, not first"
644 );
645}
646
647/// D1, the other axis: the course list had the same defect, ordered by the
648/// *course's* ULID.
649#[tokio::test]
650async fn a_class_course_list_is_ordered_by_when_it_was_attached() {
651 let (app, db) = app_and_db().await;
652 let manager_cookie = login_as(&app, &db, "manager", "manager").await;
653 let manager = UserId::from_key(&me_id(&app, &manager_cookie).await);
654 let class = class_group::create(
655 &db,
656 &manager,
657 ClassName::try_new("9-A").unwrap(),
658 GradeLevel::new(9).unwrap(),
659 None,
660 None,
661 )
662 .await
663 .unwrap()
664 .get_id()
665 .clone();
666
667 // Course ids rise with creation (monotonic mint); attaching them
668 // back-to-front makes id order and attach order disagree.
669 let mut courses = Vec::new();
670 for title in ["first", "second", "third"] {
671 courses.push(CourseId::from_key(
672 &create_course(&app, &manager_cookie, title).await,
673 ));
674 }
675 for course in courses.iter().rev() {
676 class_course::attach(&db, &class, course, &manager)
677 .await
678 .unwrap();
679 tokio::time::sleep(std::time::Duration::from_millis(2)).await;
680 }
681
682 let (attached, _) = class_course::list_for_class(&db, &class, None, 0)
683 .await
684 .unwrap();
685 let order: Vec<String> = attached
686 .iter()
687 .map(|link| link.get_course().key())
688 .collect();
689 assert_eq!(
690 order,
691 courses.iter().map(|c| c.key()).collect::<Vec<_>>(),
692 "the list must come back newest-attached first, not sorted by course id"
693 );
694}
695
696/// D2. Attaching a course writes one enrollment per member and adding a member
697/// writes one per attached course, both in a *single* transaction — with no
698/// class-size ceiling anywhere, that transaction was unbounded. The counter's
699/// claim now carries the bound, so the refusal happens before the loop runs.
700///
701/// The counter is seeded rather than filled by 200 real adds: it *is* the gate
702/// the claim reads, and the boundary is what is under test, not the 199 adds
703/// that lead up to it.
704#[tokio::test]
705async fn a_class_refuses_the_member_past_its_ceiling() {
706 let (_app, db) = app_and_db().await;
707 let manager = fixture_user(&db, "manager").await;
708 let class = class_group::create(
709 &db,
710 &manager,
711 ClassName::try_new("9-A").unwrap(),
712 GradeLevel::new(9).unwrap(),
713 None,
714 None,
715 )
716 .await
717 .unwrap()
718 .get_id()
719 .clone();
720 sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2")
721 .bind(MAX_CLASS_MEMBERS - 1)
722 .bind(class.clone())
723 .execute(&db)
724 .await
725 .unwrap();
726
727 let last = fixture_user(&db, "last").await;
728 class_member::add(&db, &class, &last, &manager)
729 .await
730 .expect("the place under the ceiling is still free");
731 let over = fixture_user(&db, "over").await;
732 let refused = class_member::add(&db, &class, &over, &manager).await;
733 assert!(
734 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
735 if code == "class_at_roster_ceiling"
736 && message.contains(&MAX_CLASS_MEMBERS.to_string())),
737 "a full class is a 409 naming its ceiling and coded, never a 404, and the code \
738 must name the ceiling the prose does — the roster, not the course list: {refused:?}"
739 );
740 assert_eq!(
741 counter(
742 "SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group",
743 &db
744 )
745 .await,
746 MAX_CLASS_MEMBERS,
747 "a refused add may not tick the counter past the cap"
748 );
749 assert_eq!(rows("SELECT count(*) FROM class_member", &db).await, 1);
750
751 // And the refusal a *deleted* class earns must stay a 404: both come out of
752 // the same counter claim matching nothing, and only one of them is a
753 // ceiling anybody can make room under.
754 wipe_row("class_group", class.uuid(), &db).await;
755 let ghost = fixture_user(&db, "ghost").await;
756 let gone = class_member::add(&db, &class, &ghost, &manager).await;
757 assert!(
758 matches!(gone, Err(AppError::NotFound)),
759 "a class that is gone is a 404: {gone:?}"
760 );
761}
762
763/// The ceilings bind the axis being *added*, and the transaction they bound is
764/// the length of the *other* one — so a class that already stands above a
765/// ceiling walked straight past both. The class layer shipped before either
766/// number existed, so a real volume can hold a 300-strong class, and attaching
767/// one course to it wrote 300 enrollments in a single transaction: exactly the
768/// unbounded write `MAX_CLASS_MEMBERS` was added to make impossible. The attach
769/// now refuses on the other axis too, and says which one.
770///
771/// The counter is seeded rather than filled by 201 real adds: it *is* what the
772/// pump reads, and it is what a stale class carries.
773#[tokio::test]
774async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
775 let (app, db) = app_and_db().await;
776 let cookie = login_as(&app, &db, "manager", "manager").await;
777 let manager = UserId::from_key(&me_id(&app, &cookie).await);
778 let class = class_group::create(
779 &db,
780 &manager,
781 ClassName::try_new("9-A").unwrap(),
782 GradeLevel::new(9).unwrap(),
783 None,
784 None,
785 )
786 .await
787 .unwrap()
788 .get_id()
789 .clone();
790 let algebra = CourseId::from_key(&create_course(&app, &cookie, "algebra").await);
791 sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2")
792 .bind(MAX_CLASS_MEMBERS + 1)
793 .bind(class.clone())
794 .execute(&db)
795 .await
796 .unwrap();
797
798 let refused = class_course::attach(&db, &class, &algebra, &manager).await;
799 assert!(
800 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
801 if code == "class_roster_too_large"
802 && message.contains(&MAX_CLASS_MEMBERS.to_string())),
803 "the refusal must name the axis that is over, not the one with room: {refused:?}"
804 );
805 assert_eq!(
806 rows("SELECT count(*) FROM class_course", &db).await,
807 0,
808 "a refused attach may not leave the link behind"
809 );
810 assert_eq!(
811 counter(
812 "SELECT COALESCE(sum(class_course_count), 0)::bigint FROM class_group",
813 &db
814 )
815 .await,
816 0,
817 "…nor tick the axis it was refused on"
818 );
819
820 // Back under the ceiling, the very same attach goes through: the refusal is
821 // the standing count, not the class.
822 sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2")
823 .bind(MAX_CLASS_MEMBERS)
824 .bind(class.clone())
825 .execute(&db)
826 .await
827 .unwrap();
828 class_course::attach(&db, &class, &algebra, &manager)
829 .await
830 .expect("a class exactly at the ceiling is still a bounded transaction");
831}
832
833/// The mirror: a class carrying more courses than `MAX_CLASS_COURSES` takes no
834/// new member, because adding one enrolls them into every attached course.
835#[tokio::test]
836async fn a_class_over_the_course_ceiling_takes_no_member() {
837 let (_app, db) = app_and_db().await;
838 let manager = fixture_user(&db, "manager").await;
839 let class = class_group::create(
840 &db,
841 &manager,
842 ClassName::try_new("9-B").unwrap(),
843 GradeLevel::new(9).unwrap(),
844 None,
845 None,
846 )
847 .await
848 .unwrap()
849 .get_id()
850 .clone();
851 sqlx::query("UPDATE class_group SET class_course_count = $1 WHERE id = $2")
852 .bind(MAX_CLASS_COURSES + 1)
853 .bind(class.clone())
854 .execute(&db)
855 .await
856 .unwrap();
857
858 let ali = fixture_user(&db, "ali").await;
859 let refused = class_member::add(&db, &class, &ali, &manager).await;
860 assert!(
861 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
862 if code == "class_course_list_too_large"
863 && message.contains(&MAX_CLASS_COURSES.to_string())),
864 "the refusal must name the courses, not the roster — in its code as well as \
865 its prose: {refused:?}"
866 );
867 assert_eq!(rows("SELECT count(*) FROM class_member", &db).await, 0);
868 assert_eq!(
869 counter(
870 "SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group",
871 &db
872 )
873 .await,
874 0
875 );
876}
877
878// ---- homeroom teacher (sınıf öğretmeni) ------------------------------------
879
880/// Create a class as `cookie` (asserts 201); returns the response with its
881/// `body` narrowed to the created class — the `201` is
882/// `{class, skipped, stocked_from}` since a create stocks from its grade's
883/// blueprint, and the tests below are about the class itself. The two outer
884/// fields have their own tests (`regress_blueprints`).
885async 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 }
889 let mut res = send(app, "POST", "/classes", Some(cookie), Some(body)).await;
890 assert_eq!(res.status, StatusCode::CREATED, "create class");
891 res.body = res.body["class"].clone();
892 res
893}
894
895/// The `teacher` block of `GET /classes/{id}`, straight out of the store's own
896/// read path — never off the write's response body.
897async fn stored_teacher(app: &axum::Router, cookie: &str, class: &str) -> serde_json::Value {
898 let res = send(app, "GET", &format!("/classes/{class}"), Some(cookie), None).await;
899 assert_eq!(res.status, StatusCode::OK, "GET /classes/{class}");
900 res.body["teacher"].clone()
901}
902
903/// The whole write contract for the homeroom teacher over HTTP: set at create,
904/// re-set and cleared by PATCH (both `null` and `""`), and — the one a
905/// whole-row save would break — untouched by a PATCH of another field. The
906/// response always names the person, never a bare id.
907#[tokio::test]
908async fn the_homeroom_teacher_round_trips_through_create_and_patch() {
909 let (app, db) = app_and_db().await;
910 let manager = login_as(&app, &db, "manager", "manager").await;
911 let teacher = login_as(&app, &db, "teacher", "teacher").await;
912 let other = login_as(&app, &db, "other", "teacher").await;
913 let teacher_id = me_id(&app, &teacher).await;
914 let other_id = me_id(&app, &other).await;
915
916 let created = create_class(
917 &app,
918 &manager,
919 json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id }),
920 )
921 .await;
922 let class = created.body["id"].as_str().unwrap().to_string();
923 assert_eq!(created.body["teacher"]["id"], json!(teacher_id));
924 assert_eq!(
925 created.body["teacher"]["username"],
926 json!("teacher"),
927 "the response must name the teacher, not echo an id"
928 );
929 assert_eq!(
930 stored_teacher(&app, &manager, &class).await["id"],
931 json!(teacher_id)
932 );
933
934 // A name-only PATCH must leave the teacher exactly where it is.
935 let renamed = send(
936 &app,
937 "PATCH",
938 &format!("/classes/{class}"),
939 Some(&manager),
940 Some(json!({ "name": "9-B", "grade_level": 9 })),
941 )
942 .await;
943 assert_eq!(renamed.status, StatusCode::OK);
944 assert_eq!(renamed.body["teacher"]["id"], json!(teacher_id));
945 assert_eq!(
946 stored_teacher(&app, &manager, &class).await["id"],
947 json!(teacher_id)
948 );
949
950 // …and a teacher-only PATCH must leave the name alone.
951 let moved = send(
952 &app,
953 "PATCH",
954 &format!("/classes/{class}"),
955 Some(&manager),
956 Some(json!({ "teacher_id": other_id })),
957 )
958 .await;
959 assert_eq!(moved.status, StatusCode::OK);
960 assert_eq!(moved.body["name"], json!("9-B"));
961 assert_eq!(moved.body["teacher"]["id"], json!(other_id));
962
963 // Both spellings of "no teacher" land on the same stored row.
964 for clear in [json!(null), json!("")] {
965 send(
966 &app,
967 "PATCH",
968 &format!("/classes/{class}"),
969 Some(&manager),
970 Some(json!({ "teacher_id": other_id })),
971 )
972 .await;
973 let cleared = send(
974 &app,
975 "PATCH",
976 &format!("/classes/{class}"),
977 Some(&manager),
978 Some(json!({ "teacher_id": clear })),
979 )
980 .await;
981 assert_eq!(cleared.status, StatusCode::OK, "clearing with {clear}");
982 assert_eq!(
983 cleared.body["teacher"],
984 json!(null),
985 "clearing with {clear}"
986 );
987 assert_eq!(stored_teacher(&app, &manager, &class).await, json!(null));
988 }
989}
990
991/// A student is not staff: naming one as the homeroom teacher is a `400` on
992/// both write paths, and so is an id that names nobody at all.
993#[tokio::test]
994async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() {
995 let (app, db) = app_and_db().await;
996 let manager = login_as(&app, &db, "manager", "manager").await;
997 let student = login_as(&app, &db, "ali", "student").await;
998 let student_id = me_id(&app, &student).await;
999 let ghost = GHOST_ID;
1000
1001 for bad in [student_id.as_str(), ghost] {
1002 let refused = send(
1003 &app,
1004 "POST",
1005 "/classes",
1006 Some(&manager),
1007 Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": bad })),
1008 )
1009 .await;
1010 assert_eq!(refused.status, StatusCode::BAD_REQUEST, "create with {bad}");
1011 }
1012 assert_eq!(
1013 rows("SELECT count(*) FROM class_group", &db).await,
1014 0,
1015 "a refused create may write no class"
1016 );
1017
1018 let class = create_class(&app, &manager, json!({ "name": "9-A", "grade_level": 9 }))
1019 .await
1020 .body["id"]
1021 .as_str()
1022 .unwrap()
1023 .to_string();
1024 for bad in [student_id.as_str(), ghost] {
1025 let refused = send(
1026 &app,
1027 "PATCH",
1028 &format!("/classes/{class}"),
1029 Some(&manager),
1030 Some(json!({ "name": "9-B", "grade_level": 9, "teacher_id": bad })),
1031 )
1032 .await;
1033 assert_eq!(refused.status, StatusCode::BAD_REQUEST, "patch with {bad}");
1034 }
1035 // The refused PATCH carried a name too — it must not have landed either.
1036 let stored = send(
1037 &app,
1038 "GET",
1039 &format!("/classes/{class}"),
1040 Some(&manager),
1041 None,
1042 )
1043 .await;
1044 assert_eq!(stored.body["name"], json!("9-A"));
1045 assert_eq!(stored.body["teacher"], json!(null));
1046}
1047
1048/// End-to-end demotion: `PATCH /users/{id}/role` down to `student` clears that
1049/// account off every class it homeroomed, and off nobody else's — a demoted
1050/// user may hold no section.
1051#[tokio::test]
1052async fn a_demotion_clears_the_homeroom_teacher_everywhere() {
1053 let (app, db) = app_and_db().await;
1054 let admin = login_as(&app, &db, "mudur", "admin").await;
1055 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1056 let keeper = login_as(&app, &db, "keeper", "teacher").await;
1057 let teacher_id = me_id(&app, &teacher).await;
1058 let keeper_id = me_id(&app, &keeper).await;
1059
1060 let mut held = Vec::new();
1061 for name in ["9-A", "9-B"] {
1062 held.push(
1063 create_class(
1064 &app,
1065 &admin,
1066 json!({ "name": name, "teacher_id": teacher_id }),
1067 )
1068 .await
1069 .body["id"]
1070 .as_str()
1071 .unwrap()
1072 .to_string(),
1073 );
1074 }
1075 let untouched = create_class(
1076 &app,
1077 &admin,
1078 json!({ "name": "10-A", "teacher_id": keeper_id }),
1079 )
1080 .await
1081 .body["id"]
1082 .as_str()
1083 .unwrap()
1084 .to_string();
1085
1086 let demoted = send(
1087 &app,
1088 "PATCH",
1089 &format!("/users/{teacher_id}/role"),
1090 Some(&admin),
1091 Some(json!({ "role": "student" })),
1092 )
1093 .await;
1094 assert_eq!(demoted.status, StatusCode::OK);
1095
1096 for class in &held {
1097 assert_eq!(
1098 stored_teacher(&app, &admin, class).await,
1099 json!(null),
1100 "a demoted user may not stay a class's homeroom teacher"
1101 );
1102 }
1103 assert_eq!(
1104 stored_teacher(&app, &admin, &untouched).await["id"],
1105 json!(keeper_id),
1106 "…and nobody else's assignment may move"
1107 );
1108}
1109
1110// ---- a student's own section ------------------------------------------------
1111
1112/// `GET /classes/me` is the one class read a student can make: it returns
1113/// exactly their own memberships (with the homeroom teacher joined on), it does
1114/// not fall through to the teacher-only `GET /classes/{id}`, and it pages.
1115#[tokio::test]
1116async fn a_student_reads_exactly_their_own_classes() {
1117 let (app, db) = app_and_db().await;
1118 let manager = login_as(&app, &db, "manager", "manager").await;
1119 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1120 let student = login_as(&app, &db, "ali", "student").await;
1121 let lonely = login_as(&app, &db, "veli", "student").await;
1122 let teacher_id = me_id(&app, &teacher).await;
1123 let student_id = me_id(&app, &student).await;
1124
1125 // Added oldest-first, with a gap wide enough that `joined_at` really
1126 // orders them — the composite ids break a tie in account-ULID order, which
1127 // says nothing about who joined first.
1128 let mut mine = Vec::new();
1129 for name in ["9-A", "9-B"] {
1130 let class = create_class(
1131 &app,
1132 &manager,
1133 json!({ "name": name, "teacher_id": teacher_id }),
1134 )
1135 .await
1136 .body["id"]
1137 .as_str()
1138 .unwrap()
1139 .to_string();
1140 let added = send(
1141 &app,
1142 "POST",
1143 &format!("/classes/{class}/members"),
1144 Some(&manager),
1145 Some(json!({ "user_id": student_id })),
1146 )
1147 .await;
1148 assert_eq!(added.status, StatusCode::CREATED);
1149 mine.push(class);
1150 tokio::time::sleep(std::time::Duration::from_millis(5)).await;
1151 }
1152 // A class the student is *not* in must never show up.
1153 create_class(&app, &manager, json!({ "name": "10-A" })).await;
1154
1155 let res = send(&app, "GET", "/classes/me", Some(&student), None).await;
1156 assert_eq!(
1157 res.status,
1158 StatusCode::OK,
1159 "/classes/me must not fall through to the teacher-only /classes/{{id}}"
1160 );
1161 assert!(
1162 res.body.get("items").is_some() && res.body.get("total").is_some(),
1163 "…which is what a page envelope, rather than one class object, proves: {:?}",
1164 res.body
1165 );
1166 assert_eq!(total(&res.body), 2);
1167 let ids = |body: &serde_json::Value| -> Vec<String> {
1168 body["items"]
1169 .as_array()
1170 .unwrap()
1171 .iter()
1172 .map(|item| item["id"].as_str().unwrap().to_string())
1173 .collect()
1174 };
1175 // Unsorted: the documented order is newest membership first, so the class
1176 // joined *second* must lead. Sorting here is what made this assertion dead.
1177 assert_eq!(
1178 ids(&res.body),
1179 vec![mine[1].clone(), mine[0].clone()],
1180 "exactly the student's own classes, newest membership first"
1181 );
1182 assert_eq!(
1183 res.body["items"][0]["teacher"]["username"],
1184 json!("teacher"),
1185 "the homeroom teacher must be resolved, not left a bare id"
1186 );
1187 // The office's account names stay out of a student's reach.
1188 assert_eq!(
1189 res.body["items"][0]["creator"],
1190 json!(null),
1191 "a student may not learn who in the office created their class"
1192 );
1193 let staff = send(&app, "GET", "/classes/me", Some(&manager), None).await;
1194 assert_eq!(total(&staff.body), 0, "staff are never class members");
1195 let staff_view = send(
1196 &app,
1197 "GET",
1198 &format!("/classes/user/{student_id}"),
1199 Some(&teacher),
1200 None,
1201 )
1202 .await;
1203 assert_eq!(
1204 staff_view.body["items"][0]["creator"]["username"],
1205 json!("manager"),
1206 "…but teacher+ still sees the creator"
1207 );
1208
1209 // The window must actually move: the second page is the *older* class, not
1210 // the first page again. Asserting only the length let `offset` be ignored.
1211 let paged = send(
1212 &app,
1213 "GET",
1214 "/classes/me?limit=1&offset=1",
1215 Some(&student),
1216 None,
1217 )
1218 .await;
1219 assert_eq!(paged.status, StatusCode::OK);
1220 assert_eq!(total(&paged.body), 2);
1221 assert_eq!(
1222 ids(&paged.body),
1223 vec![mine[0].clone()],
1224 "?offset=1 must return the second row of the full order, not the first"
1225 );
1226 let first = send(
1227 &app,
1228 "GET",
1229 "/classes/me?limit=1&offset=0",
1230 Some(&student),
1231 None,
1232 )
1233 .await;
1234 assert_eq!(ids(&first.body), vec![mine[1].clone()]);
1235
1236 // A student in no class gets an empty page, not a 404.
1237 let empty = send(&app, "GET", "/classes/me", Some(&lonely), None).await;
1238 assert_eq!(empty.status, StatusCode::OK);
1239 assert_eq!(total(&empty.body), 0);
1240 assert!(empty.body["items"].as_array().unwrap().is_empty());
1241}
1242
1243/// `GET /classes/user/{id}` follows the observer rule the per-student reports
1244/// use: teacher+ and a *linked* parent may read it, everyone else — an
1245/// unlinked parent, another student — is a `403` with no existence leak.
1246#[tokio::test]
1247async fn only_staff_and_a_linked_parent_read_another_users_classes() {
1248 let (app, db) = app_and_db().await;
1249 let admin = login_as(&app, &db, "mudur", "admin").await;
1250 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1251 let student = login_as(&app, &db, "ali", "student").await;
1252 let peer = login_as(&app, &db, "veli", "student").await;
1253 let parent = login_as(&app, &db, "anne", "parent").await;
1254 let stranger = login_as(&app, &db, "baba", "parent").await;
1255 let student_id = me_id(&app, &student).await;
1256 let parent_id = me_id(&app, &parent).await;
1257 let teacher_id = me_id(&app, &teacher).await;
1258
1259 let class = create_class(
1260 &app,
1261 &admin,
1262 json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id }),
1263 )
1264 .await
1265 .body["id"]
1266 .as_str()
1267 .unwrap()
1268 .to_string();
1269 send(
1270 &app,
1271 "POST",
1272 &format!("/classes/{class}/members"),
1273 Some(&admin),
1274 Some(json!({ "user_id": student_id })),
1275 )
1276 .await;
1277 let linked = send(
1278 &app,
1279 "POST",
1280 &format!("/users/{parent_id}/students"),
1281 Some(&admin),
1282 Some(json!({ "user_id": student_id })),
1283 )
1284 .await;
1285 assert!(
1286 linked.status.is_success(),
1287 "link student: {}",
1288 linked.status
1289 );
1290
1291 let path = format!("/classes/user/{student_id}");
1292 // `creator` is the half of this route that is not about who may read it:
1293 // a linked parent is below teacher+, so the office account that made the
1294 // class must be hidden from them exactly as it is from their child — while
1295 // the homeroom teacher, which is the point of the read, stays named for
1296 // both.
1297 for (who, cookie, creator) in [
1298 ("teacher", &teacher, json!("mudur")),
1299 ("linked parent", &parent, json!(null)),
1300 ] {
1301 let res = send(&app, "GET", &path, Some(cookie), None).await;
1302 assert_eq!(res.status, StatusCode::OK, "{who} may read");
1303 assert_eq!(total(&res.body), 1, "{who} sees the class");
1304 assert_eq!(res.body["items"][0]["id"], json!(class));
1305 assert_eq!(
1306 res.body["items"][0]["teacher"]["username"],
1307 json!("teacher"),
1308 "{who} must be told who the homeroom teacher is"
1309 );
1310 let seen = &res.body["items"][0]["creator"];
1311 match creator.as_str() {
1312 Some(name) => assert_eq!(seen["username"], json!(name), "{who} may see the creator"),
1313 None => assert_eq!(
1314 *seen,
1315 json!(null),
1316 "{who} is below teacher+ and may not learn an office account's name"
1317 ),
1318 }
1319 }
1320 for (who, cookie) in [("unlinked parent", &stranger), ("another student", &peer)] {
1321 let res = send(&app, "GET", &path, Some(cookie), None).await;
1322 assert_eq!(res.status, StatusCode::FORBIDDEN, "{who} may not");
1323 }
1324
1325 // The pagination envelope, and the 404 a user who does not exist gets.
1326 let paged = send(
1327 &app,
1328 "GET",
1329 &format!("{path}?limit=1&offset=0"),
1330 Some(&teacher),
1331 None,
1332 )
1333 .await;
1334 assert_eq!(paged.status, StatusCode::OK);
1335 assert_eq!(total(&paged.body), 1);
1336 assert_eq!(paged.body["items"].as_array().unwrap().len(), 1);
1337 let ghost = send(
1338 &app,
1339 "GET",
1340 &format!("/classes/user/{ABSENT_ID}"),
1341 Some(&teacher),
1342 None,
1343 )
1344 .await;
1345 assert_eq!(ghost.status, StatusCode::NOT_FOUND);
1346}
1347
1348/// The documented decision on a `class_member` row whose class is gone: the
1349/// page still *counts* it (the window was cut from the membership rows) but
1350/// skips it from `items`, and answers `200` rather than a `500` or a short
1351/// page that silently loses the rest. Unreachable through the API — the class
1352/// delete guard refuses while members exist — so the row is forced here the
1353/// only way it could ever arise, a class row vanishing under its memberships.
1354#[tokio::test]
1355async fn a_membership_whose_class_is_gone_is_counted_but_skipped() {
1356 let (app, db) = app_and_db().await;
1357 let manager = login_as(&app, &db, "manager", "manager").await;
1358 let student = login_as(&app, &db, "ali", "student").await;
1359 let student_id = me_id(&app, &student).await;
1360
1361 let mut classes = Vec::new();
1362 for name in ["9-A", "9-B"] {
1363 let class = create_class(&app, &manager, json!({ "name": name }))
1364 .await
1365 .body["id"]
1366 .as_str()
1367 .unwrap()
1368 .to_string();
1369 let added = send(
1370 &app,
1371 "POST",
1372 &format!("/classes/{class}/members"),
1373 Some(&manager),
1374 Some(json!({ "user_id": student_id })),
1375 )
1376 .await;
1377 assert_eq!(added.status, StatusCode::CREATED);
1378 classes.push(class);
1379 tokio::time::sleep(std::time::Duration::from_millis(5)).await;
1380 }
1381 // The guard would refuse this, so it is spelled as the raw row loss it
1382 // stands in for; the membership row is deliberately left behind.
1383 wipe_row(
1384 "class_group",
1385 uuid::Uuid::parse_str(&classes[0]).expect("a uuid class id"),
1386 &db,
1387 )
1388 .await;
1389
1390 let res = send(&app, "GET", "/classes/me", Some(&student), None).await;
1391 assert_eq!(
1392 res.status,
1393 StatusCode::OK,
1394 "a dangling membership is not a 500"
1395 );
1396 assert_eq!(
1397 total(&res.body),
1398 2,
1399 "total counts the membership rows, which is what the window was cut from"
1400 );
1401 let items = res.body["items"].as_array().unwrap();
1402 assert_eq!(
1403 items.len(),
1404 1,
1405 "the class that is gone is skipped, not faked"
1406 );
1407 assert_eq!(
1408 items[0]["id"],
1409 json!(classes[1]),
1410 "…and the surviving class is still there, in order"
1411 );
1412}
1413
1414// ---- the demotion-vs-assign race, made deterministic -----------------------
1415//
1416// The window is between a handler's "this account is teacher+" check and the
1417// write that records it: a `PATCH /users/{id}/role` landing in there sweeps
1418// nothing (the rows it would sweep are not written yet) and nothing ever
1419// re-sweeps, so the assignment would stand forever naming a non-teacher. Every
1420// such handler therefore re-reads the live role *after* its write
1421// (`web::undo_if_demoted`).
1422//
1423// Racing it from a second task would be a coin flip the in-memory engine is
1424// known to lie about, so the demotion is injected by the database itself: a
1425// `DEFINE EVENT` on the very table the handler writes fires *inside* that
1426// write, which is exactly "after the role check, before the re-read", every
1427// single time. Nothing in `src/` knows about it — the seam is the schema, and
1428// these tests are what stop the three `undo_if_demoted` calls being deleted.
1429
1430/// Demote `user` from inside the next write to `table`, the instant it lands:
1431/// an AFTER trigger fires inside the write's own transaction, between the
1432/// handler's role check and its post-write re-read.
1433async fn demote_during_writes_to(table: &str, event: &str, user: &str, db: &Database) {
1434 let firing = match event {
1435 "CREATE" => "INSERT",
1436 "UPDATE" => "UPDATE",
1437 other => panic!("unknown event kind {other}"),
1438 };
1439 let mut conn = db.acquire().await.expect("acquire for the trigger");
1440 sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1441 "CREATE FUNCTION heztest_demote_mid_write() RETURNS trigger AS $$
1442 BEGIN
1443 UPDATE app_user SET role = 'student' WHERE id = '{user}';
1444 RETURN NULL;
1445 END;
1446 $$ LANGUAGE plpgsql;
1447 CREATE TRIGGER heztest_demote_mid_write AFTER {firing} ON {table}
1448 FOR EACH ROW EXECUTE FUNCTION heztest_demote_mid_write();"
1449 )))
1450 .execute(&mut *conn)
1451 .await
1452 .expect("define the demote trigger");
1453}
1454
1455/// The homeroom teacher's live role, straight out of the store.
1456async fn role_of(user: &str, db: &Database) -> String {
1457 sqlx::query_scalar("SELECT role FROM app_user WHERE id = $1")
1458 .bind(UserId::from_key(user))
1459 .fetch_one(db)
1460 .await
1461 .unwrap()
1462}
1463
1464/// `POST /classes` naming a teacher who is demoted while the row is being
1465/// written: `409`, and the class is rolled back **whole** — no teacherless
1466/// class left standing, and no reference stranded on the academic year it
1467/// linked (which would make that year undeletable forever).
1468#[tokio::test]
1469async fn a_create_whose_teacher_is_demoted_mid_write_rolls_back_whole() {
1470 let (app, db) = app_and_db().await;
1471 let manager = login_as(&app, &db, "manager", "manager").await;
1472 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1473 let teacher_id = me_id(&app, &teacher).await;
1474 let year = create_year(&app, &manager, "2026-2027").await;
1475 let term_id = create_term(&app, &manager, &year, "1. Dönem").await;
1476
1477 demote_during_writes_to("class_group", "CREATE", &teacher_id, &db).await;
1478 let res = send(
1479 &app,
1480 "POST",
1481 "/classes",
1482 Some(&manager),
1483 Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id, "year": year })),
1484 )
1485 .await;
1486
1487 assert_eq!(
1488 res.status,
1489 StatusCode::CONFLICT,
1490 "a teacher demoted mid-write must not be recorded as one: {:?}",
1491 res.body
1492 );
1493 assert!(
1494 res.body["error"].as_str().unwrap().contains("demoted"),
1495 "the 409 must say why: {:?}",
1496 res.body
1497 );
1498 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");
1499 assert_eq!(
1500 rows("SELECT count(*) FROM class_group", &db).await,
1501 0,
1502 "the 409 promises nothing was created — so nothing may be there"
1503 );
1504 assert_eq!(
1505 counter(
1506 "SELECT COALESCE(sum(class_count), 0)::bigint FROM academic_year",
1507 &db
1508 )
1509 .await,
1510 0,
1511 "…and least of all a reference stranded on the year it linked"
1512 );
1513 let freed = send(
1514 &app,
1515 "DELETE",
1516 &format!("/terms/{term_id}"),
1517 Some(&manager),
1518 None,
1519 )
1520 .await;
1521 assert_eq!(
1522 freed.status,
1523 StatusCode::NO_CONTENT,
1524 "which is the point: the term must still be deletable"
1525 );
1526}
1527
1528/// The same rollback at a grade a **blueprint** covers, which is what pins the
1529/// order of the two: a create stocks itself from its grade's template, and that
1530/// stocking runs *after* this demotion check. Were it the other way round the
1531/// class would hold courses by the time the rollback ran, `ClassGroup::delete`
1532/// refuses one that does, and the `409` promising nothing was created would
1533/// leave a stocked section standing behind it.
1534#[tokio::test]
1535async fn a_rolled_back_create_at_a_blueprinted_grade_leaves_nothing_behind() {
1536 let (app, db) = app_and_db().await;
1537 let manager = login_as(&app, &db, "manager", "manager").await;
1538 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1539 let teacher_id = me_id(&app, &teacher).await;
1540 let course = create_course(&app, &manager, "algebra").await;
1541 let made = send(
1542 &app,
1543 "POST",
1544 "/classes/blueprints",
1545 Some(&manager),
1546 Some(json!({ "grade_level": 9, "course_ids": [course] })),
1547 )
1548 .await;
1549 assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
1550
1551 demote_during_writes_to("class_group", "CREATE", &teacher_id, &db).await;
1552 let res = send(
1553 &app,
1554 "POST",
1555 "/classes",
1556 Some(&manager),
1557 Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id })),
1558 )
1559 .await;
1560
1561 assert_eq!(
1562 res.status,
1563 StatusCode::CONFLICT,
1564 "the demotion still wins over the stocking: {:?}",
1565 res.body
1566 );
1567 assert_eq!(
1568 rows("SELECT count(*) FROM class_group", &db).await,
1569 0,
1570 "the rollback must still have been able to delete the class"
1571 );
1572 assert_eq!(
1573 rows("SELECT count(*) FROM class_course", &db).await,
1574 0,
1575 "…which it only can because nothing was stocked onto it first"
1576 );
1577}
1578
1579/// `PATCH /classes/{id}` naming a teacher who is demoted while the row is being
1580/// written: `409`, and the column it just set is taken back.
1581#[tokio::test]
1582async fn a_patch_whose_teacher_is_demoted_mid_write_undoes_the_column() {
1583 let (app, db) = app_and_db().await;
1584 let manager = login_as(&app, &db, "manager", "manager").await;
1585 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1586 let teacher_id = me_id(&app, &teacher).await;
1587 let class = create_class(&app, &manager, json!({ "name": "9-A", "grade_level": 9 }))
1588 .await
1589 .body["id"]
1590 .as_str()
1591 .unwrap()
1592 .to_string();
1593
1594 demote_during_writes_to("class_group", "UPDATE", &teacher_id, &db).await;
1595 let res = send(
1596 &app,
1597 "PATCH",
1598 &format!("/classes/{class}"),
1599 Some(&manager),
1600 Some(json!({ "teacher_id": teacher_id })),
1601 )
1602 .await;
1603
1604 assert_eq!(
1605 res.status,
1606 StatusCode::CONFLICT,
1607 "a teacher demoted mid-write must not be recorded as one: {:?}",
1608 res.body
1609 );
1610 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");
1611 assert_eq!(
1612 counter(
1613 "SELECT count(*) FROM class_group WHERE teacher IS NOT NULL",
1614 &db,
1615 )
1616 .await,
1617 0,
1618 "the assignment this request wrote must be taken back"
1619 );
1620 // The class itself is untouched — only the column this request set is.
1621 let stored = send(
1622 &app,
1623 "GET",
1624 &format!("/classes/{class}"),
1625 Some(&manager),
1626 None,
1627 )
1628 .await;
1629 assert_eq!(stored.status, StatusCode::OK);
1630 assert_eq!(stored.body["name"], json!("9-A"));
1631 assert_eq!(stored.body["teacher"], json!(null));
1632}
1633
1634/// The same guard on the other assignment it protects:
1635/// `POST /instances/{id}/teachers` for an account demoted while the list is
1636/// being written is a `409`, with the assignment dropped again. Staffing is an
1637/// *instance's* own list now — the catalog course carries no teachers.
1638#[tokio::test]
1639async fn an_instance_assignment_whose_teacher_is_demoted_mid_write_is_undone() {
1640 let (app, db) = app_and_db().await;
1641 let manager = login_as(&app, &db, "manager", "manager").await;
1642 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1643 let teacher_id = me_id(&app, &teacher).await;
1644 let instance = taught(&app, &manager, "algebra").await.instance;
1645
1646 demote_during_writes_to("class_course_teacher", "CREATE", &teacher_id, &db).await;
1647 let res = send(
1648 &app,
1649 "POST",
1650 &format!("/instances/{instance}/teachers"),
1651 Some(&manager),
1652 Some(json!({ "user_id": teacher_id })),
1653 )
1654 .await;
1655
1656 assert_eq!(
1657 res.status,
1658 StatusCode::CONFLICT,
1659 "a teacher demoted mid-write must not be recorded as one: {:?}",
1660 res.body
1661 );
1662 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");
1663 assert_eq!(
1664 counter("SELECT count(*) FROM class_course_teacher", &db).await,
1665 0,
1666 "the assignment must be dropped again, not left granting nothing"
1667 );
1668}
1669
1670/// The other end of that rollback: if the delete is ever *refused* — the class
1671/// took a member or a course between its own create and the rollback — the
1672/// class is still there, so answering the `409` whose text promises "nothing
1673/// was created" would be a lie about the stored state. It must surface as an
1674/// internal error instead.
1675///
1676/// Unreachable through the API (the class is one statement old and both of its
1677/// counters are absent), so the seam does both halves at once: demote the
1678/// teacher *and* tick `class_member_count` inside the very write that creates
1679/// the row, which is the only ordering that reaches this branch.
1680#[tokio::test]
1681async fn a_rollback_the_guard_refuses_is_a_500_not_a_lying_409() {
1682 let (app, db) = app_and_db().await;
1683 let manager = login_as(&app, &db, "manager", "manager").await;
1684 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1685 let teacher_id = me_id(&app, &teacher).await;
1686
1687 let mut conn = db.acquire().await.expect("acquire for the trigger");
1688 sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1689 "CREATE FUNCTION heztest_demote_and_occupy() RETURNS trigger AS $$
1690 BEGIN
1691 UPDATE app_user SET role = 'student' WHERE id = '{teacher_id}';
1692 UPDATE class_group SET class_member_count = 1 WHERE id = NEW.id;
1693 RETURN NULL;
1694 END;
1695 $$ LANGUAGE plpgsql;
1696 CREATE TRIGGER heztest_demote_and_occupy AFTER INSERT ON class_group
1697 FOR EACH ROW EXECUTE FUNCTION heztest_demote_and_occupy();"
1698 )))
1699 .execute(&mut *conn)
1700 .await
1701 .expect("define the demote-and-occupy trigger");
1702
1703 let res = send(
1704 &app,
1705 "POST",
1706 "/classes",
1707 Some(&manager),
1708 Some(json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id })),
1709 )
1710 .await;
1711
1712 assert_eq!(
1713 res.status,
1714 StatusCode::INTERNAL_SERVER_ERROR,
1715 "a rollback that could not happen may not be reported as one: {:?}",
1716 res.body
1717 );
1718 assert_eq!(
1719 rows("SELECT count(*) FROM class_group", &db).await,
1720 1,
1721 "the class really is still there — which is why the 409 would have lied"
1722 );
1723 assert_eq!(
1724 counter(
1725 "SELECT count(*) FROM class_group WHERE teacher IS NOT NULL",
1726 &db,
1727 )
1728 .await,
1729 0,
1730 "…though the demoted teacher is off it, the undo having run first"
1731 );
1732}
1733
1734// ---- the grade filter on the index -----------------------------------------
1735
1736/// Names of a `/classes` page, in the order it came back.
1737fn names(res: &Res) -> Vec<String> {
1738 common::items(&res.body)
1739 .iter()
1740 .map(|class| class["name"].as_str().unwrap().to_string())
1741 .collect()
1742}
1743
1744/// `?grade_level=` is the read a manager holding a blueprint's skip list
1745/// needs: which sections carry the rung the pump keyed on. It is the *query's*
1746/// `WHERE`, so `total` counts the filtered set and a window walks that set
1747/// alone — drop the predicate and every assertion below sees the unfiltered
1748/// four instead.
1749#[tokio::test]
1750async fn the_class_index_filters_by_grade() {
1751 let (app, db) = app_and_db().await;
1752 let manager = login_as(&app, &db, "mgr", "manager").await;
1753 for (name, grade_level) in [
1754 ("9-A", 9),
1755 ("9-B", 9),
1756 ("10-A", 10),
1757 // A club-shaped section: created at the ladder's floor, like every
1758 // class — it just never shares a rung with an ordinary section here.
1759 ("satranc", 0),
1760 ] {
1761 create_class(&app, &manager, json!({ "name": name, "grade_level": grade_level }))
1762 .await;
1763 }
1764 let list = async |query: &str| -> Res {
1765 let res = send(
1766 &app,
1767 "GET",
1768 &format!("/classes{query}"),
1769 Some(&manager),
1770 None,
1771 )
1772 .await;
1773 assert_eq!(
1774 res.status,
1775 StatusCode::OK,
1776 "GET /classes{query}: {}",
1777 res.body
1778 );
1779 res
1780 };
1781
1782 // Omitted: today's behaviour, every class.
1783 let res = list("").await;
1784 assert_eq!(total(&res.body), 4);
1785 assert_eq!(names(&res).len(), 4);
1786
1787 // One rung, matched exactly: both sections at it, and a `total` that
1788 // counts only them.
1789 let res = list("?grade_level=9").await;
1790 assert_eq!(total(&res.body), 2, "total counts the filtered set");
1791 assert_eq!(names(&res), ["9-B", "9-A"], "newest first, 9 only");
1792 assert_eq!(names(&list("?grade_level=10").await), ["10-A"]);
1793 // Rungs nobody carries are empty pages, not errors — the integers leave
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"] {
1797 let res = list(miss).await;
1798 assert_eq!(total(&res.body), 0, "GET /classes{miss} total");
1799 assert!(
1800 names(&res).is_empty(),
1801 "GET /classes{miss} is an empty page"
1802 );
1803 }
1804
1805 // The floor is a rung like any other: it filters, it does not mean
1806 // "no grade" — no such class exists any more.
1807 let res = list("?grade_level=0").await;
1808 assert_eq!((total(&res.body), names(&res)), (1, vec!["satranc".into()]));
1809
1810 // Filter and window compose: the window is cut from the filtered set, and
1811 // `total` stays that set's size on every page of it.
1812 let first = list("?grade_level=9&limit=1&offset=0").await;
1813 assert_eq!(total(&first.body), 2);
1814 assert_eq!(names(&first), ["9-B"]);
1815 assert_eq!(first.body["limit"], 1);
1816 let second = list("?grade_level=9&limit=1&offset=1").await;
1817 assert_eq!(total(&second.body), 2);
1818 assert_eq!(names(&second), ["9-A"], "consecutive pages are disjoint");
1819 assert_eq!(second.body["offset"], 1);
1820 let past = list("?grade_level=9&limit=1&offset=9").await;
1821 assert!(names(&past).is_empty(), "past the end is an empty page");
1822 assert_eq!(
1823 total(&past.body),
1824 2,
1825 "…with the filtered total still honest"
1826 );
1827
1828 // A rung the write paths would refuse is refused here too, rather than
1829 // reading as "no such grade".
1830 let res = send(
1831 &app,
1832 "GET",
1833 "/classes?grade_level=13",
1834 Some(&manager),
1835 None,
1836 )
1837 .await;
1838 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
1839}
1840
1841/// The member exit releases the roster row its own section wrote — and the
1842/// repair its sweep must *not* make is handing that row to a section whose row
1843/// is gone.
1844///
1845/// There is no shared row to hand anywhere since the K12 remodel: a şube
1846/// teaches the course as its **own instance**, so the section the student
1847/// leaves gives back exactly the seat that section pumped (the fixture asserts
1848/// that first — each attach writes its own row, tagged with its own class).
1849/// What survives from the old hand-off is its guard: when the sweep looks for a
1850/// rival still claiming the row, the rival it may settle on can be a section
1851/// deleted out from under its own links — a state this layer really carries
1852/// (`a_membership_whose_class_is_gone_is_counted_but_skipped`) — and such a
1853/// section must take the release arm. A row tagged with a class that is not
1854/// there is an enrollment nothing can ever sweep: both ends 404 on link rows
1855/// that are gone.
1856///
1857/// The real interleaving needs the store's conflict detection; what is
1858/// deterministic here is that half of it: the gone section is never handed the
1859/// row, the row is released, and the counter lands on zero with it.
1860#[tokio::test]
1861async fn a_member_exit_never_hands_a_row_to_a_class_that_is_gone() {
1862 let (app, db) = app_and_db().await;
1863 let staff = login_as(&app, &db, "manager", "manager").await;
1864 let manager = UserId::from_key(&me_id(&app, &staff).await);
1865 let student = fixture_user(&db, "heir_ogrenci").await;
1866 let algebra = CourseId::from_key(&create_course(&app, &staff, "algebra").await);
1867 let mut made = Vec::new();
1868 for name in ["9-B", "9-A"] {
1869 let class = class_group::create(
1870 &db,
1871 &manager,
1872 ClassName::try_new(name).unwrap(),
1873 GradeLevel::new(9).unwrap(),
1874 None,
1875 None,
1876 )
1877 .await
1878 .unwrap();
1879 let class = class.get_id().clone();
1880 class_member::add(&db, &class, &student, &manager)
1881 .await
1882 .unwrap();
1883 let instance = class_course::attach(&db, &class, &algebra, &manager)
1884 .await
1885 .unwrap();
1886 made.push((class, instance.get_id().clone()));
1887 }
1888 let owner = made[0].0.clone();
1889 let heir = made[1].0.clone();
1890 let owner_instance = made[0].1.clone();
1891 assert_eq!(
1892 sqlx::query_scalar::<_, i64>("SELECT count(*) FROM enrollment WHERE source = $1",)
1893 .bind(owner.clone())
1894 .fetch_one(&db)
1895 .await
1896 .unwrap(),
1897 1,
1898 "each attach pumps its own instance: the first class owns the row it wrote"
1899 );
1900
1901 // The heir's class row goes while both of its link rows stay: the state a
1902 // class deleted out from under its own links leaves.
1903 wipe_row("class_group", heir.uuid(), &db).await;
1904
1905 class_member::leave(&db, &owner, &student).await.unwrap();
1906 assert_eq!(
1907 sqlx::query_scalar::<_, i64>("SELECT count(*) FROM enrollment WHERE class_course = $1")
1908 .bind(owner_instance.uuid())
1909 .fetch_one(&db)
1910 .await
1911 .unwrap(),
1912 0,
1913 "a row handed to a class that is not there is one nothing can ever sweep"
1914 );
1915 assert_eq!(
1916 sqlx::query_scalar::<_, i64>(
1917 "SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM class_course WHERE id = $1"
1918 )
1919 .bind(owner_instance.uuid())
1920 .fetch_one(&db)
1921 .await
1922 .unwrap(),
1923 0,
1924 "…and its seat must come back with it"
1925 );
1926}
1927
1928/// #22. A class in an archived academic year is read-only: every write axis it
1929/// has — the class itself, its roster, its instances, their rosters and the
1930/// blueprint pump — answers the coded `academic_year_archived` 409, while every
1931/// read stays open. Re-opening the year thaws all of it.
1932///
1933/// The year is what a şube hangs off since the K12 remodel (a dönem is a
1934/// grading slice *inside* it), so this is the same freeze the term used to
1935/// carry, one level up. There is no archive route for a year yet — the `409`
1936/// that would gate one has no door — so the past is minted the way an operator
1937/// would: the column directly.
1938#[tokio::test]
1939async fn an_archived_year_freezes_every_class_write_and_no_read() {
1940 let (app, db) = app_and_db().await;
1941 let manager = login_as(&app, &db, "arch_manager", "manager").await;
1942 let student = login_as(&app, &db, "arch_student", "student").await;
1943 let other = login_as(&app, &db, "arch_other", "student").await;
1944 let student_id = me_id(&app, &student).await;
1945 let other_id = me_id(&app, &other).await;
1946
1947 let year = create_year(&app, &manager, "2024-2025").await;
1948 let term_id = create_term(&app, &manager, &year, "2024").await;
1949
1950 // The course to attach, and a second one that stays unattached — what
1951 // proves a refusal came from the *class's* side.
1952 let dated = create_course(&app, &manager, "algebra").await;
1953 let open_course = create_course(&app, &manager, "geometry").await;
1954
1955 let class = create_class(
1956 &app,
1957 &manager,
1958 json!({ "name": "9-A", "grade_level": 9, "year": year }),
1959 )
1960 .await;
1961 let class = common::id_of(&class.body);
1962
1963 // Everything the frozen state must already hold: an instance, a member,
1964 // and a blueprint at this grade for the pump to try.
1965 let attached = send(
1966 &app,
1967 "POST",
1968 &format!("/classes/{class}/instances"),
1969 Some(&manager),
1970 Some(json!({ "course_id": dated })),
1971 )
1972 .await;
1973 assert_eq!(attached.status, StatusCode::CREATED, "attach while open");
1974 let instance = instance_of(&attached);
1975 let joined = send(
1976 &app,
1977 "POST",
1978 &format!("/classes/{class}/members"),
1979 Some(&manager),
1980 Some(json!({ "user_id": student_id })),
1981 )
1982 .await;
1983 assert_eq!(joined.status, StatusCode::CREATED, "member while open");
1984 let blueprint = send(
1985 &app,
1986 "POST",
1987 "/classes/blueprints",
1988 Some(&manager),
1989 Some(json!({ "grade_level": 9, "course_ids": [dated] })),
1990 )
1991 .await;
1992 assert_eq!(blueprint.status, StatusCode::CREATED, "blueprint");
1993
1994 // The year goes past: nothing in the API archives one yet, so the column
1995 // is written the way the archive half of a term used to write it.
1996 sqlx::query("UPDATE academic_year SET archived_at = $1 WHERE id = $2")
1997 .bind(1_700_000_000_000_i64)
1998 .bind(uuid::Uuid::parse_str(&year).unwrap())
1999 .execute(&db)
2000 .await
2001 .unwrap();
2002
2003 // One refusal per write route, each 409 with the machine code — never a
2004 // bare 409, which a client cannot tell from any other refusal.
2005 let writes: Vec<(&str, String, Option<serde_json::Value>)> = vec![
2006 (
2007 "PATCH",
2008 format!("/classes/{class}"),
2009 Some(json!({ "name": "9-B", "grade_level": 9 })),
2010 ),
2011 (
2012 "POST",
2013 format!("/classes/{class}/members"),
2014 Some(json!({ "user_id": other_id })),
2015 ),
2016 (
2017 "DELETE",
2018 format!("/classes/{class}/members/{student_id}"),
2019 None,
2020 ),
2021 (
2022 "POST",
2023 format!("/classes/{class}/instances"),
2024 // An unattached *catalog* course: the class's own year is the
2025 // refusal, which is what this probe is for.
2026 Some(json!({ "course_id": open_course })),
2027 ),
2028 (
2029 "DELETE",
2030 format!("/classes/{class}/instances/{instance}"),
2031 None,
2032 ),
2033 ("POST", format!("/classes/{class}/blueprint"), None),
2034 ("DELETE", format!("/classes/{class}"), None),
2035 (
2036 "PATCH",
2037 format!("/instances/{instance}"),
2038 Some(json!({ "ders_saati": 4 })),
2039 ),
2040 (
2041 "POST",
2042 format!("/instances/{instance}/enrollments"),
2043 Some(json!({ "user_id": other_id })),
2044 ),
2045 (
2046 "POST",
2047 format!("/instances/{instance}/sessions"),
2048 Some(json!({ "starts_at": 1_900_000_000_000_i64 })),
2049 ),
2050 ];
2051 for (method, uri, body) in writes {
2052 let res = send(&app, method, &uri, Some(&manager), body).await;
2053 assert_eq!(res.status, StatusCode::CONFLICT, "{method} {uri}");
2054 assert_eq!(
2055 res.body["code"], "academic_year_archived",
2056 "{method} {uri} code"
2057 );
2058 }
2059
2060 // Reads are untouched — a past year is read-only, not hidden.
2061 for uri in [
2062 format!("/classes/{class}"),
2063 format!("/classes/{class}/members"),
2064 format!("/classes/{class}/instances"),
2065 format!("/instances/{instance}"),
2066 format!("/academic-years/{year}"),
2067 format!("/terms/{term_id}"),
2068 ] {
2069 let res = send(&app, "GET", &uri, Some(&manager), None).await;
2070 assert_eq!(res.status, StatusCode::OK, "GET {uri}");
2071 }
2072 let members = send(
2073 &app,
2074 "GET",
2075 &format!("/classes/{class}/members"),
2076 Some(&manager),
2077 None,
2078 )
2079 .await;
2080 assert_eq!(total(&members.body), 1, "no write landed");
2081
2082 // Re-opening the year thaws the whole set; one write is enough to show it.
2083 sqlx::query("UPDATE academic_year SET archived_at = NULL WHERE id = $1")
2084 .bind(uuid::Uuid::parse_str(&year).unwrap())
2085 .execute(&db)
2086 .await
2087 .unwrap();
2088 let patched = send(
2089 &app,
2090 "PATCH",
2091 &format!("/classes/{class}"),
2092 Some(&manager),
2093 Some(json!({ "name": "9-B", "grade_level": 9 })),
2094 )
2095 .await;
2096 assert_eq!(patched.status, StatusCode::OK, "thawed: {:?}", patched.body);
2097 assert_eq!(patched.body["name"], "9-B");
2098}
2099
2100// ---- the instance anchor ----------------------------------------------------
2101
2102/// The remodel's core promise: a catalog course is a *title* shared by every
2103/// section that teaches it, and each şube teaching it is its own instance. Two
2104/// şubeler attaching one course mint two instances; a student of 5-A is on
2105/// 5-A's roster alone; and an exam written on 5-A's instance is invisible from
2106/// 5-B's — which is exactly what the old school-wide singleton could not do.
2107#[tokio::test]
2108async fn two_subeler_teaching_one_course_are_two_instances() {
2109 let (app, db) = app_and_db().await;
2110 let manager = login_as(&app, &db, "manager", "manager").await;
2111 let student = login_as(&app, &db, "student", "student").await;
2112 let student_id = me_id(&app, &student).await;
2113
2114 let year = create_year(&app, &manager, "2026-2027").await;
2115 let term = create_term(&app, &manager, &year, "1. Dönem").await;
2116 let course = create_course(&app, &manager, "Matematik").await;
2117
2118 let a = create_class(
2119 &app,
2120 &manager,
2121 json!({ "name": "5-A", "grade_level": 5, "year": year }),
2122 )
2123 .await;
2124 let a = common::id_of(&a.body);
2125 let b = create_class(
2126 &app,
2127 &manager,
2128 json!({ "name": "5-B", "grade_level": 5, "year": year }),
2129 )
2130 .await;
2131 let b = common::id_of(&b.body);
2132
2133 let ia = send(
2134 &app,
2135 "POST",
2136 &format!("/classes/{a}/instances"),
2137 Some(&manager),
2138 Some(json!({ "course_id": course })),
2139 )
2140 .await;
2141 assert_eq!(ia.status, StatusCode::CREATED, "{:?}", ia.body);
2142 let ia = instance_of(&ia);
2143 let ib = send(
2144 &app,
2145 "POST",
2146 &format!("/classes/{b}/instances"),
2147 Some(&manager),
2148 Some(json!({ "course_id": course })),
2149 )
2150 .await;
2151 assert_eq!(ib.status, StatusCode::CREATED, "{:?}", ib.body);
2152 let ib = instance_of(&ib);
2153 assert_ne!(
2154 ia, ib,
2155 "one catalog course taught by two şubeler is two instances"
2156 );
2157
2158 // Each instance names the same catalog course, and its own şube.
2159 for (instance, class) in [(&ia, &a), (&ib, &b)] {
2160 let read = send(
2161 &app,
2162 "GET",
2163 &format!("/instances/{instance}"),
2164 Some(&manager),
2165 None,
2166 )
2167 .await;
2168 assert_eq!(read.status, StatusCode::OK, "{:?}", read.body);
2169 assert_eq!(read.body["course"], json!(course), "both teach one course");
2170 assert_eq!(read.body["class"], json!(class));
2171 }
2172
2173 // A student put in 5-A lands on 5-A's roster — 5-B's stays empty.
2174 add_member(&app, &manager, &a, &student_id).await;
2175 let in_a = send(
2176 &app,
2177 "GET",
2178 &format!("/instances/{ia}/enrollments"),
2179 Some(&manager),
2180 None,
2181 )
2182 .await;
2183 assert_eq!(total(&in_a.body), 1, "{:?}", in_a.body);
2184 assert_eq!(items(&in_a.body)[0]["user"]["id"], json!(student_id));
2185 let in_b = send(
2186 &app,
2187 "GET",
2188 &format!("/instances/{ib}/enrollments"),
2189 Some(&manager),
2190 None,
2191 )
2192 .await;
2193 assert_eq!(
2194 total(&in_b.body),
2195 0,
2196 "5-B's roster is its own: {:?}",
2197 in_b.body
2198 );
2199
2200 // The exam belongs to the instance it was written on, not to the course.
2201 let exam = create_exam(&app, &manager, &ia, &term, "1. Yazılı", "yazili").await;
2202 let seen = send(
2203 &app,
2204 "GET",
2205 &format!("/instances/{ia}/exams"),
2206 Some(&manager),
2207 None,
2208 )
2209 .await;
2210 assert_eq!(total(&seen.body), 1, "{:?}", seen.body);
2211 assert_eq!(items(&seen.body)[0]["id"], json!(exam));
2212 let blind = send(
2213 &app,
2214 "GET",
2215 &format!("/instances/{ib}/exams"),
2216 Some(&manager),
2217 None,
2218 )
2219 .await;
2220 assert_eq!(blind.status, StatusCode::OK);
2221 assert_eq!(
2222 total(&blind.body),
2223 0,
2224 "5-B must not see the exam 5-A sat: {:?}",
2225 blind.body
2226 );
2227}
2228
2229/// A leave is a *stint*, not a deletion: the history row stays, the counter
2230/// counts live rows only, and rejoining opens a second stint. That is what
2231/// keeps the roster cap honest — a şube whose students cycle through it must
2232/// not fill up on rows nobody holds.
2233#[tokio::test]
2234async fn a_leaver_rejoins_into_a_second_stint() {
2235 let (app, db) = app_and_db().await;
2236 let manager = login_as(&app, &db, "manager", "manager").await;
2237 let student = login_as(&app, &db, "student", "student").await;
2238 let other = login_as(&app, &db, "other", "student").await;
2239 let student_id = me_id(&app, &student).await;
2240 let other_id = me_id(&app, &other).await;
2241
2242 let class = create_class(&app, &manager, json!({ "name": "5-A" })).await;
2243 let class = common::id_of(&class.body);
2244
2245 add_member(&app, &manager, &class, &student_id).await;
2246 assert_eq!(
2247 counter(
2248 "SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group",
2249 &db
2250 )
2251 .await,
2252 1
2253 );
2254
2255 let left = send(
2256 &app,
2257 "DELETE",
2258 &format!("/classes/{class}/members/{student_id}"),
2259 Some(&manager),
2260 None,
2261 )
2262 .await;
2263 assert_eq!(left.status, StatusCode::NO_CONTENT, "{:?}", left.body);
2264 assert_eq!(
2265 counter("SELECT count(*) FROM class_member WHERE app_user = (SELECT id FROM app_user WHERE username = 'student')", &db).await,
2266 1,
2267 "the stint is stamped, not swept: the section keeps the record"
2268 );
2269 assert_eq!(
2270 counter(
2271 "SELECT count(*) FROM class_member WHERE left_at IS NULL AND app_user = (SELECT id FROM app_user WHERE username = 'student')",
2272 &db
2273 )
2274 .await,
2275 0,
2276 "…and nothing of it is live"
2277 );
2278 assert_eq!(
2279 counter(
2280 "SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group",
2281 &db
2282 )
2283 .await,
2284 0,
2285 "the counter follows the live stints, so the seat came back"
2286 );
2287
2288 // The rejoined student is a fresh row beside the history — the partial
2289 // index allows exactly that (one live stint per pair).
2290 add_member(&app, &manager, &class, &student_id).await;
2291 assert_eq!(
2292 counter("SELECT count(*) FROM class_member WHERE app_user = (SELECT id FROM app_user WHERE username = 'student')", &db).await,
2293 2
2294 );
2295 assert_eq!(
2296 counter(
2297 "SELECT count(*) FROM class_member WHERE left_at IS NULL AND app_user = (SELECT id FROM app_user WHERE username = 'student')",
2298 &db
2299 )
2300 .await,
2301 1
2302 );
2303 assert_eq!(
2304 counter(
2305 "SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group",
2306 &db
2307 )
2308 .await,
2309 1,
2310 "the counter is the live count, never the row count"
2311 );
2312
2313 // The cap reads that counter, so a live leave frees the seat it was
2314 // counting. Seeded rather than filled by `MAX_CLASS_MEMBERS` real adds:
2315 // the counter *is* what the claim reads.
2316 sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2")
2317 .bind(MAX_CLASS_MEMBERS)
2318 .bind(uuid::Uuid::parse_str(&class).unwrap())
2319 .execute(&db)
2320 .await
2321 .unwrap();
2322 let refused = send(
2323 &app,
2324 "POST",
2325 &format!("/classes/{class}/members"),
2326 Some(&manager),
2327 Some(json!({ "user_id": other_id })),
2328 )
2329 .await;
2330 assert_eq!(refused.status, StatusCode::CONFLICT, "{:?}", refused.body);
2331 assert_eq!(refused.body["code"], "class_at_roster_ceiling");
2332
2333 let freed = send(
2334 &app,
2335 "DELETE",
2336 &format!("/classes/{class}/members/{student_id}"),
2337 Some(&manager),
2338 None,
2339 )
2340 .await;
2341 assert_eq!(freed.status, StatusCode::NO_CONTENT, "{:?}", freed.body);
2342 let admitted = send(
2343 &app,
2344 "POST",
2345 &format!("/classes/{class}/members"),
2346 Some(&manager),
2347 Some(json!({ "user_id": other_id })),
2348 )
2349 .await;
2350 assert_eq!(
2351 admitted.status,
2352 StatusCode::CREATED,
2353 "a leave hands the seat back to the cap: {:?}",
2354 admitted.body
2355 );
2356 assert_eq!(
2357 counter(
2358 "SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group",
2359 &db
2360 )
2361 .await,
2362 MAX_CLASS_MEMBERS,
2363 "…and the counter lands back on the ceiling, not past it"
2364 );
2365}
2366
2367/// The dönem's own number is one average over the student's instances, each
2368/// weighted by its `ders_saati` — the karne weight the şube set — and each line
2369/// is labelled from the school's grade bands. Two instances at different hours
2370/// are what makes the weighting visible: a plain mean of 60 and 80 is 70, the
2371/// weighted one 75.
2372#[tokio::test]
2373async fn the_karne_weights_each_instance_by_its_ders_saati() {
2374 let (app, db) = app_and_db().await;
2375 let manager = login_as(&app, &db, "manager", "manager").await;
2376 let student = login_as(&app, &db, "student", "student").await;
2377 let student_id = me_id(&app, &student).await;
2378
2379 // One şube, two courses it teaches: two instances of one section.
2380 let t = taught(&app, &manager, "Matematik").await;
2381 let fizik = create_course(&app, &manager, "Fizik").await;
2382 let fizik = attach_instance(&app, &manager, &t.class, &fizik).await;
2383 let hours = send(
2384 &app,
2385 "PATCH",
2386 &format!("/instances/{fizik}"),
2387 Some(&manager),
2388 Some(json!({ "ders_saati": 3 })),
2389 )
2390 .await;
2391 assert_eq!(hours.status, StatusCode::OK, "{:?}", hours.body);
2392 assert_eq!(hours.body["ders_saati"], json!(3));
2393
2394 add_member(&app, &manager, &t.class, &student_id).await;
2395
2396 // A mark in each instance, graded by the office.
2397 for (instance, mark) in [(&t.instance, 60), (&fizik, 80)] {
2398 let exam = create_exam(&app, &manager, instance, &t.term, "1. Yazılı", "yazili").await;
2399 let graded = send(
2400 &app,
2401 "POST",
2402 &format!("/exams/{exam}/results"),
2403 Some(&manager),
2404 Some(json!({ "mark": mark, "user_id": student_id })),
2405 )
2406 .await;
2407 assert_eq!(
2408 graded.status,
2409 StatusCode::OK,
2410 "grade {mark}: {:?}",
2411 graded.body
2412 );
2413 }
2414
2415 let karne = send(
2416 &app,
2417 "GET",
2418 &format!("/marks/karne?term={}", t.term),
2419 Some(&student),
2420 None,
2421 )
2422 .await;
2423 assert_eq!(karne.status, StatusCode::OK, "{:?}", karne.body);
2424 let lines = karne.body["instances"].as_array().expect("instances[]");
2425 assert_eq!(lines.len(), 2, "{:?}", karne.body);
2426 let line = |instance: &str| {
2427 lines
2428 .iter()
2429 .find(|line| line["class_course"] == json!(instance))
2430 .unwrap_or_else(|| panic!("no line for {instance}: {}", karne.body))
2431 .clone()
2432 };
2433 let math = line(&t.instance);
2434 assert_eq!(math["course"], json!("Matematik"), "the catalog title");
2435 assert_eq!(math["ders_saati"], json!(1));
2436 assert_eq!(math["average"], json!(60.0));
2437 assert_eq!(math["band"], json!("3"), "60 is a 3 on the default bands");
2438 let physics = line(&fizik);
2439 assert_eq!(physics["ders_saati"], json!(3));
2440 assert_eq!(physics["average"], json!(80.0));
2441 assert_eq!(physics["band"], json!("4"));
2442 assert_eq!(
2443 karne.body["year_average"],
2444 json!(75.0),
2445 "the hours weigh, not the line count: {:?}",
2446 karne.body
2447 );
2448 assert_eq!(karne.body["verdict"], json!("gecti"));
2449}