forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB62f10eaAhmet Kaan Gümüş2 months ago565 commits

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