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