| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | use crate::web::tenant_state::State; |
| 16 | use axum::Json; |
| 17 | use axum::extract::{Path, Query}; |
| 18 | use axum::http::StatusCode; |
| 19 | use serde::{Deserialize, Serialize}; |
| 20 | use utoipa::ToSchema; |
| 21 | use utoipa_axum::router::OpenApiRouter; |
| 22 | use utoipa_axum::routes; |
| 23 | |
| 24 | use crate::domain::academic_year::{ |
| 25 | AcademicYear, AcademicYearId, AcademicYearName, GradePromotion, |
| 26 | }; |
| 27 | use crate::domain::grade::GradeLevel; |
| 28 | use crate::domain::timestamp::Timestamp; |
| 29 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 30 | use crate::service; |
| 31 | use crate::state::AppState; |
| 32 | |
| 33 | use super::{Page, PageParams, RequireManager, RequireTeacher, check_time_range}; |
| 34 | |
| 35 | pub 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)] |
| 44 | struct CreateYear { |
| 45 | #[schema(example = "2026-2027", max_length = 100)] |
| 46 | name: String, |
| 47 | |
| 48 | |
| 49 | #[schema(example = 1_780_000_000_000_i64)] |
| 50 | starts_at: i64, |
| 51 | |
| 52 | #[schema(example = 1_810_000_000_000_i64)] |
| 53 | ends_at: i64, |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | grade_promotions: Option<Vec<PromotionBody>>, |
| 59 | } |
| 60 | |
| 61 | #[derive(Deserialize, ToSchema)] |
| 62 | struct UpdateYear { |
| 63 | #[schema(max_length = 100)] |
| 64 | name: Option<String>, |
| 65 | starts_at: Option<i64>, |
| 66 | ends_at: Option<i64>, |
| 67 | |
| 68 | |
| 69 | grade_promotions: Option<Vec<PromotionBody>>, |
| 70 | } |
| 71 | |
| 72 | |
| 73 | |
| 74 | #[derive(Deserialize, Serialize, ToSchema)] |
| 75 | struct 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 | |
| 82 | impl 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)] |
| 92 | struct YearResponse { |
| 93 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 94 | id: String, |
| 95 | #[schema(example = "2026-2027")] |
| 96 | name: String, |
| 97 | |
| 98 | starts_at: i64, |
| 99 | |
| 100 | ends_at: i64, |
| 101 | |
| 102 | archived_at: Option<i64>, |
| 103 | |
| 104 | creator: String, |
| 105 | grade_promotions: Vec<PromotionBody>, |
| 106 | |
| 107 | #[schema(example = 12)] |
| 108 | class_count: i64, |
| 109 | |
| 110 | #[schema(example = 2)] |
| 111 | term_count: i64, |
| 112 | } |
| 113 | |
| 114 | impl 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 | |
| 138 | |
| 139 | |
| 140 | #[derive(Serialize, ToSchema)] |
| 141 | struct RolloverResponse { |
| 142 | |
| 143 | year: String, |
| 144 | #[schema(example = 12)] |
| 145 | classes: usize, |
| 146 | #[schema(example = 312)] |
| 147 | students: usize, |
| 148 | |
| 149 | |
| 150 | #[schema(example = json!(["11", "12"]))] |
| 151 | graduated: Vec<String>, |
| 152 | } |
| 153 | |
| 154 | #[derive(Deserialize, ToSchema)] |
| 155 | struct Rollover { |
| 156 | |
| 157 | |
| 158 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 159 | from_year: String, |
| 160 | } |
| 161 | |
| 162 | |
| 163 | async 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 | |
| 170 | |
| 171 | fn 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 | |
| 178 | fn 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 | |
| 195 | |
| 196 | |
| 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 | )] |
| 212 | async 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 | |
| 234 | |
| 235 | |
| 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 | )] |
| 249 | async 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 | |
| 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 | )] |
| 274 | async 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 | |
| 283 | |
| 284 | |
| 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 | )] |
| 302 | async 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 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 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 | )] |
| 348 | async 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 | |
| 358 | |
| 359 | |
| 360 | |
| 361 | |
| 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 | )] |
| 376 | async 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 | |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 392 | |
| 393 | |
| 394 | |
| 395 | |
| 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 | )] |
| 413 | async 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 | } |