| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use crate::web::tenant_state::State; |
| 11 | use axum::Json; |
| 12 | use axum::extract::{Path, Query}; |
| 13 | use axum::http::StatusCode; |
| 14 | use serde::{Deserialize, Serialize}; |
| 15 | use utoipa::{IntoParams, ToSchema}; |
| 16 | use utoipa_axum::router::OpenApiRouter; |
| 17 | use utoipa_axum::routes; |
| 18 | |
| 19 | use crate::database::Database; |
| 20 | use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId, Pumped, Skip}; |
| 21 | use crate::domain::class_course::{ClassCourse, ClassCourseId}; |
| 22 | use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; |
| 23 | use crate::domain::class_member::ClassMember; |
| 24 | use crate::domain::course::CourseId; |
| 25 | use crate::domain::role::Role; |
| 26 | use crate::domain::user::{User, UserId}; |
| 27 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 28 | use crate::service::course::can_manage_course; |
| 29 | use crate::service::parent_link::ensure_can_observe; |
| 30 | use crate::service::{academic_year, class_blueprint, class_course, class_group, class_member}; |
| 31 | use crate::state::AppState; |
| 32 | |
| 33 | use super::{ |
| 34 | CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map, |
| 35 | remove_blob, set_or_clear, undo_if_demoted, |
| 36 | }; |
| 37 | |
| 38 | pub fn routes() -> OpenApiRouter<AppState> { |
| 39 | OpenApiRouter::new() |
| 40 | .routes(routes!(create_class, list_classes)) |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | .routes(routes!(my_classes)) |
| 48 | .routes(routes!(user_classes)) |
| 49 | .routes(routes!(get_class, update_class, delete_class)) |
| 50 | .routes(routes!(add_member, list_members)) |
| 51 | .routes(routes!(remove_member)) |
| 52 | .routes(routes!(attach_course, list_class_courses)) |
| 53 | .routes(routes!(detach_course)) |
| 54 | |
| 55 | |
| 56 | |
| 57 | .routes(routes!(create_blueprint, list_blueprints)) |
| 58 | .routes(routes!(get_blueprint, update_blueprint, delete_blueprint)) |
| 59 | .routes(routes!(blueprint_status)) |
| 60 | .routes(routes!(apply_blueprint)) |
| 61 | } |
| 62 | |
| 63 | #[derive(Deserialize, ToSchema)] |
| 64 | struct CreateClass { |
| 65 | #[schema(max_length = 200, example = "9-A")] |
| 66 | name: String, |
| 67 | |
| 68 | |
| 69 | #[schema(max_length = 20, example = "9")] |
| 70 | grade: Option<String>, |
| 71 | |
| 72 | |
| 73 | year: Option<String>, |
| 74 | |
| 75 | |
| 76 | #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] |
| 77 | teacher_id: Option<String>, |
| 78 | } |
| 79 | |
| 80 | #[derive(Deserialize, ToSchema)] |
| 81 | struct UpdateClass { |
| 82 | #[schema(max_length = 200)] |
| 83 | name: Option<String>, |
| 84 | |
| 85 | |
| 86 | #[serde(default, deserialize_with = "set_or_clear")] |
| 87 | #[schema(value_type = Option<String>, max_length = 20)] |
| 88 | grade: Option<Option<String>>, |
| 89 | |
| 90 | |
| 91 | #[serde(default, deserialize_with = "set_or_clear")] |
| 92 | #[schema(value_type = Option<String>)] |
| 93 | year: Option<Option<String>>, |
| 94 | |
| 95 | |
| 96 | #[serde(default, deserialize_with = "set_or_clear")] |
| 97 | #[schema(value_type = Option<String>)] |
| 98 | teacher_id: Option<Option<String>>, |
| 99 | } |
| 100 | |
| 101 | #[derive(Deserialize, ToSchema)] |
| 102 | struct AddMember { |
| 103 | |
| 104 | #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] |
| 105 | user_id: String, |
| 106 | } |
| 107 | |
| 108 | #[derive(Deserialize, ToSchema)] |
| 109 | struct AttachCourse { |
| 110 | |
| 111 | #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] |
| 112 | course_id: String, |
| 113 | } |
| 114 | |
| 115 | #[derive(Serialize, ToSchema)] |
| 116 | struct ClassResponse { |
| 117 | #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] |
| 118 | id: String, |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | creator: Option<PersonRef>, |
| 125 | #[schema(example = "9-A")] |
| 126 | name: String, |
| 127 | |
| 128 | #[schema(example = "9")] |
| 129 | grade: Option<String>, |
| 130 | |
| 131 | |
| 132 | year: Option<String>, |
| 133 | |
| 134 | |
| 135 | |
| 136 | teacher: Option<PersonRef>, |
| 137 | } |
| 138 | |
| 139 | impl ClassResponse { |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | fn new( |
| 145 | class: &ClassGroup, |
| 146 | people: &std::collections::HashMap<String, PersonRef>, |
| 147 | with_creator: bool, |
| 148 | ) -> Self { |
| 149 | Self { |
| 150 | id: class.get_id().key().to_string(), |
| 151 | creator: with_creator.then(|| PersonRef::resolve(people, class.get_creator())), |
| 152 | name: class.get_name().as_str().to_string(), |
| 153 | grade: class.get_grade().map(|g| g.as_str().to_string()), |
| 154 | year: class.get_year().map(|year| year.key().to_string()), |
| 155 | teacher: class |
| 156 | .get_teacher() |
| 157 | .map(|teacher| PersonRef::resolve(people, teacher)), |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | #[derive(Serialize, ToSchema)] |
| 166 | struct CreateClassResponse { |
| 167 | class: ClassResponse, |
| 168 | |
| 169 | |
| 170 | skipped: Vec<SkipResponse>, |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | #[schema(example = "9")] |
| 182 | stocked_from: Option<String>, |
| 183 | } |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | fn class_people(class: &ClassGroup, with_creator: bool) -> impl Iterator<Item = UserId> + '_ { |
| 190 | with_creator |
| 191 | .then(|| *class.get_creator()) |
| 192 | .into_iter() |
| 193 | .chain(class.get_teacher().cloned()) |
| 194 | } |
| 195 | |
| 196 | #[derive(Serialize, ToSchema)] |
| 197 | struct ClassMemberResponse { |
| 198 | |
| 199 | |
| 200 | id: String, |
| 201 | class: String, |
| 202 | |
| 203 | user: PersonRef, |
| 204 | |
| 205 | added_by: PersonRef, |
| 206 | |
| 207 | joined_at: i64, |
| 208 | |
| 209 | |
| 210 | left_at: Option<i64>, |
| 211 | |
| 212 | |
| 213 | #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] |
| 214 | source_class_group: Option<String>, |
| 215 | } |
| 216 | |
| 217 | impl ClassMemberResponse { |
| 218 | fn new(member: &ClassMember, people: &std::collections::HashMap<String, PersonRef>) -> Self { |
| 219 | Self { |
| 220 | id: member.get_id().key().to_string(), |
| 221 | class: member.get_class().key().to_string(), |
| 222 | user: PersonRef::resolve(people, member.get_user()), |
| 223 | added_by: PersonRef::resolve(people, member.get_added_by()), |
| 224 | joined_at: member.get_joined_at().as_millis(), |
| 225 | left_at: member.get_left_at().map(|at| at.as_millis()), |
| 226 | source_class_group: member |
| 227 | .get_source_class_group() |
| 228 | .map(|class| class.key().to_string()), |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | #[derive(Serialize, ToSchema)] |
| 234 | struct ClassCourseResponse { |
| 235 | id: String, |
| 236 | class: String, |
| 237 | |
| 238 | |
| 239 | |
| 240 | course: String, |
| 241 | |
| 242 | attached_by: PersonRef, |
| 243 | |
| 244 | #[schema(example = 5)] |
| 245 | ders_saati: i64, |
| 246 | |
| 247 | counts_toward_karne: bool, |
| 248 | |
| 249 | #[schema(example = 28)] |
| 250 | enrollment_count: i64, |
| 251 | |
| 252 | |
| 253 | teachers: Vec<PersonRef>, |
| 254 | } |
| 255 | |
| 256 | impl ClassCourseResponse { |
| 257 | fn new( |
| 258 | link: &ClassCourse, |
| 259 | teachers: &[UserId], |
| 260 | people: &std::collections::HashMap<String, PersonRef>, |
| 261 | ) -> Self { |
| 262 | Self { |
| 263 | id: link.get_id().key().to_string(), |
| 264 | class: link.get_class().key().to_string(), |
| 265 | course: link.get_course().key().to_string(), |
| 266 | attached_by: PersonRef::resolve(people, link.get_attached_by()), |
| 267 | ders_saati: link.get_ders_saati().as_i64(), |
| 268 | counts_toward_karne: link.counts_toward_karne(), |
| 269 | enrollment_count: link.get_enrollment_count(), |
| 270 | teachers: teachers |
| 271 | .iter() |
| 272 | .map(|teacher| PersonRef::resolve(people, teacher)) |
| 273 | .collect(), |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | |
| 279 | |
| 280 | async fn class_or_404(id: &str, db: &Database) -> Result<ClassGroup, AppError> { |
| 281 | class_group::read(db, &ClassGroupId::from_key(id)) |
| 282 | .await? |
| 283 | .ok_or(AppError::NotFound) |
| 284 | } |
| 285 | |
| 286 | |
| 287 | |
| 288 | fn grade_or_none(text: Option<&str>) -> Result<Option<ClassGrade>, AppError> { |
| 289 | match text { |
| 290 | None | Some("") => Ok(None), |
| 291 | Some(text) => Ok(Some(ClassGrade::try_new(text)?)), |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | async fn teacher_or_none(text: Option<&str>, db: &Database) -> Result<Option<User>, AppError> { |
| 302 | let (None | Some("")) = text else { |
| 303 | return resolve_teacher(text.unwrap_or_default(), db) |
| 304 | .await |
| 305 | .map(Some); |
| 306 | }; |
| 307 | Ok(None) |
| 308 | } |
| 309 | |
| 310 | |
| 311 | async fn resolve_teacher(key: &str, db: &Database) -> Result<User, AppError> { |
| 312 | let Some(teacher) = crate::service::user::read(db, &UserId::from_key(key)).await? else { |
| 313 | return Err(AppError::Validation(ValidationError::Invalid { |
| 314 | field: "teacher_id", |
| 315 | reason: "target user does not exist", |
| 316 | })); |
| 317 | }; |
| 318 | if !teacher.get_role().at_least(Role::Teacher) { |
| 319 | return Err(AppError::Validation(ValidationError::Invalid { |
| 320 | field: "teacher_id", |
| 321 | reason: "only a teacher, manager or admin can be a class's homeroom teacher", |
| 322 | })); |
| 323 | } |
| 324 | Ok(teacher) |
| 325 | } |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | async fn classes_page( |
| 336 | ids: &[ClassGroupId], |
| 337 | total: i64, |
| 338 | limit: Option<i64>, |
| 339 | offset: i64, |
| 340 | with_creator: bool, |
| 341 | db: &Database, |
| 342 | ) -> Result<Page<ClassResponse>, AppError> { |
| 343 | let classes = class_group::list_by_ids(db, ids).await?; |
| 344 | let by_id: std::collections::HashMap<String, &ClassGroup> = classes |
| 345 | .iter() |
| 346 | .map(|class| (class.get_id().key(), class)) |
| 347 | .collect(); |
| 348 | let people = person_map( |
| 349 | classes |
| 350 | .iter() |
| 351 | .flat_map(|class| class_people(class, with_creator)), |
| 352 | db, |
| 353 | ) |
| 354 | .await?; |
| 355 | let items = ids |
| 356 | .iter() |
| 357 | .filter_map(|id| by_id.get(id.key().as_str())) |
| 358 | .map(|class| ClassResponse::new(class, &people, with_creator)) |
| 359 | .collect(); |
| 360 | Ok(Page::new(items, total, limit, offset)) |
| 361 | } |
| 362 | |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | #[utoipa::path( |
| 375 | post, |
| 376 | path = "/", |
| 377 | tag = "classes", |
| 378 | security(("session_cookie" = [])), |
| 379 | request_body = CreateClass, |
| 380 | responses( |
| 381 | (status = 201, description = "Class created, stocked from its grade's blueprint when one covers it", body = CreateClassResponse), |
| 382 | (status = 400, description = "Invalid name or grade, an unknown academic year, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), |
| 383 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 384 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 385 | (status = 409, description = "The named homeroom teacher was demoted below teacher while the request ran (the class was rolled back, nothing was created), or the named academic year is archived — past years are read-only", body = ErrorResponse), |
| 386 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 387 | ), |
| 388 | )] |
| 389 | async fn create_class( |
| 390 | State(st): State<AppState>, |
| 391 | RequireManager(user): RequireManager, |
| 392 | Json(req): Json<CreateClass>, |
| 393 | ) -> Result<(StatusCode, Json<CreateClassResponse>), AppError> { |
| 394 | let name = ClassName::try_new(&req.name)?; |
| 395 | let grade = grade_or_none(req.grade.as_deref())?; |
| 396 | |
| 397 | |
| 398 | |
| 399 | let year = academic_year::resolve(&st.db, req.year.as_deref()).await?; |
| 400 | let teacher = teacher_or_none(req.teacher_id.as_deref(), &st.db).await?; |
| 401 | let class = class_group::create( |
| 402 | &st.db, |
| 403 | user.get_id(), |
| 404 | name, |
| 405 | grade, |
| 406 | year, |
| 407 | teacher.as_ref().map(|t| *t.get_id()), |
| 408 | ) |
| 409 | .await?; |
| 410 | |
| 411 | |
| 412 | |
| 413 | if let Some(teacher) = teacher.as_ref() |
| 414 | && let Err(demoted) = undo_if_demoted(teacher.get_id(), &st.db).await |
| 415 | { |
| 416 | |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 422 | |
| 423 | |
| 424 | if !class_group::delete(&st.db, class.clone()).await? { |
| 425 | return Err(AppError::Internal(format!( |
| 426 | "class {} took a member or a course between its create and the \ |
| 427 | rollback of a demoted homeroom teacher; it is still there, \ |
| 428 | without a teacher", |
| 429 | class.get_id().key() |
| 430 | ))); |
| 431 | } |
| 432 | return Err(demoted); |
| 433 | } |
| 434 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | let stocked = stock_from_blueprint(&class, user.get_id(), &st.db).await; |
| 439 | |
| 440 | let mut named = vec![&user]; |
| 441 | named.extend(teacher.as_ref()); |
| 442 | let people = PersonRef::map_of(&named); |
| 443 | Ok(( |
| 444 | StatusCode::CREATED, |
| 445 | Json(CreateClassResponse { |
| 446 | class: ClassResponse::new(&class, &people, true), |
| 447 | skipped: stocked |
| 448 | .iter() |
| 449 | .flat_map(|(_, skipped)| skipped.iter().map(SkipResponse::new)) |
| 450 | .collect(), |
| 451 | stocked_from: stocked.map(|(grade, _)| grade), |
| 452 | }), |
| 453 | )) |
| 454 | } |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | |
| 460 | |
| 461 | |
| 462 | |
| 463 | |
| 464 | |
| 465 | |
| 466 | |
| 467 | |
| 468 | |
| 469 | async fn stock_from_blueprint( |
| 470 | class: &ClassGroup, |
| 471 | by: &UserId, |
| 472 | db: &Database, |
| 473 | ) -> Option<(String, Vec<Skip>)> { |
| 474 | let grade = class.get_grade()?; |
| 475 | let blueprint = class_blueprint::read(db, &ClassBlueprintId::for_grade(grade)) |
| 476 | .await |
| 477 | .ok()??; |
| 478 | let skipped = class_blueprint::apply_to(db, &blueprint, class, by) |
| 479 | .await |
| 480 | .ok()?; |
| 481 | Some((blueprint.get_grade().as_str().to_string(), skipped)) |
| 482 | } |
| 483 | |
| 484 | |
| 485 | #[derive(Deserialize, IntoParams)] |
| 486 | struct ClassFilter { |
| 487 | |
| 488 | |
| 489 | |
| 490 | |
| 491 | |
| 492 | |
| 493 | #[param(example = "9")] |
| 494 | grade: Option<String>, |
| 495 | } |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | |
| 501 | |
| 502 | |
| 503 | |
| 504 | |
| 505 | #[utoipa::path( |
| 506 | get, |
| 507 | path = "/", |
| 508 | tag = "classes", |
| 509 | security(("session_cookie" = [])), |
| 510 | params(ClassFilter, PageParams), |
| 511 | responses( |
| 512 | (status = 200, description = "A page of classes (the full list when unpaged)", body = Page<ClassResponse>), |
| 513 | (status = 400, description = "Invalid grade, limit or offset", body = ErrorResponse), |
| 514 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 515 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 516 | ), |
| 517 | )] |
| 518 | async fn list_classes( |
| 519 | State(st): State<AppState>, |
| 520 | RequireTeacher(_user): RequireTeacher, |
| 521 | Query(filter): Query<ClassFilter>, |
| 522 | Query(page): Query<PageParams>, |
| 523 | ) -> Result<Json<Page<ClassResponse>>, AppError> { |
| 524 | let (limit, offset) = page.resolve()?; |
| 525 | |
| 526 | |
| 527 | |
| 528 | let grade = filter |
| 529 | .grade |
| 530 | .as_deref() |
| 531 | .map(|grade| grade_or_none(Some(grade))) |
| 532 | .transpose()?; |
| 533 | let (classes, total) = class_group::list_all(&st.db, grade, limit, offset).await?; |
| 534 | |
| 535 | let people = person_map( |
| 536 | classes.iter().flat_map(|class| class_people(class, true)), |
| 537 | &st.db, |
| 538 | ) |
| 539 | .await?; |
| 540 | let items = classes |
| 541 | .iter() |
| 542 | .map(|class| ClassResponse::new(class, &people, true)) |
| 543 | .collect(); |
| 544 | Ok(Json(Page::new(items, total, limit, offset))) |
| 545 | } |
| 546 | |
| 547 | |
| 548 | #[utoipa::path( |
| 549 | get, |
| 550 | path = "/{id}", |
| 551 | tag = "classes", |
| 552 | security(("session_cookie" = [])), |
| 553 | params(("id" = String, Path, description = "Class id")), |
| 554 | responses( |
| 555 | (status = 200, description = "The class", body = ClassResponse), |
| 556 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 557 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 558 | (status = 404, description = "Not found", body = ErrorResponse), |
| 559 | ), |
| 560 | )] |
| 561 | async fn get_class( |
| 562 | State(st): State<AppState>, |
| 563 | RequireTeacher(_user): RequireTeacher, |
| 564 | Path(id): Path<String>, |
| 565 | ) -> Result<Json<ClassResponse>, AppError> { |
| 566 | let class = class_or_404(&id, &st.db).await?; |
| 567 | let people = person_map(class_people(&class, true), &st.db).await?; |
| 568 | Ok(Json(ClassResponse::new(&class, &people, true))) |
| 569 | } |
| 570 | |
| 571 | |
| 572 | |
| 573 | #[utoipa::path( |
| 574 | patch, |
| 575 | path = "/{id}", |
| 576 | tag = "classes", |
| 577 | security(("session_cookie" = [])), |
| 578 | params(("id" = String, Path, description = "Class id")), |
| 579 | request_body = UpdateClass, |
| 580 | responses( |
| 581 | (status = 200, description = "Updated class", body = ClassResponse), |
| 582 | (status = 400, description = "Invalid name or grade, an unknown academic year, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), |
| 583 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 584 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 585 | (status = 404, description = "Not found", body = ErrorResponse), |
| 586 | (status = 409, description = "The year this update moves the class off changed since the caller read it (nothing was written, re-read and retry), the named homeroom teacher was demoted below teacher while the request ran (the assignment was undone), or the class's own year — or the named one — is archived: past years are read-only", body = ErrorResponse), |
| 587 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 588 | ), |
| 589 | )] |
| 590 | async fn update_class( |
| 591 | State(st): State<AppState>, |
| 592 | RequireManager(_user): RequireManager, |
| 593 | Path(id): Path<String>, |
| 594 | Json(req): Json<UpdateClass>, |
| 595 | ) -> Result<Json<ClassResponse>, AppError> { |
| 596 | let class = class_or_404(&id, &st.db).await?; |
| 597 | |
| 598 | |
| 599 | |
| 600 | class_group::require_open(&st.db, &class).await?; |
| 601 | |
| 602 | |
| 603 | |
| 604 | |
| 605 | let name = req.name.as_deref().map(ClassName::try_new).transpose()?; |
| 606 | let grade = match req.grade { |
| 607 | Some(ref update) => Some(grade_or_none(update.as_deref())?), |
| 608 | None => None, |
| 609 | }; |
| 610 | let year = match req.year { |
| 611 | |
| 612 | Some(update) => Some(academic_year::resolve(&st.db, update.as_deref()).await?), |
| 613 | None => None, |
| 614 | }; |
| 615 | let teacher = match req.teacher_id { |
| 616 | |
| 617 | Some(ref update) => Some(teacher_or_none(update.as_deref(), &st.db).await?), |
| 618 | None => None, |
| 619 | }; |
| 620 | |
| 621 | let assigned = teacher |
| 622 | .as_ref() |
| 623 | .and_then(|teacher| teacher.as_ref().map(|teacher| *teacher.get_id())); |
| 624 | let updated = class_group::update( |
| 625 | &st.db, |
| 626 | class, |
| 627 | name, |
| 628 | grade, |
| 629 | year, |
| 630 | teacher.map(|teacher| teacher.map(|teacher| *teacher.get_id())), |
| 631 | ) |
| 632 | .await?; |
| 633 | |
| 634 | |
| 635 | |
| 636 | if let Some(teacher) = assigned.as_ref() { |
| 637 | undo_if_demoted(teacher, &st.db).await?; |
| 638 | } |
| 639 | let people = person_map(class_people(&updated, true), &st.db).await?; |
| 640 | Ok(Json(ClassResponse::new(&updated, &people, true))) |
| 641 | } |
| 642 | |
| 643 | |
| 644 | |
| 645 | |
| 646 | |
| 647 | |
| 648 | |
| 649 | |
| 650 | |
| 651 | #[utoipa::path( |
| 652 | get, |
| 653 | path = "/me", |
| 654 | tag = "classes", |
| 655 | security(("session_cookie" = [])), |
| 656 | params(PageParams), |
| 657 | responses( |
| 658 | (status = 200, description = "A page of the caller's classes (all of them when unpaged)", body = Page<ClassResponse>), |
| 659 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 660 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 661 | ), |
| 662 | )] |
| 663 | async fn my_classes( |
| 664 | State(st): State<AppState>, |
| 665 | CurrentUser(user): CurrentUser, |
| 666 | Query(page): Query<PageParams>, |
| 667 | ) -> Result<Json<Page<ClassResponse>>, AppError> { |
| 668 | let (limit, offset) = page.resolve()?; |
| 669 | |
| 670 | let with_creator = user.get_role().at_least(Role::Teacher); |
| 671 | Ok(Json( |
| 672 | classes_of(user.get_id(), limit, offset, with_creator, &st.db).await?, |
| 673 | )) |
| 674 | } |
| 675 | |
| 676 | |
| 677 | |
| 678 | |
| 679 | #[utoipa::path( |
| 680 | get, |
| 681 | path = "/user/{user}", |
| 682 | tag = "classes", |
| 683 | security(("session_cookie" = [])), |
| 684 | params(("user" = String, Path, description = "User id"), PageParams), |
| 685 | responses( |
| 686 | (status = 200, description = "A page of that user's classes (all of them when unpaged)", body = Page<ClassResponse>), |
| 687 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 688 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 689 | (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse), |
| 690 | (status = 404, description = "User not found", body = ErrorResponse), |
| 691 | ), |
| 692 | )] |
| 693 | async fn user_classes( |
| 694 | State(st): State<AppState>, |
| 695 | CurrentUser(caller): CurrentUser, |
| 696 | Path(user): Path<String>, |
| 697 | Query(page): Query<PageParams>, |
| 698 | ) -> Result<Json<Page<ClassResponse>>, AppError> { |
| 699 | let (limit, offset) = page.resolve()?; |
| 700 | let target = UserId::from_key(&user); |
| 701 | ensure_can_observe(&caller, &target, &st.db).await?; |
| 702 | |
| 703 | crate::service::user::read(&st.db, &target) |
| 704 | .await? |
| 705 | .ok_or(AppError::NotFound)?; |
| 706 | |
| 707 | |
| 708 | let with_creator = caller.get_role().at_least(Role::Teacher); |
| 709 | Ok(Json( |
| 710 | classes_of(&target, limit, offset, with_creator, &st.db).await?, |
| 711 | )) |
| 712 | } |
| 713 | |
| 714 | |
| 715 | |
| 716 | async fn classes_of( |
| 717 | user: &UserId, |
| 718 | limit: Option<i64>, |
| 719 | offset: i64, |
| 720 | with_creator: bool, |
| 721 | db: &Database, |
| 722 | ) -> Result<Page<ClassResponse>, AppError> { |
| 723 | let (rows, total) = class_member::list_for_user(db, user, limit, offset).await?; |
| 724 | let ids: Vec<ClassGroupId> = rows.iter().map(|row| row.get_class().clone()).collect(); |
| 725 | classes_page(&ids, total, limit, offset, with_creator, db).await |
| 726 | } |
| 727 | |
| 728 | |
| 729 | |
| 730 | |
| 731 | #[utoipa::path( |
| 732 | delete, |
| 733 | path = "/{id}", |
| 734 | tag = "classes", |
| 735 | security(("session_cookie" = [])), |
| 736 | params(("id" = String, Path, description = "Class id")), |
| 737 | responses( |
| 738 | (status = 204, description = "Deleted"), |
| 739 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 740 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 741 | (status = 404, description = "Not found", body = ErrorResponse), |
| 742 | (status = 409, description = "Students or instances are still on this class, or its academic year is archived — past years are read-only", body = ErrorResponse), |
| 743 | ), |
| 744 | )] |
| 745 | async fn delete_class( |
| 746 | State(st): State<AppState>, |
| 747 | RequireManager(_user): RequireManager, |
| 748 | Path(id): Path<String>, |
| 749 | ) -> Result<StatusCode, AppError> { |
| 750 | let class = class_or_404(&id, &st.db).await?; |
| 751 | class_group::require_open(&st.db, &class).await?; |
| 752 | if !class_group::delete(&st.db, class).await? { |
| 753 | return Err(AppError::Conflict( |
| 754 | "this class still holds students or instances — remove its members and detach its courses first", |
| 755 | )); |
| 756 | } |
| 757 | Ok(StatusCode::NO_CONTENT) |
| 758 | } |
| 759 | |
| 760 | |
| 761 | |
| 762 | |
| 763 | |
| 764 | |
| 765 | |
| 766 | |
| 767 | |
| 768 | #[utoipa::path( |
| 769 | post, |
| 770 | path = "/{id}/members", |
| 771 | tag = "classes", |
| 772 | security(("session_cookie" = [])), |
| 773 | params(("id" = String, Path, description = "Class id")), |
| 774 | request_body = AddMember, |
| 775 | responses( |
| 776 | (status = 201, description = "Student added to the class", body = ClassMemberResponse), |
| 777 | (status = 400, description = "Unknown user, or user is not a student", body = ErrorResponse), |
| 778 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 779 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 780 | (status = 404, description = "Class not found", body = ErrorResponse), |
| 781 | (status = 409, description = "Already in this class, the class is at its student ceiling (max_class_members), it carries more instances than one add may enroll at once, or one of those instances was detached while the add was walking them (retry against the class as it now stands). The body carries a machine `code` beside the prose, and this route answers exactly these: `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `linked_course_missing`, `academic_year_archived` (the class sits in an archived academic year — past years are read-only)", body = ErrorResponse), |
| 782 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 783 | ), |
| 784 | )] |
| 785 | async fn add_member( |
| 786 | State(st): State<AppState>, |
| 787 | RequireManager(user): RequireManager, |
| 788 | Path(id): Path<String>, |
| 789 | Json(req): Json<AddMember>, |
| 790 | ) -> Result<(StatusCode, Json<ClassMemberResponse>), AppError> { |
| 791 | let class = class_or_404(&id, &st.db).await?; |
| 792 | class_group::require_open(&st.db, &class).await?; |
| 793 | |
| 794 | let target = UserId::from_key(&req.user_id); |
| 795 | let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { |
| 796 | return Err(AppError::Validation(ValidationError::Invalid { |
| 797 | field: "user_id", |
| 798 | reason: "target user does not exist", |
| 799 | })); |
| 800 | }; |
| 801 | |
| 802 | |
| 803 | if target_user.get_role() != Role::Student { |
| 804 | return Err(AppError::Validation(ValidationError::Invalid { |
| 805 | field: "user_id", |
| 806 | reason: "only students can be added to a class", |
| 807 | })); |
| 808 | } |
| 809 | |
| 810 | let member = class_member::add(&st.db, class.get_id(), &target, user.get_id()).await?; |
| 811 | let people = PersonRef::map_of(&[&target_user, &user]); |
| 812 | Ok(( |
| 813 | StatusCode::CREATED, |
| 814 | Json(ClassMemberResponse::new(&member, &people)), |
| 815 | )) |
| 816 | } |
| 817 | |
| 818 | |
| 819 | |
| 820 | |
| 821 | #[utoipa::path( |
| 822 | get, |
| 823 | path = "/{id}/members", |
| 824 | tag = "classes", |
| 825 | security(("session_cookie" = [])), |
| 826 | params(("id" = String, Path, description = "Class id"), PageParams), |
| 827 | responses( |
| 828 | (status = 200, description = "A page of class members (the whole roster when unpaged)", body = Page<ClassMemberResponse>), |
| 829 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 830 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 831 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 832 | (status = 404, description = "Class not found", body = ErrorResponse), |
| 833 | ), |
| 834 | )] |
| 835 | async fn list_members( |
| 836 | State(st): State<AppState>, |
| 837 | RequireTeacher(_user): RequireTeacher, |
| 838 | Path(id): Path<String>, |
| 839 | Query(page): Query<PageParams>, |
| 840 | ) -> Result<Json<Page<ClassMemberResponse>>, AppError> { |
| 841 | let (limit, offset) = page.resolve()?; |
| 842 | let class = class_or_404(&id, &st.db).await?; |
| 843 | let (rows, total) = class_member::list_for_class(&st.db, class.get_id(), limit, offset).await?; |
| 844 | |
| 845 | let people = person_map( |
| 846 | rows.iter() |
| 847 | .flat_map(|row| [*row.get_user(), *row.get_added_by()]), |
| 848 | &st.db, |
| 849 | ) |
| 850 | .await?; |
| 851 | let items = rows |
| 852 | .iter() |
| 853 | .map(|row| ClassMemberResponse::new(row, &people)) |
| 854 | .collect(); |
| 855 | Ok(Json(Page::new(items, total, limit, offset))) |
| 856 | } |
| 857 | |
| 858 | |
| 859 | |
| 860 | |
| 861 | |
| 862 | |
| 863 | |
| 864 | |
| 865 | |
| 866 | |
| 867 | |
| 868 | |
| 869 | |
| 870 | #[utoipa::path( |
| 871 | delete, |
| 872 | path = "/{id}/members/{user}", |
| 873 | tag = "classes", |
| 874 | security(("session_cookie" = [])), |
| 875 | params( |
| 876 | ("id" = String, Path, description = "Class id"), |
| 877 | ("user" = String, Path, description = "User id"), |
| 878 | ), |
| 879 | responses( |
| 880 | (status = 204, description = "Left the class"), |
| 881 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 882 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 883 | (status = 404, description = "Class not found, or that student was not in it", body = ErrorResponse), |
| 884 | (status = 409, description = "The class's academic year is archived — past years are read-only", body = ErrorResponse), |
| 885 | ), |
| 886 | )] |
| 887 | async fn remove_member( |
| 888 | State(st): State<AppState>, |
| 889 | RequireManager(_user): RequireManager, |
| 890 | Path((id, target)): Path<(String, String)>, |
| 891 | ) -> Result<StatusCode, AppError> { |
| 892 | let class = class_or_404(&id, &st.db).await?; |
| 893 | class_group::require_open(&st.db, &class).await?; |
| 894 | class_member::leave(&st.db, class.get_id(), &UserId::from_key(&target)).await?; |
| 895 | Ok(StatusCode::NO_CONTENT) |
| 896 | } |
| 897 | |
| 898 | |
| 899 | |
| 900 | |
| 901 | |
| 902 | |
| 903 | |
| 904 | |
| 905 | |
| 906 | |
| 907 | |
| 908 | #[utoipa::path( |
| 909 | post, |
| 910 | path = "/{id}/instances", |
| 911 | tag = "classes", |
| 912 | security(("session_cookie" = [])), |
| 913 | params(("id" = String, Path, description = "Class id")), |
| 914 | request_body = AttachCourse, |
| 915 | responses( |
| 916 | (status = 201, description = "Course attached — a new instance for this class", body = ClassCourseResponse), |
| 917 | (status = 400, description = "Unknown course", body = ErrorResponse), |
| 918 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 919 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 920 | (status = 404, description = "Class not found", body = ErrorResponse), |
| 921 | (status = 409, description = "Already attached, the class is at its course ceiling (max_class_courses), or it holds more students than one attach may enroll at once. The body carries a machine `code` beside the prose, and this route answers exactly these: `duplicate`, `class_at_course_ceiling`, `class_roster_too_large`, `academic_year_archived` (the class's academic year is archived — past years are read-only)", body = ErrorResponse), |
| 922 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 923 | ), |
| 924 | )] |
| 925 | async fn attach_course( |
| 926 | State(st): State<AppState>, |
| 927 | RequireTeacher(user): RequireTeacher, |
| 928 | Path(id): Path<String>, |
| 929 | Json(req): Json<AttachCourse>, |
| 930 | ) -> Result<(StatusCode, Json<ClassCourseResponse>), AppError> { |
| 931 | let class = class_or_404(&id, &st.db).await?; |
| 932 | let Some(course) = |
| 933 | crate::service::course::read(&st.db, &CourseId::from_key(&req.course_id)).await? |
| 934 | else { |
| 935 | return Err(AppError::Validation(ValidationError::Invalid { |
| 936 | field: "course_id", |
| 937 | reason: "course does not exist", |
| 938 | })); |
| 939 | }; |
| 940 | if !can_manage_course(&course, &user) { |
| 941 | return Err(AppError::Forbidden( |
| 942 | "only the course creator or a manager/admin can attach this course to a class", |
| 943 | )); |
| 944 | } |
| 945 | |
| 946 | |
| 947 | class_group::require_open(&st.db, &class).await?; |
| 948 | |
| 949 | let link = class_course::attach(&st.db, class.get_id(), course.get_id(), user.get_id()).await?; |
| 950 | let people = PersonRef::map_of(&[&user]); |
| 951 | Ok(( |
| 952 | StatusCode::CREATED, |
| 953 | Json(ClassCourseResponse::new(&link, &[], &people)), |
| 954 | )) |
| 955 | } |
| 956 | |
| 957 | |
| 958 | |
| 959 | |
| 960 | |
| 961 | |
| 962 | #[utoipa::path( |
| 963 | get, |
| 964 | path = "/{id}/instances", |
| 965 | tag = "classes", |
| 966 | security(("session_cookie" = [])), |
| 967 | params(("id" = String, Path, description = "Class id"), PageParams), |
| 968 | responses( |
| 969 | (status = 200, description = "A page of the class's instances (all of them when unpaged)", body = Page<ClassCourseResponse>), |
| 970 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 971 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 972 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 973 | (status = 404, description = "Class not found", body = ErrorResponse), |
| 974 | ), |
| 975 | )] |
| 976 | async fn list_class_courses( |
| 977 | State(st): State<AppState>, |
| 978 | RequireTeacher(_user): RequireTeacher, |
| 979 | Path(id): Path<String>, |
| 980 | Query(page): Query<PageParams>, |
| 981 | ) -> Result<Json<Page<ClassCourseResponse>>, AppError> { |
| 982 | let (limit, offset) = page.resolve()?; |
| 983 | let class = class_or_404(&id, &st.db).await?; |
| 984 | let (rows, total) = class_course::list_for_class(&st.db, class.get_id(), limit, offset).await?; |
| 985 | |
| 986 | |
| 987 | let with_teachers = crate::db::class_course_teacher::into_instances(&st.db, rows).await?; |
| 988 | let people = person_map( |
| 989 | with_teachers.iter().flat_map(|(row, teachers)| { |
| 990 | std::iter::once(*row.get_attached_by()).chain(teachers.iter().cloned()) |
| 991 | }), |
| 992 | &st.db, |
| 993 | ) |
| 994 | .await?; |
| 995 | let items = with_teachers |
| 996 | .iter() |
| 997 | .map(|(row, teachers)| ClassCourseResponse::new(row, teachers, &people)) |
| 998 | .collect(); |
| 999 | Ok(Json(Page::new(items, total, limit, offset))) |
| 1000 | } |
| 1001 | |
| 1002 | |
| 1003 | |
| 1004 | |
| 1005 | |
| 1006 | |
| 1007 | |
| 1008 | |
| 1009 | |
| 1010 | |
| 1011 | |
| 1012 | |
| 1013 | |
| 1014 | |
| 1015 | |
| 1016 | |
| 1017 | |
| 1018 | |
| 1019 | #[utoipa::path( |
| 1020 | delete, |
| 1021 | path = "/{id}/instances/{instance}", |
| 1022 | tag = "classes", |
| 1023 | security(("session_cookie" = [])), |
| 1024 | params( |
| 1025 | ("id" = String, Path, description = "Class id"), |
| 1026 | ("instance" = String, Path, description = "Instance id (a class_course id)"), |
| 1027 | ), |
| 1028 | responses( |
| 1029 | (status = 204, description = "Detached"), |
| 1030 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1031 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 1032 | (status = 404, description = "Class not found, or no such instance under it", body = ErrorResponse), |
| 1033 | (status = 409, description = "The class's academic year is archived — past years are read-only", body = ErrorResponse), |
| 1034 | ), |
| 1035 | )] |
| 1036 | async fn detach_course( |
| 1037 | State(st): State<AppState>, |
| 1038 | RequireTeacher(user): RequireTeacher, |
| 1039 | Path((id, instance)): Path<(String, String)>, |
| 1040 | ) -> Result<StatusCode, AppError> { |
| 1041 | let class = class_or_404(&id, &st.db).await?; |
| 1042 | let Some(row) = |
| 1043 | crate::service::class_course::read(&st.db, &ClassCourseId::from_key(&instance)).await? |
| 1044 | else { |
| 1045 | return Err(AppError::NotFound); |
| 1046 | }; |
| 1047 | |
| 1048 | |
| 1049 | |
| 1050 | if row.get_class() != class.get_id() { |
| 1051 | return Err(AppError::NotFound); |
| 1052 | } |
| 1053 | |
| 1054 | |
| 1055 | |
| 1056 | |
| 1057 | |
| 1058 | |
| 1059 | |
| 1060 | if let Some(course) = crate::service::course::read(&st.db, row.get_course()).await? |
| 1061 | && !can_manage_course(&course, &user) |
| 1062 | { |
| 1063 | return Err(AppError::Forbidden( |
| 1064 | "only the course creator or a manager/admin can detach this course from a class", |
| 1065 | )); |
| 1066 | } |
| 1067 | class_group::require_open(&st.db, &class).await?; |
| 1068 | |
| 1069 | |
| 1070 | let files = class_course::detach(&st.db, class.get_id(), row.get_course()).await?; |
| 1071 | for file in &files { |
| 1072 | remove_blob(&st.files_path, file).await; |
| 1073 | } |
| 1074 | Ok(StatusCode::NO_CONTENT) |
| 1075 | } |
| 1076 | |
| 1077 | |
| 1078 | |
| 1079 | #[derive(Deserialize, ToSchema)] |
| 1080 | struct CreateBlueprint { |
| 1081 | |
| 1082 | |
| 1083 | |
| 1084 | #[schema(max_length = 20, example = "9")] |
| 1085 | grade: String, |
| 1086 | |
| 1087 | course_ids: Vec<String>, |
| 1088 | } |
| 1089 | |
| 1090 | #[derive(Deserialize, ToSchema)] |
| 1091 | struct UpdateBlueprint { |
| 1092 | |
| 1093 | |
| 1094 | |
| 1095 | course_ids: Vec<String>, |
| 1096 | } |
| 1097 | |
| 1098 | #[derive(Serialize, ToSchema)] |
| 1099 | struct BlueprintResponse { |
| 1100 | |
| 1101 | #[schema(example = "9")] |
| 1102 | grade: String, |
| 1103 | |
| 1104 | courses: Vec<String>, |
| 1105 | |
| 1106 | creator: PersonRef, |
| 1107 | } |
| 1108 | |
| 1109 | impl BlueprintResponse { |
| 1110 | fn new( |
| 1111 | blueprint: &ClassBlueprint, |
| 1112 | people: &std::collections::HashMap<String, PersonRef>, |
| 1113 | ) -> Self { |
| 1114 | Self { |
| 1115 | grade: blueprint.get_grade().as_str().to_string(), |
| 1116 | courses: blueprint |
| 1117 | .get_courses() |
| 1118 | .iter() |
| 1119 | .map(|course| course.key().to_string()) |
| 1120 | .collect(), |
| 1121 | creator: PersonRef::resolve(people, blueprint.get_creator()), |
| 1122 | } |
| 1123 | } |
| 1124 | } |
| 1125 | |
| 1126 | |
| 1127 | |
| 1128 | |
| 1129 | #[derive(Serialize, ToSchema)] |
| 1130 | struct SkipResponse { |
| 1131 | #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] |
| 1132 | class: String, |
| 1133 | #[schema(example = "9-C")] |
| 1134 | class_name: String, |
| 1135 | #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] |
| 1136 | course: String, |
| 1137 | |
| 1138 | |
| 1139 | |
| 1140 | |
| 1141 | |
| 1142 | |
| 1143 | |
| 1144 | |
| 1145 | |
| 1146 | |
| 1147 | |
| 1148 | |
| 1149 | |
| 1150 | |
| 1151 | |
| 1152 | |
| 1153 | |
| 1154 | |
| 1155 | |
| 1156 | |
| 1157 | |
| 1158 | |
| 1159 | |
| 1160 | |
| 1161 | |
| 1162 | |
| 1163 | |
| 1164 | |
| 1165 | #[schema(example = "class_at_course_ceiling")] |
| 1166 | reason: String, |
| 1167 | } |
| 1168 | |
| 1169 | impl SkipResponse { |
| 1170 | fn new(skip: &Skip) -> Self { |
| 1171 | Self { |
| 1172 | class: skip.class.key().to_string(), |
| 1173 | class_name: skip.class_name.clone(), |
| 1174 | course: skip.course.key().to_string(), |
| 1175 | reason: skip.reason.to_string(), |
| 1176 | } |
| 1177 | } |
| 1178 | } |
| 1179 | |
| 1180 | #[derive(Serialize, ToSchema)] |
| 1181 | struct BlueprintPumpResponse { |
| 1182 | blueprint: BlueprintResponse, |
| 1183 | |
| 1184 | |
| 1185 | |
| 1186 | |
| 1187 | |
| 1188 | |
| 1189 | |
| 1190 | |
| 1191 | |
| 1192 | |
| 1193 | #[schema(example = 12)] |
| 1194 | matched: i64, |
| 1195 | |
| 1196 | |
| 1197 | |
| 1198 | skipped: Vec<SkipResponse>, |
| 1199 | } |
| 1200 | |
| 1201 | |
| 1202 | #[derive(Serialize, ToSchema)] |
| 1203 | struct SectionStatusResponse { |
| 1204 | #[schema(example = "0198f1a2-3b4c-7d5e-8f90-000000000001")] |
| 1205 | class: String, |
| 1206 | #[schema(example = "9-C")] |
| 1207 | class_name: String, |
| 1208 | |
| 1209 | |
| 1210 | |
| 1211 | missing: Vec<String>, |
| 1212 | } |
| 1213 | |
| 1214 | #[derive(Serialize, ToSchema)] |
| 1215 | struct BlueprintStatusResponse { |
| 1216 | #[schema(example = "9")] |
| 1217 | grade: String, |
| 1218 | |
| 1219 | courses: Vec<String>, |
| 1220 | |
| 1221 | |
| 1222 | |
| 1223 | #[schema(example = 12)] |
| 1224 | matched: i64, |
| 1225 | |
| 1226 | |
| 1227 | sections: Vec<SectionStatusResponse>, |
| 1228 | } |
| 1229 | |
| 1230 | #[derive(Serialize, ToSchema)] |
| 1231 | struct ApplyResponse { |
| 1232 | |
| 1233 | skipped: Vec<SkipResponse>, |
| 1234 | } |
| 1235 | |
| 1236 | |
| 1237 | |
| 1238 | async fn resolve_courses(ids: &[String], db: &Database) -> Result<Vec<CourseId>, AppError> { |
| 1239 | let mut courses = Vec::with_capacity(ids.len()); |
| 1240 | for id in ids { |
| 1241 | let course = CourseId::from_key(id); |
| 1242 | if crate::service::course::read(db, &course).await?.is_none() { |
| 1243 | return Err(AppError::Validation(ValidationError::Invalid { |
| 1244 | field: "course_ids", |
| 1245 | reason: "one of these courses does not exist", |
| 1246 | })); |
| 1247 | } |
| 1248 | courses.push(course); |
| 1249 | } |
| 1250 | Ok(courses) |
| 1251 | } |
| 1252 | |
| 1253 | |
| 1254 | async fn blueprint_or_404(grade: &str, db: &Database) -> Result<ClassBlueprint, AppError> { |
| 1255 | class_blueprint::read(db, &ClassBlueprintId::from_key(grade)) |
| 1256 | .await? |
| 1257 | .ok_or(AppError::NotFound) |
| 1258 | } |
| 1259 | |
| 1260 | async fn blueprint_body( |
| 1261 | blueprint: &ClassBlueprint, |
| 1262 | pumped: &Pumped, |
| 1263 | db: &Database, |
| 1264 | ) -> Result<BlueprintPumpResponse, AppError> { |
| 1265 | let people = person_map([*blueprint.get_creator()], db).await?; |
| 1266 | Ok(BlueprintPumpResponse { |
| 1267 | blueprint: BlueprintResponse::new(blueprint, &people), |
| 1268 | matched: pumped.matched, |
| 1269 | skipped: pumped.skipped.iter().map(SkipResponse::new).collect(), |
| 1270 | }) |
| 1271 | } |
| 1272 | |
| 1273 | |
| 1274 | |
| 1275 | |
| 1276 | |
| 1277 | |
| 1278 | |
| 1279 | |
| 1280 | |
| 1281 | |
| 1282 | |
| 1283 | |
| 1284 | #[utoipa::path( |
| 1285 | post, |
| 1286 | path = "/blueprints", |
| 1287 | tag = "classes", |
| 1288 | security(("session_cookie" = [])), |
| 1289 | request_body = CreateBlueprint, |
| 1290 | responses( |
| 1291 | (status = 201, description = "Blueprint created, with the number of sections it reached and the classes it could not stock", body = BlueprintPumpResponse), |
| 1292 | (status = 400, description = "Invalid or unaddressable grade, too many courses, or a course that does not exist", body = ErrorResponse), |
| 1293 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1294 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 1295 | (status = 409, description = "A blueprint already exists for that grade", body = ErrorResponse), |
| 1296 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 1297 | ), |
| 1298 | )] |
| 1299 | async fn create_blueprint( |
| 1300 | State(st): State<AppState>, |
| 1301 | RequireManager(user): RequireManager, |
| 1302 | Json(req): Json<CreateBlueprint>, |
| 1303 | ) -> Result<(StatusCode, Json<BlueprintPumpResponse>), AppError> { |
| 1304 | let grade = ClassBlueprint::grade_key(&req.grade)?; |
| 1305 | let courses = resolve_courses(&req.course_ids, &st.db).await?; |
| 1306 | let mut blueprint = class_blueprint::create(&st.db, user.get_id(), grade, courses).await?; |
| 1307 | let pumped = class_blueprint::pump(&st.db, &mut blueprint, user.get_id()).await?; |
| 1308 | let body = blueprint_body(&blueprint, &pumped, &st.db).await?; |
| 1309 | Ok((StatusCode::CREATED, Json(body))) |
| 1310 | } |
| 1311 | |
| 1312 | |
| 1313 | |
| 1314 | #[utoipa::path( |
| 1315 | get, |
| 1316 | path = "/blueprints", |
| 1317 | tag = "classes", |
| 1318 | security(("session_cookie" = [])), |
| 1319 | params(PageParams), |
| 1320 | responses( |
| 1321 | (status = 200, description = "A page of blueprints (all of them when unpaged)", body = Page<BlueprintResponse>), |
| 1322 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 1323 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1324 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 1325 | ), |
| 1326 | )] |
| 1327 | async fn list_blueprints( |
| 1328 | State(st): State<AppState>, |
| 1329 | RequireManager(_user): RequireManager, |
| 1330 | Query(page): Query<PageParams>, |
| 1331 | ) -> Result<Json<Page<BlueprintResponse>>, AppError> { |
| 1332 | let (limit, offset) = page.resolve()?; |
| 1333 | let (blueprints, total) = class_blueprint::list_all(&st.db, limit, offset).await?; |
| 1334 | let people = person_map( |
| 1335 | blueprints.iter().map(|blueprint| *blueprint.get_creator()), |
| 1336 | &st.db, |
| 1337 | ) |
| 1338 | .await?; |
| 1339 | let items = blueprints |
| 1340 | .iter() |
| 1341 | .map(|blueprint| BlueprintResponse::new(blueprint, &people)) |
| 1342 | .collect(); |
| 1343 | Ok(Json(Page::new(items, total, limit, offset))) |
| 1344 | } |
| 1345 | |
| 1346 | |
| 1347 | #[utoipa::path( |
| 1348 | get, |
| 1349 | path = "/blueprints/{grade}", |
| 1350 | tag = "classes", |
| 1351 | security(("session_cookie" = [])), |
| 1352 | params(("grade" = String, Path, description = "Grade label")), |
| 1353 | responses( |
| 1354 | (status = 200, description = "The blueprint", body = BlueprintResponse), |
| 1355 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1356 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 1357 | (status = 404, description = "No blueprint for that grade", body = ErrorResponse), |
| 1358 | ), |
| 1359 | )] |
| 1360 | async fn get_blueprint( |
| 1361 | State(st): State<AppState>, |
| 1362 | RequireManager(_user): RequireManager, |
| 1363 | Path(grade): Path<String>, |
| 1364 | ) -> Result<Json<BlueprintResponse>, AppError> { |
| 1365 | let blueprint = blueprint_or_404(&grade, &st.db).await?; |
| 1366 | let people = person_map([*blueprint.get_creator()], &st.db).await?; |
| 1367 | Ok(Json(BlueprintResponse::new(&blueprint, &people))) |
| 1368 | } |
| 1369 | |
| 1370 | |
| 1371 | |
| 1372 | |
| 1373 | |
| 1374 | |
| 1375 | |
| 1376 | |
| 1377 | |
| 1378 | |
| 1379 | |
| 1380 | |
| 1381 | |
| 1382 | |
| 1383 | |
| 1384 | |
| 1385 | #[utoipa::path( |
| 1386 | patch, |
| 1387 | path = "/blueprints/{grade}", |
| 1388 | tag = "classes", |
| 1389 | security(("session_cookie" = [])), |
| 1390 | params(("grade" = String, Path, description = "Grade label")), |
| 1391 | request_body = UpdateBlueprint, |
| 1392 | responses( |
| 1393 | (status = 200, description = "Updated blueprint, with the number of sections it reached and the classes it could not stock", body = BlueprintPumpResponse), |
| 1394 | (status = 400, description = "Too many courses, or a course that does not exist", body = ErrorResponse), |
| 1395 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1396 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 1397 | (status = 404, description = "No blueprint for that grade", body = ErrorResponse), |
| 1398 | (status = 409, description = "The course list changed since the caller read it — nothing was written, re-read and retry", body = ErrorResponse), |
| 1399 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 1400 | ), |
| 1401 | )] |
| 1402 | async fn update_blueprint( |
| 1403 | State(st): State<AppState>, |
| 1404 | RequireManager(user): RequireManager, |
| 1405 | Path(grade): Path<String>, |
| 1406 | Json(req): Json<UpdateBlueprint>, |
| 1407 | ) -> Result<Json<BlueprintPumpResponse>, AppError> { |
| 1408 | let blueprint = blueprint_or_404(&grade, &st.db).await?; |
| 1409 | let courses = resolve_courses(&req.course_ids, &st.db).await?; |
| 1410 | |
| 1411 | |
| 1412 | |
| 1413 | let (saved, pumped, files) = |
| 1414 | class_blueprint::set_courses(&st.db, blueprint, courses, user.get_id()).await?; |
| 1415 | for file in &files { |
| 1416 | remove_blob(&st.files_path, file).await; |
| 1417 | } |
| 1418 | Ok(Json(blueprint_body(&saved, &pumped, &st.db).await?)) |
| 1419 | } |
| 1420 | |
| 1421 | |
| 1422 | |
| 1423 | |
| 1424 | |
| 1425 | |
| 1426 | |
| 1427 | |
| 1428 | #[utoipa::path( |
| 1429 | delete, |
| 1430 | path = "/blueprints/{grade}", |
| 1431 | tag = "classes", |
| 1432 | security(("session_cookie" = [])), |
| 1433 | params(("grade" = String, Path, description = "Grade label")), |
| 1434 | responses( |
| 1435 | (status = 204, description = "Deleted"), |
| 1436 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1437 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 1438 | (status = 404, description = "No blueprint for that grade", body = ErrorResponse), |
| 1439 | (status = 409, description = "The course list changed since this call read it — nothing was written, re-read and retry", body = ErrorResponse), |
| 1440 | ), |
| 1441 | )] |
| 1442 | async fn delete_blueprint( |
| 1443 | State(st): State<AppState>, |
| 1444 | RequireManager(_user): RequireManager, |
| 1445 | Path(grade): Path<String>, |
| 1446 | ) -> Result<StatusCode, AppError> { |
| 1447 | let blueprint = blueprint_or_404(&grade, &st.db).await?; |
| 1448 | |
| 1449 | |
| 1450 | |
| 1451 | |
| 1452 | for file in &class_blueprint::delete(&st.db, blueprint).await? { |
| 1453 | remove_blob(&st.files_path, file).await; |
| 1454 | } |
| 1455 | Ok(StatusCode::NO_CONTENT) |
| 1456 | } |
| 1457 | |
| 1458 | |
| 1459 | |
| 1460 | |
| 1461 | |
| 1462 | |
| 1463 | |
| 1464 | |
| 1465 | |
| 1466 | |
| 1467 | |
| 1468 | |
| 1469 | |
| 1470 | |
| 1471 | |
| 1472 | |
| 1473 | |
| 1474 | |
| 1475 | #[utoipa::path( |
| 1476 | get, |
| 1477 | path = "/blueprints/{grade}/status", |
| 1478 | tag = "classes", |
| 1479 | security(("session_cookie" = [])), |
| 1480 | params(("grade" = String, Path, description = "Grade label")), |
| 1481 | responses( |
| 1482 | (status = 200, description = "Every section at the grade, with the template courses it is missing", body = BlueprintStatusResponse), |
| 1483 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1484 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 1485 | (status = 404, description = "No blueprint for that grade", body = ErrorResponse), |
| 1486 | ), |
| 1487 | )] |
| 1488 | async fn blueprint_status( |
| 1489 | State(st): State<AppState>, |
| 1490 | RequireManager(_user): RequireManager, |
| 1491 | Path(grade): Path<String>, |
| 1492 | ) -> Result<Json<BlueprintStatusResponse>, AppError> { |
| 1493 | let blueprint = blueprint_or_404(&grade, &st.db).await?; |
| 1494 | let sections = class_blueprint::status(&st.db, &blueprint).await?; |
| 1495 | Ok(Json(BlueprintStatusResponse { |
| 1496 | grade: blueprint.get_grade().as_str().to_string(), |
| 1497 | courses: blueprint |
| 1498 | .get_courses() |
| 1499 | .iter() |
| 1500 | .map(|course| course.key().to_string()) |
| 1501 | .collect(), |
| 1502 | matched: sections.len() as i64, |
| 1503 | sections: sections |
| 1504 | .iter() |
| 1505 | .map(|section| SectionStatusResponse { |
| 1506 | class: section.class.key().to_string(), |
| 1507 | class_name: section.class_name.clone(), |
| 1508 | missing: section |
| 1509 | .missing |
| 1510 | .iter() |
| 1511 | .map(|course| course.key().to_string()) |
| 1512 | .collect(), |
| 1513 | }) |
| 1514 | .collect(), |
| 1515 | })) |
| 1516 | } |
| 1517 | |
| 1518 | |
| 1519 | |
| 1520 | |
| 1521 | |
| 1522 | |
| 1523 | |
| 1524 | |
| 1525 | |
| 1526 | #[utoipa::path( |
| 1527 | post, |
| 1528 | path = "/{id}/blueprint", |
| 1529 | tag = "classes", |
| 1530 | security(("session_cookie" = [])), |
| 1531 | params(("id" = String, Path, description = "Class id")), |
| 1532 | responses( |
| 1533 | (status = 200, description = "The class was stocked, minus the courses it could not take", body = ApplyResponse), |
| 1534 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1535 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 1536 | (status = 404, description = "Class not found, or no blueprint covers its grade", body = ErrorResponse), |
| 1537 | (status = 409, description = "The class's academic year is archived — past years are read-only", body = ErrorResponse), |
| 1538 | ), |
| 1539 | )] |
| 1540 | async fn apply_blueprint( |
| 1541 | State(st): State<AppState>, |
| 1542 | RequireManager(user): RequireManager, |
| 1543 | Path(id): Path<String>, |
| 1544 | ) -> Result<Json<ApplyResponse>, AppError> { |
| 1545 | let class = class_or_404(&id, &st.db).await?; |
| 1546 | let grade = class.get_grade().ok_or(AppError::NotFound)?; |
| 1547 | let blueprint = blueprint_or_404(grade.as_str(), &st.db).await?; |
| 1548 | |
| 1549 | |
| 1550 | |
| 1551 | |
| 1552 | |
| 1553 | class_group::require_open(&st.db, &class).await?; |
| 1554 | let skipped = class_blueprint::apply_to(&st.db, &blueprint, &class, user.get_id()).await?; |
| 1555 | Ok(Json(ApplyResponse { |
| 1556 | skipped: skipped.iter().map(SkipResponse::new).collect(), |
| 1557 | })) |
| 1558 | } |
| 1559 | |
| 1560 | #[cfg(test)] |
| 1561 | mod tests { |
| 1562 | use super::*; |
| 1563 | |
| 1564 | |
| 1565 | |
| 1566 | |
| 1567 | #[test] |
| 1568 | fn an_empty_grade_is_no_grade() { |
| 1569 | assert!(grade_or_none(None).unwrap().is_none()); |
| 1570 | assert!(grade_or_none(Some("")).unwrap().is_none()); |
| 1571 | assert_eq!( |
| 1572 | grade_or_none(Some("9")) |
| 1573 | .unwrap() |
| 1574 | .map(|g| g.as_str().to_string()), |
| 1575 | Some("9".to_string()) |
| 1576 | ); |
| 1577 | assert!(grade_or_none(Some(&"x".repeat(1000))).is_err()); |
| 1578 | } |
| 1579 | |
| 1580 | |
| 1581 | |
| 1582 | |
| 1583 | |
| 1584 | #[tokio::test] |
| 1585 | async fn an_empty_teacher_is_no_teacher_and_a_student_is_never_one() { |
| 1586 | use crate::domain::role::Role; |
| 1587 | use crate::domain::user::Username; |
| 1588 | |
| 1589 | let (db, _leases) = crate::database::init_test_db().await; |
| 1590 | assert!(teacher_or_none(None, &db).await.unwrap().is_none()); |
| 1591 | assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none()); |
| 1592 | |
| 1593 | let make = async |name: &str, role: Role| { |
| 1594 | let user = crate::service::user::create(&db, Username::try_new(name).unwrap(), None) |
| 1595 | .await |
| 1596 | .unwrap(); |
| 1597 | crate::service::user::set_role(&db, user.get_id(), role) |
| 1598 | .await |
| 1599 | .unwrap() |
| 1600 | .0 |
| 1601 | }; |
| 1602 | let student = make("ali", Role::Student).await; |
| 1603 | let teacher = make("ada", Role::Teacher).await; |
| 1604 | |
| 1605 | for (field, id) in [ |
| 1606 | ("gone", "0198f1a2-3b4c-7d5e-8f90-000000000001"), |
| 1607 | ("student", student.get_id().key().as_str()), |
| 1608 | ] { |
| 1609 | let refused = teacher_or_none(Some(id), &db).await; |
| 1610 | assert!( |
| 1611 | matches!( |
| 1612 | refused, |
| 1613 | Err(AppError::Validation(ValidationError::Invalid { |
| 1614 | field: "teacher_id", |
| 1615 | .. |
| 1616 | })) |
| 1617 | ), |
| 1618 | "a {field} id must be a 400 naming teacher_id: {refused:?}" |
| 1619 | ); |
| 1620 | } |
| 1621 | assert_eq!( |
| 1622 | teacher_or_none(Some(teacher.get_id().key().as_str()), &db) |
| 1623 | .await |
| 1624 | .unwrap() |
| 1625 | .map(|found| *found.get_id()), |
| 1626 | Some(*teacher.get_id()), |
| 1627 | "a teacher account is the one thing that resolves" |
| 1628 | ); |
| 1629 | } |
| 1630 | } |