| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | use std::collections::HashMap; |
| 19 | |
| 20 | use crate::web::tenant_state::State; |
| 21 | use axum::Json; |
| 22 | use axum::extract::{Path, Query}; |
| 23 | use axum::http::StatusCode; |
| 24 | use serde::{Deserialize, Serialize}; |
| 25 | use utoipa::{IntoParams, ToSchema}; |
| 26 | use utoipa_axum::router::OpenApiRouter; |
| 27 | use utoipa_axum::routes; |
| 28 | |
| 29 | use crate::database::Database; |
| 30 | use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; |
| 31 | use crate::domain::course::{CourseDescription, CourseTitle}; |
| 32 | use crate::domain::course_session::SessionTopic; |
| 33 | use crate::domain::enrollment::Enrollment; |
| 34 | use crate::domain::exam::{ |
| 35 | ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, |
| 36 | }; |
| 37 | use crate::domain::homework::HomeworkTitle; |
| 38 | use crate::domain::term::TermId; |
| 39 | use crate::domain::timestamp::Timestamp; |
| 40 | use crate::domain::user::{User, UserId}; |
| 41 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 42 | use crate::service; |
| 43 | use crate::service::instance::{can_manage_instance, visible_instances}; |
| 44 | use crate::state::AppState; |
| 45 | |
| 46 | use super::exam_weights::ExamWeightEntry; |
| 47 | use super::homework::{description_or_none, resolve_assigned}; |
| 48 | use super::weekly_plan::WeeklySlotDto; |
| 49 | use super::{ |
| 50 | CurrentUser, ExamResponse, HomeworkResponse, Page, PageParams, PersonRef, RequireManager, |
| 51 | RequireTeacher, SessionResponse, SubjectResponse, check_not_past, check_time_range, paginate, |
| 52 | person_map, |
| 53 | }; |
| 54 | |
| 55 | pub fn routes() -> OpenApiRouter<AppState> { |
| 56 | OpenApiRouter::new() |
| 57 | .routes(routes!(my_instances)) |
| 58 | .routes(routes!(get_instance, update_instance)) |
| 59 | .routes(routes!(reset_instance)) |
| 60 | .routes(routes!(assign_teacher)) |
| 61 | .routes(routes!(unassign_teacher)) |
| 62 | .routes(routes!(enroll, list_roster)) |
| 63 | .routes(routes!(unenroll)) |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | pub fn exam_routes() -> OpenApiRouter<AppState> { |
| 72 | OpenApiRouter::new().routes(routes!(create_exam_in_instance, list_instance_exams)) |
| 73 | } |
| 74 | |
| 75 | pub fn session_routes() -> OpenApiRouter<AppState> { |
| 76 | OpenApiRouter::new().routes(routes!(create_session_in_instance, list_instance_sessions)) |
| 77 | } |
| 78 | |
| 79 | pub fn homework_routes() -> OpenApiRouter<AppState> { |
| 80 | OpenApiRouter::new().routes(routes!(create_homework_in_instance, list_instance_homework)) |
| 81 | } |
| 82 | |
| 83 | #[derive(Deserialize, ToSchema)] |
| 84 | struct UpdateInstance { |
| 85 | |
| 86 | |
| 87 | |
| 88 | #[schema(max_length = 200, example = "9-A Matematik")] |
| 89 | title: Option<String>, |
| 90 | |
| 91 | #[schema(max_length = 2_000)] |
| 92 | description: Option<String>, |
| 93 | |
| 94 | |
| 95 | |
| 96 | #[schema(minimum = 1, maximum = 40, example = 5)] |
| 97 | ders_saati: Option<i64>, |
| 98 | |
| 99 | |
| 100 | counts_toward_karne: Option<bool>, |
| 101 | } |
| 102 | |
| 103 | #[derive(Deserialize, ToSchema)] |
| 104 | struct ResetInstanceOverrides { |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | fields: Vec<String>, |
| 110 | } |
| 111 | |
| 112 | #[derive(Deserialize, ToSchema)] |
| 113 | struct AssignTeacher { |
| 114 | |
| 115 | |
| 116 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 117 | user_id: String, |
| 118 | } |
| 119 | |
| 120 | #[derive(Deserialize, ToSchema)] |
| 121 | struct EnrollUser { |
| 122 | |
| 123 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 124 | user_id: String, |
| 125 | } |
| 126 | |
| 127 | #[derive(Deserialize, ToSchema)] |
| 128 | struct CreateExamInCourse { |
| 129 | #[schema(max_length = 200, example = "Midterm")] |
| 130 | title: String, |
| 131 | #[schema(max_length = 2000)] |
| 132 | description: Option<String>, |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | #[schema(max_length = 50, example = "yazili")] |
| 138 | kind: String, |
| 139 | |
| 140 | |
| 141 | |
| 142 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 143 | term: String, |
| 144 | |
| 145 | |
| 146 | |
| 147 | #[schema(example = "sync")] |
| 148 | mode: Option<String>, |
| 149 | |
| 150 | |
| 151 | #[schema(example = 1_900_000_000_000_i64)] |
| 152 | starts_at: Option<i64>, |
| 153 | |
| 154 | |
| 155 | #[schema(example = 1_900_000_360_000_i64)] |
| 156 | ends_at: Option<i64>, |
| 157 | |
| 158 | |
| 159 | #[schema(minimum = 60_000, maximum = 86_400_000, example = 3_600_000_i64)] |
| 160 | duration_ms: Option<i64>, |
| 161 | |
| 162 | |
| 163 | #[schema(minimum = 0, maximum = 100, example = 1)] |
| 164 | max_attempts: Option<i64>, |
| 165 | |
| 166 | |
| 167 | allow_rejoin: Option<bool>, |
| 168 | |
| 169 | |
| 170 | allow_review: Option<bool>, |
| 171 | |
| 172 | |
| 173 | draft: Option<bool>, |
| 174 | } |
| 175 | |
| 176 | #[derive(Deserialize, ToSchema)] |
| 177 | struct CreateHomework { |
| 178 | #[schema(max_length = 200, example = "Read chapter 3 and answer Q1-Q5")] |
| 179 | title: String, |
| 180 | #[schema(max_length = 2000)] |
| 181 | description: Option<String>, |
| 182 | |
| 183 | |
| 184 | |
| 185 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 186 | subject_id: String, |
| 187 | |
| 188 | |
| 189 | #[schema(example = 1_900_000_000_000_i64)] |
| 190 | due_at: i64, |
| 191 | |
| 192 | |
| 193 | |
| 194 | #[schema(max_items = 200)] |
| 195 | assigned: Option<Vec<String>>, |
| 196 | } |
| 197 | |
| 198 | #[derive(Deserialize, ToSchema)] |
| 199 | struct CreateSessionInCourse { |
| 200 | |
| 201 | #[schema(max_length = 200, example = "Limits and continuity")] |
| 202 | topic: Option<String>, |
| 203 | |
| 204 | |
| 205 | teacher_id: Option<String>, |
| 206 | |
| 207 | #[schema(example = 1_900_000_000_000_i64)] |
| 208 | starts_at: i64, |
| 209 | |
| 210 | |
| 211 | ends_at: Option<i64>, |
| 212 | } |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | #[derive(Serialize, ToSchema)] |
| 223 | pub struct InstanceResponse { |
| 224 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 225 | pub id: String, |
| 226 | |
| 227 | pub class: String, |
| 228 | |
| 229 | |
| 230 | pub course: String, |
| 231 | |
| 232 | |
| 233 | pub offering: String, |
| 234 | |
| 235 | |
| 236 | pub title: String, |
| 237 | |
| 238 | |
| 239 | pub title_overridden: bool, |
| 240 | |
| 241 | pub description: String, |
| 242 | |
| 243 | pub description_overridden: bool, |
| 244 | |
| 245 | |
| 246 | |
| 247 | #[schema(example = 5)] |
| 248 | pub ders_saati: i64, |
| 249 | |
| 250 | pub ders_saati_overridden: bool, |
| 251 | |
| 252 | |
| 253 | pub counts_toward_karne: bool, |
| 254 | |
| 255 | pub counts_toward_karne_overridden: bool, |
| 256 | |
| 257 | |
| 258 | pub subjects_inherited: bool, |
| 259 | |
| 260 | |
| 261 | pub subjects: Vec<SubjectResponse>, |
| 262 | |
| 263 | |
| 264 | pub exam_weights_inherited: bool, |
| 265 | |
| 266 | |
| 267 | pub exam_weights: Vec<ExamWeightEntry>, |
| 268 | |
| 269 | pub weekly_plan_inherited: bool, |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | pub weekly_plan: Vec<WeeklySlotDto>, |
| 277 | |
| 278 | #[schema(example = 28)] |
| 279 | pub enrollment_count: i64, |
| 280 | |
| 281 | |
| 282 | pub teachers: Vec<PersonRef>, |
| 283 | } |
| 284 | |
| 285 | impl InstanceResponse { |
| 286 | async fn new( |
| 287 | db: &Database, |
| 288 | instance: &ClassCourse, |
| 289 | teachers: &[UserId], |
| 290 | people: &HashMap<String, PersonRef>, |
| 291 | ) -> Result<Self, AppError> { |
| 292 | |
| 293 | |
| 294 | let resolved = service::instance_resolve::resolve(db, instance).await?; |
| 295 | Ok(Self { |
| 296 | id: instance.get_id().key().to_string(), |
| 297 | class: instance.get_class().key().to_string(), |
| 298 | course: instance.get_course().key().to_string(), |
| 299 | offering: instance.get_offering().key(), |
| 300 | title: resolved.title, |
| 301 | title_overridden: resolved.title_overridden, |
| 302 | description: resolved.description, |
| 303 | description_overridden: resolved.description_overridden, |
| 304 | ders_saati: resolved.ders_saati.as_i64(), |
| 305 | ders_saati_overridden: resolved.ders_saati_overridden, |
| 306 | counts_toward_karne: resolved.counts_toward_karne, |
| 307 | counts_toward_karne_overridden: resolved.counts_toward_karne_overridden, |
| 308 | subjects_inherited: resolved.subjects_inherited, |
| 309 | subjects: resolved.subjects.iter().map(SubjectResponse::new).collect(), |
| 310 | exam_weights_inherited: resolved.exam_weights_inherited, |
| 311 | exam_weights: resolved |
| 312 | .exam_weights |
| 313 | .iter() |
| 314 | .map(ExamWeightEntry::of) |
| 315 | .collect(), |
| 316 | weekly_plan_inherited: resolved.weekly_plan_inherited, |
| 317 | weekly_plan: resolved.weekly_plan.iter().map(WeeklySlotDto::new).collect(), |
| 318 | enrollment_count: instance.get_enrollment_count(), |
| 319 | teachers: teachers |
| 320 | .iter() |
| 321 | .map(|teacher| PersonRef::resolve(people, teacher)) |
| 322 | .collect(), |
| 323 | }) |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | #[derive(Serialize, ToSchema)] |
| 328 | struct EnrollmentResponse { |
| 329 | id: String, |
| 330 | |
| 331 | class_course: String, |
| 332 | |
| 333 | user: PersonRef, |
| 334 | |
| 335 | enrolled_by: PersonRef, |
| 336 | |
| 337 | |
| 338 | |
| 339 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 340 | source: Option<String>, |
| 341 | } |
| 342 | |
| 343 | impl EnrollmentResponse { |
| 344 | fn new(enrollment: &Enrollment, people: &HashMap<String, PersonRef>) -> Self { |
| 345 | Self { |
| 346 | id: enrollment.get_id().key().to_string(), |
| 347 | class_course: enrollment.get_class_course().key().to_string(), |
| 348 | user: PersonRef::resolve(people, enrollment.get_user()), |
| 349 | enrolled_by: PersonRef::resolve(people, enrollment.get_enrolled_by()), |
| 350 | source: enrollment.get_source().map(|class| class.key().to_string()), |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | |
| 356 | |
| 357 | async fn instance_or_404(key: &ClassCourseId, db: &Database) -> Result<ClassCourse, AppError> { |
| 358 | service::class_course::read(db, key) |
| 359 | .await? |
| 360 | .ok_or(AppError::NotFound) |
| 361 | } |
| 362 | |
| 363 | |
| 364 | |
| 365 | pub(crate) async fn can_view_instance( |
| 366 | db: &Database, |
| 367 | instance: &ClassCourseId, |
| 368 | user: &User, |
| 369 | ) -> Result<bool, AppError> { |
| 370 | if can_manage_instance(db, instance, user).await? { |
| 371 | return Ok(true); |
| 372 | } |
| 373 | Ok( |
| 374 | service::enrollment::read_for_user(db, instance, user.get_id()) |
| 375 | .await? |
| 376 | .is_some(), |
| 377 | ) |
| 378 | } |
| 379 | |
| 380 | |
| 381 | |
| 382 | pub(crate) async fn instance_people( |
| 383 | rows: &[(ClassCourse, Vec<UserId>)], |
| 384 | db: &Database, |
| 385 | ) -> Result<HashMap<String, PersonRef>, AppError> { |
| 386 | person_map( |
| 387 | rows.iter() |
| 388 | .flat_map(|(_, teachers)| teachers.iter().cloned()), |
| 389 | db, |
| 390 | ) |
| 391 | .await |
| 392 | } |
| 393 | |
| 394 | |
| 395 | |
| 396 | |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | #[utoipa::path( |
| 406 | get, |
| 407 | path = "/me", |
| 408 | tag = "instances", |
| 409 | security(("session_cookie" = [])), |
| 410 | params(PageParams), |
| 411 | responses( |
| 412 | (status = 200, description = "A page of the caller's instances (all of them when unpaged)", body = Page<InstanceResponse>), |
| 413 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 414 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 415 | ), |
| 416 | )] |
| 417 | async fn my_instances( |
| 418 | State(st): State<AppState>, |
| 419 | CurrentUser(user): CurrentUser, |
| 420 | Query(page): Query<PageParams>, |
| 421 | ) -> Result<Json<Page<InstanceResponse>>, AppError> { |
| 422 | let (limit, offset) = page.resolve()?; |
| 423 | |
| 424 | |
| 425 | |
| 426 | |
| 427 | |
| 428 | let mut visible = visible_instances(&user, &st.db).await?; |
| 429 | visible.sort_by(|(a, _), (b, _)| { |
| 430 | b.get_attached_at() |
| 431 | .cmp(&a.get_attached_at()) |
| 432 | .then_with(|| b.get_id().uuid().cmp(&a.get_id().uuid())) |
| 433 | }); |
| 434 | let total = visible.len() as i64; |
| 435 | let window: Vec<ClassCourse> = paginate(&visible, limit, offset) |
| 436 | .iter() |
| 437 | .map(|(instance, _)| instance.clone()) |
| 438 | .collect(); |
| 439 | let with_teachers = crate::db::class_course_teacher::into_instances(&st.db, window).await?; |
| 440 | let people = instance_people(&with_teachers, &st.db).await?; |
| 441 | let mut items = Vec::with_capacity(with_teachers.len()); |
| 442 | for (instance, teachers) in &with_teachers { |
| 443 | items.push(InstanceResponse::new(&st.db, instance, teachers, &people).await?); |
| 444 | } |
| 445 | Ok(Json(Page::new(items, total, limit, offset))) |
| 446 | } |
| 447 | |
| 448 | |
| 449 | |
| 450 | #[utoipa::path( |
| 451 | get, |
| 452 | path = "/{id}", |
| 453 | tag = "instances", |
| 454 | security(("session_cookie" = [])), |
| 455 | params(("id" = String, Path, description = "Instance id")), |
| 456 | responses( |
| 457 | (status = 200, description = "The instance", body = InstanceResponse), |
| 458 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 459 | (status = 403, description = "Not enrolled, and not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 460 | (status = 404, description = "Not found", body = ErrorResponse), |
| 461 | ), |
| 462 | )] |
| 463 | async fn get_instance( |
| 464 | State(st): State<AppState>, |
| 465 | CurrentUser(user): CurrentUser, |
| 466 | Path(id): Path<String>, |
| 467 | ) -> Result<Json<InstanceResponse>, AppError> { |
| 468 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 469 | if !can_view_instance(&st.db, instance.get_id(), &user).await? { |
| 470 | return Err(AppError::Forbidden( |
| 471 | "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view it", |
| 472 | )); |
| 473 | } |
| 474 | let teachers = |
| 475 | crate::db::class_course_teacher::list_for_instance(&st.db, instance.get_id()).await?; |
| 476 | let people = person_map(teachers.iter().cloned(), &st.db).await?; |
| 477 | Ok(Json(InstanceResponse::new(&st.db, &instance, &teachers, &people).await?)) |
| 478 | } |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | |
| 484 | #[utoipa::path( |
| 485 | patch, |
| 486 | path = "/{id}", |
| 487 | tag = "instances", |
| 488 | security(("session_cookie" = [])), |
| 489 | params(("id" = String, Path, description = "Instance id")), |
| 490 | request_body = UpdateInstance, |
| 491 | responses( |
| 492 | (status = 200, description = "Updated instance", body = InstanceResponse), |
| 493 | (status = 400, description = "Invalid title, description, or ders_saati", body = ErrorResponse), |
| 494 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 495 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 496 | (status = 404, description = "Not found", body = ErrorResponse), |
| 497 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 498 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 499 | ), |
| 500 | )] |
| 501 | async fn update_instance( |
| 502 | State(st): State<AppState>, |
| 503 | RequireTeacher(user): RequireTeacher, |
| 504 | Path(id): Path<String>, |
| 505 | Json(req): Json<UpdateInstance>, |
| 506 | ) -> Result<Json<InstanceResponse>, AppError> { |
| 507 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 508 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 509 | service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 510 | |
| 511 | let title = match &req.title { |
| 512 | Some(title) => Some(CourseTitle::try_new(title)?), |
| 513 | None => None, |
| 514 | }; |
| 515 | let description = match &req.description { |
| 516 | Some(description) => Some(CourseDescription::try_new(description)?), |
| 517 | None => None, |
| 518 | }; |
| 519 | let staff = req.ders_saati.map(DersSaati::try_new).transpose()?; |
| 520 | let updated = service::class_course::update( |
| 521 | &st.db, |
| 522 | instance.get_id(), |
| 523 | title, |
| 524 | description, |
| 525 | staff, |
| 526 | req.counts_toward_karne, |
| 527 | ) |
| 528 | .await?; |
| 529 | let teachers = |
| 530 | crate::db::class_course_teacher::list_for_instance(&st.db, updated.get_id()).await?; |
| 531 | let people = person_map(teachers.iter().cloned(), &st.db).await?; |
| 532 | Ok(Json(InstanceResponse::new(&st.db, &updated, &teachers, &people).await?)) |
| 533 | } |
| 534 | |
| 535 | |
| 536 | |
| 537 | |
| 538 | |
| 539 | |
| 540 | |
| 541 | #[utoipa::path( |
| 542 | post, |
| 543 | path = "/{id}/reset", |
| 544 | tag = "instances", |
| 545 | security(("session_cookie" = [])), |
| 546 | params(("id" = String, Path, description = "Instance id")), |
| 547 | request_body = ResetInstanceOverrides, |
| 548 | responses( |
| 549 | (status = 200, description = "The overrides cleared; the instance now inherits the named fields", body = InstanceResponse), |
| 550 | (status = 400, description = "A field name is unknown, or the list is empty", body = ErrorResponse), |
| 551 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 552 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 553 | (status = 404, description = "Not found", body = ErrorResponse), |
| 554 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 555 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 556 | ), |
| 557 | )] |
| 558 | async fn reset_instance( |
| 559 | State(st): State<AppState>, |
| 560 | RequireTeacher(user): RequireTeacher, |
| 561 | Path(id): Path<String>, |
| 562 | Json(req): Json<ResetInstanceOverrides>, |
| 563 | ) -> Result<Json<InstanceResponse>, AppError> { |
| 564 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 565 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 566 | service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 567 | |
| 568 | let mut fields = Vec::with_capacity(req.fields.len()); |
| 569 | for name in &req.fields { |
| 570 | fields.push(service::class_course::parse_reset_field(name)?); |
| 571 | } |
| 572 | let updated = |
| 573 | service::class_course::reset_overrides(&st.db, instance.get_id(), &fields).await?; |
| 574 | let teachers = |
| 575 | crate::db::class_course_teacher::list_for_instance(&st.db, updated.get_id()).await?; |
| 576 | let people = person_map(teachers.iter().cloned(), &st.db).await?; |
| 577 | Ok(Json(InstanceResponse::new(&st.db, &updated, &teachers, &people).await?)) |
| 578 | } |
| 579 | |
| 580 | |
| 581 | |
| 582 | |
| 583 | |
| 584 | |
| 585 | #[utoipa::path( |
| 586 | post, |
| 587 | path = "/{id}/teachers", |
| 588 | tag = "instances", |
| 589 | security(("session_cookie" = [])), |
| 590 | params(("id" = String, Path, description = "Instance id")), |
| 591 | request_body = AssignTeacher, |
| 592 | responses( |
| 593 | (status = 200, description = "Assigned (or already assigned)", body = InstanceResponse), |
| 594 | (status = 400, description = "Unknown user, or user is not a teacher or higher", body = ErrorResponse), |
| 595 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 596 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 597 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 598 | (status = 409, description = "That user was demoted below teacher while the request ran — the assignment was undone; or this instance's academic year is archived", body = ErrorResponse), |
| 599 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 600 | ), |
| 601 | )] |
| 602 | async fn assign_teacher( |
| 603 | State(st): State<AppState>, |
| 604 | RequireManager(manager): RequireManager, |
| 605 | Path(id): Path<String>, |
| 606 | Json(req): Json<AssignTeacher>, |
| 607 | ) -> Result<Json<InstanceResponse>, AppError> { |
| 608 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 609 | let target = UserId::from_key(&req.user_id); |
| 610 | service::class_course::assign_teacher(&st.db, instance.get_id(), &target, manager.get_id()) |
| 611 | .await?; |
| 612 | |
| 613 | |
| 614 | super::undo_if_demoted(&target, &st.db).await?; |
| 615 | let teachers = |
| 616 | crate::db::class_course_teacher::list_for_instance(&st.db, instance.get_id()).await?; |
| 617 | let people = person_map(teachers.iter().cloned(), &st.db).await?; |
| 618 | Ok(Json(InstanceResponse::new(&st.db, &instance, &teachers, &people).await?)) |
| 619 | } |
| 620 | |
| 621 | |
| 622 | |
| 623 | |
| 624 | #[utoipa::path( |
| 625 | delete, |
| 626 | path = "/{id}/teachers/{user}", |
| 627 | tag = "instances", |
| 628 | security(("session_cookie" = [])), |
| 629 | params( |
| 630 | ("id" = String, Path, description = "Instance id"), |
| 631 | ("user" = String, Path, description = "User id"), |
| 632 | ), |
| 633 | responses( |
| 634 | (status = 204, description = "Unassigned"), |
| 635 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 636 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 637 | (status = 404, description = "Instance not found, or that user was not assigned to it", body = ErrorResponse), |
| 638 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 639 | ), |
| 640 | )] |
| 641 | async fn unassign_teacher( |
| 642 | State(st): State<AppState>, |
| 643 | RequireManager(_manager): RequireManager, |
| 644 | Path((id, target)): Path<(String, String)>, |
| 645 | ) -> Result<StatusCode, AppError> { |
| 646 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 647 | let removed = service::class_course::unassign_teacher( |
| 648 | &st.db, |
| 649 | instance.get_id(), |
| 650 | &UserId::from_key(&target), |
| 651 | ) |
| 652 | .await?; |
| 653 | if !removed { |
| 654 | return Err(AppError::NotFound); |
| 655 | } |
| 656 | Ok(StatusCode::NO_CONTENT) |
| 657 | } |
| 658 | |
| 659 | |
| 660 | |
| 661 | |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | #[utoipa::path( |
| 667 | post, |
| 668 | path = "/{id}/enrollments", |
| 669 | tag = "instances", |
| 670 | security(("session_cookie" = [])), |
| 671 | params(("id" = String, Path, description = "Instance id")), |
| 672 | request_body = EnrollUser, |
| 673 | responses( |
| 674 | (status = 200, description = "Enrolled (or already enrolled)", body = EnrollmentResponse), |
| 675 | (status = 400, description = "Unknown user, or user is not a student", body = ErrorResponse), |
| 676 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 677 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 678 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 679 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 680 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 681 | ), |
| 682 | )] |
| 683 | async fn enroll( |
| 684 | State(st): State<AppState>, |
| 685 | RequireTeacher(user): RequireTeacher, |
| 686 | Path(id): Path<String>, |
| 687 | Json(req): Json<EnrollUser>, |
| 688 | ) -> Result<Json<EnrollmentResponse>, AppError> { |
| 689 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 690 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 691 | service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 692 | |
| 693 | let target = UserId::from_key(&req.user_id); |
| 694 | let enrollment = |
| 695 | service::enrollment::enroll(&st.db, instance.get_id(), &target, user.get_id()).await?; |
| 696 | let people = person_map([target, *user.get_id()], &st.db).await?; |
| 697 | Ok(Json(EnrollmentResponse::new(&enrollment, &people))) |
| 698 | } |
| 699 | |
| 700 | |
| 701 | |
| 702 | |
| 703 | |
| 704 | #[utoipa::path( |
| 705 | get, |
| 706 | path = "/{id}/enrollments", |
| 707 | tag = "instances", |
| 708 | security(("session_cookie" = [])), |
| 709 | params(("id" = String, Path, description = "Instance id"), PageParams), |
| 710 | responses( |
| 711 | (status = 200, description = "A page of enrollments (the whole roster when unpaged)", body = Page<EnrollmentResponse>), |
| 712 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 713 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 714 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 715 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 716 | ), |
| 717 | )] |
| 718 | async fn list_roster( |
| 719 | State(st): State<AppState>, |
| 720 | RequireTeacher(user): RequireTeacher, |
| 721 | Path(id): Path<String>, |
| 722 | Query(page): Query<PageParams>, |
| 723 | ) -> Result<Json<Page<EnrollmentResponse>>, AppError> { |
| 724 | let (limit, offset) = page.resolve()?; |
| 725 | |
| 726 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 727 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 728 | let (rows, total) = |
| 729 | service::enrollment::list_for_class_course(&st.db, instance.get_id(), limit, offset) |
| 730 | .await?; |
| 731 | |
| 732 | let people = person_map( |
| 733 | rows.iter() |
| 734 | .flat_map(|e| [*e.get_user(), *e.get_enrolled_by()]), |
| 735 | &st.db, |
| 736 | ) |
| 737 | .await?; |
| 738 | let items = rows |
| 739 | .iter() |
| 740 | .map(|e| EnrollmentResponse::new(e, &people)) |
| 741 | .collect(); |
| 742 | Ok(Json(Page::new(items, total, limit, offset))) |
| 743 | } |
| 744 | |
| 745 | |
| 746 | |
| 747 | |
| 748 | #[utoipa::path( |
| 749 | delete, |
| 750 | path = "/{id}/enrollments/{user}", |
| 751 | tag = "instances", |
| 752 | security(("session_cookie" = [])), |
| 753 | params( |
| 754 | ("id" = String, Path, description = "Instance id"), |
| 755 | ("user" = String, Path, description = "User id"), |
| 756 | ), |
| 757 | responses( |
| 758 | (status = 204, description = "Unenrolled"), |
| 759 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 760 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 761 | (status = 404, description = "Not found", body = ErrorResponse), |
| 762 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 763 | ), |
| 764 | )] |
| 765 | async fn unenroll( |
| 766 | State(st): State<AppState>, |
| 767 | RequireTeacher(user): RequireTeacher, |
| 768 | Path((id, target)): Path<(String, String)>, |
| 769 | ) -> Result<StatusCode, AppError> { |
| 770 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 771 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 772 | service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 773 | service::enrollment::unenroll(&st.db, instance.get_id(), &UserId::from_key(&target)).await?; |
| 774 | Ok(StatusCode::NO_CONTENT) |
| 775 | } |
| 776 | |
| 777 | |
| 778 | |
| 779 | |
| 780 | |
| 781 | |
| 782 | |
| 783 | |
| 784 | |
| 785 | |
| 786 | |
| 787 | |
| 788 | |
| 789 | |
| 790 | |
| 791 | #[utoipa::path( |
| 792 | post, |
| 793 | path = "/{id}/exams", |
| 794 | tag = "instances", |
| 795 | security(("session_cookie" = [])), |
| 796 | params(("id" = String, Path, description = "Instance id")), |
| 797 | request_body = CreateExamInCourse, |
| 798 | responses( |
| 799 | (status = 201, description = "Exam created", body = ExamResponse), |
| 800 | (status = 400, description = "Invalid fields, kind, attempt limit, schedule, an unknown or foreign dönem, or a club/etüt instance", body = ErrorResponse), |
| 801 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 802 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 803 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 804 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 805 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 806 | ), |
| 807 | )] |
| 808 | async fn create_exam_in_instance( |
| 809 | State(st): State<AppState>, |
| 810 | RequireTeacher(user): RequireTeacher, |
| 811 | Path(id): Path<String>, |
| 812 | Json(req): Json<CreateExamInCourse>, |
| 813 | ) -> Result<(StatusCode, Json<ExamResponse>), AppError> { |
| 814 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 815 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 816 | |
| 817 | let title = ExamTitle::try_new(&req.title)?; |
| 818 | let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; |
| 819 | let school = service::settings::load(&st.db).await?; |
| 820 | let kind = ExamKind::try_new(&req.kind, school.get_exam_kinds())?; |
| 821 | |
| 822 | |
| 823 | |
| 824 | let Some(term) = service::term::read(&st.db, &TermId::from_key(&req.term)).await? else { |
| 825 | return Err(AppError::Validation(ValidationError::Invalid { |
| 826 | field: "term", |
| 827 | reason: "term does not exist", |
| 828 | })); |
| 829 | }; |
| 830 | let starts_at = req.starts_at.map(Timestamp::from_millis); |
| 831 | let ends_at = req.ends_at.map(Timestamp::from_millis); |
| 832 | check_not_past("starts_at", starts_at)?; |
| 833 | check_not_past("ends_at", ends_at)?; |
| 834 | let schedule = ExamSchedule::try_new( |
| 835 | req.mode.as_deref().map(ExamMode::try_new).transpose()?, |
| 836 | starts_at, |
| 837 | ends_at, |
| 838 | req.duration_ms.map(ExamDuration::try_new).transpose()?, |
| 839 | )?; |
| 840 | let max_attempts = match req.max_attempts { |
| 841 | Some(limit) => ExamAttemptLimit::try_new(limit)?, |
| 842 | None => ExamAttemptLimit::single(), |
| 843 | }; |
| 844 | let exam = crate::service::exam::create( |
| 845 | &st.db, |
| 846 | user.get_id(), |
| 847 | instance.get_id(), |
| 848 | term.get_id(), |
| 849 | title, |
| 850 | description, |
| 851 | kind, |
| 852 | schedule, |
| 853 | max_attempts, |
| 854 | req.allow_rejoin.unwrap_or(true), |
| 855 | req.allow_review.unwrap_or(false), |
| 856 | req.draft.unwrap_or(false), |
| 857 | ) |
| 858 | .await?; |
| 859 | Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) |
| 860 | } |
| 861 | |
| 862 | |
| 863 | |
| 864 | |
| 865 | |
| 866 | |
| 867 | #[utoipa::path( |
| 868 | get, |
| 869 | path = "/{id}/exams", |
| 870 | tag = "instances", |
| 871 | security(("session_cookie" = [])), |
| 872 | params(("id" = String, Path, description = "Instance id"), PageParams), |
| 873 | responses( |
| 874 | (status = 200, description = "A page of the instance's exams (all of them when unpaged)", body = Page<ExamResponse>), |
| 875 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 876 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 877 | (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse), |
| 878 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 879 | ), |
| 880 | )] |
| 881 | async fn list_instance_exams( |
| 882 | State(st): State<AppState>, |
| 883 | CurrentUser(user): CurrentUser, |
| 884 | Path(id): Path<String>, |
| 885 | Query(page): Query<PageParams>, |
| 886 | ) -> Result<Json<Page<ExamResponse>>, AppError> { |
| 887 | let (limit, offset) = page.resolve()?; |
| 888 | |
| 889 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 890 | if !can_view_instance(&st.db, instance.get_id(), &user).await? { |
| 891 | return Err(AppError::Forbidden( |
| 892 | "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its exams", |
| 893 | )); |
| 894 | } |
| 895 | let mut exams = crate::service::exam::list_for_class_course(&st.db, instance.get_id()).await?; |
| 896 | |
| 897 | if !can_manage_instance(&st.db, instance.get_id(), &user).await? { |
| 898 | exams.retain(|exam| !exam.is_draft()); |
| 899 | } |
| 900 | let total = exams.len() as i64; |
| 901 | |
| 902 | let items = paginate(&exams, limit, offset) |
| 903 | .iter() |
| 904 | .map(ExamResponse::new) |
| 905 | .collect(); |
| 906 | Ok(Json(Page::new(items, total, limit, offset))) |
| 907 | } |
| 908 | |
| 909 | |
| 910 | |
| 911 | |
| 912 | |
| 913 | |
| 914 | |
| 915 | #[utoipa::path( |
| 916 | post, |
| 917 | path = "/{id}/homework", |
| 918 | tag = "instances", |
| 919 | security(("session_cookie" = [])), |
| 920 | params(("id" = String, Path, description = "Instance id")), |
| 921 | request_body = CreateHomework, |
| 922 | responses( |
| 923 | (status = 201, description = "Homework created", body = HomeworkResponse), |
| 924 | (status = 400, description = "Invalid fields, a due date in the past, an unknown subject (or one from another course), or an assigned student not enrolled / over the cap", body = ErrorResponse), |
| 925 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 926 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 927 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 928 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 929 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 930 | ), |
| 931 | )] |
| 932 | async fn create_homework_in_instance( |
| 933 | State(st): State<AppState>, |
| 934 | RequireTeacher(user): RequireTeacher, |
| 935 | Path(id): Path<String>, |
| 936 | Json(req): Json<CreateHomework>, |
| 937 | ) -> Result<(StatusCode, Json<HomeworkResponse>), AppError> { |
| 938 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 939 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 940 | service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 941 | |
| 942 | let title = HomeworkTitle::try_new(&req.title)?; |
| 943 | let description = match req.description.as_deref() { |
| 944 | Some(text) => description_or_none(text)?, |
| 945 | None => None, |
| 946 | }; |
| 947 | let due_at = Timestamp::from_millis(req.due_at); |
| 948 | check_not_past("due_at", Some(due_at))?; |
| 949 | |
| 950 | |
| 951 | |
| 952 | let subject = |
| 953 | service::subject::in_course(&st.db, &req.subject_id, instance.get_course()).await?; |
| 954 | let assigned = resolve_assigned(req.assigned, instance.get_id(), &st.db).await?; |
| 955 | let homework = service::homework::create( |
| 956 | &st.db, |
| 957 | instance.get_id(), |
| 958 | &subject, |
| 959 | title, |
| 960 | description, |
| 961 | due_at, |
| 962 | assigned, |
| 963 | user.get_id(), |
| 964 | ) |
| 965 | .await?; |
| 966 | Ok((StatusCode::CREATED, Json(HomeworkResponse::new(&homework)))) |
| 967 | } |
| 968 | |
| 969 | |
| 970 | |
| 971 | |
| 972 | |
| 973 | |
| 974 | |
| 975 | #[utoipa::path( |
| 976 | get, |
| 977 | path = "/{id}/homework", |
| 978 | tag = "instances", |
| 979 | security(("session_cookie" = [])), |
| 980 | params(("id" = String, Path, description = "Instance id"), PageParams), |
| 981 | responses( |
| 982 | (status = 200, description = "A page of the instance's homework (all of it when unpaged)", body = Page<HomeworkResponse>), |
| 983 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 984 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 985 | (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse), |
| 986 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 987 | ), |
| 988 | )] |
| 989 | async fn list_instance_homework( |
| 990 | State(st): State<AppState>, |
| 991 | CurrentUser(user): CurrentUser, |
| 992 | Path(id): Path<String>, |
| 993 | Query(page): Query<PageParams>, |
| 994 | ) -> Result<Json<Page<HomeworkResponse>>, AppError> { |
| 995 | let (limit, offset) = page.resolve()?; |
| 996 | |
| 997 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 998 | if !can_view_instance(&st.db, instance.get_id(), &user).await? { |
| 999 | return Err(AppError::Forbidden( |
| 1000 | "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its homework", |
| 1001 | )); |
| 1002 | } |
| 1003 | let mut homework = service::homework::list_for_class_course(&st.db, instance.get_id()).await?; |
| 1004 | |
| 1005 | let manages = can_manage_instance(&st.db, instance.get_id(), &user).await?; |
| 1006 | if !manages { |
| 1007 | homework.retain(|hw| hw.student_sees(user.get_id())); |
| 1008 | } |
| 1009 | let total = homework.len() as i64; |
| 1010 | |
| 1011 | |
| 1012 | |
| 1013 | let items = paginate(&homework, limit, offset) |
| 1014 | .iter() |
| 1015 | .map(|hw| { |
| 1016 | if manages { |
| 1017 | HomeworkResponse::new(hw) |
| 1018 | } else { |
| 1019 | HomeworkResponse::for_viewer(hw, user.get_id()) |
| 1020 | } |
| 1021 | }) |
| 1022 | .collect(); |
| 1023 | Ok(Json(Page::new(items, total, limit, offset))) |
| 1024 | } |
| 1025 | |
| 1026 | |
| 1027 | |
| 1028 | |
| 1029 | |
| 1030 | #[utoipa::path( |
| 1031 | post, |
| 1032 | path = "/{id}/sessions", |
| 1033 | tag = "instances", |
| 1034 | security(("session_cookie" = [])), |
| 1035 | params(("id" = String, Path, description = "Instance id")), |
| 1036 | request_body = CreateSessionInCourse, |
| 1037 | responses( |
| 1038 | (status = 201, description = "Session created", body = SessionResponse), |
| 1039 | (status = 400, description = "Invalid fields, time range, times in the past, or teacher", body = ErrorResponse), |
| 1040 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1041 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 1042 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 1043 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 1044 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 1045 | ), |
| 1046 | )] |
| 1047 | async fn create_session_in_instance( |
| 1048 | State(st): State<AppState>, |
| 1049 | RequireTeacher(user): RequireTeacher, |
| 1050 | Path(id): Path<String>, |
| 1051 | Json(req): Json<CreateSessionInCourse>, |
| 1052 | ) -> Result<(StatusCode, Json<SessionResponse>), AppError> { |
| 1053 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 1054 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 1055 | service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 1056 | |
| 1057 | let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; |
| 1058 | let teacher = |
| 1059 | service::course_session::resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db) |
| 1060 | .await?; |
| 1061 | let starts_at = Timestamp::from_millis(req.starts_at); |
| 1062 | let ends_at = req.ends_at.map(Timestamp::from_millis); |
| 1063 | check_not_past("starts_at", Some(starts_at))?; |
| 1064 | check_not_past("ends_at", ends_at)?; |
| 1065 | check_time_range(Some(starts_at), ends_at)?; |
| 1066 | |
| 1067 | let session = service::course_session::create( |
| 1068 | &st.db, |
| 1069 | instance.get_id(), |
| 1070 | teacher.get_id(), |
| 1071 | topic, |
| 1072 | starts_at, |
| 1073 | ends_at, |
| 1074 | ) |
| 1075 | .await?; |
| 1076 | let people = PersonRef::map_of(&[&teacher]); |
| 1077 | Ok(( |
| 1078 | StatusCode::CREATED, |
| 1079 | Json(SessionResponse::new(&session, &people)), |
| 1080 | )) |
| 1081 | } |
| 1082 | |
| 1083 | |
| 1084 | |
| 1085 | |
| 1086 | #[derive(Debug, Deserialize, IntoParams)] |
| 1087 | struct SessionWindow { |
| 1088 | |
| 1089 | |
| 1090 | #[param(minimum = 0, example = 1_760_000_000_000_i64)] |
| 1091 | #[serde(default)] |
| 1092 | starts_after: Option<i64>, |
| 1093 | |
| 1094 | |
| 1095 | #[param(minimum = 0, example = 1_760_259_599_999_i64)] |
| 1096 | #[serde(default)] |
| 1097 | starts_before: Option<i64>, |
| 1098 | } |
| 1099 | |
| 1100 | impl SessionWindow { |
| 1101 | fn validate(&self) -> Result<(), AppError> { |
| 1102 | for (field, value) in [ |
| 1103 | ("starts_after", self.starts_after), |
| 1104 | ("starts_before", self.starts_before), |
| 1105 | ] { |
| 1106 | if value.is_some_and(|value| value < 0) { |
| 1107 | return Err(AppError::Validation(ValidationError::Invalid { |
| 1108 | field, |
| 1109 | reason: "must not be negative", |
| 1110 | })); |
| 1111 | } |
| 1112 | } |
| 1113 | Ok(()) |
| 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | |
| 1118 | |
| 1119 | |
| 1120 | |
| 1121 | |
| 1122 | |
| 1123 | |
| 1124 | |
| 1125 | |
| 1126 | |
| 1127 | #[utoipa::path( |
| 1128 | get, |
| 1129 | path = "/{id}/sessions", |
| 1130 | tag = "instances", |
| 1131 | security(("session_cookie" = [])), |
| 1132 | params(("id" = String, Path, description = "Instance id"), SessionWindow, PageParams), |
| 1133 | responses( |
| 1134 | (status = 200, description = "A page of the instance's sessions (all of them when unpaged)", body = Page<SessionResponse>), |
| 1135 | (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse), |
| 1136 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1137 | (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse), |
| 1138 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 1139 | ), |
| 1140 | )] |
| 1141 | async fn list_instance_sessions( |
| 1142 | State(st): State<AppState>, |
| 1143 | CurrentUser(user): CurrentUser, |
| 1144 | Path(id): Path<String>, |
| 1145 | Query(window): Query<SessionWindow>, |
| 1146 | Query(page): Query<PageParams>, |
| 1147 | ) -> Result<Json<Page<SessionResponse>>, AppError> { |
| 1148 | let (limit, offset) = page.resolve()?; |
| 1149 | window.validate()?; |
| 1150 | |
| 1151 | let instance = instance_or_404(&ClassCourseId::from_key(&id), &st.db).await?; |
| 1152 | if !can_view_instance(&st.db, instance.get_id(), &user).await? { |
| 1153 | return Err(AppError::Forbidden( |
| 1154 | "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its sessions", |
| 1155 | )); |
| 1156 | } |
| 1157 | let (rows, total) = service::course_session::list_windowed( |
| 1158 | &st.db, |
| 1159 | instance.get_id(), |
| 1160 | window.starts_after, |
| 1161 | window.starts_before, |
| 1162 | limit, |
| 1163 | offset, |
| 1164 | ) |
| 1165 | .await?; |
| 1166 | |
| 1167 | let people = person_map(rows.iter().map(|s| *s.get_teacher()), &st.db).await?; |
| 1168 | let items = rows |
| 1169 | .iter() |
| 1170 | .map(|s| SessionResponse::new(s, &people)) |
| 1171 | .collect(); |
| 1172 | Ok(Json(Page::new(items, total, limit, offset))) |
| 1173 | } |
| 1174 | |
| 1175 | #[cfg(test)] |
| 1176 | mod tests { |
| 1177 | use super::*; |
| 1178 | use crate::domain::class_group::ClassGroupId; |
| 1179 | |
| 1180 | |
| 1181 | |
| 1182 | #[test] |
| 1183 | fn a_negative_session_window_bound_is_refused_naming_the_field() { |
| 1184 | let clean = SessionWindow { |
| 1185 | starts_after: None, |
| 1186 | starts_before: None, |
| 1187 | }; |
| 1188 | assert!(clean.validate().is_ok()); |
| 1189 | |
| 1190 | for (field, window) in [ |
| 1191 | ( |
| 1192 | "starts_after", |
| 1193 | SessionWindow { |
| 1194 | starts_after: Some(-1), |
| 1195 | starts_before: None, |
| 1196 | }, |
| 1197 | ), |
| 1198 | ( |
| 1199 | "starts_before", |
| 1200 | SessionWindow { |
| 1201 | starts_after: None, |
| 1202 | starts_before: Some(-1), |
| 1203 | }, |
| 1204 | ), |
| 1205 | ] { |
| 1206 | let AppError::Validation(ValidationError::Invalid { |
| 1207 | field: named, |
| 1208 | reason, |
| 1209 | }) = window.validate().unwrap_err() |
| 1210 | else { |
| 1211 | panic!("expected a validation error for {field}"); |
| 1212 | }; |
| 1213 | assert_eq!(named, field); |
| 1214 | assert_eq!(reason, "must not be negative"); |
| 1215 | } |
| 1216 | } |
| 1217 | |
| 1218 | |
| 1219 | |
| 1220 | |
| 1221 | |
| 1222 | #[tokio::test] |
| 1223 | async fn a_member_reads_their_own_sections_instances() { |
| 1224 | let (db, _leases) = crate::database::init_test_db().await; |
| 1225 | let office = crate::db::class_member::tests::fixture_user(&db, "instances-office").await; |
| 1226 | let student = crate::db::class_member::tests::fixture_user(&db, "instances-student").await; |
| 1227 | let course = crate::db::class_member::tests::a_course("Matematik", &db).await; |
| 1228 | let a = crate::db::class_member::tests::a_class("5-A", &db).await; |
| 1229 | let b = crate::db::class_member::tests::a_class("5-B", &db).await; |
| 1230 | service::class_course::attach(&db, &a, &course, &office) |
| 1231 | .await |
| 1232 | .unwrap(); |
| 1233 | service::class_course::attach(&db, &b, &course, &office) |
| 1234 | .await |
| 1235 | .unwrap(); |
| 1236 | service::class_member::add(&db, &a, &student, &office) |
| 1237 | .await |
| 1238 | .unwrap(); |
| 1239 | |
| 1240 | let (members, _) = crate::db::class_member::list_for_user(&db, &student, None, 0) |
| 1241 | .await |
| 1242 | .unwrap(); |
| 1243 | let classes: Vec<ClassGroupId> = members |
| 1244 | .iter() |
| 1245 | .map(|member| member.get_class().clone()) |
| 1246 | .collect(); |
| 1247 | let rows = crate::db::class_course::list_for_class_ids(&db, &classes) |
| 1248 | .await |
| 1249 | .unwrap(); |
| 1250 | assert_eq!(rows.len(), 1, "the student reads 5-B's instance too"); |
| 1251 | assert_eq!(rows[0].get_class(), &a); |
| 1252 | } |
| 1253 | |
| 1254 | |
| 1255 | |
| 1256 | |
| 1257 | |
| 1258 | |
| 1259 | #[tokio::test] |
| 1260 | async fn a_homeroom_teacher_sees_their_sections_instances() { |
| 1261 | use crate::domain::class_group::ClassName; |
| 1262 | |
| 1263 | let (db, _leases) = crate::database::init_test_db().await; |
| 1264 | let office = crate::db::class_member::tests::fixture_user(&db, "visible-office").await; |
| 1265 | let teacher = crate::db::class_member::tests::fixture_user(&db, "visible-teacher").await; |
| 1266 | sqlx::query("UPDATE app_user SET role = 'teacher' WHERE id = $1") |
| 1267 | .bind(teacher.uuid()) |
| 1268 | .execute(&db) |
| 1269 | .await |
| 1270 | .unwrap(); |
| 1271 | let course = crate::db::class_member::tests::a_course("Matematik", &db).await; |
| 1272 | let class = service::class_group::create( |
| 1273 | &db, |
| 1274 | &office, |
| 1275 | ClassName::try_new("5-A").unwrap(), |
| 1276 | crate::domain::grade::GradeLevel::new(5).unwrap(), |
| 1277 | None, |
| 1278 | Some(teacher), |
| 1279 | ) |
| 1280 | .await |
| 1281 | .unwrap(); |
| 1282 | service::class_course::attach(&db, class.get_id(), &course, &office) |
| 1283 | .await |
| 1284 | .unwrap(); |
| 1285 | |
| 1286 | let homeroom_teacher = crate::service::user::read(&db, &teacher) |
| 1287 | .await |
| 1288 | .unwrap() |
| 1289 | .unwrap(); |
| 1290 | let visible = visible_instances(&homeroom_teacher, &db).await.unwrap(); |
| 1291 | assert_eq!( |
| 1292 | visible.len(), |
| 1293 | 1, |
| 1294 | "the section the teacher runs is invisible to them" |
| 1295 | ); |
| 1296 | assert!(visible[0].1, "and they run it"); |
| 1297 | assert_eq!(visible[0].0.get_class(), class.get_id()); |
| 1298 | } |
| 1299 | |
| 1300 | |
| 1301 | |
| 1302 | |
| 1303 | |
| 1304 | |
| 1305 | #[tokio::test] |
| 1306 | async fn an_assigned_teacher_reads_the_instances_they_teach_once() { |
| 1307 | let (db, _leases) = crate::database::init_test_db().await; |
| 1308 | let office = crate::db::class_member::tests::fixture_user(&db, "union-office").await; |
| 1309 | let teacher = crate::db::class_member::tests::fixture_user(&db, "union-teacher").await; |
| 1310 | sqlx::query("UPDATE app_user SET role = 'teacher' WHERE id = $1") |
| 1311 | .bind(teacher.uuid()) |
| 1312 | .execute(&db) |
| 1313 | .await |
| 1314 | .unwrap(); |
| 1315 | let stranger = crate::db::class_member::tests::fixture_user(&db, "union-stranger").await; |
| 1316 | let course = crate::db::class_member::tests::a_course("Matematik", &db).await; |
| 1317 | let a = crate::db::class_member::tests::a_class("5-A", &db).await; |
| 1318 | let b = crate::db::class_member::tests::a_class("5-B", &db).await; |
| 1319 | let first = service::class_course::attach(&db, &a, &course, &office) |
| 1320 | .await |
| 1321 | .unwrap(); |
| 1322 | service::class_course::attach(&db, &b, &course, &office) |
| 1323 | .await |
| 1324 | .unwrap(); |
| 1325 | |
| 1326 | |
| 1327 | crate::db::class_course_teacher::assign(&db, first.get_id(), &teacher) |
| 1328 | .await |
| 1329 | .unwrap(); |
| 1330 | |
| 1331 | let teacher_user = crate::service::user::read(&db, &teacher) |
| 1332 | .await |
| 1333 | .unwrap() |
| 1334 | .unwrap(); |
| 1335 | let visible = visible_instances(&teacher_user, &db).await.unwrap(); |
| 1336 | assert_eq!(visible.len(), 1, "the instance they teach, exactly once"); |
| 1337 | assert_eq!(visible[0].0.get_id(), first.get_id()); |
| 1338 | assert!(visible[0].1, "and they run it"); |
| 1339 | |
| 1340 | |
| 1341 | |
| 1342 | let stranger_user = crate::service::user::read(&db, &stranger) |
| 1343 | .await |
| 1344 | .unwrap() |
| 1345 | .unwrap(); |
| 1346 | assert!( |
| 1347 | visible_instances(&stranger_user, &db) |
| 1348 | .await |
| 1349 | .unwrap() |
| 1350 | .is_empty() |
| 1351 | ); |
| 1352 | } |
| 1353 | |
| 1354 | |
| 1355 | |
| 1356 | |
| 1357 | |
| 1358 | #[tokio::test] |
| 1359 | async fn a_homeroom_teacher_assigned_to_the_same_instance_reads_it_once() { |
| 1360 | use crate::domain::class_group::ClassName; |
| 1361 | |
| 1362 | let (db, _leases) = crate::database::init_test_db().await; |
| 1363 | let office = crate::db::class_member::tests::fixture_user(&db, "dedupe-office").await; |
| 1364 | let teacher = crate::db::class_member::tests::fixture_user(&db, "dedupe-teacher").await; |
| 1365 | sqlx::query("UPDATE app_user SET role = 'teacher' WHERE id = $1") |
| 1366 | .bind(teacher.uuid()) |
| 1367 | .execute(&db) |
| 1368 | .await |
| 1369 | .unwrap(); |
| 1370 | let course = crate::db::class_member::tests::a_course("Matematik", &db).await; |
| 1371 | let class = service::class_group::create( |
| 1372 | &db, |
| 1373 | &office, |
| 1374 | ClassName::try_new("5-A").unwrap(), |
| 1375 | crate::domain::grade::GradeLevel::new(5).unwrap(), |
| 1376 | None, |
| 1377 | Some(teacher), |
| 1378 | ) |
| 1379 | .await |
| 1380 | .unwrap(); |
| 1381 | let instance = service::class_course::attach(&db, class.get_id(), &course, &office) |
| 1382 | .await |
| 1383 | .unwrap(); |
| 1384 | crate::db::class_course_teacher::assign(&db, instance.get_id(), &teacher) |
| 1385 | .await |
| 1386 | .unwrap(); |
| 1387 | |
| 1388 | let teacher_user = crate::service::user::read(&db, &teacher) |
| 1389 | .await |
| 1390 | .unwrap() |
| 1391 | .unwrap(); |
| 1392 | let visible = visible_instances(&teacher_user, &db).await.unwrap(); |
| 1393 | assert_eq!( |
| 1394 | visible.len(), |
| 1395 | 1, |
| 1396 | "homeroom and assignment are one instance, not two rows" |
| 1397 | ); |
| 1398 | assert_eq!(visible[0].0.get_id(), instance.get_id()); |
| 1399 | } |
| 1400 | } |