From 67ced099295e53b358eb48d81267116193d6a0e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 4 Aug 2026 21:25:59 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8F=97=EF=B8=8F=20stock=20a=20new?= =?UTF-8?q?=20section=20from=20its=20grade's=20blueprint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Editing a template reached every section already at the grade, but making a section reached no template — so a blueprint described every section except the ones created after it, and the office had to remember a second call each time. A create now applies its grade's blueprint, after the homeroom demotion rollback and never before it: the rollback deletes the class, and that delete refuses while the class holds courses. The 201 body carries the class, what could not be stocked, and which grade's template stocked it — null when none covers the grade, which is also what a stocking that faulted reports, because a 500 here would strand a section whose id nothing else returns. --- README.md | 32 +++- src/lib.rs | 2 +- src/web/classes.rs | 73 ++++++++- tests/board_invite.rs | 2 +- tests/e2e.rs | 4 +- tests/integration.rs | 17 ++- tests/pagination.rs | 2 +- tests/persistence.rs | 2 +- tests/regress_blueprints.rs | 210 +++++++++++++++++++++++++- tests/regress_classes.rs | 68 ++++++++- tests/regress_event_class_audience.rs | 2 +- 11 files changed, 385 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 2b2e642..e9c35dc 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,9 @@ other class read is teacher+, a student reads their own section at `GET /classes/user/{user}`). A grade can also carry a **blueprint** — the course list every section at that grade takes (`/classes/blueprints`), applied to each section best-effort, with anything a limit refuses returned in -`skipped` and anything a human attached by hand left alone. Students read a +`skipped` and anything a human attached by hand left alone; a section created +afterwards at that grade is stocked by `POST /classes` itself, which reports it +as `stocked_from`. Students read a per-course weighted average and an overall average from their mark report — each exam weighted by its **kind** (midterms can count double, orals once: weights are set per kind in settings, @@ -830,7 +832,7 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back | | GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) — each row carries `source`, the class that pumped it or `null` for hand-placed · paged | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | -| POST | `/classes` | manager | `{name, grade?, term_id?, teacher_id?}` — create a class section (şube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (sınıf öğretmeni, teacher+; `409` + full rollback if that account is demoted mid-request) | +| POST | `/classes` | manager | `{name, grade?, term_id?, teacher_id?}` — create a class section (şube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (sınıf öğretmeni, teacher+; `409` + full rollback if that account is demoted mid-request). Stocked at once from its grade's blueprint when one covers it, so the `201` is `{class, skipped, stocked_from}` | | GET | `/classes` | teacher | List classes, newest first · paged | | GET | `/classes/me` | any | The caller's own classes, newest membership first · paged; `creator` is `null` below teacher+ | | GET | `/classes/user/{user}` | teacher | Another user's classes (a parent linked to that student may read it too) · paged; `creator` is `null` below teacher+ | @@ -2855,6 +2857,28 @@ see. new list (a set, not a delta) and reconciles every section at the grade, including the ones that existed before the blueprint did. +**Creating a section stocks it.** The other direction of the same rule: +`POST /classes` at a grade a blueprint covers runs that blueprint's pump on the +new section itself, so a manager opening "9-D" does not have to remember a +second call. Its `201` is therefore `{class, skipped, stocked_from}` — the class +where the bare class object used to be, the pump's usual `skipped` list, and +`stocked_from`, the grade label of the template that stocked it. `stocked_from` +is `null` when **no** template covers the grade, which is what tells that apart +from a template that applied cleanly (`skipped: []` alone reads the same either +way — the ambiguity `matched` closes on the grade-wide pumps). + +Stocking is best-effort all the way to the end of that route: a template that +could not be read, or a pump that faulted part-way, leaves `stocked_from` null +rather than turning a class that *exists* into a `500` whose caller never learns +its id — a class id is a ULID and `POST /classes` is the only place it is +returned from, unlike a blueprint, whose id is the grade label the caller sent. +The retry is `POST /classes/{id}/blueprint`, which is idempotent and is also +what a caller runs when there is genuinely no template, so the two cases need +no telling apart. The stocking runs **after** the homeroom-teacher rollback, and +must: a class holding courses refuses deletion, so a section stocked first could +not be rolled back and the `409` would leave one standing behind a promise that +nothing was created. + **Pumping is best-effort.** Each (section, course) pair is one all-or-nothing transaction. A pair that would breach a limit — the section is at `max_class_courses`, or the course has no free seat for the whole section — is @@ -2874,7 +2898,9 @@ not match the one those sections carry, and the fix is the label, not the template. It counts the sections **reached**, not the ones the grade holds: `blueprint_deleted` ends the run, and then the number is what happened. `POST /classes/{id}/blueprint` has no `matched` — it pumps the one section in -the path. +the path — and neither has `POST /classes`, for the same reason: the one +section it pumps is the one it just created, and `stocked_from` already says +whether a template was found. A skip's `reason` is a **machine code**, not a sentence: the client owns the wording (and the language), the same id-plus-client-label shape roles and diff --git a/src/lib.rs b/src/lib.rs index bb613e7..c730f72 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,7 +50,7 @@ use crate::state::AppState; (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"), - (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. Creating or editing one retro-pumps every class already at the grade, and does so best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `linked_course_missing`, `blueprint_deleted`), like every other enum here. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list — the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"), + (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `linked_course_missing`, `blueprint_deleted`), like every other enum here. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list — the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher). Roll call is also what feeds two badge counters (see `users`): the first mark taken for a lesson credits its teacher's `lessons_held_total` once, and a student marked `present` or `late` gains a `lessons_attended_total` a later correction gives back"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), diff --git a/src/web/classes.rs b/src/web/classes.rs index 1a5257b..793d0d8 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -155,6 +155,29 @@ impl ClassResponse { } } +/// A created class plus what its grade's blueprint did to it — the shape +/// [`BlueprintPumpResponse`] already has on the other write that pumps, with the +/// class in place of the template. +#[derive(Serialize, ToSchema)] +struct CreateClassResponse { + class: ClassResponse, + /// The courses the template could not put on this section, empty when it + /// took them all (and always empty when no template covered its grade). + skipped: Vec, + /// The grade label of the blueprint that stocked this section, or `null` + /// when none did. `null` with an empty `skipped` is what tells "no template + /// covers this grade" apart from "the template applied cleanly" — the + /// distinction `matched` makes on the grade-wide pumps. + /// + /// Stocking is best-effort to the end: a template that could not be read, + /// or a pump that faulted part-way, also reads `null` rather than turning a + /// section that exists into a `500` whose caller never learns its id. The + /// remedy is the same either way — `POST /classes/{id}/blueprint`, which is + /// idempotent and `404`s when there is genuinely no template. + #[schema(example = "9")] + stocked_from: Option, +} + /// Every person a [`ClassResponse`] names: its homeroom teacher, plus its /// creator when the caller is cleared to see one. Feed this into `person_map` — /// an id the map is missing renders as a bare ULID, so a creator left out here @@ -297,6 +320,12 @@ async fn classes_page( /// teacher's own room. `grade` is a free-text label for the year ("9", "10-A"), /// `term_id` links the school calendar, `teacher_id` names the homeroom teacher /// (sınıf öğretmeni, a teacher+ account); all optional. +/// +/// If a blueprint covers the new class's grade, the class is **stocked from it +/// at once** — the same best-effort pump `POST /classes/{id}/blueprint` runs, so +/// a course that does not fit comes back in `skipped` and the class is created +/// either way. `stocked_from` names the template that did it, and is `null` when +/// none covered the grade. #[utoipa::path( post, path = "/", @@ -304,7 +333,7 @@ async fn classes_page( security(("session_cookie" = [])), request_body = CreateClass, responses( - (status = 201, description = "Class created", body = ClassResponse), + (status = 201, description = "Class created, stocked from its grade's blueprint when one covers it", body = CreateClassResponse), (status = 400, description = "Invalid name or grade, an unknown term, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), @@ -316,7 +345,7 @@ async fn create_class( State(st): State, RequireManager(user): RequireManager, Json(req): Json, -) -> Result<(StatusCode, Json), AppError> { +) -> Result<(StatusCode, Json), AppError> { let name = ClassName::try_new(&req.name)?; let grade = grade_or_none(req.grade.as_deref())?; // Pre-flight only: `ClassGroup::create` claims a reference on the term @@ -357,16 +386,54 @@ async fn create_class( } return Err(demoted); } + // Stocking runs **after** that rollback, never before: `ClassGroup::delete` + // refuses a class holding courses, so a section pumped first could not be + // rolled back and the `409` above would leave a half-created class standing + // behind a promise that nothing was created. + let stocked = stock_from_blueprint(&class, user.get_id(), &st.db).await; // The creator is the caller and the teacher was just read — no extra lookup. let mut named = vec![&user]; named.extend(teacher.as_ref()); let people = PersonRef::map_of(&named); Ok(( StatusCode::CREATED, - Json(ClassResponse::new(&class, &people, true)), + Json(CreateClassResponse { + class: ClassResponse::new(&class, &people, true), + skipped: stocked + .iter() + .flat_map(|(_, skipped)| skipped.iter().map(SkipResponse::new)) + .collect(), + stocked_from: stocked.map(|(grade, _)| grade), + }), )) } +/// Stock a freshly created class from its grade's blueprint, if one covers it: +/// the template's grade label and the pairs it could not place, or `None` when +/// the class has no grade, no blueprint holds that grade, or the stocking could +/// not be carried out. +/// +/// Swallowing that last case is the deliberate one. Every other pump here may +/// fail its whole request, because the caller can name what it asked for again — +/// a blueprint's id *is* the grade label they sent. A class's id is a ULID this +/// request is the only place it is ever returned from, so a `500` after the row +/// is written loses a section that exists. Best-effort therefore runs to the end +/// of this route: the class is reported, `stocked_from` stays `null`, and the +/// retry is the idempotent `POST /classes/{id}/blueprint` — which is also the +/// remedy when no template covers the grade, so the two need not be told apart. +async fn stock_from_blueprint( + class: &ClassGroup, + by: &UserId, + db: &Database, +) -> Option<(String, Vec)> { + let grade = class.get_grade()?; + let blueprint = ClassBlueprint::read(&ClassBlueprintId::for_grade(grade), db) + .await + .ok()??; + let skipped = blueprint.apply_to(class, by, db).await.ok()?; + Some((blueprint.get_grade().as_str().to_string(), skipped)) +} + /// List every class, newest first. Requires teacher+. Paged via `?limit=&offset=` /// (omit `limit` for the full list); returns a `{items, total, limit, offset}` /// envelope. diff --git a/tests/board_invite.rs b/tests/board_invite.rs index 064c73a..6fc44e3 100644 --- a/tests/board_invite.rs +++ b/tests/board_invite.rs @@ -70,7 +70,7 @@ async fn a_class(app: &axum::Router, manager: &str, name: &str, members: &[&str] ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let class = res.body["id"].as_str().unwrap().to_string(); + let class = res.body["class"]["id"].as_str().unwrap().to_string(); for user in members { let res = send( app, diff --git a/tests/e2e.rs b/tests/e2e.rs index 37e9f7f..e5c3019 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -3172,7 +3172,9 @@ async fn a_class_seats_its_roster_and_gives_the_seat_back() { .await .unwrap(); assert_eq!(res.status(), StatusCode::CREATED); - let class = id_of(&res.json::().await.unwrap()); + // `POST /classes` answers `{class, skipped, stocked_from}` — it stocks the + // new section from its grade's blueprint, and there is none here. + let class = id_of(&res.json::().await.unwrap()["class"]); let res = manager .post(format!("{base}/classes/{class}/members")) .json(&json!({ "user_id": student_id })) diff --git a/tests/integration.rs b/tests/integration.rs index b1294d5..5b40e48 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -25359,8 +25359,11 @@ async fn a_class_pumps_enrollments_and_guards_each_axis_separately() { ) .await; assert_eq!(res.status, StatusCode::CREATED); - assert!(res.body["grade"].is_null(), "an empty grade is no grade"); - let class = id_of(&res.body); + assert!( + res.body["class"]["grade"].is_null(), + "an empty grade is no grade" + ); + let class = id_of(&res.body["class"]); assert_eq!( send(&app, "GET", "/classes", Some(&teacher), None) .await @@ -25540,7 +25543,7 @@ async fn class_reads_are_staff_only_and_a_manager_manages_every_course() { ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let class = id_of(&res.body); + let class = id_of(&res.body["class"]); // The student really is on this roster, so the 403s below are the gate // talking and not an empty database. let res = send( @@ -25641,7 +25644,7 @@ async fn a_demotion_sweeps_the_class_membership_and_what_it_pumped() { ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let class = id_of(&res.body); + let class = id_of(&res.body["class"]); let res = send( &app, "POST", @@ -25793,8 +25796,8 @@ async fn a_term_a_class_points_at_refuses_to_delete() { ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - assert_eq!(res.body["term"].as_str(), Some(term.as_str())); - let class = id_of(&res.body); + assert_eq!(res.body["class"]["term"].as_str(), Some(term.as_str())); + let class = id_of(&res.body["class"]); let res = send( &app, @@ -25885,7 +25888,7 @@ async fn a_course_that_cannot_seat_the_whole_class_seats_none_of_it() { ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let class = id_of(&res.body); + let class = id_of(&res.body["class"]); for student in [&ali_id, &veli_id] { let res = send( &app, diff --git a/tests/pagination.rs b/tests/pagination.rs index e1dce93..e439651 100644 --- a/tests/pagination.rs +++ b/tests/pagination.rs @@ -590,7 +590,7 @@ async fn class_lists_are_paged() { ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - classes.push(res.body["id"].as_str().unwrap().to_string()); + classes.push(res.body["class"]["id"].as_str().unwrap().to_string()); } let class = classes[0].clone(); for n in 0..3 { diff --git a/tests/persistence.rs b/tests/persistence.rs index fe5d87b..0342e77 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -2175,7 +2175,7 @@ async fn pre_class_enrollments_keep_their_absent_source() { ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let class = common::id_of(&res.body); + let class = common::id_of(&res.body["class"]); let res = send( &app, "POST", diff --git a/tests/regress_blueprints.rs b/tests/regress_blueprints.rs index f391636..6f28dcb 100644 --- a/tests/regress_blueprints.rs +++ b/tests/regress_blueprints.rs @@ -82,7 +82,10 @@ async fn create_class(app: &axum::Router, cookie: &str, name: &str, grade: &str) ) .await; assert_eq!(res.status, StatusCode::CREATED, "create class {name}"); - res.body["id"].as_str().expect("class id").to_string() + res.body["class"]["id"] + .as_str() + .expect("class id") + .to_string() } /// Register a student, put them in a class, and hand back their id. @@ -304,6 +307,193 @@ async fn a_fresh_class_takes_its_grades_blueprint() { assert_eq!(none.status, StatusCode::NOT_FOUND); } +/// The other direction of the retro-pump: a section created *after* the +/// template exists is stocked by `POST /classes` itself, and a grade no +/// template covers says so with `stocked_from: null` rather than being +/// indistinguishable from a template that applied cleanly. +#[tokio::test] +async fn creating_a_class_stocks_it_from_its_grades_blueprint() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "mgr", "manager").await; + let algebra = create_course(&app, &manager, "algebra").await; + let physics = create_course(&app, &manager, "physics").await; + let made = send( + &app, + "POST", + "/classes/blueprints", + Some(&manager), + Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })), + ) + .await; + assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); + + let res = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A", "grade": "9" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); + assert_eq!( + res.body["stocked_from"], "9", + "the create must name the template that stocked it: {:?}", + res.body + ); + assert!(skips(&res).is_empty(), "{:?}", res.body); + let class = res.body["class"]["id"] + .as_str() + .expect("class id") + .to_string(); + + // Stored state, not the answer: the links are really there, and they carry + // the blueprint's tag, so a later edit or delete can take them back. + for course in [&algebra, &physics] { + assert!(attached(&class, course, &db).await, "{course} is attached"); + assert_eq!( + source_of(&class, course, &db).await, + Some("9".to_string()), + "the blueprint must own what a create attached, exactly as a pump does" + ); + } + assert_eq!( + counter( + &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"), + &db + ) + .await, + 2 + ); + + // A class is empty at create, so this is the first place the enrollment + // rows the attachments owe can be seen: a member added now is enrolled into + // both courses, in real rows. + let student = student_in(&app, &db, &class, &manager, "ali").await; + for course in [&algebra, &physics] { + assert_eq!( + rows( + &format!( + "SELECT VALUE id FROM enrollment WHERE course = course:{course} \ + AND user = user:{student}" + ), + &db + ) + .await, + 1, + "a stocked class enrolls its roster like any other" + ); + } + + // A grade no template covers, and a class with no grade at all: `null`, + // which is the one thing an empty `skipped` could never say. + for body in [ + json!({ "name": "10-A", "grade": "10" }), + json!({ "name": "satranç", "grade": "" }), + ] { + let res = send(&app, "POST", "/classes", Some(&manager), Some(body)).await; + assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); + assert!( + res.body["stocked_from"].is_null(), + "no template covers it: {:?}", + res.body + ); + assert!(skips(&res).is_empty(), "{:?}", res.body); + let bare = res.body["class"]["id"].as_str().unwrap(); + assert_eq!( + rows( + &format!("SELECT VALUE id FROM class_course WHERE class = class_group:{bare}"), + &db + ) + .await, + 0, + "nothing may be attached to a section no template reached" + ); + } +} + +/// A create whose stocking cannot place everything still creates the class: the +/// pair that did not fit comes back in `skipped`, best-effort exactly like +/// every other pump here. +#[tokio::test] +async fn a_create_reports_what_its_blueprint_could_not_stock() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "mgr", "manager").await; + let algebra = create_course(&app, &manager, "algebra").await; + let physics = create_course(&app, &manager, "physics").await; + let made = send( + &app, + "POST", + "/classes/blueprints", + Some(&manager), + Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })), + ) + .await; + assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); + + // Delete a course out from under the template. Nothing carries it yet — no + // section exists at grade 9 — so this is the pair that cannot fit when the + // first one is created. + let dropped = send( + &app, + "DELETE", + &format!("/courses/{physics}"), + Some(&manager), + None, + ) + .await; + assert_eq!(dropped.status, StatusCode::NO_CONTENT, "{:?}", dropped.body); + + let res = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A", "grade": "9" })), + ) + .await; + assert_eq!( + res.status, + StatusCode::CREATED, + "a pair that will not fit may not cost the class: {:?}", + res.body + ); + assert_eq!(res.body["stocked_from"], "9"); + assert_eq!(skips(&res).len(), 1, "{:?}", res.body); + assert_eq!(skips(&res)[0]["reason"], "course_deleted"); + assert_eq!(skips(&res)[0]["course"], physics.as_str()); + assert_eq!(skips(&res)[0]["class_name"], "9-A"); + + let class = res.body["class"]["id"] + .as_str() + .expect("class id") + .to_string(); + assert_eq!( + rows( + &format!("SELECT VALUE id FROM class_group WHERE id = class_group:{class}"), + &db + ) + .await, + 1, + "the class is really there — the skip is a report, not a rollback" + ); + assert!( + attached(&class, &algebra, &db).await, + "…and the course that did fit is on it" + ); + assert_eq!( + rows( + &format!("SELECT VALUE id FROM class_course WHERE class = class_group:{class}"), + &db + ) + .await, + 1 + ); + // The dangling id is pruned by the run that found it, here as anywhere. + let read = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await; + assert_eq!(read.body["courses"].as_array().unwrap().len(), 1); +} + /// The ruling that costs the most: editing the template reaches every section /// already at the grade, not just the ones made afterwards. And the sections at /// *other* grades are left alone. @@ -674,9 +864,21 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() { ) .await; assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); - // The section comes after the template, so nothing is attached until the - // pump below runs. - let class = create_class(&app, &manager, "9-A", "9").await; + // The section has to reach grade 9 without being stocked on the way, so + // that the pump below is the *first* attach: a section created at the grade + // is stocked by its own create, and one that existed already was stocked by + // the template's. Moving it there afterwards is neither — a grade change is + // deliberately a blueprint no-op. + let class = create_class(&app, &manager, "9-A", "10").await; + let moved = send( + &app, + "PATCH", + &format!("/classes/{class}"), + Some(&manager), + Some(json!({ "grade": "9" })), + ) + .await; + assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body); assert!(!attached(&class, &algebra, &db).await); // Delete the blueprint from inside the very write that attaches on its diff --git a/tests/regress_classes.rs b/tests/regress_classes.rs index 67d9bf3..0fe5d21 100644 --- a/tests/regress_classes.rs +++ b/tests/regress_classes.rs @@ -109,7 +109,7 @@ async fn a_stale_link_detaches_and_frees_its_class() { ) .await; assert_eq!(res.status, StatusCode::CREATED); - res.body["id"].as_str().unwrap().to_string() + res.body["class"]["id"].as_str().unwrap().to_string() }; let attached = send( &app, @@ -185,7 +185,7 @@ async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() { Some(json!({ "name": "9-A" })), ) .await; - res.body["id"].as_str().unwrap().to_string() + res.body["class"]["id"].as_str().unwrap().to_string() }; send( &app, @@ -241,7 +241,7 @@ async fn a_hand_enroll_takes_the_row_off_the_class() { Some(json!({ "name": "9-A" })), ) .await; - res.body["id"].as_str().unwrap().to_string() + res.body["class"]["id"].as_str().unwrap().to_string() }; send( &app, @@ -338,7 +338,7 @@ async fn a_role_change_sweeps_memberships_and_enrollments_together() { Some(json!({ "name": "9-A" })), ) .await; - res.body["id"].as_str().unwrap().to_string() + res.body["class"]["id"].as_str().unwrap().to_string() }; send( &app, @@ -781,10 +781,15 @@ async fn a_class_over_the_course_ceiling_takes_no_member() { // ---- homeroom teacher (sınıf öğretmeni) ------------------------------------ -/// Create a class as `cookie` (asserts 201); returns the whole response body. +/// Create a class as `cookie` (asserts 201); returns the response with its +/// `body` narrowed to the created class — the `201` is +/// `{class, skipped, stocked_from}` since a create stocks from its grade's +/// blueprint, and the tests below are about the class itself. The two outer +/// fields have their own tests (`regress_blueprints`). async fn create_class(app: &axum::Router, cookie: &str, body: serde_json::Value) -> Res { - let res = send(app, "POST", "/classes", Some(cookie), Some(body)).await; + let mut res = send(app, "POST", "/classes", Some(cookie), Some(body)).await; assert_eq!(res.status, StatusCode::CREATED, "create class"); + res.body = res.body["class"].clone(); res } @@ -1415,6 +1420,57 @@ async fn a_create_whose_teacher_is_demoted_mid_write_rolls_back_whole() { ); } +/// The same rollback at a grade a **blueprint** covers, which is what pins the +/// order of the two: a create stocks itself from its grade's template, and that +/// stocking runs *after* this demotion check. Were it the other way round the +/// class would hold courses by the time the rollback ran, `ClassGroup::delete` +/// refuses one that does, and the `409` promising nothing was created would +/// leave a stocked section standing behind it. +#[tokio::test] +async fn a_rolled_back_create_at_a_blueprinted_grade_leaves_nothing_behind() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + let course = create_course(&app, &manager, "algebra").await; + let made = send( + &app, + "POST", + "/classes/blueprints", + Some(&manager), + Some(json!({ "grade": "9", "course_ids": [course] })), + ) + .await; + assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); + + demote_during_writes_to("class_group", "CREATE", &teacher_id, &db).await; + let res = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A", "grade": "9", "teacher_id": teacher_id })), + ) + .await; + + assert_eq!( + res.status, + StatusCode::CONFLICT, + "the demotion still wins over the stocking: {:?}", + res.body + ); + assert_eq!( + rows("SELECT VALUE id FROM class_group", &db).await, + 0, + "the rollback must still have been able to delete the class" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "…which it only can because nothing was stocked onto it first" + ); +} + /// `PATCH /classes/{id}` naming a teacher who is demoted while the row is being /// written: `409`, and the column it just set is taken back. #[tokio::test] diff --git a/tests/regress_event_class_audience.rs b/tests/regress_event_class_audience.rs index 482de2a..2cf14e0 100644 --- a/tests/regress_event_class_audience.rs +++ b/tests/regress_event_class_audience.rs @@ -23,7 +23,7 @@ async fn create_class(app: &Router, cookie: &str, name: &str) -> String { ) .await; assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); - id_of(&res.body) + id_of(&res.body["class"]) } /// An event aimed at `class`, created by a teacher+.