forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

instances.rs1400 lines, 62.4 KiBHistoryRawDownload
1//! The **instance**: one catalog course as taught in one class section — the
2//! anchor of the K12 model.
3//!
4//! Everything a class actually runs hangs off this row: its roster, its
5//! teachers, its exams, its lessons and its homework. Two sections teaching the
6//! same course are two instances and share none of it. Each instance points at
7//! its grade-level **offering** template and may override the content fields
8//! (`title`, `description`, `ders_saati`, `counts_toward_karne`) — a `PATCH`
9//! sets an override, `POST /{id}/reset` clears back to inherit, and what a
10//! read presents is the resolved value (override → offering default →
11//! constant), never the raw `NULL`.
12//!
13//! The catalog CRUD stays in [`super::courses`]; the exam, session and
14//! homework sub-routers live *here* now (they used to hang off `/courses/{id}`)
15//! and are split out per module so each still carries its own gate — see
16//! [`crate::web::module_gate`].
17
18use std::collections::HashMap;
19
20use crate::web::tenant_state::State;
21use axum::Json;
22use axum::extract::{Path, Query};
23use axum::http::StatusCode;
24use serde::{Deserialize, Serialize};
25use utoipa::{IntoParams, ToSchema};
26use utoipa_axum::router::OpenApiRouter;
27use utoipa_axum::routes;
28
29use crate::database::Database;
30use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati};
31use crate::domain::course::{CourseDescription, CourseTitle};
32use crate::domain::course_session::SessionTopic;
33use crate::domain::enrollment::Enrollment;
34use crate::domain::exam::{
35 ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle,
36};
37use crate::domain::homework::HomeworkTitle;
38use crate::domain::term::TermId;
39use crate::domain::timestamp::Timestamp;
40use crate::domain::user::{User, UserId};
41use crate::error::{AppError, ErrorResponse, ValidationError};
42use crate::service;
43use crate::service::instance::{can_manage_instance, visible_instances};
44use crate::state::AppState;
45
46use super::exam_weights::ExamWeightEntry;
47use super::homework::{description_or_none, resolve_assigned};
48use super::weekly_plan::WeeklySlotDto;
49use super::{
50 CurrentUser, ExamResponse, HomeworkResponse, Page, PageParams, PersonRef, RequireManager,
51 RequireTeacher, SessionResponse, SubjectResponse, check_not_past, check_time_range, paginate,
52 person_map,
53};
54
55pub fn routes() -> OpenApiRouter<AppState> {
56 OpenApiRouter::new()
57 .routes(routes!(my_instances))
58 .routes(routes!(get_instance, update_instance))
59 .routes(routes!(reset_instance))
60 .routes(routes!(assign_teacher))
61 .routes(routes!(unassign_teacher))
62 .routes(routes!(enroll, list_roster))
63 .routes(routes!(unenroll))
64}
65
66// The three route pairs below belong to another module, so each is split out
67// to carry that module's gate as well as the instance one — see
68// `crate::web::module_gate`. They are merged back in `build_router`, so the
69// URL space is unchanged.
70
71pub fn exam_routes() -> OpenApiRouter<AppState> {
72 OpenApiRouter::new().routes(routes!(create_exam_in_instance, list_instance_exams))
73}
74
75pub fn session_routes() -> OpenApiRouter<AppState> {
76 OpenApiRouter::new().routes(routes!(create_session_in_instance, list_instance_sessions))
77}
78
79pub fn homework_routes() -> OpenApiRouter<AppState> {
80 OpenApiRouter::new().routes(routes!(create_homework_in_instance, list_instance_homework))
81}
82
83#[derive(Deserialize, ToSchema)]
84struct UpdateInstance {
85 /// The section's own title override. Omit to keep the stored value; a
86 /// PATCH **sets**, it never clears — clearing back to inherit is the
87 /// reset door's (`POST /instances/{id}/reset`).
88 #[schema(max_length = 200, example = "9-A Matematik")]
89 title: Option<String>,
90 /// The section's own description override. Omit to keep; never clears.
91 #[schema(max_length = 2_000)]
92 description: Option<String>,
93 /// The section's own weekly-hours override: the weight it takes in the
94 /// year's report-card average while it is set. Omit to keep the stored
95 /// value (`null` to clear is the reset door's); at least 1 and at most 40.
96 #[schema(minimum = 1, maximum = 40, example = 5)]
97 ders_saati: Option<i64>,
98 /// The section's own report-card policy override. Omit to keep; never
99 /// clears.
100 counts_toward_karne: Option<bool>,
101}
102
103#[derive(Deserialize, ToSchema)]
104struct ResetInstanceOverrides {
105 /// The overrides to clear back to **inherit**: `title`, `description`,
106 /// `ders_saati`, `counts_toward_karne` — and, flipping the section's own
107 /// table back to non-authoritative (the offering's set applies again),
108 /// `subjects`, `exam_weights`, `weekly_plan`. Unknown names are a 400.
109 fields: Vec<String>,
110}
111
112#[derive(Deserialize, ToSchema)]
113struct AssignTeacher {
114 /// The staff member to put in charge of this instance. Must hold the
115 /// `teacher` role or higher.
116 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
117 user_id: String,
118}
119
120#[derive(Deserialize, ToSchema)]
121struct EnrollUser {
122 /// The user to enroll.
123 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
124 user_id: String,
125}
126
127#[derive(Deserialize, ToSchema)]
128struct CreateExamInCourse {
129 #[schema(max_length = 200, example = "Midterm")]
130 title: String,
131 #[schema(max_length = 2000)]
132 description: Option<String>,
133 /// The assessment form — one of the school's exam kinds (`GET /settings`;
134 /// defaults: `yazili`, `sozlu`, `uygulama` — written, oral, practice). The
135 /// kind's settings-configured weight decides how heavily the exam counts
136 /// into the instance's average.
137 #[schema(max_length = 50, example = "yazili")]
138 kind: String,
139 /// The term the exam is sat in (`GET /terms`). Required, and it must be a
140 /// term of this instance's section's academic year — that is the slice the
141 /// exam's marks are counted into.
142 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
143 term: String,
144 /// `sync` (one fixed window for everyone), `async` (each student starts
145 /// inside the window and gets `duration_ms`), or `open` (no window — sit
146 /// anytime). Omit for an offline-graded exam that cannot be sat.
147 #[schema(example = "sync")]
148 mode: Option<String>,
149 /// Window open, UTC unix-milliseconds (`sync`/`async`). Must not be in the
150 /// past.
151 #[schema(example = 1_900_000_000_000_i64)]
152 starts_at: Option<i64>,
153 /// Window close, UTC unix-milliseconds (`sync`/`async`). Must not precede
154 /// `starts_at`.
155 #[schema(example = 1_900_000_360_000_i64)]
156 ends_at: Option<i64>,
157 /// Per-attempt time budget in milliseconds. Required for `async`,
158 /// optional for `open`; must fit inside the window when there is one.
159 #[schema(minimum = 60_000, maximum = 86_400_000, example = 3_600_000_i64)]
160 duration_ms: Option<i64>,
161 /// How many attempts each student gets. Defaults to 1; `0` means
162 /// unlimited.
163 #[schema(minimum = 0, maximum = 100, example = 1)]
164 max_attempts: Option<i64>,
165 /// Whether a student who left the exam room may come back in and keep
166 /// answering. Defaults to `true`.
167 allow_rejoin: Option<bool>,
168 /// Whether students may review their graded attempt once results are out.
169 /// Defaults to `false`.
170 allow_review: Option<bool>,
171 /// Keep the exam private while it is still being written. Defaults to
172 /// `false` (published).
173 draft: Option<bool>,
174}
175
176#[derive(Deserialize, ToSchema)]
177struct CreateHomework {
178 #[schema(max_length = 200, example = "Read chapter 3 and answer Q1-Q5")]
179 title: String,
180 #[schema(max_length = 2000)]
181 description: Option<String>,
182 /// The course subject this homework belongs to
183 /// (`GET /courses/{id}/subjects`). Required — every homework is tagged with
184 /// one of its course's subjects.
185 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
186 subject_id: String,
187 /// When the homework is due, UTC unix-milliseconds. Required; must not be
188 /// in the past. Late submissions are still accepted, just flagged late.
189 #[schema(example = 1_900_000_000_000_i64)]
190 due_at: i64,
191 /// The students this homework is for: a list of enrolled student ids. Omit,
192 /// send `null`, or send `[]` to assign the whole enrolled roster (whoever
193 /// is enrolled when they submit); a subset caps at 200 named students.
194 #[schema(max_items = 200)]
195 assigned: Option<Vec<String>>,
196}
197
198#[derive(Deserialize, ToSchema)]
199struct CreateSessionInCourse {
200 /// What the lesson covers. Optional.
201 #[schema(max_length = 200, example = "Limits and continuity")]
202 topic: Option<String>,
203 /// Who teaches the session. Defaults to the caller; must hold the
204 /// `teacher` role or higher.
205 teacher_id: Option<String>,
206 /// Lesson start, UTC unix-milliseconds. Must not be in the past.
207 #[schema(example = 1_900_000_000_000_i64)]
208 starts_at: i64,
209 /// Lesson end, UTC unix-milliseconds. Optional (open-ended); must not be
210 /// in the past.
211 ends_at: Option<i64>,
212}
213
214/// Public shape of one instance: the course as this section teaches it. Every
215/// content field is the **resolved** view the instance resolver composes —
216/// scalar chains run override → offering → catalog/constant, the set axes are
217/// flag-driven — so a client renders this verbatim and renders a per-class
218/// edit screen from this one call: `*_overridden` tells its own override from
219/// an inherited value, `*_inherited` tells whose set is authoritative. The
220/// raw template values (nullable, unset = inherit) live one level up, on
221/// `GET /offerings/{id}`.
222#[derive(Serialize, ToSchema)]
223pub struct InstanceResponse {
224 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
225 pub id: String,
226 /// The class section that teaches it.
227 pub class: String,
228 /// The catalog course being taught (`GET /courses/{id}`) — its title lives
229 /// there, shared by every instance of it.
230 pub course: String,
231 /// The grade-level offering template this section teaches from
232 /// (`GET /offerings/{id}`) — the thing its unset fields inherit from.
233 pub offering: String,
234 /// The section's **resolved** title: its own override, else its
235 /// offering's, else the catalog course's.
236 pub title: String,
237 /// `true` when `title` is this section's own override rather than
238 /// inherited from the offering or the catalog.
239 pub title_overridden: bool,
240 /// The section's **resolved** description, the same chain as `title`.
241 pub description: String,
242 /// `true` when `description` is this section's own override.
243 pub description_overridden: bool,
244 /// The section's **effective** weekly hours: its own override, else the
245 /// offering's default, else 1 — the weight it takes in the year's
246 /// report-card average.
247 #[schema(example = 5)]
248 pub ders_saati: i64,
249 /// `true` when the hours are this section's own override.
250 pub ders_saati_overridden: bool,
251 /// The effective report-card policy: own override, else the offering's
252 /// default, else counted.
253 pub counts_toward_karne: bool,
254 /// `true` when the policy is this section's own override.
255 pub counts_toward_karne_overridden: bool,
256 /// `false` = this section's own subject table is authoritative, including
257 /// when empty; `true` = the offering's subject set applies.
258 pub subjects_inherited: bool,
259 /// The section's **resolved** syllabus — the same set
260 /// `GET /{id}/subjects` serves, name-then-id order.
261 pub subjects: Vec<SubjectResponse>,
262 /// `true` = the section follows its offering's weight map; `false` = its
263 /// own table is authoritative, empty included.
264 pub exam_weights_inherited: bool,
265 /// The section's **resolved** weight map: every kind at its effective
266 /// weight (override → offering → settings → 1).
267 pub exam_weights: Vec<ExamWeightEntry>,
268 /// The same switch for the section's weekly plan.
269 pub weekly_plan_inherited: bool,
270 /// The section's **resolved** weekly plan: its own `class_course_slot`
271 /// rows when the flag above is `false` — including when that set is
272 /// empty — the offering's `offering_slot` template week when `true`.
273 /// Weekday first, then start time. Template data a timetable renders; no
274 /// dated `course_session` rows come from it until a caller asks
275 /// (`POST /instances/{id}/weekly-plan/materialize`).
276 pub weekly_plan: Vec<WeeklySlotDto>,
277 /// How many students are enrolled right now.
278 #[schema(example = 28)]
279 pub enrollment_count: i64,
280 /// The staff assigned to run this instance — separate from the section's
281 /// homeroom teacher, who may also act here (see `GET /instances/{id}`).
282 pub teachers: Vec<PersonRef>,
283}
284
285impl InstanceResponse {
286 async fn new(
287 db: &Database,
288 instance: &ClassCourse,
289 teachers: &[UserId],
290 people: &HashMap<String, PersonRef>,
291 ) -> Result<Self, AppError> {
292 // One composed resolver call: title, description, the policy pair and
293 // the three set axes — never a fallback chain re-implemented here.
294 let resolved = service::instance_resolve::resolve(db, instance).await?;
295 Ok(Self {
296 id: instance.get_id().key().to_string(),
297 class: instance.get_class().key().to_string(),
298 course: instance.get_course().key().to_string(),
299 offering: instance.get_offering().key(),
300 title: resolved.title,
301 title_overridden: resolved.title_overridden,
302 description: resolved.description,
303 description_overridden: resolved.description_overridden,
304 ders_saati: resolved.ders_saati.as_i64(),
305 ders_saati_overridden: resolved.ders_saati_overridden,
306 counts_toward_karne: resolved.counts_toward_karne,
307 counts_toward_karne_overridden: resolved.counts_toward_karne_overridden,
308 subjects_inherited: resolved.subjects_inherited,
309 subjects: resolved.subjects.iter().map(SubjectResponse::new).collect(),
310 exam_weights_inherited: resolved.exam_weights_inherited,
311 exam_weights: resolved
312 .exam_weights
313 .iter()
314 .map(ExamWeightEntry::of)
315 .collect(),
316 weekly_plan_inherited: resolved.weekly_plan_inherited,
317 weekly_plan: resolved.weekly_plan.iter().map(WeeklySlotDto::new).collect(),
318 enrollment_count: instance.get_enrollment_count(),
319 teachers: teachers
320 .iter()
321 .map(|teacher| PersonRef::resolve(people, teacher))
322 .collect(),
323 })
324 }
325}
326
327#[derive(Serialize, ToSchema)]
328struct EnrollmentResponse {
329 id: String,
330 /// The instance this roster row is under (`GET /instances/{id}`).
331 class_course: String,
332 /// The enrolled student.
333 user: PersonRef,
334 /// Who enrolled them.
335 enrolled_by: PersonRef,
336 /// The section this row was pumped by, or `null` when a human placed it
337 /// directly. A row with a section on it is *swept* when that section drops
338 /// the student or detaches the course; a `null` one is nobody's to take back.
339 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
340 source: Option<String>,
341}
342
343impl EnrollmentResponse {
344 fn new(enrollment: &Enrollment, people: &HashMap<String, PersonRef>) -> Self {
345 Self {
346 id: enrollment.get_id().key().to_string(),
347 class_course: enrollment.get_class_course().key().to_string(),
348 user: PersonRef::resolve(people, enrollment.get_user()),
349 enrolled_by: PersonRef::resolve(people, enrollment.get_enrolled_by()),
350 source: enrollment.get_source().map(|class| class.key().to_string()),
351 }
352 }
353}
354
355/// The instance a path id names, or a 404 — every route under `/instances/{id}`
356/// gates on it, so a missing instance never reads as an empty roster.
357async fn instance_or_404(key: &ClassCourseId, db: &Database) -> Result<ClassCourse, AppError> {
358 service::class_course::read(db, key)
359 .await?
360 .ok_or(AppError::NotFound)
361}
362
363/// Who may read inside an instance: anyone who can manage it, plus its
364/// enrolled students. Other teachers and unenrolled students see nothing.
365pub(crate) async fn can_view_instance(
366 db: &Database,
367 instance: &ClassCourseId,
368 user: &User,
369) -> Result<bool, AppError> {
370 if can_manage_instance(db, instance, user).await? {
371 return Ok(true);
372 }
373 Ok(
374 service::enrollment::read_for_user(db, instance, user.get_id())
375 .await?
376 .is_some(),
377 )
378}
379
380/// Join the people a page of instances names (their assigned teachers) in one
381/// batch read — the lookup shrinks with the window, never the whole table.
382pub(crate) async fn instance_people(
383 rows: &[(ClassCourse, Vec<UserId>)],
384 db: &Database,
385) -> Result<HashMap<String, PersonRef>, AppError> {
386 person_map(
387 rows.iter()
388 .flat_map(|(_, teachers)| teachers.iter().cloned()),
389 db,
390 )
391 .await
392}
393
394/// The instances the caller may act in or see, paged via `?limit=&offset=`
395/// (omit `limit` for all of them), newest first; returns a
396/// `{items, total, limit, offset}` envelope. The route a student reads to find
397/// the courses their section is being taught, and a teacher the ones they run.
398///
399/// The set is exactly
400/// [`crate::service::instance::visible_instances`]'s — the caller's sections (a
401/// student's live membership, a homeroom teacher's) unioned with the instances
402/// they were assigned to teach, deduped by instance. One rule for what the
403/// caller may see, so this list and every instance-scoped gate can never
404/// disagree about which instances are theirs.
405#[utoipa::path(
406 get,
407 path = "/me",
408 tag = "instances",
409 security(("session_cookie" = [])),
410 params(PageParams),
411 responses(
412 (status = 200, description = "A page of the caller's instances (all of them when unpaged)", body = Page<InstanceResponse>),
413 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
414 (status = 401, description = "Not authenticated", body = ErrorResponse),
415 ),
416)]
417async fn my_instances(
418 State(st): State<AppState>,
419 CurrentUser(user): CurrentUser,
420 Query(page): Query<PageParams>,
421) -> Result<Json<Page<InstanceResponse>>, AppError> {
422 let (limit, offset) = page.resolve()?;
423 // Both reads the caller's identity feeds (`class_member` and the teach /
424 // homeroom assignments) are `visible_instances`'. Its order is the two
425 // arms' own — each newest first — so the union is sorted back into one
426 // newest-first order: `?limit=&offset=` pages over a total order, and a
427 // stable one is what keeps a page from handing the same row out twice.
428 let mut visible = visible_instances(&user, &st.db).await?;
429 visible.sort_by(|(a, _), (b, _)| {
430 b.get_attached_at()
431 .cmp(&a.get_attached_at())
432 .then_with(|| b.get_id().uuid().cmp(&a.get_id().uuid()))
433 });
434 let total = visible.len() as i64;
435 let window: Vec<ClassCourse> = paginate(&visible, limit, offset)
436 .iter()
437 .map(|(instance, _)| instance.clone())
438 .collect();
439 let with_teachers = crate::db::class_course_teacher::into_instances(&st.db, window).await?;
440 let people = instance_people(&with_teachers, &st.db).await?;
441 let mut items = Vec::with_capacity(with_teachers.len());
442 for (instance, teachers) in &with_teachers {
443 items.push(InstanceResponse::new(&st.db, instance, teachers, &people).await?);
444 }
445 Ok(Json(Page::new(items, total, limit, offset)))
446}
447
448/// Fetch one instance by id. Visible to its enrolled students, its assigned
449/// teachers, its section's homeroom teacher, and managers/admins.
450#[utoipa::path(
451 get,
452 path = "/{id}",
453 tag = "instances",
454 security(("session_cookie" = [])),
455 params(("id" = String, Path, description = "Instance id")),
456 responses(
457 (status = 200, description = "The instance", body = InstanceResponse),
458 (status = 401, description = "Not authenticated", body = ErrorResponse),
459 (status = 403, description = "Not enrolled, and not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
460 (status = 404, description = "Not found", body = ErrorResponse),
461 ),
462)]
463async fn get_instance(
464 State(st): State<AppState>,
465 CurrentUser(user): CurrentUser,
466 Path(id): Path<String>,
467) -> Result<Json<InstanceResponse>, AppError> {
468 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
469 if !can_view_instance(&st.db, instance.get_id(), &user).await? {
470 return Err(AppError::Forbidden(
471 "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view it",
472 ));
473 }
474 let teachers =
475 crate::db::class_course_teacher::list_for_instance(&st.db, instance.get_id()).await?;
476 let people = person_map(teachers.iter().cloned(), &st.db).await?;
477 Ok(Json(InstanceResponse::new(&st.db, &instance, &teachers, &people).await?))
478}
479
480/// Update one instance's own policy overrides. Requires teacher+ and a right
481/// over this instance: manager+, one of its assigned teachers, or its
482/// section's homeroom teacher. Omitted fields keep their value; a PATCH
483/// **sets**, it never clears — `POST /{id}/reset` is the clear door.
484#[utoipa::path(
485 patch,
486 path = "/{id}",
487 tag = "instances",
488 security(("session_cookie" = [])),
489 params(("id" = String, Path, description = "Instance id")),
490 request_body = UpdateInstance,
491 responses(
492 (status = 200, description = "Updated instance", body = InstanceResponse),
493 (status = 400, description = "Invalid title, description, or ders_saati", body = ErrorResponse),
494 (status = 401, description = "Not authenticated", body = ErrorResponse),
495 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
496 (status = 404, description = "Not found", body = ErrorResponse),
497 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
498 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
499 ),
500)]
501async fn update_instance(
502 State(st): State<AppState>,
503 RequireTeacher(user): RequireTeacher,
504 Path(id): Path<String>,
505 Json(req): Json<UpdateInstance>,
506) -> Result<Json<InstanceResponse>, AppError> {
507 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
508 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
509 service::class_course::require_open(&st.db, instance.get_id()).await?;
510
511 let title = match &req.title {
512 Some(title) => Some(CourseTitle::try_new(title)?),
513 None => None,
514 };
515 let description = match &req.description {
516 Some(description) => Some(CourseDescription::try_new(description)?),
517 None => None,
518 };
519 let staff = req.ders_saati.map(DersSaati::try_new).transpose()?;
520 let updated = service::class_course::update(
521 &st.db,
522 instance.get_id(),
523 title,
524 description,
525 staff,
526 req.counts_toward_karne,
527 )
528 .await?;
529 let teachers =
530 crate::db::class_course_teacher::list_for_instance(&st.db, updated.get_id()).await?;
531 let people = person_map(teachers.iter().cloned(), &st.db).await?;
532 Ok(Json(InstanceResponse::new(&st.db, &updated, &teachers, &people).await?))
533}
534
535/// Clear the named overrides back to inherit — the door a PATCH never is.
536/// Same gate as the PATCH: teacher+ with a right over this instance, and a
537/// live (non-archived) year. Resetting a set policy (`subjects`,
538/// `exam_weights`, `weekly_plan`) flips the section's flag back to
539/// *inherited*; deleting the section's own rows under it rides the child
540/// tables' own reset doors.
541#[utoipa::path(
542 post,
543 path = "/{id}/reset",
544 tag = "instances",
545 security(("session_cookie" = [])),
546 params(("id" = String, Path, description = "Instance id")),
547 request_body = ResetInstanceOverrides,
548 responses(
549 (status = 200, description = "The overrides cleared; the instance now inherits the named fields", body = InstanceResponse),
550 (status = 400, description = "A field name is unknown, or the list is empty", body = ErrorResponse),
551 (status = 401, description = "Not authenticated", body = ErrorResponse),
552 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
553 (status = 404, description = "Not found", body = ErrorResponse),
554 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
555 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
556 ),
557)]
558async fn reset_instance(
559 State(st): State<AppState>,
560 RequireTeacher(user): RequireTeacher,
561 Path(id): Path<String>,
562 Json(req): Json<ResetInstanceOverrides>,
563) -> Result<Json<InstanceResponse>, AppError> {
564 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
565 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
566 service::class_course::require_open(&st.db, instance.get_id()).await?;
567
568 let mut fields = Vec::with_capacity(req.fields.len());
569 for name in &req.fields {
570 fields.push(service::class_course::parse_reset_field(name)?);
571 }
572 let updated =
573 service::class_course::reset_overrides(&st.db, instance.get_id(), &fields).await?;
574 let teachers =
575 crate::db::class_course_teacher::list_for_instance(&st.db, updated.get_id()).await?;
576 let people = person_map(teachers.iter().cloned(), &st.db).await?;
577 Ok(Json(InstanceResponse::new(&st.db, &updated, &teachers, &people).await?))
578}
579
580/// Assign a teacher to this instance (idempotent). Manager+ only — staffing is
581/// the office's call. The assignee must already hold the `teacher` role or
582/// higher; the assignment gives them full management of the instance (exams,
583/// sessions, homework, roster, grading) but they keep no catalog rights over
584/// the course itself.
585#[utoipa::path(
586 post,
587 path = "/{id}/teachers",
588 tag = "instances",
589 security(("session_cookie" = [])),
590 params(("id" = String, Path, description = "Instance id")),
591 request_body = AssignTeacher,
592 responses(
593 (status = 200, description = "Assigned (or already assigned)", body = InstanceResponse),
594 (status = 400, description = "Unknown user, or user is not a teacher or higher", body = ErrorResponse),
595 (status = 401, description = "Not authenticated", body = ErrorResponse),
596 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
597 (status = 404, description = "Instance not found", body = ErrorResponse),
598 (status = 409, description = "That user was demoted below teacher while the request ran — the assignment was undone; or this instance's academic year is archived", body = ErrorResponse),
599 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
600 ),
601)]
602async fn assign_teacher(
603 State(st): State<AppState>,
604 RequireManager(manager): RequireManager,
605 Path(id): Path<String>,
606 Json(req): Json<AssignTeacher>,
607) -> Result<Json<InstanceResponse>, AppError> {
608 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
609 let target = UserId::from_key(&req.user_id);
610 service::class_course::assign_teacher(&st.db, instance.get_id(), &target, manager.get_id())
611 .await?;
612 // The row is written; a demotion that raced the gate inside the assignment
613 // swept the list before this row was in it (see [`super::undo_if_demoted`]).
614 super::undo_if_demoted(&target, &st.db).await?;
615 let teachers =
616 crate::db::class_course_teacher::list_for_instance(&st.db, instance.get_id()).await?;
617 let people = person_map(teachers.iter().cloned(), &st.db).await?;
618 Ok(Json(InstanceResponse::new(&st.db, &instance, &teachers, &people).await?))
619}
620
621/// Unassign a teacher from this instance. Manager+ only. The instance, its
622/// exams, sessions, and roster are untouched — the teacher just loses their
623/// management rights over it. A user who was never assigned is a 404.
624#[utoipa::path(
625 delete,
626 path = "/{id}/teachers/{user}",
627 tag = "instances",
628 security(("session_cookie" = [])),
629 params(
630 ("id" = String, Path, description = "Instance id"),
631 ("user" = String, Path, description = "User id"),
632 ),
633 responses(
634 (status = 204, description = "Unassigned"),
635 (status = 401, description = "Not authenticated", body = ErrorResponse),
636 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
637 (status = 404, description = "Instance not found, or that user was not assigned to it", body = ErrorResponse),
638 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
639 ),
640)]
641async fn unassign_teacher(
642 State(st): State<AppState>,
643 RequireManager(_manager): RequireManager,
644 Path((id, target)): Path<(String, String)>,
645) -> Result<StatusCode, AppError> {
646 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
647 let removed = service::class_course::unassign_teacher(
648 &st.db,
649 instance.get_id(),
650 &UserId::from_key(&target),
651 )
652 .await?;
653 if !removed {
654 return Err(AppError::NotFound);
655 }
656 Ok(StatusCode::NO_CONTENT)
657}
658
659// ---- enrollments ----------------------------------------------------------
660
661/// Enroll a student into this instance (idempotent upsert). Requires teacher+
662/// and a right over the instance. Only students can be enrolled — enrollment is
663/// student membership, and it gates sitting exams, being graded, and the
664/// roster. The row is hand-placed (`source` `null`), so no section sweep can take
665/// it back.
666#[utoipa::path(
667 post,
668 path = "/{id}/enrollments",
669 tag = "instances",
670 security(("session_cookie" = [])),
671 params(("id" = String, Path, description = "Instance id")),
672 request_body = EnrollUser,
673 responses(
674 (status = 200, description = "Enrolled (or already enrolled)", body = EnrollmentResponse),
675 (status = 400, description = "Unknown user, or user is not a student", body = ErrorResponse),
676 (status = 401, description = "Not authenticated", body = ErrorResponse),
677 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
678 (status = 404, description = "Instance not found", body = ErrorResponse),
679 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
680 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
681 ),
682)]
683async fn enroll(
684 State(st): State<AppState>,
685 RequireTeacher(user): RequireTeacher,
686 Path(id): Path<String>,
687 Json(req): Json<EnrollUser>,
688) -> Result<Json<EnrollmentResponse>, AppError> {
689 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
690 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
691 service::class_course::require_open(&st.db, instance.get_id()).await?;
692
693 let target = UserId::from_key(&req.user_id);
694 let enrollment =
695 service::enrollment::enroll(&st.db, instance.get_id(), &target, user.get_id()).await?;
696 let people = person_map([target, *user.get_id()], &st.db).await?;
697 Ok(Json(EnrollmentResponse::new(&enrollment, &people)))
698}
699
700/// List this instance's roster, paged via `?limit=&offset=` (omit `limit` for
701/// the whole roster). Requires teacher+ and a right over the instance —
702/// students see their own instances via `GET /instances/me`. Returns a
703/// `{items, total, limit, offset}` envelope.
704#[utoipa::path(
705 get,
706 path = "/{id}/enrollments",
707 tag = "instances",
708 security(("session_cookie" = [])),
709 params(("id" = String, Path, description = "Instance id"), PageParams),
710 responses(
711 (status = 200, description = "A page of enrollments (the whole roster when unpaged)", body = Page<EnrollmentResponse>),
712 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
713 (status = 401, description = "Not authenticated", body = ErrorResponse),
714 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
715 (status = 404, description = "Instance not found", body = ErrorResponse),
716 ),
717)]
718async fn list_roster(
719 State(st): State<AppState>,
720 RequireTeacher(user): RequireTeacher,
721 Path(id): Path<String>,
722 Query(page): Query<PageParams>,
723) -> Result<Json<Page<EnrollmentResponse>>, AppError> {
724 let (limit, offset) = page.resolve()?;
725 // The instance must exist — a missing one is a 404, not an empty roster.
726 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
727 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
728 let (rows, total) =
729 service::enrollment::list_for_class_course(&st.db, instance.get_id(), limit, offset)
730 .await?;
731 // Join people onto the page alone — the lookup shrinks with the window.
732 let people = person_map(
733 rows.iter()
734 .flat_map(|e| [*e.get_user(), *e.get_enrolled_by()]),
735 &st.db,
736 )
737 .await?;
738 let items = rows
739 .iter()
740 .map(|e| EnrollmentResponse::new(e, &people))
741 .collect();
742 Ok(Json(Page::new(items, total, limit, offset)))
743}
744
745/// Unenroll a student from this instance. Requires teacher+ and a right over
746/// the instance. Existing exam results are kept (they disappear from the
747/// student's marks report until re-enrolled).
748#[utoipa::path(
749 delete,
750 path = "/{id}/enrollments/{user}",
751 tag = "instances",
752 security(("session_cookie" = [])),
753 params(
754 ("id" = String, Path, description = "Instance id"),
755 ("user" = String, Path, description = "User id"),
756 ),
757 responses(
758 (status = 204, description = "Unenrolled"),
759 (status = 401, description = "Not authenticated", body = ErrorResponse),
760 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
761 (status = 404, description = "Not found", body = ErrorResponse),
762 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
763 ),
764)]
765async fn unenroll(
766 State(st): State<AppState>,
767 RequireTeacher(user): RequireTeacher,
768 Path((id, target)): Path<(String, String)>,
769) -> Result<StatusCode, AppError> {
770 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
771 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
772 service::class_course::require_open(&st.db, instance.get_id()).await?;
773 service::enrollment::unenroll(&st.db, instance.get_id(), &UserId::from_key(&target)).await?;
774 Ok(StatusCode::NO_CONTENT)
775}
776
777// ---- exams in an instance ---------------------------------------------------
778
779/// Create an exam inside one instance. Requires teacher+ and a right over the
780/// instance; the exam's marks count into the instance's average with its
781/// kind's weight (`GET /settings`) and into the term's report card named by `term`.
782/// Omit `mode` for an offline-graded exam nobody can sit; `sync`/`async` take
783/// a window (async also `duration_ms`), `open` is sittable anytime with an
784/// optional per-attempt `duration_ms`. `max_attempts` (default 1, `0` =
785/// unlimited) meters retakes and `allow_rejoin` (default `true`) is the
786/// exam-room door — both stay editable while the exam runs. Send `draft: true`
787/// to keep the exam private while it's still being written: only the
788/// instance's managers see it, and sitting and grading are blocked until it's
789/// published (`PATCH` `draft: false`). Only a class-delivered course (`kind`
790/// `course`) carries exams.
791#[utoipa::path(
792 post,
793 path = "/{id}/exams",
794 tag = "instances",
795 security(("session_cookie" = [])),
796 params(("id" = String, Path, description = "Instance id")),
797 request_body = CreateExamInCourse,
798 responses(
799 (status = 201, description = "Exam created", body = ExamResponse),
800 (status = 400, description = "Invalid fields, kind, attempt limit, schedule, an unknown or foreign dönem, or a club/etüt instance", body = ErrorResponse),
801 (status = 401, description = "Not authenticated", body = ErrorResponse),
802 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
803 (status = 404, description = "Instance not found", body = ErrorResponse),
804 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
805 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
806 ),
807)]
808async fn create_exam_in_instance(
809 State(st): State<AppState>,
810 RequireTeacher(user): RequireTeacher,
811 Path(id): Path<String>,
812 Json(req): Json<CreateExamInCourse>,
813) -> Result<(StatusCode, Json<ExamResponse>), AppError> {
814 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
815 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
816
817 let title = ExamTitle::try_new(&req.title)?;
818 let description = ExamDescription::try_new(&req.description.unwrap_or_default())?;
819 let school = service::settings::load(&st.db).await?;
820 let kind = ExamKind::try_new(&req.kind, school.get_exam_kinds())?;
821 // The term is resolved *without* the archive gate: a term archived inside
822 // an open year is a record, not a wall (the year is what
823 // [`service::exam::create`] refuses). An unknown id is this route's 400.
824 let Some(term) = service::term::read(&st.db, &TermId::from_key(&req.term)).await? else {
825 return Err(AppError::Validation(ValidationError::Invalid {
826 field: "term",
827 reason: "term does not exist",
828 }));
829 };
830 let starts_at = req.starts_at.map(Timestamp::from_millis);
831 let ends_at = req.ends_at.map(Timestamp::from_millis);
832 check_not_past("starts_at", starts_at)?;
833 check_not_past("ends_at", ends_at)?;
834 let schedule = ExamSchedule::try_new(
835 req.mode.as_deref().map(ExamMode::try_new).transpose()?,
836 starts_at,
837 ends_at,
838 req.duration_ms.map(ExamDuration::try_new).transpose()?,
839 )?;
840 let max_attempts = match req.max_attempts {
841 Some(limit) => ExamAttemptLimit::try_new(limit)?,
842 None => ExamAttemptLimit::single(),
843 };
844 let exam = crate::service::exam::create(
845 &st.db,
846 user.get_id(),
847 instance.get_id(),
848 term.get_id(),
849 title,
850 description,
851 kind,
852 schedule,
853 max_attempts,
854 req.allow_rejoin.unwrap_or(true),
855 req.allow_review.unwrap_or(false),
856 req.draft.unwrap_or(false),
857 )
858 .await?;
859 Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam))))
860}
861
862/// List one instance's exams, paged via `?limit=&offset=` (omit `limit` for
863/// all of them). Visible to the instance's enrolled students, its teachers,
864/// its section's homeroom teacher, and managers/admins — but drafts appear only
865/// to the instance's managers. Returns a `{items, total, limit, offset}`
866/// envelope.
867#[utoipa::path(
868 get,
869 path = "/{id}/exams",
870 tag = "instances",
871 security(("session_cookie" = [])),
872 params(("id" = String, Path, description = "Instance id"), PageParams),
873 responses(
874 (status = 200, description = "A page of the instance's exams (all of them when unpaged)", body = Page<ExamResponse>),
875 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
876 (status = 401, description = "Not authenticated", body = ErrorResponse),
877 (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse),
878 (status = 404, description = "Instance not found", body = ErrorResponse),
879 ),
880)]
881async fn list_instance_exams(
882 State(st): State<AppState>,
883 CurrentUser(user): CurrentUser,
884 Path(id): Path<String>,
885 Query(page): Query<PageParams>,
886) -> Result<Json<Page<ExamResponse>>, AppError> {
887 let (limit, offset) = page.resolve()?;
888 // The instance must exist — a missing one is a 404, not an empty exam list.
889 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
890 if !can_view_instance(&st.db, instance.get_id(), &user).await? {
891 return Err(AppError::Forbidden(
892 "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its exams",
893 ));
894 }
895 let mut exams = crate::service::exam::list_for_class_course(&st.db, instance.get_id()).await?;
896 // Drafts are the managers' workbench — enrolled students don't see them.
897 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
898 exams.retain(|exam| !exam.is_draft());
899 }
900 let total = exams.len() as i64;
901 // Paged in the web layer: the draft filter above is per-row Rust.
902 let items = paginate(&exams, limit, offset)
903 .iter()
904 .map(ExamResponse::new)
905 .collect();
906 Ok(Json(Page::new(items, total, limit, offset)))
907}
908
909// ---- homework in an instance -------------------------------------------------
910
911/// Assign homework inside one instance. Requires teacher+ and a right over the
912/// instance. The homework is tagged with one of the catalog course's subjects
913/// and given a future `due_at`; `assigned` optionally narrows it to a subset of
914/// the enrolled students (omit or empty = the whole roster).
915#[utoipa::path(
916 post,
917 path = "/{id}/homework",
918 tag = "instances",
919 security(("session_cookie" = [])),
920 params(("id" = String, Path, description = "Instance id")),
921 request_body = CreateHomework,
922 responses(
923 (status = 201, description = "Homework created", body = HomeworkResponse),
924 (status = 400, description = "Invalid fields, a due date in the past, an unknown subject (or one from another course), or an assigned student not enrolled / over the cap", body = ErrorResponse),
925 (status = 401, description = "Not authenticated", body = ErrorResponse),
926 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
927 (status = 404, description = "Instance not found", body = ErrorResponse),
928 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
929 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
930 ),
931)]
932async fn create_homework_in_instance(
933 State(st): State<AppState>,
934 RequireTeacher(user): RequireTeacher,
935 Path(id): Path<String>,
936 Json(req): Json<CreateHomework>,
937) -> Result<(StatusCode, Json<HomeworkResponse>), AppError> {
938 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
939 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
940 service::class_course::require_open(&st.db, instance.get_id()).await?;
941
942 let title = HomeworkTitle::try_new(&req.title)?;
943 let description = match req.description.as_deref() {
944 Some(text) => description_or_none(text)?,
945 None => None,
946 };
947 let due_at = Timestamp::from_millis(req.due_at);
948 check_not_past("due_at", Some(due_at))?;
949 // No lease: the create takes the subject's reference counter in the same
950 // breath as the row, and the subject delete is refused while that counter
951 // is non-zero — so the check below is only a pre-flight for the message.
952 let subject =
953 service::subject::in_course(&st.db, &req.subject_id, instance.get_course()).await?;
954 let assigned = resolve_assigned(req.assigned, instance.get_id(), &st.db).await?;
955 let homework = service::homework::create(
956 &st.db,
957 instance.get_id(),
958 &subject,
959 title,
960 description,
961 due_at,
962 assigned,
963 user.get_id(),
964 )
965 .await?;
966 Ok((StatusCode::CREATED, Json(HomeworkResponse::new(&homework))))
967}
968
969/// List one instance's homework, newest first, paged via `?limit=&offset=`
970/// (omit `limit` for all of it). Visible to the instance's enrolled students,
971/// its teachers, and managers/admins — but a student sees only the homework
972/// they are assigned (whole-roster ones plus subsets that name them, each with
973/// its `assigned` narrowed to themselves). Returns a `{items, total, limit,
974/// offset}` envelope.
975#[utoipa::path(
976 get,
977 path = "/{id}/homework",
978 tag = "instances",
979 security(("session_cookie" = [])),
980 params(("id" = String, Path, description = "Instance id"), PageParams),
981 responses(
982 (status = 200, description = "A page of the instance's homework (all of it when unpaged)", body = Page<HomeworkResponse>),
983 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
984 (status = 401, description = "Not authenticated", body = ErrorResponse),
985 (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse),
986 (status = 404, description = "Instance not found", body = ErrorResponse),
987 ),
988)]
989async fn list_instance_homework(
990 State(st): State<AppState>,
991 CurrentUser(user): CurrentUser,
992 Path(id): Path<String>,
993 Query(page): Query<PageParams>,
994) -> Result<Json<Page<HomeworkResponse>>, AppError> {
995 let (limit, offset) = page.resolve()?;
996 // The instance must exist — a missing one is a 404, not an empty list.
997 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
998 if !can_view_instance(&st.db, instance.get_id(), &user).await? {
999 return Err(AppError::Forbidden(
1000 "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its homework",
1001 ));
1002 }
1003 let mut homework = service::homework::list_for_class_course(&st.db, instance.get_id()).await?;
1004 // A student sees only the homework they are assigned; managers see all.
1005 let manages = can_manage_instance(&st.db, instance.get_id(), &user).await?;
1006 if !manages {
1007 homework.retain(|hw| hw.student_sees(user.get_id()));
1008 }
1009 let total = homework.len() as i64;
1010 // Paged in the web layer: the audience filter above is per-row Rust. A
1011 // subset roster goes out whole only to a manager of the instance; a student
1012 // sees themselves in it and no one else.
1013 let items = paginate(&homework, limit, offset)
1014 .iter()
1015 .map(|hw| {
1016 if manages {
1017 HomeworkResponse::new(hw)
1018 } else {
1019 HomeworkResponse::for_viewer(hw, user.get_id())
1020 }
1021 })
1022 .collect();
1023 Ok(Json(Page::new(items, total, limit, offset)))
1024}
1025
1026// ---- sessions in an instance -------------------------------------------------
1027
1028/// Create a lesson session inside one instance. Requires teacher+ and a right
1029/// over the instance. The session's teacher defaults to the caller.
1030#[utoipa::path(
1031 post,
1032 path = "/{id}/sessions",
1033 tag = "instances",
1034 security(("session_cookie" = [])),
1035 params(("id" = String, Path, description = "Instance id")),
1036 request_body = CreateSessionInCourse,
1037 responses(
1038 (status = 201, description = "Session created", body = SessionResponse),
1039 (status = 400, description = "Invalid fields, time range, times in the past, or teacher", body = ErrorResponse),
1040 (status = 401, description = "Not authenticated", body = ErrorResponse),
1041 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
1042 (status = 404, description = "Instance not found", body = ErrorResponse),
1043 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
1044 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
1045 ),
1046)]
1047async fn create_session_in_instance(
1048 State(st): State<AppState>,
1049 RequireTeacher(user): RequireTeacher,
1050 Path(id): Path<String>,
1051 Json(req): Json<CreateSessionInCourse>,
1052) -> Result<(StatusCode, Json<SessionResponse>), AppError> {
1053 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
1054 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
1055 service::class_course::require_open(&st.db, instance.get_id()).await?;
1056
1057 let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?;
1058 let teacher =
1059 service::course_session::resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db)
1060 .await?;
1061 let starts_at = Timestamp::from_millis(req.starts_at);
1062 let ends_at = req.ends_at.map(Timestamp::from_millis);
1063 check_not_past("starts_at", Some(starts_at))?;
1064 check_not_past("ends_at", ends_at)?;
1065 check_time_range(Some(starts_at), ends_at)?;
1066
1067 let session = service::course_session::create(
1068 &st.db,
1069 instance.get_id(),
1070 teacher.get_id(),
1071 topic,
1072 starts_at,
1073 ends_at,
1074 )
1075 .await?;
1076 let people = PersonRef::map_of(&[&teacher]);
1077 Ok((
1078 StatusCode::CREATED,
1079 Json(SessionResponse::new(&session, &people)),
1080 ))
1081}
1082
1083/// The optional `?starts_after=&starts_before=` window on the session list:
1084/// half-open on `starts_at`, both bounds unix milliseconds. A negative value
1085/// is a `400` naming the field.
1086#[derive(Debug, Deserialize, IntoParams)]
1087struct SessionWindow {
1088 /// Keep sessions starting at or after this unix-millisecond instant
1089 /// (inclusive).
1090 #[param(minimum = 0, example = 1_760_000_000_000_i64)]
1091 #[serde(default)]
1092 starts_after: Option<i64>,
1093 /// Keep sessions starting strictly before this unix-millisecond instant,
1094 /// so `[month_start, next_month_start)` names a month exactly.
1095 #[param(minimum = 0, example = 1_760_259_599_999_i64)]
1096 #[serde(default)]
1097 starts_before: Option<i64>,
1098}
1099
1100impl SessionWindow {
1101 fn validate(&self) -> Result<(), AppError> {
1102 for (field, value) in [
1103 ("starts_after", self.starts_after),
1104 ("starts_before", self.starts_before),
1105 ] {
1106 if value.is_some_and(|value| value < 0) {
1107 return Err(AppError::Validation(ValidationError::Invalid {
1108 field,
1109 reason: "must not be negative",
1110 }));
1111 }
1112 }
1113 Ok(())
1114 }
1115}
1116
1117/// List one instance's lesson sessions, most recent first, paged via
1118/// `?limit=&offset=` (omit `limit` for all of them). Visible to the instance's
1119/// enrolled students, its teachers, and managers/admins. Returns a
1120/// `{items, total, limit, offset}` envelope.
1121///
1122/// The optional `?starts_after=&starts_before=` window (unix milliseconds)
1123/// narrows the list to the half-open `[starts_after, starts_before)` on
1124/// `starts_at` — a calendar month is `[month_start, next_month_start)`. The
1125/// window rides the same SQL `WHERE` as the page and the count; the order is
1126/// unchanged. Absent, the response is the unfiltered list.
1127#[utoipa::path(
1128 get,
1129 path = "/{id}/sessions",
1130 tag = "instances",
1131 security(("session_cookie" = [])),
1132 params(("id" = String, Path, description = "Instance id"), SessionWindow, PageParams),
1133 responses(
1134 (status = 200, description = "A page of the instance's sessions (all of them when unpaged)", body = Page<SessionResponse>),
1135 (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse),
1136 (status = 401, description = "Not authenticated", body = ErrorResponse),
1137 (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse),
1138 (status = 404, description = "Instance not found", body = ErrorResponse),
1139 ),
1140)]
1141async fn list_instance_sessions(
1142 State(st): State<AppState>,
1143 CurrentUser(user): CurrentUser,
1144 Path(id): Path<String>,
1145 Query(window): Query<SessionWindow>,
1146 Query(page): Query<PageParams>,
1147) -> Result<Json<Page<SessionResponse>>, AppError> {
1148 let (limit, offset) = page.resolve()?;
1149 window.validate()?;
1150 // The instance must exist — a missing one is a 404, not an empty list.
1151 let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?;
1152 if !can_view_instance(&st.db, instance.get_id(), &user).await? {
1153 return Err(AppError::Forbidden(
1154 "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its sessions",
1155 ));
1156 }
1157 let (rows, total) = service::course_session::list_windowed(
1158 &st.db,
1159 instance.get_id(),
1160 window.starts_after,
1161 window.starts_before,
1162 limit,
1163 offset,
1164 )
1165 .await?;
1166 // Join teachers onto the page alone — the lookup shrinks with the window.
1167 let people = person_map(rows.iter().map(|s| *s.get_teacher()), &st.db).await?;
1168 let items = rows
1169 .iter()
1170 .map(|s| SessionResponse::new(s, &people))
1171 .collect();
1172 Ok(Json(Page::new(items, total, limit, offset)))
1173}
1174
1175#[cfg(test)]
1176mod tests {
1177 use super::*;
1178 use crate::domain::class_group::ClassGroupId;
1179
1180 /// A negative window bound is a `400` naming the field, whichever bound
1181 /// it is; both absent validates clean.
1182 #[test]
1183 fn a_negative_session_window_bound_is_refused_naming_the_field() {
1184 let clean = SessionWindow {
1185 starts_after: None,
1186 starts_before: None,
1187 };
1188 assert!(clean.validate().is_ok());
1189
1190 for (field, window) in [
1191 (
1192 "starts_after",
1193 SessionWindow {
1194 starts_after: Some(-1),
1195 starts_before: None,
1196 },
1197 ),
1198 (
1199 "starts_before",
1200 SessionWindow {
1201 starts_after: None,
1202 starts_before: Some(-1),
1203 },
1204 ),
1205 ] {
1206 let AppError::Validation(ValidationError::Invalid {
1207 field: named,
1208 reason,
1209 }) = window.validate().unwrap_err()
1210 else {
1211 panic!("expected a validation error for {field}");
1212 };
1213 assert_eq!(named, field);
1214 assert_eq!(reason, "must not be negative");
1215 }
1216 }
1217
1218 /// The read path behind `GET /instances/me` is `class_member` → the sections
1219 /// → their instances. A student enrolled by a section sees exactly that
1220 /// section's instances, and a second section teaching the same course is a
1221 /// different row.
1222 #[tokio::test]
1223 async fn a_member_reads_their_own_sections_instances() {
1224 let (db, _leases) = crate::database::init_test_db().await;
1225 let office = crate::db::class_member::tests::fixture_user(&db, "instances-office").await;
1226 let student = crate::db::class_member::tests::fixture_user(&db, "instances-student").await;
1227 let course = crate::db::class_member::tests::a_course("Matematik", &db).await;
1228 let a = crate::db::class_member::tests::a_class("5-A", &db).await;
1229 let b = crate::db::class_member::tests::a_class("5-B", &db).await;
1230 service::class_course::attach(&db, &a, &course, &office)
1231 .await
1232 .unwrap();
1233 service::class_course::attach(&db, &b, &course, &office)
1234 .await
1235 .unwrap();
1236 service::class_member::add(&db, &a, &student, &office)
1237 .await
1238 .unwrap();
1239
1240 let (members, _) = crate::db::class_member::list_for_user(&db, &student, None, 0)
1241 .await
1242 .unwrap();
1243 let classes: Vec<ClassGroupId> = members
1244 .iter()
1245 .map(|member| member.get_class().clone())
1246 .collect();
1247 let rows = crate::db::class_course::list_for_class_ids(&db, &classes)
1248 .await
1249 .unwrap();
1250 assert_eq!(rows.len(), 1, "the student reads 5-B's instance too");
1251 assert_eq!(rows[0].get_class(), &a);
1252 }
1253
1254 /// A homeroom teacher is **not** a member of the section they run, so the
1255 /// member read alone left their own instances out of
1256 /// [`visible_instances`] — while [`can_manage_instance`] let them act on
1257 /// every one of them. The homeroom column is the second, separate way a
1258 /// teacher reaches a section, and it has to be unioned in.
1259 #[tokio::test]
1260 async fn a_homeroom_teacher_sees_their_sections_instances() {
1261 use crate::domain::class_group::ClassName;
1262
1263 let (db, _leases) = crate::database::init_test_db().await;
1264 let office = crate::db::class_member::tests::fixture_user(&db, "visible-office").await;
1265 let teacher = crate::db::class_member::tests::fixture_user(&db, "visible-teacher").await;
1266 sqlx::query("UPDATE app_user SET role = 'teacher' WHERE id = $1")
1267 .bind(teacher.uuid())
1268 .execute(&db)
1269 .await
1270 .unwrap();
1271 let course = crate::db::class_member::tests::a_course("Matematik", &db).await;
1272 let class = service::class_group::create(
1273 &db,
1274 &office,
1275 ClassName::try_new("5-A").unwrap(),
1276 crate::domain::grade::GradeLevel::new(5).unwrap(),
1277 None,
1278 Some(teacher),
1279 )
1280 .await
1281 .unwrap();
1282 service::class_course::attach(&db, class.get_id(), &course, &office)
1283 .await
1284 .unwrap();
1285
1286 let homeroom_teacher = crate::service::user::read(&db, &teacher)
1287 .await
1288 .unwrap()
1289 .unwrap();
1290 let visible = visible_instances(&homeroom_teacher, &db).await.unwrap();
1291 assert_eq!(
1292 visible.len(),
1293 1,
1294 "the section the teacher runs is invisible to them"
1295 );
1296 assert!(visible[0].1, "and they run it");
1297 assert_eq!(visible[0].0.get_class(), class.get_id());
1298 }
1299
1300 /// `GET /instances/me` serves [`visible_instances`]' set, so the second arm
1301 /// of the union — the instances a teacher was *assigned* to teach — has to
1302 /// surface there even when they are neither enrolled in nor homeroom of
1303 /// the section. Before the union the route was the member read alone, and a
1304 /// teacher's assigned instances were invisible to them.
1305 #[tokio::test]
1306 async fn an_assigned_teacher_reads_the_instances_they_teach_once() {
1307 let (db, _leases) = crate::database::init_test_db().await;
1308 let office = crate::db::class_member::tests::fixture_user(&db, "union-office").await;
1309 let teacher = crate::db::class_member::tests::fixture_user(&db, "union-teacher").await;
1310 sqlx::query("UPDATE app_user SET role = 'teacher' WHERE id = $1")
1311 .bind(teacher.uuid())
1312 .execute(&db)
1313 .await
1314 .unwrap();
1315 let stranger = crate::db::class_member::tests::fixture_user(&db, "union-stranger").await;
1316 let course = crate::db::class_member::tests::a_course("Matematik", &db).await;
1317 let a = crate::db::class_member::tests::a_class("5-A", &db).await;
1318 let b = crate::db::class_member::tests::a_class("5-B", &db).await;
1319 let first = service::class_course::attach(&db, &a, &course, &office)
1320 .await
1321 .unwrap();
1322 service::class_course::attach(&db, &b, &course, &office)
1323 .await
1324 .unwrap();
1325 // The office staffing call, minus its role gate: what this test is
1326 // about is the read, not who may write the row.
1327 crate::db::class_course_teacher::assign(&db, first.get_id(), &teacher)
1328 .await
1329 .unwrap();
1330
1331 let teacher_user = crate::service::user::read(&db, &teacher)
1332 .await
1333 .unwrap()
1334 .unwrap();
1335 let visible = visible_instances(&teacher_user, &db).await.unwrap();
1336 assert_eq!(visible.len(), 1, "the instance they teach, exactly once");
1337 assert_eq!(visible[0].0.get_id(), first.get_id());
1338 assert!(visible[0].1, "and they run it");
1339
1340 // A caller tied to neither section reads nothing — the union is not a
1341 // door to every instance.
1342 let stranger_user = crate::service::user::read(&db, &stranger)
1343 .await
1344 .unwrap()
1345 .unwrap();
1346 assert!(
1347 visible_instances(&stranger_user, &db)
1348 .await
1349 .unwrap()
1350 .is_empty()
1351 );
1352 }
1353
1354 /// The two arms meet on a homeroom teacher who is also assigned to the
1355 /// same instance: one instance, one row. The union is a set — a duplicate
1356 /// would show the same instance twice on `GET /instances/me` and count it
1357 /// twice in the page's `total`.
1358 #[tokio::test]
1359 async fn a_homeroom_teacher_assigned_to_the_same_instance_reads_it_once() {
1360 use crate::domain::class_group::ClassName;
1361
1362 let (db, _leases) = crate::database::init_test_db().await;
1363 let office = crate::db::class_member::tests::fixture_user(&db, "dedupe-office").await;
1364 let teacher = crate::db::class_member::tests::fixture_user(&db, "dedupe-teacher").await;
1365 sqlx::query("UPDATE app_user SET role = 'teacher' WHERE id = $1")
1366 .bind(teacher.uuid())
1367 .execute(&db)
1368 .await
1369 .unwrap();
1370 let course = crate::db::class_member::tests::a_course("Matematik", &db).await;
1371 let class = service::class_group::create(
1372 &db,
1373 &office,
1374 ClassName::try_new("5-A").unwrap(),
1375 crate::domain::grade::GradeLevel::new(5).unwrap(),
1376 None,
1377 Some(teacher),
1378 )
1379 .await
1380 .unwrap();
1381 let instance = service::class_course::attach(&db, class.get_id(), &course, &office)
1382 .await
1383 .unwrap();
1384 crate::db::class_course_teacher::assign(&db, instance.get_id(), &teacher)
1385 .await
1386 .unwrap();
1387
1388 let teacher_user = crate::service::user::read(&db, &teacher)
1389 .await
1390 .unwrap()
1391 .unwrap();
1392 let visible = visible_instances(&teacher_user, &db).await.unwrap();
1393 assert_eq!(
1394 visible.len(),
1395 1,
1396 "homeroom and assignment are one instance, not two rows"
1397 );
1398 assert_eq!(visible[0].0.get_id(), instance.get_id());
1399 }
1400}