forge
Explore
Log in

Don't you dare go Hollow

🏗️ stock a new section from its grade's blueprint

Browse files at this commit

67ced099295e53b358eb48d81267116193d6a0e9Ahmet Kaan GümüşParent: 81c5490
  • feat
    • 🏗️ stock a new section from its grade's blueprint
Show full message
feat: 🏗️ stock a new section from its grade's blueprint

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.mdmodified+29 -3
@@ -49,7 +49,9 @@ other class read is teacher+, a student reads their own section at
49 `GET /classes/user/{user}`). A grade can also carry a **blueprint** — the49 `GET /classes/user/{user}`). A grade can also carry a **blueprint** — the
50 course list every section at that grade takes (`/classes/blueprints`), applied50 course list every section at that grade takes (`/classes/blueprints`), applied
51 to each section best-effort, with anything a limit refuses returned in51 to each section best-effort, with anything a limit refuses returned in
52-`skipped` and anything a human attached by hand left alone. Students read a52+`skipped` and anything a human attached by hand left alone; a section created
53+afterwards at that grade is stocked by `POST /classes` itself, which reports it
54+as `stocked_from`. Students read a
53 per-course weighted average and55 per-course weighted average and
54 an overall average from their mark report — each exam weighted by its **kind**56 an overall average from their mark report — each exam weighted by its **kind**
55 (midterms can count double, orals once: weights are set per kind in settings,57 (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.
830 | 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 |832 | 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 |
831 | 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 |833 | 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 |
832 | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |834 | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |
833-| 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) |835+| 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}` |
834 | GET | `/classes` | teacher | List classes, newest first · paged |836 | GET | `/classes` | teacher | List classes, newest first · paged |
835 | GET | `/classes/me` | any | The caller's own classes, newest membership first · paged; `creator` is `null` below teacher+ |837 | GET | `/classes/me` | any | The caller's own classes, newest membership first · paged; `creator` is `null` below teacher+ |
836 | 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+ |838 | 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.
2855 new list (a set, not a delta) and reconciles every section at the grade,2857 new list (a set, not a delta) and reconciles every section at the grade,
2856 including the ones that existed before the blueprint did.2858 including the ones that existed before the blueprint did.
2857 2859
2860+**Creating a section stocks it.** The other direction of the same rule:
2861+`POST /classes` at a grade a blueprint covers runs that blueprint's pump on the
2862+new section itself, so a manager opening "9-D" does not have to remember a
2863+second call. Its `201` is therefore `{class, skipped, stocked_from}` — the class
2864+where the bare class object used to be, the pump's usual `skipped` list, and
2865+`stocked_from`, the grade label of the template that stocked it. `stocked_from`
2866+is `null` when **no** template covers the grade, which is what tells that apart
2867+from a template that applied cleanly (`skipped: []` alone reads the same either
2868+way — the ambiguity `matched` closes on the grade-wide pumps).
2869+
2870+Stocking is best-effort all the way to the end of that route: a template that
2871+could not be read, or a pump that faulted part-way, leaves `stocked_from` null
2872+rather than turning a class that *exists* into a `500` whose caller never learns
2873+its id — a class id is a ULID and `POST /classes` is the only place it is
2874+returned from, unlike a blueprint, whose id is the grade label the caller sent.
2875+The retry is `POST /classes/{id}/blueprint`, which is idempotent and is also
2876+what a caller runs when there is genuinely no template, so the two cases need
2877+no telling apart. The stocking runs **after** the homeroom-teacher rollback, and
2878+must: a class holding courses refuses deletion, so a section stocked first could
2879+not be rolled back and the `409` would leave one standing behind a promise that
2880+nothing was created.
2881+
2858 **Pumping is best-effort.** Each (section, course) pair is one all-or-nothing2882 **Pumping is best-effort.** Each (section, course) pair is one all-or-nothing
2859 transaction. A pair that would breach a limit — the section is at2883 transaction. A pair that would breach a limit — the section is at
2860 `max_class_courses`, or the course has no free seat for the whole section — is2884 `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
2874 template. It counts the sections **reached**, not the ones the grade holds:2898 template. It counts the sections **reached**, not the ones the grade holds:
2875 `blueprint_deleted` ends the run, and then the number is what happened.2899 `blueprint_deleted` ends the run, and then the number is what happened.
2876 `POST /classes/{id}/blueprint` has no `matched` — it pumps the one section in2900 `POST /classes/{id}/blueprint` has no `matched` — it pumps the one section in
2877-the path.2901+the path — and neither has `POST /classes`, for the same reason: the one
2902+section it pumps is the one it just created, and `stocked_from` already says
2903+whether a template was found.
2878 2904
2879 A skip's `reason` is a **machine code**, not a sentence: the client owns the2905 A skip's `reason` is a **machine code**, not a sentence: the client owns the
2880 wording (and the language), the same id-plus-client-label shape roles and2906 wording (and the language), the same id-plus-client-label shape roles and
src/lib.rsmodified+1 -1
@@ -50,7 +50,7 @@ use crate::state::AppState;
50 (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"),50 (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"),
51 (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"),51 (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"),
52 (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"),52 (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"),
53- (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 `/ \\ ? # %`"),53+ (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 `/ \\ ? # %`"),
54 (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"),54 (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"),
55 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),55 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
56 (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"),56 (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"),
src/web/classes.rsmodified+70 -3
@@ -155,6 +155,29 @@ impl ClassResponse {
155 }155 }
156 }156 }
157 157
158+/// A created class plus what its grade's blueprint did to it — the shape
159+/// [`BlueprintPumpResponse`] already has on the other write that pumps, with the
160+/// class in place of the template.
161+#[derive(Serialize, ToSchema)]
162+struct CreateClassResponse {
163+ class: ClassResponse,
164+ /// The courses the template could not put on this section, empty when it
165+ /// took them all (and always empty when no template covered its grade).
166+ skipped: Vec<SkipResponse>,
167+ /// The grade label of the blueprint that stocked this section, or `null`
168+ /// when none did. `null` with an empty `skipped` is what tells "no template
169+ /// covers this grade" apart from "the template applied cleanly" — the
170+ /// distinction `matched` makes on the grade-wide pumps.
171+ ///
172+ /// Stocking is best-effort to the end: a template that could not be read,
173+ /// or a pump that faulted part-way, also reads `null` rather than turning a
174+ /// section that exists into a `500` whose caller never learns its id. The
175+ /// remedy is the same either way — `POST /classes/{id}/blueprint`, which is
176+ /// idempotent and `404`s when there is genuinely no template.
177+ #[schema(example = "9")]
178+ stocked_from: Option<String>,
179+}
180+
158 /// Every person a [`ClassResponse`] names: its homeroom teacher, plus its181 /// Every person a [`ClassResponse`] names: its homeroom teacher, plus its
159 /// creator when the caller is cleared to see one. Feed this into `person_map` —182 /// creator when the caller is cleared to see one. Feed this into `person_map` —
160 /// an id the map is missing renders as a bare ULID, so a creator left out here183 /// 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(
297 /// teacher's own room. `grade` is a free-text label for the year ("9", "10-A"),320 /// teacher's own room. `grade` is a free-text label for the year ("9", "10-A"),
298 /// `term_id` links the school calendar, `teacher_id` names the homeroom teacher321 /// `term_id` links the school calendar, `teacher_id` names the homeroom teacher
299 /// (sınıf öğretmeni, a teacher+ account); all optional.322 /// (sınıf öğretmeni, a teacher+ account); all optional.
323+///
324+/// If a blueprint covers the new class's grade, the class is **stocked from it
325+/// at once** — the same best-effort pump `POST /classes/{id}/blueprint` runs, so
326+/// a course that does not fit comes back in `skipped` and the class is created
327+/// either way. `stocked_from` names the template that did it, and is `null` when
328+/// none covered the grade.
300 #[utoipa::path(329 #[utoipa::path(
301 post,330 post,
302 path = "/",331 path = "/",
@@ -304,7 +333,7 @@ async fn classes_page(
304 security(("session_cookie" = [])),333 security(("session_cookie" = [])),
305 request_body = CreateClass,334 request_body = CreateClass,
306 responses(335 responses(
307- (status = 201, description = "Class created", body = ClassResponse),336+ (status = 201, description = "Class created, stocked from its grade's blueprint when one covers it", body = CreateClassResponse),
308 (status = 400, description = "Invalid name or grade, an unknown term, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse),337 (status = 400, description = "Invalid name or grade, an unknown term, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse),
309 (status = 401, description = "Not authenticated", body = ErrorResponse),338 (status = 401, description = "Not authenticated", body = ErrorResponse),
310 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),339 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
@@ -316,7 +345,7 @@ async fn create_class(
316 State(st): State<AppState>,345 State(st): State<AppState>,
317 RequireManager(user): RequireManager,346 RequireManager(user): RequireManager,
318 Json(req): Json<CreateClass>,347 Json(req): Json<CreateClass>,
319-) -> Result<(StatusCode, Json<ClassResponse>), AppError> {348+) -> Result<(StatusCode, Json<CreateClassResponse>), AppError> {
320 let name = ClassName::try_new(&req.name)?;349 let name = ClassName::try_new(&req.name)?;
321 let grade = grade_or_none(req.grade.as_deref())?;350 let grade = grade_or_none(req.grade.as_deref())?;
322 // Pre-flight only: `ClassGroup::create` claims a reference on the term351 // Pre-flight only: `ClassGroup::create` claims a reference on the term
@@ -357,16 +386,54 @@ async fn create_class(
357 }386 }
358 return Err(demoted);387 return Err(demoted);
359 }388 }
389+ // Stocking runs **after** that rollback, never before: `ClassGroup::delete`
390+ // refuses a class holding courses, so a section pumped first could not be
391+ // rolled back and the `409` above would leave a half-created class standing
392+ // behind a promise that nothing was created.
393+ let stocked = stock_from_blueprint(&class, user.get_id(), &st.db).await;
360 // The creator is the caller and the teacher was just read — no extra lookup.394 // The creator is the caller and the teacher was just read — no extra lookup.
361 let mut named = vec![&user];395 let mut named = vec![&user];
362 named.extend(teacher.as_ref());396 named.extend(teacher.as_ref());
363 let people = PersonRef::map_of(&named);397 let people = PersonRef::map_of(&named);
364 Ok((398 Ok((
365 StatusCode::CREATED,399 StatusCode::CREATED,
366- Json(ClassResponse::new(&class, &people, true)),400+ Json(CreateClassResponse {
401+ class: ClassResponse::new(&class, &people, true),
402+ skipped: stocked
403+ .iter()
404+ .flat_map(|(_, skipped)| skipped.iter().map(SkipResponse::new))
405+ .collect(),
406+ stocked_from: stocked.map(|(grade, _)| grade),
407+ }),
367 ))408 ))
368 }409 }
369 410
411+/// Stock a freshly created class from its grade's blueprint, if one covers it:
412+/// the template's grade label and the pairs it could not place, or `None` when
413+/// the class has no grade, no blueprint holds that grade, or the stocking could
414+/// not be carried out.
415+///
416+/// Swallowing that last case is the deliberate one. Every other pump here may
417+/// fail its whole request, because the caller can name what it asked for again —
418+/// a blueprint's id *is* the grade label they sent. A class's id is a ULID this
419+/// request is the only place it is ever returned from, so a `500` after the row
420+/// is written loses a section that exists. Best-effort therefore runs to the end
421+/// of this route: the class is reported, `stocked_from` stays `null`, and the
422+/// retry is the idempotent `POST /classes/{id}/blueprint` — which is also the
423+/// remedy when no template covers the grade, so the two need not be told apart.
424+async fn stock_from_blueprint(
425+ class: &ClassGroup,
426+ by: &UserId,
427+ db: &Database,
428+) -> Option<(String, Vec<Skip>)> {
429+ let grade = class.get_grade()?;
430+ let blueprint = ClassBlueprint::read(&ClassBlueprintId::for_grade(grade), db)
431+ .await
432+ .ok()??;
433+ let skipped = blueprint.apply_to(class, by, db).await.ok()?;
434+ Some((blueprint.get_grade().as_str().to_string(), skipped))
435+}
436+
370 /// List every class, newest first. Requires teacher+. Paged via `?limit=&offset=`437 /// List every class, newest first. Requires teacher+. Paged via `?limit=&offset=`
371 /// (omit `limit` for the full list); returns a `{items, total, limit, offset}`438 /// (omit `limit` for the full list); returns a `{items, total, limit, offset}`
372 /// envelope.439 /// envelope.
tests/board_invite.rsmodified+1 -1
@@ -70,7 +70,7 @@ async fn a_class(app: &axum::Router, manager: &str, name: &str, members: &[&str]
70 )70 )
71 .await;71 .await;
72 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);72 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
73- let class = res.body["id"].as_str().unwrap().to_string();73+ let class = res.body["class"]["id"].as_str().unwrap().to_string();
74 for user in members {74 for user in members {
75 let res = send(75 let res = send(
76 app,76 app,
tests/e2e.rsmodified+3 -1
@@ -3172,7 +3172,9 @@ async fn a_class_seats_its_roster_and_gives_the_seat_back() {
3172 .await3172 .await
3173 .unwrap();3173 .unwrap();
3174 assert_eq!(res.status(), StatusCode::CREATED);3174 assert_eq!(res.status(), StatusCode::CREATED);
3175- let class = id_of(&res.json::<Value>().await.unwrap());3175+ // `POST /classes` answers `{class, skipped, stocked_from}` — it stocks the
3176+ // new section from its grade's blueprint, and there is none here.
3177+ let class = id_of(&res.json::<Value>().await.unwrap()["class"]);
3176 let res = manager3178 let res = manager
3177 .post(format!("{base}/classes/{class}/members"))3179 .post(format!("{base}/classes/{class}/members"))
3178 .json(&json!({ "user_id": student_id }))3180 .json(&json!({ "user_id": student_id }))
tests/integration.rsmodified+10 -7
@@ -25359,8 +25359,11 @@ async fn a_class_pumps_enrollments_and_guards_each_axis_separately() {
25359 )25359 )
25360 .await;25360 .await;
25361 assert_eq!(res.status, StatusCode::CREATED);25361 assert_eq!(res.status, StatusCode::CREATED);
25362- assert!(res.body["grade"].is_null(), "an empty grade is no grade");25362+ assert!(
25363- let class = id_of(&res.body);25363+ res.body["class"]["grade"].is_null(),
25364+ "an empty grade is no grade"
25365+ );
25366+ let class = id_of(&res.body["class"]);
25364 assert_eq!(25367 assert_eq!(
25365 send(&app, "GET", "/classes", Some(&teacher), None)25368 send(&app, "GET", "/classes", Some(&teacher), None)
25366 .await25369 .await
@@ -25540,7 +25543,7 @@ async fn class_reads_are_staff_only_and_a_manager_manages_every_course() {
25540 )25543 )
25541 .await;25544 .await;
25542 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);25545 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
25543- let class = id_of(&res.body);25546+ let class = id_of(&res.body["class"]);
25544 // The student really is on this roster, so the 403s below are the gate25547 // The student really is on this roster, so the 403s below are the gate
25545 // talking and not an empty database.25548 // talking and not an empty database.
25546 let res = send(25549 let res = send(
@@ -25641,7 +25644,7 @@ async fn a_demotion_sweeps_the_class_membership_and_what_it_pumped() {
25641 )25644 )
25642 .await;25645 .await;
25643 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);25646 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
25644- let class = id_of(&res.body);25647+ let class = id_of(&res.body["class"]);
25645 let res = send(25648 let res = send(
25646 &app,25649 &app,
25647 "POST",25650 "POST",
@@ -25793,8 +25796,8 @@ async fn a_term_a_class_points_at_refuses_to_delete() {
25793 )25796 )
25794 .await;25797 .await;
25795 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);25798 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
25796- assert_eq!(res.body["term"].as_str(), Some(term.as_str()));25799+ assert_eq!(res.body["class"]["term"].as_str(), Some(term.as_str()));
25797- let class = id_of(&res.body);25800+ let class = id_of(&res.body["class"]);
25798 25801
25799 let res = send(25802 let res = send(
25800 &app,25803 &app,
@@ -25885,7 +25888,7 @@ async fn a_course_that_cannot_seat_the_whole_class_seats_none_of_it() {
25885 )25888 )
25886 .await;25889 .await;
25887 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);25890 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
25888- let class = id_of(&res.body);25891+ let class = id_of(&res.body["class"]);
25889 for student in [&ali_id, &veli_id] {25892 for student in [&ali_id, &veli_id] {
25890 let res = send(25893 let res = send(
25891 &app,25894 &app,
tests/pagination.rsmodified+1 -1
@@ -590,7 +590,7 @@ async fn class_lists_are_paged() {
590 )590 )
591 .await;591 .await;
592 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);592 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
593- classes.push(res.body["id"].as_str().unwrap().to_string());593+ classes.push(res.body["class"]["id"].as_str().unwrap().to_string());
594 }594 }
595 let class = classes[0].clone();595 let class = classes[0].clone();
596 for n in 0..3 {596 for n in 0..3 {
tests/persistence.rsmodified+1 -1
@@ -2175,7 +2175,7 @@ async fn pre_class_enrollments_keep_their_absent_source() {
2175 )2175 )
2176 .await;2176 .await;
2177 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);2177 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
2178- let class = common::id_of(&res.body);2178+ let class = common::id_of(&res.body["class"]);
2179 let res = send(2179 let res = send(
2180 &app,2180 &app,
2181 "POST",2181 "POST",
tests/regress_blueprints.rsmodified+206 -4
@@ -82,7 +82,10 @@ async fn create_class(app: &axum::Router, cookie: &str, name: &str, grade: &str)
82 )82 )
83 .await;83 .await;
84 assert_eq!(res.status, StatusCode::CREATED, "create class {name}");84 assert_eq!(res.status, StatusCode::CREATED, "create class {name}");
85- res.body["id"].as_str().expect("class id").to_string()85+ res.body["class"]["id"]
86+ .as_str()
87+ .expect("class id")
88+ .to_string()
86 }89 }
87 90
88 /// Register a student, put them in a class, and hand back their id.91 /// 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() {
304 assert_eq!(none.status, StatusCode::NOT_FOUND);307 assert_eq!(none.status, StatusCode::NOT_FOUND);
305 }308 }
306 309
310+/// The other direction of the retro-pump: a section created *after* the
311+/// template exists is stocked by `POST /classes` itself, and a grade no
312+/// template covers says so with `stocked_from: null` rather than being
313+/// indistinguishable from a template that applied cleanly.
314+#[tokio::test]
315+async fn creating_a_class_stocks_it_from_its_grades_blueprint() {
316+ let (app, db) = app_and_db().await;
317+ let manager = login_as(&app, &db, "mgr", "manager").await;
318+ let algebra = create_course(&app, &manager, "algebra").await;
319+ let physics = create_course(&app, &manager, "physics").await;
320+ let made = send(
321+ &app,
322+ "POST",
323+ "/classes/blueprints",
324+ Some(&manager),
325+ Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })),
326+ )
327+ .await;
328+ assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
329+
330+ let res = send(
331+ &app,
332+ "POST",
333+ "/classes",
334+ Some(&manager),
335+ Some(json!({ "name": "9-A", "grade": "9" })),
336+ )
337+ .await;
338+ assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body);
339+ assert_eq!(
340+ res.body["stocked_from"], "9",
341+ "the create must name the template that stocked it: {:?}",
342+ res.body
343+ );
344+ assert!(skips(&res).is_empty(), "{:?}", res.body);
345+ let class = res.body["class"]["id"]
346+ .as_str()
347+ .expect("class id")
348+ .to_string();
349+
350+ // Stored state, not the answer: the links are really there, and they carry
351+ // the blueprint's tag, so a later edit or delete can take them back.
352+ for course in [&algebra, &physics] {
353+ assert!(attached(&class, course, &db).await, "{course} is attached");
354+ assert_eq!(
355+ source_of(&class, course, &db).await,
356+ Some("9".to_string()),
357+ "the blueprint must own what a create attached, exactly as a pump does"
358+ );
359+ }
360+ assert_eq!(
361+ counter(
362+ &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"),
363+ &db
364+ )
365+ .await,
366+ 2
367+ );
368+
369+ // A class is empty at create, so this is the first place the enrollment
370+ // rows the attachments owe can be seen: a member added now is enrolled into
371+ // both courses, in real rows.
372+ let student = student_in(&app, &db, &class, &manager, "ali").await;
373+ for course in [&algebra, &physics] {
374+ assert_eq!(
375+ rows(
376+ &format!(
377+ "SELECT VALUE id FROM enrollment WHERE course = course:{course} \
378+ AND user = user:{student}"
379+ ),
380+ &db
381+ )
382+ .await,
383+ 1,
384+ "a stocked class enrolls its roster like any other"
385+ );
386+ }
387+
388+ // A grade no template covers, and a class with no grade at all: `null`,
389+ // which is the one thing an empty `skipped` could never say.
390+ for body in [
391+ json!({ "name": "10-A", "grade": "10" }),
392+ json!({ "name": "satranç", "grade": "" }),
393+ ] {
394+ let res = send(&app, "POST", "/classes", Some(&manager), Some(body)).await;
395+ assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body);
396+ assert!(
397+ res.body["stocked_from"].is_null(),
398+ "no template covers it: {:?}",
399+ res.body
400+ );
401+ assert!(skips(&res).is_empty(), "{:?}", res.body);
402+ let bare = res.body["class"]["id"].as_str().unwrap();
403+ assert_eq!(
404+ rows(
405+ &format!("SELECT VALUE id FROM class_course WHERE class = class_group:{bare}"),
406+ &db
407+ )
408+ .await,
409+ 0,
410+ "nothing may be attached to a section no template reached"
411+ );
412+ }
413+}
414+
415+/// A create whose stocking cannot place everything still creates the class: the
416+/// pair that did not fit comes back in `skipped`, best-effort exactly like
417+/// every other pump here.
418+#[tokio::test]
419+async fn a_create_reports_what_its_blueprint_could_not_stock() {
420+ let (app, db) = app_and_db().await;
421+ let manager = login_as(&app, &db, "mgr", "manager").await;
422+ let algebra = create_course(&app, &manager, "algebra").await;
423+ let physics = create_course(&app, &manager, "physics").await;
424+ let made = send(
425+ &app,
426+ "POST",
427+ "/classes/blueprints",
428+ Some(&manager),
429+ Some(json!({ "grade": "9", "course_ids": [algebra.clone(), physics.clone()] })),
430+ )
431+ .await;
432+ assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
433+
434+ // Delete a course out from under the template. Nothing carries it yet — no
435+ // section exists at grade 9 — so this is the pair that cannot fit when the
436+ // first one is created.
437+ let dropped = send(
438+ &app,
439+ "DELETE",
440+ &format!("/courses/{physics}"),
441+ Some(&manager),
442+ None,
443+ )
444+ .await;
445+ assert_eq!(dropped.status, StatusCode::NO_CONTENT, "{:?}", dropped.body);
446+
447+ let res = send(
448+ &app,
449+ "POST",
450+ "/classes",
451+ Some(&manager),
452+ Some(json!({ "name": "9-A", "grade": "9" })),
453+ )
454+ .await;
455+ assert_eq!(
456+ res.status,
457+ StatusCode::CREATED,
458+ "a pair that will not fit may not cost the class: {:?}",
459+ res.body
460+ );
461+ assert_eq!(res.body["stocked_from"], "9");
462+ assert_eq!(skips(&res).len(), 1, "{:?}", res.body);
463+ assert_eq!(skips(&res)[0]["reason"], "course_deleted");
464+ assert_eq!(skips(&res)[0]["course"], physics.as_str());
465+ assert_eq!(skips(&res)[0]["class_name"], "9-A");
466+
467+ let class = res.body["class"]["id"]
468+ .as_str()
469+ .expect("class id")
470+ .to_string();
471+ assert_eq!(
472+ rows(
473+ &format!("SELECT VALUE id FROM class_group WHERE id = class_group:{class}"),
474+ &db
475+ )
476+ .await,
477+ 1,
478+ "the class is really there — the skip is a report, not a rollback"
479+ );
480+ assert!(
481+ attached(&class, &algebra, &db).await,
482+ "…and the course that did fit is on it"
483+ );
484+ assert_eq!(
485+ rows(
486+ &format!("SELECT VALUE id FROM class_course WHERE class = class_group:{class}"),
487+ &db
488+ )
489+ .await,
490+ 1
491+ );
492+ // The dangling id is pruned by the run that found it, here as anywhere.
493+ let read = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await;
494+ assert_eq!(read.body["courses"].as_array().unwrap().len(), 1);
495+}
496+
307 /// The ruling that costs the most: editing the template reaches every section497 /// The ruling that costs the most: editing the template reaches every section
308 /// already at the grade, not just the ones made afterwards. And the sections at498 /// already at the grade, not just the ones made afterwards. And the sections at
309 /// *other* grades are left alone.499 /// *other* grades are left alone.
@@ -674,9 +864,21 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() {
674 )864 )
675 .await;865 .await;
676 assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);866 assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
677- // The section comes after the template, so nothing is attached until the867+ // The section has to reach grade 9 without being stocked on the way, so
678- // pump below runs.868+ // that the pump below is the *first* attach: a section created at the grade
679- let class = create_class(&app, &manager, "9-A", "9").await;869+ // is stocked by its own create, and one that existed already was stocked by
870+ // the template's. Moving it there afterwards is neither — a grade change is
871+ // deliberately a blueprint no-op.
872+ let class = create_class(&app, &manager, "9-A", "10").await;
873+ let moved = send(
874+ &app,
875+ "PATCH",
876+ &format!("/classes/{class}"),
877+ Some(&manager),
878+ Some(json!({ "grade": "9" })),
879+ )
880+ .await;
881+ assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body);
680 assert!(!attached(&class, &algebra, &db).await);882 assert!(!attached(&class, &algebra, &db).await);
681 883
682 // Delete the blueprint from inside the very write that attaches on its884 // Delete the blueprint from inside the very write that attaches on its
tests/regress_classes.rsmodified+62 -6
@@ -109,7 +109,7 @@ async fn a_stale_link_detaches_and_frees_its_class() {
109 )109 )
110 .await;110 .await;
111 assert_eq!(res.status, StatusCode::CREATED);111 assert_eq!(res.status, StatusCode::CREATED);
112- res.body["id"].as_str().unwrap().to_string()112+ res.body["class"]["id"].as_str().unwrap().to_string()
113 };113 };
114 let attached = send(114 let attached = send(
115 &app,115 &app,
@@ -185,7 +185,7 @@ async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() {
185 Some(json!({ "name": "9-A" })),185 Some(json!({ "name": "9-A" })),
186 )186 )
187 .await;187 .await;
188- res.body["id"].as_str().unwrap().to_string()188+ res.body["class"]["id"].as_str().unwrap().to_string()
189 };189 };
190 send(190 send(
191 &app,191 &app,
@@ -241,7 +241,7 @@ async fn a_hand_enroll_takes_the_row_off_the_class() {
241 Some(json!({ "name": "9-A" })),241 Some(json!({ "name": "9-A" })),
242 )242 )
243 .await;243 .await;
244- res.body["id"].as_str().unwrap().to_string()244+ res.body["class"]["id"].as_str().unwrap().to_string()
245 };245 };
246 send(246 send(
247 &app,247 &app,
@@ -338,7 +338,7 @@ async fn a_role_change_sweeps_memberships_and_enrollments_together() {
338 Some(json!({ "name": "9-A" })),338 Some(json!({ "name": "9-A" })),
339 )339 )
340 .await;340 .await;
341- res.body["id"].as_str().unwrap().to_string()341+ res.body["class"]["id"].as_str().unwrap().to_string()
342 };342 };
343 send(343 send(
344 &app,344 &app,
@@ -781,10 +781,15 @@ async fn a_class_over_the_course_ceiling_takes_no_member() {
781 781
782 // ---- homeroom teacher (sınıf öğretmeni) ------------------------------------782 // ---- homeroom teacher (sınıf öğretmeni) ------------------------------------
783 783
784-/// Create a class as `cookie` (asserts 201); returns the whole response body.784+/// Create a class as `cookie` (asserts 201); returns the response with its
785+/// `body` narrowed to the created class — the `201` is
786+/// `{class, skipped, stocked_from}` since a create stocks from its grade's
787+/// blueprint, and the tests below are about the class itself. The two outer
788+/// fields have their own tests (`regress_blueprints`).
785 async fn create_class(app: &axum::Router, cookie: &str, body: serde_json::Value) -> Res {789 async fn create_class(app: &axum::Router, cookie: &str, body: serde_json::Value) -> Res {
786- let res = send(app, "POST", "/classes", Some(cookie), Some(body)).await;790+ let mut res = send(app, "POST", "/classes", Some(cookie), Some(body)).await;
787 assert_eq!(res.status, StatusCode::CREATED, "create class");791 assert_eq!(res.status, StatusCode::CREATED, "create class");
792+ res.body = res.body["class"].clone();
788 res793 res
789 }794 }
790 795
@@ -1415,6 +1420,57 @@ async fn a_create_whose_teacher_is_demoted_mid_write_rolls_back_whole() {
1415 );1420 );
1416 }1421 }
1417 1422
1423+/// The same rollback at a grade a **blueprint** covers, which is what pins the
1424+/// order of the two: a create stocks itself from its grade's template, and that
1425+/// stocking runs *after* this demotion check. Were it the other way round the
1426+/// class would hold courses by the time the rollback ran, `ClassGroup::delete`
1427+/// refuses one that does, and the `409` promising nothing was created would
1428+/// leave a stocked section standing behind it.
1429+#[tokio::test]
1430+async fn a_rolled_back_create_at_a_blueprinted_grade_leaves_nothing_behind() {
1431+ let (app, db) = app_and_db().await;
1432+ let manager = login_as(&app, &db, "manager", "manager").await;
1433+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1434+ let teacher_id = me_id(&app, &teacher).await;
1435+ let course = create_course(&app, &manager, "algebra").await;
1436+ let made = send(
1437+ &app,
1438+ "POST",
1439+ "/classes/blueprints",
1440+ Some(&manager),
1441+ Some(json!({ "grade": "9", "course_ids": [course] })),
1442+ )
1443+ .await;
1444+ assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
1445+
1446+ demote_during_writes_to("class_group", "CREATE", &teacher_id, &db).await;
1447+ let res = send(
1448+ &app,
1449+ "POST",
1450+ "/classes",
1451+ Some(&manager),
1452+ Some(json!({ "name": "9-A", "grade": "9", "teacher_id": teacher_id })),
1453+ )
1454+ .await;
1455+
1456+ assert_eq!(
1457+ res.status,
1458+ StatusCode::CONFLICT,
1459+ "the demotion still wins over the stocking: {:?}",
1460+ res.body
1461+ );
1462+ assert_eq!(
1463+ rows("SELECT VALUE id FROM class_group", &db).await,
1464+ 0,
1465+ "the rollback must still have been able to delete the class"
1466+ );
1467+ assert_eq!(
1468+ rows("SELECT VALUE id FROM class_course", &db).await,
1469+ 0,
1470+ "…which it only can because nothing was stocked onto it first"
1471+ );
1472+}
1473+
1418 /// `PATCH /classes/{id}` naming a teacher who is demoted while the row is being1474 /// `PATCH /classes/{id}` naming a teacher who is demoted while the row is being
1419 /// written: `409`, and the column it just set is taken back.1475 /// written: `409`, and the column it just set is taken back.
1420 #[tokio::test]1476 #[tokio::test]
tests/regress_event_class_audience.rsmodified+1 -1
@@ -23,7 +23,7 @@ async fn create_class(app: &Router, cookie: &str, name: &str) -> String {
23 )23 )
24 .await;24 .await;
25 assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body);25 assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body);
26- id_of(&res.body)26+ id_of(&res.body["class"])
27 }27 }
28 28
29 /// An event aimed at `class`, created by a teacher+.29 /// An event aimed at `class`, created by a teacher+.