forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

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