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

academic_years.rs430 lines, 17.0 KiBHistoryRawDownload
1//! Academic years — the top of the calendar.
2//!
3//! A year is the container a class section and its terms belong to, and the one
4//! that carries the grade-promotion policy (`grade_promotions`). A grade absent
5//! from that policy is not carried over by
6//! [`rollover`](crate::service::academic_year::rollover)
7//! — that is how graduation is expressed — so the command is explicit and
8//! idempotent rather than automatic at a date.
9//!
10//! A year with structure still on it cannot be deleted (`409`), and an archived
11//! year is read-only: no new section, no new term, no new exam inside it. A
12//! finished year is closed with `POST /{id}/archive` (manager+), idempotently;
13//! there is deliberately no unarchive route.
14
15use crate::web::tenant_state::State;
16use axum::Json;
17use axum::extract::{Path, Query};
18use axum::http::StatusCode;
19use serde::{Deserialize, Serialize};
20use utoipa::ToSchema;
21use utoipa_axum::router::OpenApiRouter;
22use utoipa_axum::routes;
23
24use crate::domain::academic_year::{
25 AcademicYear, AcademicYearId, AcademicYearName, GradePromotion,
26};
27use crate::domain::grade::GradeLevel;
28use crate::domain::timestamp::Timestamp;
29use crate::error::{AppError, ErrorResponse, ValidationError};
30use crate::service;
31use crate::state::AppState;
32
33use super::{Page, PageParams, RequireManager, RequireTeacher, check_time_range};
34
35pub fn routes() -> OpenApiRouter<AppState> {
36 OpenApiRouter::new()
37 .routes(routes!(create_year, list_years))
38 .routes(routes!(get_year, update_year, delete_year))
39 .routes(routes!(archive_year))
40 .routes(routes!(rollover))
41}
42
43#[derive(Deserialize, ToSchema)]
44struct CreateYear {
45 #[schema(example = "2026-2027", max_length = 100)]
46 name: String,
47 /// Year start, UTC unix-milliseconds. May lie in the past — a school
48 /// adopting the app mid-year backfills its calendar legitimately.
49 #[schema(example = 1_780_000_000_000_i64)]
50 starts_at: i64,
51 /// Year end, UTC unix-milliseconds; must be after `starts_at`.
52 #[schema(example = 1_810_000_000_000_i64)]
53 ends_at: i64,
54 /// The grade-promotion policy: each pair maps a grade label to the label its
55 /// students move to at `POST /academic-years/{id}/rollover`. A grade the
56 /// list does not name is not rolled over — it graduates. Omit for a year
57 /// whose rollover is not decided yet.
58 grade_promotions: Option<Vec<PromotionBody>>,
59}
60
61#[derive(Deserialize, ToSchema)]
62struct UpdateYear {
63 #[schema(max_length = 100)]
64 name: Option<String>,
65 starts_at: Option<i64>,
66 ends_at: Option<i64>,
67 /// The whole new policy — a *set*, not a delta: a grade missing from it is
68 /// no longer promoted at the next rollover.
69 grade_promotions: Option<Vec<PromotionBody>>,
70}
71
72/// One grade-promotion pair off the wire: two rungs on the grade ladder
73/// (`0` = anaokulu, `1..=12` the school years).
74#[derive(Deserialize, Serialize, ToSchema)]
75struct PromotionBody {
76 #[schema(minimum = 0, maximum = 12, example = 5)]
77 from_grade: i16,
78 #[schema(minimum = 0, maximum = 12, example = 6)]
79 to_grade: i16,
80}
81
82impl PromotionBody {
83 fn parse(&self) -> Result<GradePromotion, AppError> {
84 Ok(GradePromotion::new(
85 GradeLevel::new(self.from_grade)?,
86 GradeLevel::new(self.to_grade)?,
87 ))
88 }
89}
90
91#[derive(Serialize, ToSchema)]
92struct YearResponse {
93 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
94 id: String,
95 #[schema(example = "2026-2027")]
96 name: String,
97 /// Year start, UTC unix-milliseconds.
98 starts_at: i64,
99 /// Year end, UTC unix-milliseconds.
100 ends_at: i64,
101 /// Archived at, UTC unix-millis; null while the year is open.
102 archived_at: Option<i64>,
103 /// Who created it.
104 creator: String,
105 grade_promotions: Vec<PromotionBody>,
106 /// How many class sections sit in this year.
107 #[schema(example = 12)]
108 class_count: i64,
109 /// How many terms it holds.
110 #[schema(example = 2)]
111 term_count: i64,
112}
113
114impl YearResponse {
115 fn new(year: &AcademicYear) -> Self {
116 Self {
117 id: year.get_id().key().to_string(),
118 name: year.get_name().as_str().to_string(),
119 starts_at: year.get_starts_at().as_millis(),
120 ends_at: year.get_ends_at().as_millis(),
121 archived_at: year.get_archived_at().map(|at| at.as_millis()),
122 creator: year.get_creator().key().to_string(),
123 grade_promotions: year
124 .get_grade_promotions()
125 .iter()
126 .map(|promo| PromotionBody {
127 from_grade: promo.get_from_grade().get(),
128 to_grade: promo.get_to_grade().get(),
129 })
130 .collect(),
131 class_count: year.get_class_count(),
132 term_count: year.get_term_count(),
133 }
134 }
135}
136
137/// What one rollover carried: how many class sections were planted in the
138/// target year, how many live students came with them, and the grades left
139/// behind because the year names no promotion for them — the graduating ones.
140#[derive(Serialize, ToSchema)]
141struct RolloverResponse {
142 /// The year that received the class sections.
143 year: String,
144 #[schema(example = 12)]
145 classes: usize,
146 #[schema(example = 312)]
147 students: usize,
148 /// The labels of the rungs that stayed behind (graduation), in the order
149 /// they were met — `"Anaokulu"` at the floor, the year number elsewhere.
150 #[schema(example = json!(["11", "12"]))]
151 graduated: Vec<String>,
152}
153
154#[derive(Deserialize, ToSchema)]
155struct Rollover {
156 /// The year the class sections come *from* — usually the one that just ended.
157 /// Must be a different, existing year; the target must still be empty.
158 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
159 from_year: String,
160}
161
162/// The year a path id names, or a 404.
163async fn year_or_404(id: &str, db: &crate::database::Database) -> Result<AcademicYear, AppError> {
164 service::academic_year::read(db, &AcademicYearId::from_key(id))
165 .await?
166 .ok_or(AppError::NotFound)
167}
168
169/// The promotion list off the wire, each pair validated against the grade
170/// bound.
171fn promotions(bodies: Option<Vec<PromotionBody>>) -> Result<Option<Vec<GradePromotion>>, AppError> {
172 bodies
173 .map(|bodies| bodies.iter().map(PromotionBody::parse).collect())
174 .transpose()
175}
176
177/// The merged range check for a PATCH: an omitted end keeps the stored one.
178fn check_range(
179 starts_at: Option<Timestamp>,
180 ends_at: Option<Timestamp>,
181 year: &AcademicYear,
182) -> Result<(), AppError> {
183 let starts = starts_at.unwrap_or_else(|| year.get_starts_at());
184 let ends = ends_at.unwrap_or_else(|| year.get_ends_at());
185 if ends <= starts {
186 return Err(AppError::Validation(ValidationError::Invalid {
187 field: "ends_at",
188 reason: "must be after starts_at",
189 }));
190 }
191 Ok(())
192}
193
194/// Create an academic year. Requires manager+. Past dates are allowed — years
195/// are calendar structure, not schedules. `grade_promotions` is the
196/// grade-promotion policy the rollover applies.
197#[utoipa::path(
198 post,
199 path = "/",
200 tag = "academic-years",
201 security(("session_cookie" = [])),
202 request_body = CreateYear,
203 responses(
204 (status = 201, description = "Academic year created", body = YearResponse),
205 (status = 400, description = "Invalid name, range, or grade labels", body = ErrorResponse),
206 (status = 401, description = "Not authenticated", body = ErrorResponse),
207 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
208 (status = 409, description = "A year with that name already exists", body = ErrorResponse),
209 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
210 ),
211)]
212async fn create_year(
213 State(st): State<AppState>,
214 RequireManager(user): RequireManager,
215 Json(req): Json<CreateYear>,
216) -> Result<(StatusCode, Json<YearResponse>), AppError> {
217 let name = AcademicYearName::try_new(&req.name)?;
218 let starts_at = Timestamp::from_millis(req.starts_at);
219 let ends_at = Timestamp::from_millis(req.ends_at);
220 check_time_range(Some(starts_at), Some(ends_at))?;
221 let year = service::academic_year::create(
222 &st.db,
223 user.get_id(),
224 name,
225 starts_at,
226 ends_at,
227 promotions(req.grade_promotions)?.unwrap_or_default(),
228 )
229 .await?;
230 Ok((StatusCode::CREATED, Json(YearResponse::new(&year))))
231}
232
233/// List every academic year, newest first. Requires teacher+. Paged via
234/// `?limit=&offset=` (omit `limit` for the full list); returns a
235/// `{items, total, limit, offset}` envelope.
236#[utoipa::path(
237 get,
238 path = "/",
239 tag = "academic-years",
240 security(("session_cookie" = [])),
241 params(PageParams),
242 responses(
243 (status = 200, description = "A page of academic years (the full list when unpaged)", body = Page<YearResponse>),
244 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
245 (status = 401, description = "Not authenticated", body = ErrorResponse),
246 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
247 ),
248)]
249async fn list_years(
250 State(st): State<AppState>,
251 RequireTeacher(_user): RequireTeacher,
252 Query(page): Query<PageParams>,
253) -> Result<Json<Page<YearResponse>>, AppError> {
254 let (limit, offset) = page.resolve()?;
255 let (years, total) = service::academic_year::list_all(&st.db, limit, offset).await?;
256 let items = years.iter().map(YearResponse::new).collect();
257 Ok(Json(Page::new(items, total, limit, offset)))
258}
259
260/// Fetch a single academic year by id. Requires teacher+.
261#[utoipa::path(
262 get,
263 path = "/{id}",
264 tag = "academic-years",
265 security(("session_cookie" = [])),
266 params(("id" = String, Path, description = "Academic year id")),
267 responses(
268 (status = 200, description = "The academic year", body = YearResponse),
269 (status = 401, description = "Not authenticated", body = ErrorResponse),
270 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
271 (status = 404, description = "Not found", body = ErrorResponse),
272 ),
273)]
274async fn get_year(
275 State(st): State<AppState>,
276 RequireTeacher(_user): RequireTeacher,
277 Path(id): Path<String>,
278) -> Result<Json<YearResponse>, AppError> {
279 Ok(Json(YearResponse::new(&year_or_404(&id, &st.db).await?)))
280}
281
282/// Update an academic year. Requires manager+. Omitted fields keep their
283/// value; `grade_promotions` is replaced as a whole when sent. An archived
284/// year is read-only.
285#[utoipa::path(
286 patch,
287 path = "/{id}",
288 tag = "academic-years",
289 security(("session_cookie" = [])),
290 params(("id" = String, Path, description = "Academic year id")),
291 request_body = UpdateYear,
292 responses(
293 (status = 200, description = "Updated academic year", body = YearResponse),
294 (status = 400, description = "Invalid name, range, or grade labels", body = ErrorResponse),
295 (status = 401, description = "Not authenticated", body = ErrorResponse),
296 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
297 (status = 404, description = "Not found", body = ErrorResponse),
298 (status = 409, description = "The year is archived — past years are read-only, a rename collided with an existing year, or the year changed under concurrent edits (re-read and retry)", body = ErrorResponse),
299 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
300 ),
301)]
302async fn update_year(
303 State(st): State<AppState>,
304 RequireManager(_user): RequireManager,
305 Path(id): Path<String>,
306 Json(req): Json<UpdateYear>,
307) -> Result<Json<YearResponse>, AppError> {
308 let year = year_or_404(&id, &st.db).await?;
309 service::academic_year::require_writable(&year)?;
310 let name = req
311 .name
312 .as_deref()
313 .map(AcademicYearName::try_new)
314 .transpose()?;
315 let starts_at = req.starts_at.map(Timestamp::from_millis);
316 let ends_at = req.ends_at.map(Timestamp::from_millis);
317 check_range(starts_at, ends_at, &year)?;
318 let updated = service::academic_year::update(
319 &st.db,
320 year,
321 name,
322 starts_at,
323 ends_at,
324 promotions(req.grade_promotions)?,
325 )
326 .await?;
327 Ok(Json(YearResponse::new(&updated)))
328}
329
330/// Archive an academic year. Requires manager+. Stamps `archived_at`, and from
331/// then on the whole year is past structure: no new section, no new term, no
332/// exam inside it, and no edit or delete of the year itself. Idempotent — a
333/// second archive answers `200` with the stamp that already stood. There is no
334/// unarchive route: the row is deletable only while open.
335#[utoipa::path(
336 post,
337 path = "/{id}/archive",
338 tag = "academic-years",
339 security(("session_cookie" = [])),
340 params(("id" = String, Path, description = "Academic year id")),
341 responses(
342 (status = 200, description = "The archived academic year", body = YearResponse),
343 (status = 401, description = "Not authenticated", body = ErrorResponse),
344 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
345 (status = 404, description = "Not found", body = ErrorResponse),
346 ),
347)]
348async fn archive_year(
349 State(st): State<AppState>,
350 RequireManager(_user): RequireManager,
351 Path(id): Path<String>,
352) -> Result<Json<YearResponse>, AppError> {
353 let archived = service::academic_year::archive(&st.db, &AcademicYearId::from_key(&id)).await?;
354 Ok(Json(YearResponse::new(&archived)))
355}
356
357/// Delete an academic year. Requires manager+. Refused with a 409 while any
358/// section or term still links it — move or delete them first. An archived year
359/// must be re-opened (`PATCH` is not enough: there is no unarchive here, so
360/// the row is only deletable while open) like every other past-structure
361/// write.
362#[utoipa::path(
363 delete,
364 path = "/{id}",
365 tag = "academic-years",
366 security(("session_cookie" = [])),
367 params(("id" = String, Path, description = "Academic year id")),
368 responses(
369 (status = 204, description = "Deleted"),
370 (status = 401, description = "Not authenticated", body = ErrorResponse),
371 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
372 (status = 404, description = "Not found", body = ErrorResponse),
373 (status = 409, description = "Classes or terms are still linked to this year, or the year is archived — past years are read-only", body = ErrorResponse),
374 ),
375)]
376async fn delete_year(
377 State(st): State<AppState>,
378 RequireManager(_user): RequireManager,
379 Path(id): Path<String>,
380) -> Result<StatusCode, AppError> {
381 let year = year_or_404(&id, &st.db).await?;
382 service::academic_year::require_writable(&year)?;
383 service::academic_year::delete(&st.db, year).await?;
384 Ok(StatusCode::NO_CONTENT)
385}
386
387/// Carry another year's class sections into this one. Requires manager+. Each
388/// section of `from_year` whose grade the target year promotes is planted afresh
389/// here — same name, mapped grade, and copies of its instances (`ders_saati`,
390/// report-card
391/// policy, teachers) and of every live member, who are also enrolled into the
392/// new instances. A grade with no promotion entry stays behind: that is
393/// graduation, and `graduated` names it. The target must be empty (a second
394/// rollover into it is a 409, which is what makes the command idempotent),
395/// open, and different from the source.
396#[utoipa::path(
397 post,
398 path = "/{id}/rollover",
399 tag = "academic-years",
400 security(("session_cookie" = [])),
401 params(("id" = String, Path, description = "Target academic year id")),
402 request_body = Rollover,
403 responses(
404 (status = 200, description = "What the rollover carried", body = RolloverResponse),
405 (status = 400, description = "Unknown from_year", body = ErrorResponse),
406 (status = 401, description = "Not authenticated", body = ErrorResponse),
407 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
408 (status = 404, description = "Target year not found", body = ErrorResponse),
409 (status = 409, description = "The target year already holds classes, is archived, or is the source year itself", body = ErrorResponse),
410 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
411 ),
412)]
413async fn rollover(
414 State(st): State<AppState>,
415 RequireManager(user): RequireManager,
416 Path(id): Path<String>,
417 Json(req): Json<Rollover>,
418) -> Result<Json<RolloverResponse>, AppError> {
419 let target = year_or_404(&id, &st.db).await?;
420 let from = year_or_404(&req.from_year, &st.db).await?;
421 let report =
422 service::academic_year::rollover(&st.db, target.get_id(), from.get_id(), user.get_id())
423 .await?;
424 Ok(Json(RolloverResponse {
425 year: target.get_id().key(),
426 classes: report.classes,
427 students: report.students,
428 graduated: report.graduated,
429 }))
430}