forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB0346717Ahmet Kaan Gümüş3 months ago230 commits

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