forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB466ea10Ahmet Kaan Gümüş2 months ago341 commits

classes.rs1542 lines, 67.6 KiBHistoryRawDownload
1//! Class sections (şube): a named set of students the school moves as one.
2//!
3//! Nothing here is a second kind of membership — adding a student to a class
4//! enrolls them into every course the class carries, and attaching a course
5//! enrolls the whole roster into it, as real `enrollment` rows. So the two
6//! write axes are gated exactly like the writes they stand in for: the class
7//! and its roster are the office's (manager+), while attaching a course writes
8//! *that course's* roster and takes the same right enrolling into it does.
9
10use crate::web::tenant_state::State;
11use axum::Json;
12use axum::extract::{Path, Query};
13use axum::http::StatusCode;
14use serde::{Deserialize, Serialize};
15use utoipa::{IntoParams, ToSchema};
16use utoipa_axum::router::OpenApiRouter;
17use utoipa_axum::routes;
18
19use crate::database::Database;
20use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId, Pumped, Skip};
21use crate::domain::class_course::ClassCourse;
22use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName};
23use crate::domain::class_member::ClassMember;
24use crate::domain::course::{Course, CourseId};
25use crate::domain::role::Role;
26use crate::domain::user::{User, UserId};
27use crate::error::{AppError, ErrorResponse, ValidationError};
28use crate::state::AppState;
29
30use super::courses::can_manage_course;
31use super::terms::resolve_term;
32use super::{
33 CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, ensure_can_observe,
34 person_map, set_or_clear, undo_if_demoted,
35};
36
37pub fn routes() -> OpenApiRouter<AppState> {
38 OpenApiRouter::new()
39 .routes(routes!(create_class, list_classes))
40 // Registration order is irrelevant here, and saying otherwise would be
41 // a comment pinning nothing: axum routes on `matchit`, which prefers a
42 // static segment over a parameter no matter when either was added, so
43 // `/classes/me` reaches `my_classes` and never `get_class` with an id
44 // of `"me"`. `a_student_reads_exactly_their_own_classes` is what
45 // actually checks it, by asserting the body is a page envelope.
46 .routes(routes!(my_classes))
47 .routes(routes!(user_classes))
48 .routes(routes!(get_class, update_class, delete_class))
49 .routes(routes!(add_member, list_members))
50 .routes(routes!(remove_member))
51 .routes(routes!(attach_course, list_class_courses))
52 .routes(routes!(detach_course))
53 // Static before parameter is a matchit rule, not a registration order —
54 // `/classes/blueprints` reaches the template list and never `get_class`
55 // with an id of `"blueprints"`, exactly as `/classes/me` does.
56 .routes(routes!(create_blueprint, list_blueprints))
57 .routes(routes!(get_blueprint, update_blueprint, delete_blueprint))
58 .routes(routes!(blueprint_status))
59 .routes(routes!(apply_blueprint))
60}
61
62#[derive(Deserialize, ToSchema)]
63struct CreateClass {
64 #[schema(max_length = 200, example = "9-A")]
65 name: String,
66 /// The school's own label for the year this class sits in ("9", "10-A",
67 /// "anaokulu"). Free text; omit (or send `""`) for a class with no grade.
68 #[schema(max_length = 20, example = "9")]
69 grade: Option<String>,
70 /// The academic term this class belongs to (`GET /terms`). Optional.
71 term_id: Option<String>,
72 /// The class's homeroom teacher (sınıf öğretmeni) — a teacher, manager or
73 /// admin account. Optional; omit (or send `""`) for a class with none.
74 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
75 teacher_id: Option<String>,
76}
77
78#[derive(Deserialize, ToSchema)]
79struct UpdateClass {
80 #[schema(max_length = 200)]
81 name: Option<String>,
82 /// Omit to keep the current grade, send `null` (or `""`) to clear it, or
83 /// send a label to (re)set it.
84 #[serde(default, deserialize_with = "set_or_clear")]
85 #[schema(value_type = Option<String>, max_length = 20)]
86 grade: Option<Option<String>>,
87 /// Omit to keep the current term, send `null` to unlink, or send a term id
88 /// to (re)assign.
89 #[serde(default, deserialize_with = "set_or_clear")]
90 #[schema(value_type = Option<String>)]
91 term_id: Option<Option<String>>,
92 /// Omit to keep the current homeroom teacher, send `null` (or `""`) to
93 /// clear it, or send a teacher+ user id to (re)assign.
94 #[serde(default, deserialize_with = "set_or_clear")]
95 #[schema(value_type = Option<String>)]
96 teacher_id: Option<Option<String>>,
97}
98
99#[derive(Deserialize, ToSchema)]
100struct AddMember {
101 /// The student to put in the class.
102 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
103 user_id: String,
104}
105
106#[derive(Deserialize, ToSchema)]
107struct AttachCourse {
108 /// The course the whole class takes.
109 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
110 course_id: String,
111}
112
113#[derive(Serialize, ToSchema)]
114struct ClassResponse {
115 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
116 id: String,
117 /// Who created the class — always a manager or admin, so it is `null` for
118 /// a caller below teacher+. `GET /classes/me` and a parent's
119 /// `GET /classes/user/{user}` are the only reads a non-staff account can
120 /// make here, and the office's account names are not theirs to learn:
121 /// `GET /users` is admin-only and `/users/search` is teacher+.
122 creator: Option<PersonRef>,
123 #[schema(example = "9-A")]
124 name: String,
125 /// The school's own free-text grade label; `null` when the class has none.
126 #[schema(example = "9")]
127 grade: Option<String>,
128 /// The academic term this class belongs to (`GET /terms`); `null` when
129 /// unassigned.
130 term: Option<String>,
131 /// The class's homeroom teacher (sınıf öğretmeni); `null` when none is
132 /// assigned — as it is for every class after the account was demoted below
133 /// `teacher`.
134 teacher: Option<PersonRef>,
135}
136
137impl ClassResponse {
138 /// `with_creator` is the caller's clearance: every route but the two
139 /// membership reads is teacher+ and passes `true`; those two pass it only
140 /// for a staff caller. The homeroom teacher is never hidden — naming them
141 /// is the whole point of a student's own section read.
142 fn new(
143 class: &ClassGroup,
144 people: &std::collections::HashMap<String, PersonRef>,
145 with_creator: bool,
146 ) -> Self {
147 Self {
148 id: class.get_id().key().to_string(),
149 creator: with_creator.then(|| PersonRef::resolve(people, class.get_creator())),
150 name: class.get_name().as_str().to_string(),
151 grade: class.get_grade().map(|g| g.as_str().to_string()),
152 term: class.get_term().map(|term| term.key().to_string()),
153 teacher: class
154 .get_teacher()
155 .map(|teacher| PersonRef::resolve(people, teacher)),
156 }
157 }
158}
159
160/// A created class plus what its grade's blueprint did to it — the shape
161/// [`BlueprintPumpResponse`] already has on the other write that pumps, with the
162/// class in place of the template.
163#[derive(Serialize, ToSchema)]
164struct CreateClassResponse {
165 class: ClassResponse,
166 /// The courses the template could not put on this section, empty when it
167 /// took them all (and always empty when no template covered its grade).
168 skipped: Vec<SkipResponse>,
169 /// The grade label of the blueprint that stocked this section, or `null`
170 /// when none did. `null` with an empty `skipped` is what tells "no template
171 /// covers this grade" apart from "the template applied cleanly" — the
172 /// distinction `matched` makes on the grade-wide pumps.
173 ///
174 /// Stocking is best-effort to the end: a template that could not be read,
175 /// or a pump that faulted part-way, also reads `null` rather than turning a
176 /// section that exists into a `500` whose caller never learns its id. The
177 /// remedy is the same either way — `POST /classes/{id}/blueprint`, which is
178 /// idempotent and `404`s when there is genuinely no template.
179 #[schema(example = "9")]
180 stocked_from: Option<String>,
181}
182
183/// Every person a [`ClassResponse`] names: its homeroom teacher, plus its
184/// creator when the caller is cleared to see one. Feed this into `person_map` —
185/// an id the map is missing renders as a bare ULID, so a creator left out here
186/// must also be left out of the response.
187fn class_people(class: &ClassGroup, with_creator: bool) -> impl Iterator<Item = UserId> + '_ {
188 with_creator
189 .then(|| class.get_creator().clone())
190 .into_iter()
191 .chain(class.get_teacher().cloned())
192}
193
194#[derive(Serialize, ToSchema)]
195struct ClassMemberResponse {
196 id: String,
197 class: String,
198 /// The student in the class.
199 user: PersonRef,
200 /// Who put them there.
201 added_by: PersonRef,
202}
203
204impl ClassMemberResponse {
205 fn new(member: &ClassMember, people: &std::collections::HashMap<String, PersonRef>) -> Self {
206 Self {
207 id: member.get_id().key().to_string(),
208 class: member.get_class().key().to_string(),
209 user: PersonRef::resolve(people, member.get_user()),
210 added_by: PersonRef::resolve(people, member.get_added_by()),
211 }
212 }
213}
214
215#[derive(Serialize, ToSchema)]
216struct ClassCourseResponse {
217 id: String,
218 class: String,
219 /// The course the class takes.
220 course: String,
221 /// Who attached it.
222 attached_by: PersonRef,
223}
224
225impl ClassCourseResponse {
226 fn new(link: &ClassCourse, people: &std::collections::HashMap<String, PersonRef>) -> Self {
227 Self {
228 id: link.get_id().key().to_string(),
229 class: link.get_class().key().to_string(),
230 course: link.get_course().key().to_string(),
231 attached_by: PersonRef::resolve(people, link.get_attached_by()),
232 }
233 }
234}
235
236/// The class a path id names, or a 404 — every route under `/classes/{id}`
237/// gates on it, so a missing class never reads as an empty roster.
238async fn class_or_404(id: &str, db: &Database) -> Result<ClassGroup, AppError> {
239 ClassGroup::read(&ClassGroupId::from_key(id), db)
240 .await?
241 .ok_or(AppError::NotFound)
242}
243
244/// An empty grade is *no* grade: the column is nullable, so a client that omits
245/// it and one that sends `""` must land on the same stored row.
246fn grade_or_none(text: Option<&str>) -> Result<Option<ClassGrade>, AppError> {
247 match text {
248 None | Some("") => Ok(None),
249 Some(text) => Ok(Some(ClassGrade::try_new(text)?)),
250 }
251}
252
253/// The homeroom teacher a request names, as the row itself — an empty string is
254/// *no* teacher, exactly like `grade`, so omitting the field and clearing it
255/// with `""` land on the same stored row. The named account must exist and hold
256/// teacher-or-higher: a class's sınıf öğretmeni is staff, and the check is the
257/// same shape `add_member` uses for a non-student. The `User` comes back so the
258/// caller can name them in the response without a second read.
259async fn teacher_or_none(text: Option<&str>, db: &Database) -> Result<Option<User>, AppError> {
260 let (None | Some("")) = text else {
261 return resolve_teacher(text.unwrap_or_default(), db)
262 .await
263 .map(Some);
264 };
265 Ok(None)
266}
267
268/// The teacher-or-higher account `key` names, or the 400 both write paths give.
269async fn resolve_teacher(key: &str, db: &Database) -> Result<User, AppError> {
270 let Some(teacher) = User::read(&UserId::from_key(key), db).await? else {
271 return Err(AppError::Validation(ValidationError::Invalid {
272 field: "teacher_id",
273 reason: "target user does not exist",
274 }));
275 };
276 if !teacher.get_role().at_least(Role::Teacher) {
277 return Err(AppError::Validation(ValidationError::Invalid {
278 field: "teacher_id",
279 reason: "only a teacher, manager or admin can be a class's homeroom teacher",
280 }));
281 }
282 Ok(teacher)
283}
284
285/// One page of classes with their people joined on — the shared tail of the two
286/// membership reads. Ordering follows `rows`, so the page stays newest-first.
287///
288/// A membership whose class id resolves to nothing is *skipped*: class deletion
289/// is refused while members exist, so it is unreachable, and if a repair ever
290/// left one behind a student's own section list must degrade to one row short
291/// rather than 500. `total` still counts the membership rows, which is what the
292/// window was cut from.
293async fn classes_page(
294 ids: &[ClassGroupId],
295 total: i64,
296 limit: Option<i64>,
297 offset: i64,
298 with_creator: bool,
299 db: &Database,
300) -> Result<Page<ClassResponse>, AppError> {
301 let classes = ClassGroup::list_by_ids(ids, db).await?;
302 let by_id: std::collections::HashMap<&str, &ClassGroup> = classes
303 .iter()
304 .map(|class| (class.get_id().key(), class))
305 .collect();
306 let people = person_map(
307 classes
308 .iter()
309 .flat_map(|class| class_people(class, with_creator)),
310 db,
311 )
312 .await?;
313 let items = ids
314 .iter()
315 .filter_map(|id| by_id.get(id.key()))
316 .map(|class| ClassResponse::new(class, &people, with_creator))
317 .collect();
318 Ok(Page::new(items, total, limit, offset))
319}
320
321/// Create a class. Requires manager+ — a class is school structure, not a
322/// teacher's own room. `grade` is a free-text label for the year ("9", "10-A"),
323/// `term_id` links the school calendar, `teacher_id` names the homeroom teacher
324/// (sınıf öğretmeni, a teacher+ account); all optional.
325///
326/// If a blueprint covers the new class's grade, the class is **stocked from it
327/// at once** — the same best-effort pump `POST /classes/{id}/blueprint` runs, so
328/// a course that does not fit comes back in `skipped` and the class is created
329/// either way. `stocked_from` names the template that did it, and is `null` when
330/// none covered the grade.
331#[utoipa::path(
332 post,
333 path = "/",
334 tag = "classes",
335 security(("session_cookie" = [])),
336 request_body = CreateClass,
337 responses(
338 (status = 201, description = "Class created, stocked from its grade's blueprint when one covers it", body = CreateClassResponse),
339 (status = 400, description = "Invalid name or grade, an unknown term, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse),
340 (status = 401, description = "Not authenticated", body = ErrorResponse),
341 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
342 (status = 409, description = "The named homeroom teacher was demoted below teacher while the request ran (the class was rolled back, nothing was created), or the named term is archived — past years are read-only", body = ErrorResponse),
343 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
344 ),
345)]
346async fn create_class(
347 State(st): State<AppState>,
348 RequireManager(user): RequireManager,
349 Json(req): Json<CreateClass>,
350) -> Result<(StatusCode, Json<CreateClassResponse>), AppError> {
351 let name = ClassName::try_new(&req.name)?;
352 let grade = grade_or_none(req.grade.as_deref())?;
353 // Pre-flight only: `ClassGroup::create` claims a reference on the term
354 // before it writes the link, and a term deleted in between fails that claim
355 // with this very error — so an unknown id reads the same whichever side wins.
356 let term = resolve_term(req.term_id.as_deref(), &st.db).await?;
357 let teacher = teacher_or_none(req.teacher_id.as_deref(), &st.db).await?;
358 let class = ClassGroup::create(
359 user.get_id(),
360 name,
361 grade,
362 term,
363 teacher.as_ref().map(|t| t.get_id().clone()),
364 &st.db,
365 )
366 .await?;
367 // The row is written; a demotion that raced this request's role check swept
368 // it too early to see it, so the live role is re-read now (see
369 // [`undo_if_demoted`]).
370 if let Some(teacher) = teacher.as_ref()
371 && let Err(demoted) = undo_if_demoted(teacher.get_id(), &st.db).await
372 {
373 // Roll the whole create back, not just the column: a `409` that left a
374 // teacherless class standing would have the caller either retrying into
375 // a duplicate or never learning it was there.
376 //
377 // The guard cannot refuse this delete — the class is one statement old
378 // and both of its counters are still absent — so a refusal is a broken
379 // invariant, not a client error, and it must not be reported as the
380 // `409` whose text promises nothing was created.
381 if !class.clone().delete(&st.db).await? {
382 return Err(AppError::Internal(format!(
383 "class {} took a member or a course between its create and the \
384 rollback of a demoted homeroom teacher; it is still there, \
385 without a teacher",
386 class.get_id().key()
387 )));
388 }
389 return Err(demoted);
390 }
391 // Stocking runs **after** that rollback, never before: `ClassGroup::delete`
392 // refuses a class holding courses, so a section pumped first could not be
393 // rolled back and the `409` above would leave a half-created class standing
394 // behind a promise that nothing was created.
395 let stocked = stock_from_blueprint(&class, user.get_id(), &st.db).await;
396 // The creator is the caller and the teacher was just read — no extra lookup.
397 let mut named = vec![&user];
398 named.extend(teacher.as_ref());
399 let people = PersonRef::map_of(&named);
400 Ok((
401 StatusCode::CREATED,
402 Json(CreateClassResponse {
403 class: ClassResponse::new(&class, &people, true),
404 skipped: stocked
405 .iter()
406 .flat_map(|(_, skipped)| skipped.iter().map(SkipResponse::new))
407 .collect(),
408 stocked_from: stocked.map(|(grade, _)| grade),
409 }),
410 ))
411}
412
413/// Stock a freshly created class from its grade's blueprint, if one covers it:
414/// the template's grade label and the pairs it could not place, or `None` when
415/// the class has no grade, no blueprint holds that grade, or the stocking could
416/// not be carried out.
417///
418/// Swallowing that last case is the deliberate one. Every other pump here may
419/// fail its whole request, because the caller can name what it asked for again —
420/// a blueprint's id *is* the grade label they sent. A class's id is a ULID this
421/// request is the only place it is ever returned from, so a `500` after the row
422/// is written loses a section that exists. Best-effort therefore runs to the end
423/// of this route: the class is reported, `stocked_from` stays `null`, and the
424/// retry is the idempotent `POST /classes/{id}/blueprint` — which is also the
425/// remedy when no template covers the grade, so the two need not be told apart.
426async fn stock_from_blueprint(
427 class: &ClassGroup,
428 by: &UserId,
429 db: &Database,
430) -> Option<(String, Vec<Skip>)> {
431 let grade = class.get_grade()?;
432 let blueprint = ClassBlueprint::read(&ClassBlueprintId::for_grade(grade), db)
433 .await
434 .ok()??;
435 let skipped = blueprint.apply_to(class, by, db).await.ok()?;
436 Some((blueprint.get_grade().as_str().to_string(), skipped))
437}
438
439/// Filter for the class index.
440#[derive(Deserialize, IntoParams)]
441struct ClassFilter {
442 /// Narrow to the sections carrying this exact grade label — the same
443 /// spelling a blueprint is keyed by, matched verbatim (no trimming, no case
444 /// folding: a filter that normalized would disagree with the pump it exists
445 /// to debug). `?grade=` (empty) asks for the sections carrying *no* grade,
446 /// exactly as an empty `grade` on a write means no grade. Omit for every
447 /// class.
448 #[param(example = "9")]
449 grade: Option<String>,
450}
451
452/// List every class, newest first. Requires teacher+. `?grade=` narrows to one
453/// grade label, matched exactly as written — the label a blueprint is keyed by,
454/// so this is the read that shows which sections a `POST /classes/blueprints`
455/// pump covered (and `?grade=` on its own lists the sections with no grade at
456/// all). An unknown label is an empty page, not a `404`. Paged via
457/// `?limit=&offset=` (omit `limit` for the full list); returns a
458/// `{items, total, limit, offset}` envelope whose `total` counts every class
459/// under the same filter, not just this page.
460#[utoipa::path(
461 get,
462 path = "/",
463 tag = "classes",
464 security(("session_cookie" = [])),
465 params(ClassFilter, PageParams),
466 responses(
467 (status = 200, description = "A page of classes (the full list when unpaged)", body = Page<ClassResponse>),
468 (status = 400, description = "Invalid grade, limit or offset", body = ErrorResponse),
469 (status = 401, description = "Not authenticated", body = ErrorResponse),
470 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
471 ),
472)]
473async fn list_classes(
474 State(st): State<AppState>,
475 RequireTeacher(_user): RequireTeacher,
476 Query(filter): Query<ClassFilter>,
477 Query(page): Query<PageParams>,
478) -> Result<Json<Page<ClassResponse>>, AppError> {
479 let (limit, offset) = page.resolve()?;
480 // The same newtype the write paths validate against, so an over-long label
481 // is the same `400` here as on a create. `grade_or_none` folds `""` into
482 // "no grade"; the outer `Option` is what keeps *omitted* apart from it.
483 let grade = filter
484 .grade
485 .as_deref()
486 .map(|grade| grade_or_none(Some(grade)))
487 .transpose()?;
488 let (classes, total) = ClassGroup::list_all(grade, limit, offset, &st.db).await?;
489 // Join people onto the page alone — the lookup shrinks with the window.
490 let people = person_map(
491 classes.iter().flat_map(|class| class_people(class, true)),
492 &st.db,
493 )
494 .await?;
495 let items = classes
496 .iter()
497 .map(|class| ClassResponse::new(class, &people, true))
498 .collect();
499 Ok(Json(Page::new(items, total, limit, offset)))
500}
501
502/// Fetch a single class by id. Requires teacher+.
503#[utoipa::path(
504 get,
505 path = "/{id}",
506 tag = "classes",
507 security(("session_cookie" = [])),
508 params(("id" = String, Path, description = "Class id")),
509 responses(
510 (status = 200, description = "The class", body = ClassResponse),
511 (status = 401, description = "Not authenticated", body = ErrorResponse),
512 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
513 (status = 404, description = "Not found", body = ErrorResponse),
514 ),
515)]
516async fn get_class(
517 State(st): State<AppState>,
518 RequireTeacher(_user): RequireTeacher,
519 Path(id): Path<String>,
520) -> Result<Json<ClassResponse>, AppError> {
521 let class = class_or_404(&id, &st.db).await?;
522 let people = person_map(class_people(&class, true), &st.db).await?;
523 Ok(Json(ClassResponse::new(&class, &people, true)))
524}
525
526/// Update a class. Requires manager+. Omitted fields keep their value; `grade`,
527/// `term_id` and `teacher_id` are nullable, so an explicit `null` clears them.
528#[utoipa::path(
529 patch,
530 path = "/{id}",
531 tag = "classes",
532 security(("session_cookie" = [])),
533 params(("id" = String, Path, description = "Class id")),
534 request_body = UpdateClass,
535 responses(
536 (status = 200, description = "Updated class", body = ClassResponse),
537 (status = 400, description = "Invalid name or grade, an unknown term, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse),
538 (status = 401, description = "Not authenticated", body = ErrorResponse),
539 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
540 (status = 404, description = "Not found", body = ErrorResponse),
541 (status = 409, description = "The term this update moves the class off changed since the caller read it (nothing was written, re-read and retry), the named homeroom teacher was demoted below teacher while the request ran (the assignment was undone), or the class's own term — or the named one — is archived: past years are read-only", body = ErrorResponse),
542 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
543 ),
544)]
545async fn update_class(
546 State(st): State<AppState>,
547 RequireManager(_user): RequireManager,
548 Path(id): Path<String>,
549 Json(req): Json<UpdateClass>,
550) -> Result<Json<ClassResponse>, AppError> {
551 let class = class_or_404(&id, &st.db).await?;
552 // The class's *current* term, so a move off an archived year is refused
553 // too; `resolve_term` below holds the other end (the term moved onto).
554 class.require_open(&st.db).await?;
555
556 // Only what the request actually carried is validated and written — an
557 // omitted field stays `None` so the save never re-sends this snapshot's
558 // value over a concurrent PATCH of that field.
559 let name = req.name.as_deref().map(ClassName::try_new).transpose()?;
560 let grade = match req.grade {
561 Some(ref update) => Some(grade_or_none(update.as_deref())?),
562 None => None,
563 };
564 let term = match req.term_id {
565 // Explicit `null` clears the link; a value must name a real term.
566 Some(ref update) => Some(resolve_term(update.as_deref(), &st.db).await?),
567 None => None,
568 };
569 let teacher = match req.teacher_id {
570 // Explicit `null` (or `""`) clears it; a value must name a teacher+.
571 Some(ref update) => Some(teacher_or_none(update.as_deref(), &st.db).await?),
572 None => None,
573 };
574
575 let assigned = teacher
576 .as_ref()
577 .and_then(|teacher| teacher.as_ref().map(|teacher| teacher.get_id().clone()));
578 let updated = class
579 .update(
580 name,
581 grade,
582 term,
583 teacher.map(|teacher| teacher.map(|teacher| teacher.get_id().clone())),
584 &st.db,
585 )
586 .await?;
587 // Only when this request named a teacher: a PATCH that left the column
588 // alone raced nobody's demotion (see [`undo_if_demoted`]). The undo clears
589 // the column, which is the whole of what this request wrote to it.
590 if let Some(teacher) = assigned.as_ref() {
591 undo_if_demoted(teacher, &st.db).await?;
592 }
593 let people = person_map(class_people(&updated, true), &st.db).await?;
594 Ok(Json(ClassResponse::new(&updated, &people, true)))
595}
596
597// ---- a student's own class -------------------------------------------------
598
599/// The classes the caller is a member of, newest membership first. Any
600/// authenticated role — this is the one class read a student (or a parent, for
601/// themselves) can make, since every other `/classes` route is teacher+. Paged
602/// via `?limit=&offset=` (omit `limit` for all of them); returns a
603/// `{items, total, limit, offset}` envelope. Staff, who are never class
604/// members, simply get an empty page.
605#[utoipa::path(
606 get,
607 path = "/me",
608 tag = "classes",
609 security(("session_cookie" = [])),
610 params(PageParams),
611 responses(
612 (status = 200, description = "A page of the caller's classes (all of them when unpaged)", body = Page<ClassResponse>),
613 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
614 (status = 401, description = "Not authenticated", body = ErrorResponse),
615 ),
616)]
617async fn my_classes(
618 State(st): State<AppState>,
619 CurrentUser(user): CurrentUser,
620 Query(page): Query<PageParams>,
621) -> Result<Json<Page<ClassResponse>>, AppError> {
622 let (limit, offset) = page.resolve()?;
623 // A student may not learn who in the office created their class; staff may.
624 let with_creator = user.get_role().at_least(Role::Teacher);
625 Ok(Json(
626 classes_of(user.get_id(), limit, offset, with_creator, &st.db).await?,
627 ))
628}
629
630/// Another user's classes. Requires teacher+, or a parent tied to the target
631/// student — the same bar the per-student reports hold, and the same 403 for
632/// everyone else (a student reads their own at `GET /classes/me`).
633#[utoipa::path(
634 get,
635 path = "/user/{user}",
636 tag = "classes",
637 security(("session_cookie" = [])),
638 params(("user" = String, Path, description = "User id"), PageParams),
639 responses(
640 (status = 200, description = "A page of that user's classes (all of them when unpaged)", body = Page<ClassResponse>),
641 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
642 (status = 401, description = "Not authenticated", body = ErrorResponse),
643 (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
644 (status = 404, description = "User not found", body = ErrorResponse),
645 ),
646)]
647async fn user_classes(
648 State(st): State<AppState>,
649 CurrentUser(caller): CurrentUser,
650 Path(user): Path<String>,
651 Query(page): Query<PageParams>,
652) -> Result<Json<Page<ClassResponse>>, AppError> {
653 let (limit, offset) = page.resolve()?;
654 let target = UserId::from_key(&user);
655 ensure_can_observe(&caller, &target, &st.db).await?;
656 // User must exist — a missing user is a 404, not an empty page.
657 User::read(&target, &st.db)
658 .await?
659 .ok_or(AppError::NotFound)?;
660 // A linked parent reads this too, and is no more entitled to the office's
661 // account names than their child is.
662 let with_creator = caller.get_role().at_least(Role::Teacher);
663 Ok(Json(
664 classes_of(&target, limit, offset, with_creator, &st.db).await?,
665 ))
666}
667
668/// One user's class page: the membership rows are what the window is cut from,
669/// and the class rows are joined onto that page alone.
670async fn classes_of(
671 user: &UserId,
672 limit: Option<i64>,
673 offset: i64,
674 with_creator: bool,
675 db: &Database,
676) -> Result<Page<ClassResponse>, AppError> {
677 let (rows, total) = ClassMember::list_for_user(user, limit, offset, db).await?;
678 let ids: Vec<ClassGroupId> = rows.iter().map(|row| row.get_class().clone()).collect();
679 classes_page(&ids, total, limit, offset, with_creator, db).await
680}
681
682/// Delete a class. Requires manager+. Refused with a 409 while it still holds
683/// students or courses — nothing cascades, because dropping the class silently
684/// would leave the enrollments it pumped with nothing left to sweep them.
685#[utoipa::path(
686 delete,
687 path = "/{id}",
688 tag = "classes",
689 security(("session_cookie" = [])),
690 params(("id" = String, Path, description = "Class id")),
691 responses(
692 (status = 204, description = "Deleted"),
693 (status = 401, description = "Not authenticated", body = ErrorResponse),
694 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
695 (status = 404, description = "Not found", body = ErrorResponse),
696 (status = 409, description = "Students or courses are still on this class, or its term is archived — past years are read-only", body = ErrorResponse),
697 ),
698)]
699async fn delete_class(
700 State(st): State<AppState>,
701 RequireManager(_user): RequireManager,
702 Path(id): Path<String>,
703) -> Result<StatusCode, AppError> {
704 let class = class_or_404(&id, &st.db).await?;
705 class.require_open(&st.db).await?;
706 if !class.delete(&st.db).await? {
707 return Err(AppError::Conflict(
708 "this class still holds students or courses — remove its members and detach its courses first",
709 ));
710 }
711 Ok(StatusCode::NO_CONTENT)
712}
713
714// ---- members ---------------------------------------------------------------
715
716/// Put a student in a class. Requires manager+. They are enrolled into every
717/// course the class already carries, in one go: a course with no free seat
718/// refuses the whole join with a 409 naming it, and a student already enrolled
719/// by hand keeps the row they have (no second seat, and it survives their
720/// removal from the class). Adding the same student twice is a 409.
721#[utoipa::path(
722 post,
723 path = "/{id}/members",
724 tag = "classes",
725 security(("session_cookie" = [])),
726 params(("id" = String, Path, description = "Class id")),
727 request_body = AddMember,
728 responses(
729 (status = 201, description = "Student added to the class", body = ClassMemberResponse),
730 (status = 400, description = "Unknown user, or user is not a student", body = ErrorResponse),
731 (status = 401, description = "Not authenticated", body = ErrorResponse),
732 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
733 (status = 404, description = "Class not found", body = ErrorResponse),
734 (status = 409, description = "Already in this class, the class is at its student ceiling (max_class_members), it carries more courses than one add may enroll at once, one of its courses is full, or one of them no longer exists (a stale attachment — detach it). The body carries a machine `code` beside the prose, and this route answers exactly these: `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full`, `linked_course_missing`, `term_archived` (the class sits on an archived term — past years are read-only)", body = ErrorResponse),
735 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
736 ),
737)]
738async fn add_member(
739 State(st): State<AppState>,
740 RequireManager(user): RequireManager,
741 Path(id): Path<String>,
742 Json(req): Json<AddMember>,
743) -> Result<(StatusCode, Json<ClassMemberResponse>), AppError> {
744 let class = class_or_404(&id, &st.db).await?;
745 class.require_open(&st.db).await?;
746
747 let target = UserId::from_key(&req.user_id);
748 let Some(target_user) = User::read(&target, &st.db).await? else {
749 return Err(AppError::Validation(ValidationError::Invalid {
750 field: "user_id",
751 reason: "target user does not exist",
752 }));
753 };
754 // A class membership is enrollment in bulk, and enrollment is student
755 // membership — the same bar `POST /courses/{id}/enrollments` holds.
756 if target_user.get_role() != Role::Student {
757 return Err(AppError::Validation(ValidationError::Invalid {
758 field: "user_id",
759 reason: "only students can be added to a class",
760 }));
761 }
762
763 let member = ClassMember::add(class.get_id(), &target, user.get_id(), &st.db).await?;
764 let people = PersonRef::map_of(&[&target_user, &user]);
765 Ok((
766 StatusCode::CREATED,
767 Json(ClassMemberResponse::new(&member, &people)),
768 ))
769}
770
771/// List a class's roster, newest first, paged via `?limit=&offset=` (omit
772/// `limit` for the whole roster). Requires teacher+. Returns a
773/// `{items, total, limit, offset}` envelope.
774#[utoipa::path(
775 get,
776 path = "/{id}/members",
777 tag = "classes",
778 security(("session_cookie" = [])),
779 params(("id" = String, Path, description = "Class id"), PageParams),
780 responses(
781 (status = 200, description = "A page of class members (the whole roster when unpaged)", body = Page<ClassMemberResponse>),
782 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
783 (status = 401, description = "Not authenticated", body = ErrorResponse),
784 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
785 (status = 404, description = "Class not found", body = ErrorResponse),
786 ),
787)]
788async fn list_members(
789 State(st): State<AppState>,
790 RequireTeacher(_user): RequireTeacher,
791 Path(id): Path<String>,
792 Query(page): Query<PageParams>,
793) -> Result<Json<Page<ClassMemberResponse>>, AppError> {
794 let (limit, offset) = page.resolve()?;
795 let class = class_or_404(&id, &st.db).await?;
796 let (rows, total) = ClassMember::list_for_class(class.get_id(), limit, offset, &st.db).await?;
797 // Join people onto the page alone — the lookup shrinks with the window.
798 let people = person_map(
799 rows.iter()
800 .flat_map(|row| [row.get_user().clone(), row.get_added_by().clone()]),
801 &st.db,
802 )
803 .await?;
804 let items = rows
805 .iter()
806 .map(|row| ClassMemberResponse::new(row, &people))
807 .collect();
808 Ok(Json(Page::new(items, total, limit, offset)))
809}
810
811/// Take a student out of a class. Requires manager+. The enrollments the class
812/// pumped for them are swept with it — except rows another attached class still
813/// claims (re-tagged to it) and rows placed by hand (left standing). A student
814/// who was not in the class is a 404.
815#[utoipa::path(
816 delete,
817 path = "/{id}/members/{user}",
818 tag = "classes",
819 security(("session_cookie" = [])),
820 params(
821 ("id" = String, Path, description = "Class id"),
822 ("user" = String, Path, description = "User id"),
823 ),
824 responses(
825 (status = 204, description = "Removed"),
826 (status = 401, description = "Not authenticated", body = ErrorResponse),
827 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
828 (status = 404, description = "Class not found, or that student was not in it", body = ErrorResponse),
829 (status = 409, description = "The class's (or course's) term is archived — past years are read-only", body = ErrorResponse),
830 ),
831)]
832async fn remove_member(
833 State(st): State<AppState>,
834 RequireManager(_user): RequireManager,
835 Path((id, target)): Path<(String, String)>,
836) -> Result<StatusCode, AppError> {
837 let class = class_or_404(&id, &st.db).await?;
838 class.require_open(&st.db).await?;
839 ClassMember::remove(class.get_id(), &UserId::from_key(&target), &st.db).await?;
840 Ok(StatusCode::NO_CONTENT)
841}
842
843// ---- attached courses ------------------------------------------------------
844
845/// Attach a course to a class. Requires teacher+ and management rights **on
846/// that course** — attaching writes its roster, so it takes exactly the right
847/// enrolling into it does. The class's whole roster is enrolled in one go: a
848/// course that cannot hold all of them takes none (409), and students already
849/// enrolled by hand keep their own rows. Attaching the same course twice is a
850/// 409.
851#[utoipa::path(
852 post,
853 path = "/{id}/courses",
854 tag = "classes",
855 security(("session_cookie" = [])),
856 params(("id" = String, Path, description = "Class id")),
857 request_body = AttachCourse,
858 responses(
859 (status = 201, description = "Course attached to the class", body = ClassCourseResponse),
860 (status = 400, description = "Unknown course", body = ErrorResponse),
861 (status = 401, description = "Not authenticated", body = ErrorResponse),
862 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
863 (status = 404, description = "Class not found", body = ErrorResponse),
864 (status = 409, description = "Already attached, the class is at its course ceiling (max_class_courses), it holds more students than one attach may enroll at once, or the course cannot hold the whole class. The body carries a machine `code` beside the prose, and this route answers exactly these: `duplicate`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `term_archived` (the class's or the course's term is archived — past years are read-only)", body = ErrorResponse),
865 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
866 ),
867)]
868async fn attach_course(
869 State(st): State<AppState>,
870 RequireTeacher(user): RequireTeacher,
871 Path(id): Path<String>,
872 Json(req): Json<AttachCourse>,
873) -> Result<(StatusCode, Json<ClassCourseResponse>), AppError> {
874 let class = class_or_404(&id, &st.db).await?;
875 let Some(course) = Course::read(&CourseId::from_key(&req.course_id), &st.db).await? else {
876 return Err(AppError::Validation(ValidationError::Invalid {
877 field: "course_id",
878 reason: "course does not exist",
879 }));
880 };
881 if !can_manage_course(&course, &user) {
882 return Err(AppError::Forbidden(
883 "only the course creator, an assigned teacher, or a manager/admin can attach this course to a class",
884 ));
885 }
886 // Both ends: neither a class nor a course on a past year takes a new link.
887 class.require_open(&st.db).await?;
888 course.require_open(&st.db).await?;
889
890 let link = ClassCourse::attach(class.get_id(), course.get_id(), user.get_id(), &st.db).await?;
891 let people = PersonRef::map_of(&[&user]);
892 Ok((
893 StatusCode::CREATED,
894 Json(ClassCourseResponse::new(&link, &people)),
895 ))
896}
897
898/// List the courses a class is attached to, newest first, paged via
899/// `?limit=&offset=` (omit `limit` for all of them). Requires teacher+. Returns
900/// a `{items, total, limit, offset}` envelope.
901#[utoipa::path(
902 get,
903 path = "/{id}/courses",
904 tag = "classes",
905 security(("session_cookie" = [])),
906 params(("id" = String, Path, description = "Class id"), PageParams),
907 responses(
908 (status = 200, description = "A page of the class's courses (all of them when unpaged)", body = Page<ClassCourseResponse>),
909 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
910 (status = 401, description = "Not authenticated", body = ErrorResponse),
911 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
912 (status = 404, description = "Class not found", body = ErrorResponse),
913 ),
914)]
915async fn list_class_courses(
916 State(st): State<AppState>,
917 RequireTeacher(_user): RequireTeacher,
918 Path(id): Path<String>,
919 Query(page): Query<PageParams>,
920) -> Result<Json<Page<ClassCourseResponse>>, AppError> {
921 let (limit, offset) = page.resolve()?;
922 let class = class_or_404(&id, &st.db).await?;
923 let (rows, total) = ClassCourse::list_for_class(class.get_id(), limit, offset, &st.db).await?;
924 let people = person_map(rows.iter().map(|row| row.get_attached_by().clone()), &st.db).await?;
925 let items = rows
926 .iter()
927 .map(|row| ClassCourseResponse::new(row, &people))
928 .collect();
929 Ok(Json(Page::new(items, total, limit, offset)))
930}
931
932/// Detach a course from a class. Requires teacher+ and management rights on
933/// that course, like attaching. The enrollments the class pumped into it are
934/// swept — except rows another attached class still claims (re-tagged to it)
935/// and rows placed by hand (left standing). A course that was not attached is a
936/// 404 — but a course row that is *gone* is not: the link a deleted course left
937/// behind detaches (the rights check has nothing left to read, and no roster
938/// left to protect), or the class holding it could never be deleted.
939#[utoipa::path(
940 delete,
941 path = "/{id}/courses/{course}",
942 tag = "classes",
943 security(("session_cookie" = [])),
944 params(
945 ("id" = String, Path, description = "Class id"),
946 ("course" = String, Path, description = "Course id"),
947 ),
948 responses(
949 (status = 204, description = "Detached"),
950 (status = 401, description = "Not authenticated", body = ErrorResponse),
951 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
952 (status = 404, description = "Class not found, or that course was not attached — a course row that is gone does not refuse the detach, it is the reason for it", body = ErrorResponse),
953 (status = 409, description = "The class's (or course's) term is archived — past years are read-only", body = ErrorResponse),
954 ),
955)]
956async fn detach_course(
957 State(st): State<AppState>,
958 RequireTeacher(user): RequireTeacher,
959 Path((id, course)): Path<(String, String)>,
960) -> Result<StatusCode, AppError> {
961 let class = class_or_404(&id, &st.db).await?;
962 let course = CourseId::from_key(&course);
963 // The rights check is skipped when the course row is gone, rather than the
964 // whole detach refused: management rights are read *off* the course, so a
965 // link left pointing at a deleted course had no readable owner and this
966 // route answered 404 forever — which also left the class undeletable, its
967 // attachment counter counting a row nothing could sweep. There is no roster
968 // left to protect, and the caller is already teacher+.
969 let row = Course::read(&course, &st.db).await?;
970 if let Some(row) = row.as_ref()
971 && !can_manage_course(row, &user)
972 {
973 return Err(AppError::Forbidden(
974 "only the course creator, an assigned teacher, or a manager/admin can detach this course from a class",
975 ));
976 }
977 // Both ends, and only what is still there: a link whose course row is gone
978 // has no term to read, and sweeping it is the whole point of the route.
979 class.require_open(&st.db).await?;
980 if let Some(row) = row.as_ref() {
981 row.require_open(&st.db).await?;
982 }
983 ClassCourse::detach(class.get_id(), &course, &st.db).await?;
984 Ok(StatusCode::NO_CONTENT)
985}
986
987// ---- grade blueprints ------------------------------------------------------
988
989#[derive(Deserialize, ToSchema)]
990struct CreateBlueprint {
991 /// The grade label this template stocks — the same free text a class
992 /// carries in `grade` ("9", "10-A"). It is the blueprint's own id, so it
993 /// must be non-empty and free of `/ \ ? # %`.
994 #[schema(max_length = 20, example = "9")]
995 grade: String,
996 /// The courses every class section at that grade takes.
997 course_ids: Vec<String>,
998}
999
1000#[derive(Deserialize, ToSchema)]
1001struct UpdateBlueprint {
1002 /// The whole new course list — a *set*, not a delta: courses missing from
1003 /// it are dropped from the blueprint and detached from the classes it
1004 /// attached them to.
1005 course_ids: Vec<String>,
1006}
1007
1008#[derive(Serialize, ToSchema)]
1009struct BlueprintResponse {
1010 /// The grade label, which is also the blueprint's id in every path here.
1011 #[schema(example = "9")]
1012 grade: String,
1013 /// The course ids this grade's sections take.
1014 courses: Vec<String>,
1015 /// Who wrote the template.
1016 creator: PersonRef,
1017}
1018
1019impl BlueprintResponse {
1020 fn new(
1021 blueprint: &ClassBlueprint,
1022 people: &std::collections::HashMap<String, PersonRef>,
1023 ) -> Self {
1024 Self {
1025 grade: blueprint.get_grade().as_str().to_string(),
1026 courses: blueprint
1027 .get_courses()
1028 .iter()
1029 .map(|course| course.key().to_string())
1030 .collect(),
1031 creator: PersonRef::resolve(people, blueprint.get_creator()),
1032 }
1033 }
1034}
1035
1036/// One class a pump did *not* stock, and why. The class is named as well as
1037/// identified: a manager reading a skip list has to know which section is short
1038/// a course, and a bare ULID is not that.
1039#[derive(Serialize, ToSchema)]
1040struct SkipResponse {
1041 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
1042 class: String,
1043 #[schema(example = "9-C")]
1044 class_name: String,
1045 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
1046 course: String,
1047 /// Why that course could not be attached to that class, as a machine code
1048 /// the client words itself — the same id-plus-client-label shape roles and
1049 /// course kinds have. The set is closed: `class_deleted` (the section was
1050 /// deleted while the pump ran), `course_deleted` (the course itself was
1051 /// deleted while the pump ran — a course deleted before it started is
1052 /// already out of the template; the pump drops that id too, so this is
1053 /// reported once for the whole grade and never again),
1054 /// `class_at_course_ceiling` (the
1055 /// section already holds `max_class_courses`), `class_roster_too_large`
1056 /// (the section holds more students than one attach may enroll at once),
1057 /// `course_full` (the course has no free seat for the whole section), and
1058 /// `blueprint_deleted` (the blueprint itself was deleted while the pump
1059 /// ran; nothing was attached, and there is nothing left to retry — it ends
1060 /// the run, so it appears once however many sections were left).
1061 ///
1062 /// The **same vocabulary** answers the manual routes as their `code`
1063 /// field. `POST /classes/{id}/courses` attaches along this very axis and so
1064 /// answers this list's ceilings, plus `duplicate` — a refusal there (the
1065 /// call asked for a row and did not get it) but not here (the course is
1066 /// already on the class, which is what the blueprint asks for).
1067 /// `POST /classes/{id}/members` attaches along the *other* axis, so its two
1068 /// ceilings are the mirror ones, named for the ceiling actually hit:
1069 /// `class_at_roster_ceiling` (the section already holds
1070 /// `max_class_members`) and `class_course_list_too_large` (it carries more
1071 /// courses than one member add may enroll at once). It also owns
1072 /// `linked_course_missing` (another course already attached to that section
1073 /// no longer exists — detach it first): it is the one attach that walks the
1074 /// section's existing course links, while a pump attaches a course it has
1075 /// just proved alive.
1076 #[schema(example = "course_full")]
1077 reason: String,
1078}
1079
1080impl SkipResponse {
1081 fn new(skip: &Skip) -> Self {
1082 Self {
1083 class: skip.class.key().to_string(),
1084 class_name: skip.class_name.clone(),
1085 course: skip.course.key().to_string(),
1086 reason: skip.reason.to_string(),
1087 }
1088 }
1089}
1090
1091#[derive(Serialize, ToSchema)]
1092struct BlueprintPumpResponse {
1093 blueprint: BlueprintResponse,
1094 /// How many class sections this pump reached. **`0` means no section
1095 /// carries this grade label** — the template was saved and stocked
1096 /// nothing. A grade is free text and matched exactly, so `"9 "`, `"9-A"`
1097 /// and `"9"` are three different grades: check the label against the one
1098 /// the sections actually carry, since an empty `skipped` alone reads the
1099 /// same whether every section took the list or none was found.
1100 ///
1101 /// The sections *reached*, not the ones the grade holds: a
1102 /// `blueprint_deleted` skip ends the run, and this then counts the ones
1103 /// walked before it.
1104 #[schema(example = 12)]
1105 matched: i64,
1106 /// Every (class, course) pair this write could not place. Empty when every
1107 /// section it reached took the whole list. The blueprint itself was still
1108 /// saved — a pump is best-effort by design.
1109 skipped: Vec<SkipResponse>,
1110}
1111
1112/// One section measured against its grade's template.
1113#[derive(Serialize, ToSchema)]
1114struct SectionStatusResponse {
1115 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
1116 class: String,
1117 #[schema(example = "9-C")]
1118 class_name: String,
1119 /// The template's courses this section does not carry, empty when it is in
1120 /// sync. A course attached **by hand** counts as carried, exactly as it
1121 /// does for the pump.
1122 missing: Vec<String>,
1123}
1124
1125#[derive(Serialize, ToSchema)]
1126struct BlueprintStatusResponse {
1127 #[schema(example = "9")]
1128 grade: String,
1129 /// The template every section below is measured against.
1130 courses: Vec<String>,
1131 /// How many sections carry this grade label — the same count a pump
1132 /// reports, and `0` still means the label matches nothing rather than that
1133 /// every section is stocked.
1134 #[schema(example = 12)]
1135 matched: i64,
1136 /// Every section at the grade, in sync or not. Unpaged: it is the şube one
1137 /// school runs at one grade.
1138 sections: Vec<SectionStatusResponse>,
1139}
1140
1141#[derive(Serialize, ToSchema)]
1142struct ApplyResponse {
1143 /// The courses this class could not take, empty when it took them all.
1144 skipped: Vec<SkipResponse>,
1145}
1146
1147/// The courses a request names, each of which must exist. Order and duplicates
1148/// are the blueprint's to settle ([`ClassBlueprint`] deduplicates).
1149async fn resolve_courses(ids: &[String], db: &Database) -> Result<Vec<CourseId>, AppError> {
1150 let mut courses = Vec::with_capacity(ids.len());
1151 for id in ids {
1152 let course = CourseId::from_key(id);
1153 if Course::read(&course, db).await?.is_none() {
1154 return Err(AppError::Validation(ValidationError::Invalid {
1155 field: "course_ids",
1156 reason: "one of these courses does not exist",
1157 }));
1158 }
1159 courses.push(course);
1160 }
1161 Ok(courses)
1162}
1163
1164/// The blueprint a path grade names, or a 404.
1165async fn blueprint_or_404(grade: &str, db: &Database) -> Result<ClassBlueprint, AppError> {
1166 ClassBlueprint::read(&ClassBlueprintId::from_key(grade), db)
1167 .await?
1168 .ok_or(AppError::NotFound)
1169}
1170
1171async fn blueprint_body(
1172 blueprint: &ClassBlueprint,
1173 pumped: &Pumped,
1174 db: &Database,
1175) -> Result<BlueprintPumpResponse, AppError> {
1176 let people = person_map([blueprint.get_creator().clone()], db).await?;
1177 Ok(BlueprintPumpResponse {
1178 blueprint: BlueprintResponse::new(blueprint, &people),
1179 matched: pumped.matched,
1180 skipped: pumped.skipped.iter().map(SkipResponse::new).collect(),
1181 })
1182}
1183
1184/// Create a grade's course blueprint and stock every class section already at
1185/// that grade with it. Requires manager+.
1186///
1187/// The pump is **best-effort**: a class that cannot take one of the courses (it
1188/// is at its own course ceiling, or the course has no free seat for the whole
1189/// section) is skipped and reported in `skipped`, while every other class is
1190/// still stocked. The blueprint is saved either way.
1191///
1192/// `matched` says how many sections it actually reached — `0` with an empty
1193/// `skipped` is a saved template that stocked nothing, which almost always
1194/// means the grade label does not match the one those sections carry.
1195#[utoipa::path(
1196 post,
1197 path = "/blueprints",
1198 tag = "classes",
1199 security(("session_cookie" = [])),
1200 request_body = CreateBlueprint,
1201 responses(
1202 (status = 201, description = "Blueprint created, with the number of sections it reached and the classes it could not stock", body = BlueprintPumpResponse),
1203 (status = 400, description = "Invalid or unaddressable grade, too many courses, or a course that does not exist", body = ErrorResponse),
1204 (status = 401, description = "Not authenticated", body = ErrorResponse),
1205 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
1206 (status = 409, description = "A blueprint already exists for that grade", body = ErrorResponse),
1207 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
1208 ),
1209)]
1210async fn create_blueprint(
1211 State(st): State<AppState>,
1212 RequireManager(user): RequireManager,
1213 Json(req): Json<CreateBlueprint>,
1214) -> Result<(StatusCode, Json<BlueprintPumpResponse>), AppError> {
1215 let grade = ClassBlueprint::grade_key(&req.grade)?;
1216 let courses = resolve_courses(&req.course_ids, &st.db).await?;
1217 let mut blueprint = ClassBlueprint::create(user.get_id(), grade, courses, &st.db).await?;
1218 let pumped = blueprint.pump(user.get_id(), &st.db).await?;
1219 let body = blueprint_body(&blueprint, &pumped, &st.db).await?;
1220 Ok((StatusCode::CREATED, Json(body)))
1221}
1222
1223/// List every grade blueprint, by grade label. Requires manager+. Paged via
1224/// `?limit=&offset=` (omit `limit` for all of them).
1225#[utoipa::path(
1226 get,
1227 path = "/blueprints",
1228 tag = "classes",
1229 security(("session_cookie" = [])),
1230 params(PageParams),
1231 responses(
1232 (status = 200, description = "A page of blueprints (all of them when unpaged)", body = Page<BlueprintResponse>),
1233 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1234 (status = 401, description = "Not authenticated", body = ErrorResponse),
1235 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
1236 ),
1237)]
1238async fn list_blueprints(
1239 State(st): State<AppState>,
1240 RequireManager(_user): RequireManager,
1241 Query(page): Query<PageParams>,
1242) -> Result<Json<Page<BlueprintResponse>>, AppError> {
1243 let (limit, offset) = page.resolve()?;
1244 let (blueprints, total) = ClassBlueprint::list_all(limit, offset, &st.db).await?;
1245 let people = person_map(
1246 blueprints
1247 .iter()
1248 .map(|blueprint| blueprint.get_creator().clone()),
1249 &st.db,
1250 )
1251 .await?;
1252 let items = blueprints
1253 .iter()
1254 .map(|blueprint| BlueprintResponse::new(blueprint, &people))
1255 .collect();
1256 Ok(Json(Page::new(items, total, limit, offset)))
1257}
1258
1259/// Fetch one grade's blueprint. Requires manager+.
1260#[utoipa::path(
1261 get,
1262 path = "/blueprints/{grade}",
1263 tag = "classes",
1264 security(("session_cookie" = [])),
1265 params(("grade" = String, Path, description = "Grade label")),
1266 responses(
1267 (status = 200, description = "The blueprint", body = BlueprintResponse),
1268 (status = 401, description = "Not authenticated", body = ErrorResponse),
1269 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
1270 (status = 404, description = "No blueprint for that grade", body = ErrorResponse),
1271 ),
1272)]
1273async fn get_blueprint(
1274 State(st): State<AppState>,
1275 RequireManager(_user): RequireManager,
1276 Path(grade): Path<String>,
1277) -> Result<Json<BlueprintResponse>, AppError> {
1278 let blueprint = blueprint_or_404(&grade, &st.db).await?;
1279 let people = person_map([blueprint.get_creator().clone()], &st.db).await?;
1280 Ok(Json(BlueprintResponse::new(&blueprint, &people)))
1281}
1282
1283/// Replace a blueprint's course list and reconcile every class section at that
1284/// grade with it. Requires manager+.
1285///
1286/// `course_ids` is the whole list, not a delta. A course dropped from it is
1287/// **detached** from the classes this blueprint attached it to (their pumped
1288/// enrollments swept the usual way) — but a course a human attached to a class
1289/// by hand carries no blueprint tag and is left exactly where it is. Courses
1290/// still in the list are pumped into every class at the grade that does not
1291/// already carry them.
1292///
1293/// The pump is **best-effort**: a class that cannot take a course is skipped
1294/// and reported in `skipped`, and the rest are still stocked. `matched` says
1295/// how many sections it reached, so a `0` tells a grade label nothing carries
1296/// apart from a list every section already had. A `409` means the list changed
1297/// since you read it — nothing was written; re-read and retry.
1298#[utoipa::path(
1299 patch,
1300 path = "/blueprints/{grade}",
1301 tag = "classes",
1302 security(("session_cookie" = [])),
1303 params(("grade" = String, Path, description = "Grade label")),
1304 request_body = UpdateBlueprint,
1305 responses(
1306 (status = 200, description = "Updated blueprint, with the number of sections it reached and the classes it could not stock", body = BlueprintPumpResponse),
1307 (status = 400, description = "Too many courses, or a course that does not exist", body = ErrorResponse),
1308 (status = 401, description = "Not authenticated", body = ErrorResponse),
1309 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
1310 (status = 404, description = "No blueprint for that grade", body = ErrorResponse),
1311 (status = 409, description = "The course list changed since the caller read it — nothing was written, re-read and retry", body = ErrorResponse),
1312 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
1313 ),
1314)]
1315async fn update_blueprint(
1316 State(st): State<AppState>,
1317 RequireManager(user): RequireManager,
1318 Path(grade): Path<String>,
1319 Json(req): Json<UpdateBlueprint>,
1320) -> Result<Json<BlueprintPumpResponse>, AppError> {
1321 let blueprint = blueprint_or_404(&grade, &st.db).await?;
1322 let courses = resolve_courses(&req.course_ids, &st.db).await?;
1323 let (saved, pumped) = blueprint
1324 .set_courses(courses, user.get_id(), &st.db)
1325 .await?;
1326 Ok(Json(blueprint_body(&saved, &pumped, &st.db).await?))
1327}
1328
1329/// Delete a grade's blueprint. Requires manager+. Every attachment the
1330/// blueprint made is detached with it (their pumped enrollments swept the usual
1331/// way); a course a human attached to one of those classes by hand carries no
1332/// blueprint tag and survives.
1333///
1334/// A `409` means the course list changed between this call reading the
1335/// blueprint and deleting it — nothing was written; re-read and retry.
1336#[utoipa::path(
1337 delete,
1338 path = "/blueprints/{grade}",
1339 tag = "classes",
1340 security(("session_cookie" = [])),
1341 params(("grade" = String, Path, description = "Grade label")),
1342 responses(
1343 (status = 204, description = "Deleted"),
1344 (status = 401, description = "Not authenticated", body = ErrorResponse),
1345 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
1346 (status = 404, description = "No blueprint for that grade", body = ErrorResponse),
1347 (status = 409, description = "The course list changed since this call read it — nothing was written, re-read and retry", body = ErrorResponse),
1348 ),
1349)]
1350async fn delete_blueprint(
1351 State(st): State<AppState>,
1352 RequireManager(_user): RequireManager,
1353 Path(grade): Path<String>,
1354) -> Result<StatusCode, AppError> {
1355 blueprint_or_404(&grade, &st.db)
1356 .await?
1357 .delete(&st.db)
1358 .await?;
1359 Ok(StatusCode::NO_CONTENT)
1360}
1361
1362/// Which sections at a grade are out of sync with its blueprint. Requires
1363/// manager+. Reads only — nothing is attached, detached or pruned.
1364///
1365/// A pump's `skipped` list lives only in the response that reported it; this is
1366/// how a manager asks the same question afterwards. Every section carrying the
1367/// grade label is listed with the template courses it does not carry, so an
1368/// empty `missing` everywhere is a grade fully stocked.
1369///
1370/// A course a human attached by hand counts as carried, exactly as it does for
1371/// the pump — the template asks for the course, not for the pump's tag.
1372/// Deleting a course takes it out of every template naming it, so `missing`
1373/// names courses that still exist — only a row written before that cascade
1374/// existed can still show a dangling id.
1375///
1376/// The fix for anything listed is one of two idempotent calls:
1377/// `POST /classes/{id}/blueprint` for one section, or `PATCH` the blueprint
1378/// with the list it already holds to re-run the whole grade's pump.
1379#[utoipa::path(
1380 get,
1381 path = "/blueprints/{grade}/status",
1382 tag = "classes",
1383 security(("session_cookie" = [])),
1384 params(("grade" = String, Path, description = "Grade label")),
1385 responses(
1386 (status = 200, description = "Every section at the grade, with the template courses it is missing", body = BlueprintStatusResponse),
1387 (status = 401, description = "Not authenticated", body = ErrorResponse),
1388 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
1389 (status = 404, description = "No blueprint for that grade", body = ErrorResponse),
1390 ),
1391)]
1392async fn blueprint_status(
1393 State(st): State<AppState>,
1394 RequireManager(_user): RequireManager,
1395 Path(grade): Path<String>,
1396) -> Result<Json<BlueprintStatusResponse>, AppError> {
1397 let blueprint = blueprint_or_404(&grade, &st.db).await?;
1398 let sections = blueprint.status(&st.db).await?;
1399 Ok(Json(BlueprintStatusResponse {
1400 grade: blueprint.get_grade().as_str().to_string(),
1401 courses: blueprint
1402 .get_courses()
1403 .iter()
1404 .map(|course| course.key().to_string())
1405 .collect(),
1406 matched: sections.len() as i64,
1407 sections: sections
1408 .iter()
1409 .map(|section| SectionStatusResponse {
1410 class: section.class.key().to_string(),
1411 class_name: section.class_name.clone(),
1412 missing: section
1413 .missing
1414 .iter()
1415 .map(|course| course.key().to_string())
1416 .collect(),
1417 })
1418 .collect(),
1419 }))
1420}
1421
1422/// Stock one class section from its grade's blueprint. Requires manager+ — this
1423/// writes the roster of every course in the template, which is the office's
1424/// call, not one course owner's.
1425///
1426/// Idempotent: a course the class already carries is left alone, whoever
1427/// attached it. Best-effort like every other pump — the courses that did not
1428/// fit come back in `skipped` and the rest are attached. A class with no grade,
1429/// or a grade no blueprint covers, is a 404.
1430#[utoipa::path(
1431 post,
1432 path = "/{id}/blueprint",
1433 tag = "classes",
1434 security(("session_cookie" = [])),
1435 params(("id" = String, Path, description = "Class id")),
1436 responses(
1437 (status = 200, description = "The class was stocked, minus the courses it could not take", body = ApplyResponse),
1438 (status = 401, description = "Not authenticated", body = ErrorResponse),
1439 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
1440 (status = 404, description = "Class not found, or no blueprint covers its grade", body = ErrorResponse),
1441 (status = 409, description = "The class's (or course's) term is archived — past years are read-only", body = ErrorResponse),
1442 ),
1443)]
1444async fn apply_blueprint(
1445 State(st): State<AppState>,
1446 RequireManager(user): RequireManager,
1447 Path(id): Path<String>,
1448) -> Result<Json<ApplyResponse>, AppError> {
1449 let class = class_or_404(&id, &st.db).await?;
1450 let grade = class.get_grade().ok_or(AppError::NotFound)?;
1451 let blueprint = blueprint_or_404(grade.as_str(), &st.db).await?;
1452 // The pump writes both ends, so both are guarded — the class, and every
1453 // course the template would attach. A course the template names that is
1454 // already gone is the pump's own `skipped` business, not a term refusal.
1455 class.require_open(&st.db).await?;
1456 for id in blueprint.get_courses() {
1457 if let Some(course) = Course::read(id, &st.db).await? {
1458 course.require_open(&st.db).await?;
1459 }
1460 }
1461 let skipped = blueprint.apply_to(&class, user.get_id(), &st.db).await?;
1462 Ok(Json(ApplyResponse {
1463 skipped: skipped.iter().map(SkipResponse::new).collect(),
1464 }))
1465}
1466
1467#[cfg(test)]
1468mod tests {
1469 use super::*;
1470
1471 /// The nullable-grade rule both write paths share: absent and `""` are the
1472 /// same *no grade*, so a PATCH clearing with `""` cannot store a blank
1473 /// label a create could never make.
1474 #[test]
1475 fn an_empty_grade_is_no_grade() {
1476 assert!(grade_or_none(None).unwrap().is_none());
1477 assert!(grade_or_none(Some("")).unwrap().is_none());
1478 assert_eq!(
1479 grade_or_none(Some("9"))
1480 .unwrap()
1481 .map(|g| g.as_str().to_string()),
1482 Some("9".to_string())
1483 );
1484 assert!(grade_or_none(Some(&"x".repeat(1000))).is_err());
1485 }
1486
1487 /// The same nullable rule on the homeroom teacher, plus the bar it holds:
1488 /// absent and `""` are the same *no teacher* (and never touch the store),
1489 /// an id naming nobody is a `400`, and so is one naming a student — a
1490 /// class's sınıf öğretmeni is staff.
1491 #[tokio::test]
1492 async fn an_empty_teacher_is_no_teacher_and_a_student_is_never_one() {
1493 use crate::domain::role::Role;
1494 use crate::domain::user::{Password, User, Username};
1495
1496 let db = crate::database::init_mem().await.unwrap();
1497 assert!(teacher_or_none(None, &db).await.unwrap().is_none());
1498 assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none());
1499
1500 let make = async |name: &str, role: Role| {
1501 let user = User::create(
1502 Username::try_new(name).unwrap(),
1503 Password::try_new("secret1")
1504 .unwrap()
1505 .hash_async()
1506 .await
1507 .unwrap(),
1508 &db,
1509 )
1510 .await
1511 .unwrap();
1512 user.set_role(role, &db).await.unwrap().0
1513 };
1514 let student = make("ali", Role::Student).await;
1515 let teacher = make("ada", Role::Teacher).await;
1516
1517 for (field, id) in [
1518 ("gone", "01J8XZ0K3Q8G7X2M4N5P6R7S8T"),
1519 ("student", student.get_id().key()),
1520 ] {
1521 let refused = teacher_or_none(Some(id), &db).await;
1522 assert!(
1523 matches!(
1524 refused,
1525 Err(AppError::Validation(ValidationError::Invalid {
1526 field: "teacher_id",
1527 ..
1528 }))
1529 ),
1530 "a {field} id must be a 400 naming teacher_id: {refused:?}"
1531 );
1532 }
1533 assert_eq!(
1534 teacher_or_none(Some(teacher.get_id().key()), &db)
1535 .await
1536 .unwrap()
1537 .map(|found| found.get_id().clone()),
1538 Some(teacher.get_id().clone()),
1539 "a teacher account is the one thing that resolves"
1540 );
1541 }
1542}