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