forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB69d4295Ahmet Kaan Gümüş2 months ago536 commits

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