| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | |
| 3 | use crate::web::tenant_state::State; |
| 4 | use axum::Json; |
| 5 | use axum::extract::{Path, Query}; |
| 6 | use axum::http::StatusCode; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | use utoipa::{IntoParams, ToSchema}; |
| 9 | use utoipa_axum::router::OpenApiRouter; |
| 10 | use utoipa_axum::routes; |
| 11 | |
| 12 | use crate::database::Database; |
| 13 | use crate::domain::appointment::{ |
| 14 | Appointment, AppointmentId, AppointmentReason, AppointmentStatus, |
| 15 | }; |
| 16 | use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries}; |
| 17 | use crate::domain::role::Role; |
| 18 | use crate::domain::timestamp::Timestamp; |
| 19 | use crate::domain::user::{User, UserId}; |
| 20 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 21 | use crate::service; |
| 22 | use crate::state::AppState; |
| 23 | |
| 24 | use super::{ |
| 25 | CurrentUser, Page, PageParams, PersonRef, RequireTeacher, check_not_past, check_time_range, |
| 26 | paginate, person_map, |
| 27 | }; |
| 28 | |
| 29 | pub fn routes() -> OpenApiRouter<AppState> { |
| 30 | OpenApiRouter::new() |
| 31 | .routes(routes!(publish_slots, list_slots)) |
| 32 | .routes(routes!(delete_slot)) |
| 33 | .routes(routes!(delete_slot_series)) |
| 34 | .routes(routes!(book, list_appointments)) |
| 35 | .routes(routes!(approve)) |
| 36 | .routes(routes!(reject)) |
| 37 | .routes(routes!(cancel)) |
| 38 | .routes(routes!(reschedule)) |
| 39 | .routes(routes!(accept_reschedule)) |
| 40 | .routes(routes!(decline_reschedule)) |
| 41 | } |
| 42 | |
| 43 | #[derive(Deserialize, ToSchema)] |
| 44 | struct PublishSlots { |
| 45 | |
| 46 | #[schema(example = 1_900_000_000_000_i64)] |
| 47 | starts_at: i64, |
| 48 | ends_at: i64, |
| 49 | |
| 50 | #[schema(max_length = 500)] |
| 51 | note: Option<String>, |
| 52 | |
| 53 | #[serde(default)] |
| 54 | repeat_weekly: bool, |
| 55 | |
| 56 | |
| 57 | until: Option<i64>, |
| 58 | } |
| 59 | |
| 60 | #[derive(Deserialize, ToSchema)] |
| 61 | struct BookAppointment { |
| 62 | |
| 63 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 64 | slot: String, |
| 65 | |
| 66 | #[schema(max_length = 1000, example = "Ders notlarını konuşmak istiyorum")] |
| 67 | reason: String, |
| 68 | } |
| 69 | |
| 70 | #[derive(Deserialize, ToSchema)] |
| 71 | struct CancelRequest { |
| 72 | |
| 73 | |
| 74 | #[schema(max_length = 1000, example = "Rahatsızlandım, katılamayacağım")] |
| 75 | reason: Option<String>, |
| 76 | } |
| 77 | |
| 78 | #[derive(Deserialize, ToSchema)] |
| 79 | struct RejectRequest { |
| 80 | |
| 81 | |
| 82 | #[schema(max_length = 1000, example = "Bu saatte müsait değilim")] |
| 83 | reason: Option<String>, |
| 84 | } |
| 85 | |
| 86 | #[derive(Deserialize, ToSchema)] |
| 87 | struct Reschedule { |
| 88 | |
| 89 | #[schema(example = 1_900_000_000_000_i64)] |
| 90 | starts_at: i64, |
| 91 | ends_at: i64, |
| 92 | } |
| 93 | |
| 94 | #[derive(Deserialize, ToSchema)] |
| 95 | struct AcceptReschedule { |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | #[schema(example = 1_900_000_000_000_i64)] |
| 102 | proposed_starts_at: i64, |
| 103 | proposed_ends_at: i64, |
| 104 | } |
| 105 | |
| 106 | #[derive(Serialize, ToSchema)] |
| 107 | struct SlotResponse { |
| 108 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 109 | id: String, |
| 110 | |
| 111 | teacher: PersonRef, |
| 112 | |
| 113 | |
| 114 | starts_at: i64, |
| 115 | ends_at: i64, |
| 116 | note: Option<String>, |
| 117 | |
| 118 | |
| 119 | series: Option<String>, |
| 120 | created_at: i64, |
| 121 | } |
| 122 | |
| 123 | impl SlotResponse { |
| 124 | fn new(slot: &AppointmentSlot, people: &HashMap<String, PersonRef>) -> Self { |
| 125 | Self { |
| 126 | id: slot.get_id().key().to_string(), |
| 127 | teacher: PersonRef::resolve(people, slot.get_teacher()), |
| 128 | starts_at: slot.get_starts_at().as_millis(), |
| 129 | ends_at: slot.get_ends_at().as_millis(), |
| 130 | note: slot.get_note().map(|note| note.as_str().to_string()), |
| 131 | series: slot.get_series().map(|series| series.as_str().to_string()), |
| 132 | created_at: slot.get_created_at().as_millis(), |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | #[derive(Serialize, ToSchema)] |
| 138 | struct AppointmentResponse { |
| 139 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 140 | id: String, |
| 141 | |
| 142 | slot: String, |
| 143 | |
| 144 | teacher: Option<PersonRef>, |
| 145 | |
| 146 | requester: PersonRef, |
| 147 | |
| 148 | |
| 149 | #[schema(example = "pending")] |
| 150 | status: String, |
| 151 | reason: String, |
| 152 | |
| 153 | |
| 154 | starts_at: Option<i64>, |
| 155 | ends_at: Option<i64>, |
| 156 | |
| 157 | proposed_starts_at: Option<i64>, |
| 158 | proposed_ends_at: Option<i64>, |
| 159 | proposed_by: Option<PersonRef>, |
| 160 | |
| 161 | decided_by: Option<PersonRef>, |
| 162 | |
| 163 | |
| 164 | cancelled_by: Option<PersonRef>, |
| 165 | |
| 166 | |
| 167 | |
| 168 | cancel_reason: Option<String>, |
| 169 | |
| 170 | |
| 171 | reject_reason: Option<String>, |
| 172 | created_at: i64, |
| 173 | } |
| 174 | |
| 175 | impl AppointmentResponse { |
| 176 | fn new( |
| 177 | appointment: &Appointment, |
| 178 | slot: Option<&AppointmentSlot>, |
| 179 | people: &HashMap<String, PersonRef>, |
| 180 | ) -> Self { |
| 181 | let window = slot.map(|slot| appointment.window(slot)); |
| 182 | Self { |
| 183 | id: appointment.get_id().key().to_string(), |
| 184 | |
| 185 | |
| 186 | |
| 187 | slot: appointment |
| 188 | .get_slot() |
| 189 | .map(|slot| slot.key()) |
| 190 | .unwrap_or_default(), |
| 191 | teacher: slot.map(|slot| PersonRef::resolve(people, slot.get_teacher())), |
| 192 | requester: PersonRef::resolve(people, appointment.get_requester()), |
| 193 | status: appointment.get_status().as_str().to_string(), |
| 194 | reason: appointment.get_reason().as_str().to_string(), |
| 195 | starts_at: window.map(|(starts_at, _)| starts_at.as_millis()), |
| 196 | ends_at: window.map(|(_, ends_at)| ends_at.as_millis()), |
| 197 | proposed_starts_at: appointment.get_proposed_starts_at().map(|t| t.as_millis()), |
| 198 | proposed_ends_at: appointment.get_proposed_ends_at().map(|t| t.as_millis()), |
| 199 | proposed_by: appointment |
| 200 | .get_proposed_by() |
| 201 | .map(|id| PersonRef::resolve(people, id)), |
| 202 | decided_by: appointment |
| 203 | .get_decided_by() |
| 204 | .map(|id| PersonRef::resolve(people, id)), |
| 205 | cancelled_by: appointment |
| 206 | .get_cancelled_by() |
| 207 | .map(|id| PersonRef::resolve(people, id)), |
| 208 | cancel_reason: appointment |
| 209 | .get_cancel_reason() |
| 210 | .map(|reason| reason.as_str().to_string()), |
| 211 | reject_reason: appointment |
| 212 | .get_reject_reason() |
| 213 | .map(|reason| reason.as_str().to_string()), |
| 214 | created_at: appointment.get_created_at().as_millis(), |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | |
| 220 | |
| 221 | async fn appointment_responses( |
| 222 | rows: &[Appointment], |
| 223 | db: &Database, |
| 224 | ) -> Result<Vec<AppointmentResponse>, AppError> { |
| 225 | let mut slots = Vec::with_capacity(rows.len()); |
| 226 | for row in rows { |
| 227 | let slot = match row.get_slot() { |
| 228 | Some(slot_id) => service::appointment_slot::read(db, slot_id).await?, |
| 229 | |
| 230 | None => None, |
| 231 | }; |
| 232 | slots.push(slot); |
| 233 | } |
| 234 | |
| 235 | |
| 236 | |
| 237 | let mut ids = Vec::with_capacity(rows.len() * 2); |
| 238 | for (row, slot) in rows.iter().zip(&slots) { |
| 239 | ids.push(*row.get_requester()); |
| 240 | ids.extend(slot.as_ref().map(|slot| *slot.get_teacher())); |
| 241 | ids.extend(row.get_proposed_by().cloned()); |
| 242 | ids.extend(row.get_decided_by().cloned()); |
| 243 | ids.extend(row.get_cancelled_by().cloned()); |
| 244 | } |
| 245 | let people = person_map(ids, db).await?; |
| 246 | Ok(rows |
| 247 | .iter() |
| 248 | .zip(&slots) |
| 249 | .map(|(row, slot)| AppointmentResponse::new(row, slot.as_ref(), &people)) |
| 250 | .collect()) |
| 251 | } |
| 252 | |
| 253 | |
| 254 | |
| 255 | async fn one_appointment( |
| 256 | appointment: Appointment, |
| 257 | db: &Database, |
| 258 | ) -> Result<Json<AppointmentResponse>, AppError> { |
| 259 | appointment_responses(std::slice::from_ref(&appointment), db) |
| 260 | .await? |
| 261 | .pop() |
| 262 | .map(Json) |
| 263 | .ok_or_else(|| AppError::Internal("failed to render the appointment".into())) |
| 264 | } |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | fn can_manage(slot: &AppointmentSlot, user: &User) -> bool { |
| 280 | user.get_role().at_least(Role::Teacher) |
| 281 | && (slot.get_teacher() == user.get_id() || user.get_role().at_least(Role::Manager)) |
| 282 | } |
| 283 | |
| 284 | |
| 285 | async fn for_decision( |
| 286 | id: &AppointmentId, |
| 287 | user: &User, |
| 288 | db: &Database, |
| 289 | ) -> Result<Appointment, AppError> { |
| 290 | let appointment = service::appointment::read(db, id) |
| 291 | .await? |
| 292 | .ok_or(AppError::NotFound)?; |
| 293 | let slot_id = appointment.get_slot().ok_or(AppError::NotFound)?; |
| 294 | let slot = service::appointment_slot::read(db, slot_id) |
| 295 | .await? |
| 296 | .ok_or(AppError::NotFound)?; |
| 297 | if !can_manage(&slot, user) { |
| 298 | return Err(AppError::Forbidden( |
| 299 | "only the slot's teacher or a manager/admin can decide this appointment", |
| 300 | )); |
| 301 | } |
| 302 | Ok(appointment) |
| 303 | } |
| 304 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | #[utoipa::path( |
| 322 | post, |
| 323 | path = "/slots", |
| 324 | tag = "appointments", |
| 325 | security(("session_cookie" = [])), |
| 326 | request_body = PublishSlots, |
| 327 | responses( |
| 328 | (status = 201, description = "Slots published", body = Vec<SlotResponse>), |
| 329 | (status = 400, description = "Invalid note, time range, times in the past, `until` missing with `repeat_weekly`, more than 52 occurrences, or a window too far ahead to shift by a week", body = ErrorResponse), |
| 330 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 331 | (status = 403, description = "Requires teacher role or higher — including an account demoted while this request ran, whose calendar the demotion is withdrawing", body = ErrorResponse), |
| 332 | (status = 409, description = "The window overlaps one the caller has already published, or (weekly) two occurrences overlap each other — the whole publish is refused, nothing is written", body = ErrorResponse), |
| 333 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 334 | ), |
| 335 | )] |
| 336 | async fn publish_slots( |
| 337 | State(st): State<AppState>, |
| 338 | RequireTeacher(user): RequireTeacher, |
| 339 | Json(req): Json<PublishSlots>, |
| 340 | ) -> Result<(StatusCode, Json<Vec<SlotResponse>>), AppError> { |
| 341 | let note = match req.note { |
| 342 | Some(ref note) => Some(SlotNote::try_new(note)?), |
| 343 | None => None, |
| 344 | }; |
| 345 | let starts_at = Timestamp::from_millis(req.starts_at); |
| 346 | let ends_at = Timestamp::from_millis(req.ends_at); |
| 347 | check_not_past("starts_at", Some(starts_at))?; |
| 348 | check_not_past("ends_at", Some(ends_at))?; |
| 349 | check_time_range(Some(starts_at), Some(ends_at))?; |
| 350 | |
| 351 | let slots = if req.repeat_weekly { |
| 352 | let until = req |
| 353 | .until |
| 354 | .map(Timestamp::from_millis) |
| 355 | .ok_or(AppError::Validation(ValidationError::Invalid { |
| 356 | field: "until", |
| 357 | reason: "is required with repeat_weekly", |
| 358 | }))?; |
| 359 | check_not_past("until", Some(until))?; |
| 360 | service::appointment_slot::publish_weekly( |
| 361 | &st.db, |
| 362 | user.get_id(), |
| 363 | starts_at, |
| 364 | ends_at, |
| 365 | note, |
| 366 | until, |
| 367 | ) |
| 368 | .await? |
| 369 | } else { |
| 370 | vec![ |
| 371 | service::appointment_slot::create(&st.db, user.get_id(), starts_at, ends_at, note) |
| 372 | .await?, |
| 373 | ] |
| 374 | }; |
| 375 | |
| 376 | let people = PersonRef::map_of(&[&user]); |
| 377 | let items = slots |
| 378 | .iter() |
| 379 | .map(|slot| SlotResponse::new(slot, &people)) |
| 380 | .collect(); |
| 381 | Ok((StatusCode::CREATED, Json(items))) |
| 382 | } |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | |
| 389 | fn teacher_filter(raw: Option<&str>, caller: &UserId) -> Result<Option<UserId>, AppError> { |
| 390 | let Some(raw) = raw else { |
| 391 | return Ok(None); |
| 392 | }; |
| 393 | let key = raw.trim(); |
| 394 | if key.is_empty() { |
| 395 | return Err(AppError::Validation(ValidationError::Invalid { |
| 396 | field: "teacher", |
| 397 | reason: "must not be empty", |
| 398 | })); |
| 399 | } |
| 400 | Ok(Some(match key { |
| 401 | "me" => *caller, |
| 402 | other => { |
| 403 | let id = UserId::from_key(other); |
| 404 | if id.uuid().is_nil() { |
| 405 | return Err(AppError::Validation(ValidationError::Invalid { |
| 406 | field: "teacher", |
| 407 | reason: "must be a hyphenated uuid", |
| 408 | })); |
| 409 | } |
| 410 | id |
| 411 | } |
| 412 | })) |
| 413 | } |
| 414 | |
| 415 | |
| 416 | |
| 417 | fn starts_bound_filter(field: &'static str, raw: Option<i64>) -> Result<Option<Timestamp>, AppError> { |
| 418 | match raw { |
| 419 | None => Ok(None), |
| 420 | Some(value) if value < 0 => Err(AppError::Validation(ValidationError::Invalid { |
| 421 | field, |
| 422 | reason: "must not be negative", |
| 423 | })), |
| 424 | Some(value) => Ok(Some(Timestamp::from_millis(value))), |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | |
| 429 | |
| 430 | #[derive(Debug, Deserialize, IntoParams)] |
| 431 | struct SlotFilter { |
| 432 | |
| 433 | #[param(example = "me")] |
| 434 | teacher: Option<String>, |
| 435 | |
| 436 | #[param(minimum = 0, example = 1_760_000_000_000_i64)] |
| 437 | starts_after: Option<i64>, |
| 438 | } |
| 439 | |
| 440 | impl SlotFilter { |
| 441 | fn resolve_teacher(&self, caller: &UserId) -> Result<Option<UserId>, AppError> { |
| 442 | teacher_filter(self.teacher.as_deref(), caller) |
| 443 | } |
| 444 | |
| 445 | fn resolve_starts_after(&self) -> Result<Option<Timestamp>, AppError> { |
| 446 | starts_bound_filter("starts_after", self.starts_after) |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | |
| 451 | |
| 452 | |
| 453 | |
| 454 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | |
| 460 | |
| 461 | |
| 462 | |
| 463 | |
| 464 | |
| 465 | |
| 466 | |
| 467 | |
| 468 | |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | |
| 474 | |
| 475 | |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | #[utoipa::path( |
| 484 | get, |
| 485 | path = "/slots", |
| 486 | tag = "appointments", |
| 487 | security(("session_cookie" = [])), |
| 488 | params(PageParams, SlotFilter), |
| 489 | responses( |
| 490 | (status = 200, description = "A page of slots (all of them when unpaged)", body = Page<SlotResponse>), |
| 491 | (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse), |
| 492 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 493 | ), |
| 494 | )] |
| 495 | async fn list_slots( |
| 496 | State(st): State<AppState>, |
| 497 | CurrentUser(user): CurrentUser, |
| 498 | Query(page): Query<PageParams>, |
| 499 | Query(filter): Query<SlotFilter>, |
| 500 | ) -> Result<Json<Page<SlotResponse>>, AppError> { |
| 501 | let (limit, offset) = page.resolve()?; |
| 502 | let narrow_to = filter.resolve_teacher(user.get_id())?; |
| 503 | let starts_after = filter.resolve_starts_after()?; |
| 504 | let (slots, people) = if user.get_role().at_least(Role::Teacher) { |
| 505 | |
| 506 | |
| 507 | |
| 508 | |
| 509 | |
| 510 | match narrow_to { |
| 511 | Some(other) if other != *user.get_id() => { |
| 512 | (Vec::new(), PersonRef::map_of(&[&user])) |
| 513 | } |
| 514 | _ => ( |
| 515 | service::appointment_slot::list_calendar( |
| 516 | &st.db, |
| 517 | user.get_id(), |
| 518 | starts_after, |
| 519 | ) |
| 520 | .await?, |
| 521 | PersonRef::map_of(&[&user]), |
| 522 | ), |
| 523 | } |
| 524 | } else { |
| 525 | let mut slots = service::appointment_slot::list_upcoming( |
| 526 | &st.db, |
| 527 | Timestamp::now(), |
| 528 | narrow_to.as_ref(), |
| 529 | starts_after, |
| 530 | ) |
| 531 | .await?; |
| 532 | |
| 533 | |
| 534 | |
| 535 | let mut seen = HashSet::new(); |
| 536 | let teachers: Vec<UserId> = slots |
| 537 | .iter() |
| 538 | .map(AppointmentSlot::get_teacher) |
| 539 | .filter(|teacher| seen.insert(teacher.key().to_string())) |
| 540 | .cloned() |
| 541 | .collect(); |
| 542 | let people: HashMap<String, PersonRef> = |
| 543 | crate::service::user::list_by_ids(&st.db, &teachers) |
| 544 | .await? |
| 545 | .iter() |
| 546 | .filter(|teacher| teacher.get_role().at_least(Role::Teacher)) |
| 547 | .map(|teacher| (teacher.get_id().key().to_string(), PersonRef::new(teacher))) |
| 548 | .collect(); |
| 549 | slots.retain(|slot| people.contains_key(slot.get_teacher().key().as_str())); |
| 550 | (slots, people) |
| 551 | }; |
| 552 | let total = slots.len() as i64; |
| 553 | |
| 554 | let items = paginate(&slots, limit, offset) |
| 555 | .iter() |
| 556 | .map(|slot| SlotResponse::new(slot, &people)) |
| 557 | .collect(); |
| 558 | Ok(Json(Page::new(items, total, limit, offset))) |
| 559 | } |
| 560 | |
| 561 | |
| 562 | |
| 563 | |
| 564 | |
| 565 | #[utoipa::path( |
| 566 | delete, |
| 567 | path = "/slots/{id}", |
| 568 | tag = "appointments", |
| 569 | security(("session_cookie" = [])), |
| 570 | params(("id" = String, Path, description = "Slot id")), |
| 571 | responses( |
| 572 | (status = 204, description = "Deleted"), |
| 573 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 574 | (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), |
| 575 | (status = 404, description = "Not found", body = ErrorResponse), |
| 576 | (status = 409, description = "The slot has a pending or approved booking", body = ErrorResponse), |
| 577 | ), |
| 578 | )] |
| 579 | async fn delete_slot( |
| 580 | State(st): State<AppState>, |
| 581 | RequireTeacher(user): RequireTeacher, |
| 582 | Path(id): Path<String>, |
| 583 | ) -> Result<StatusCode, AppError> { |
| 584 | let slot = service::appointment_slot::read(&st.db, &AppointmentSlotId::from_key(&id)) |
| 585 | .await? |
| 586 | .ok_or(AppError::NotFound)?; |
| 587 | if !can_manage(&slot, &user) { |
| 588 | return Err(AppError::Forbidden( |
| 589 | "only the slot's teacher or a manager/admin can delete it", |
| 590 | )); |
| 591 | } |
| 592 | service::appointment_slot::delete(&st.db, slot).await?; |
| 593 | Ok(StatusCode::NO_CONTENT) |
| 594 | } |
| 595 | |
| 596 | |
| 597 | |
| 598 | |
| 599 | |
| 600 | #[utoipa::path( |
| 601 | delete, |
| 602 | path = "/slots/series/{series}", |
| 603 | tag = "appointments", |
| 604 | security(("session_cookie" = [])), |
| 605 | params(("series" = String, Path, description = "Series id, from a slot's `series` field")), |
| 606 | responses( |
| 607 | (status = 204, description = "Deleted"), |
| 608 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 609 | (status = 403, description = "Not the series' teacher (and not a manager/admin)", body = ErrorResponse), |
| 610 | (status = 404, description = "No such series", body = ErrorResponse), |
| 611 | (status = 409, description = "Some occurrence has a pending or approved booking", body = ErrorResponse), |
| 612 | ), |
| 613 | )] |
| 614 | async fn delete_slot_series( |
| 615 | State(st): State<AppState>, |
| 616 | RequireTeacher(user): RequireTeacher, |
| 617 | Path(series): Path<String>, |
| 618 | ) -> Result<StatusCode, AppError> { |
| 619 | let series = SlotSeries::from_key(&series); |
| 620 | |
| 621 | |
| 622 | let slot = service::appointment_slot::list_for_series(&st.db, &series) |
| 623 | .await? |
| 624 | .into_iter() |
| 625 | .next() |
| 626 | .ok_or(AppError::NotFound)?; |
| 627 | if !can_manage(&slot, &user) { |
| 628 | return Err(AppError::Forbidden( |
| 629 | "only the slot's teacher or a manager/admin can delete it", |
| 630 | )); |
| 631 | } |
| 632 | service::appointment_slot::delete_series(&st.db, &series).await?; |
| 633 | Ok(StatusCode::NO_CONTENT) |
| 634 | } |
| 635 | |
| 636 | |
| 637 | |
| 638 | |
| 639 | |
| 640 | |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | #[utoipa::path( |
| 646 | post, |
| 647 | path = "/", |
| 648 | tag = "appointments", |
| 649 | security(("session_cookie" = [])), |
| 650 | request_body = BookAppointment, |
| 651 | responses( |
| 652 | (status = 201, description = "Booking requested", body = AppointmentResponse), |
| 653 | (status = 400, description = "Missing or over-long reason", body = ErrorResponse), |
| 654 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 655 | (status = 403, description = "Only students and parents book appointments", body = ErrorResponse), |
| 656 | (status = 404, description = "Slot not found", body = ErrorResponse), |
| 657 | (status = 409, description = "The slot has started or is taken, the requester is busy, or its teacher is no longer staff", body = ErrorResponse), |
| 658 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 659 | ), |
| 660 | )] |
| 661 | async fn book( |
| 662 | State(st): State<AppState>, |
| 663 | CurrentUser(user): CurrentUser, |
| 664 | Json(req): Json<BookAppointment>, |
| 665 | ) -> Result<(StatusCode, Json<AppointmentResponse>), AppError> { |
| 666 | if !matches!(user.get_role(), Role::Student | Role::Parent) { |
| 667 | return Err(AppError::Forbidden( |
| 668 | "only students and parents can book an appointment", |
| 669 | )); |
| 670 | } |
| 671 | let slot_id = AppointmentSlotId::from_key(&req.slot); |
| 672 | let slot = service::appointment_slot::read(&st.db, &slot_id) |
| 673 | .await? |
| 674 | .ok_or(AppError::NotFound)?; |
| 675 | |
| 676 | |
| 677 | if !crate::service::user::read(&st.db, slot.get_teacher()) |
| 678 | .await? |
| 679 | .is_some_and(|teacher| teacher.get_role().at_least(Role::Teacher)) |
| 680 | { |
| 681 | return Err(AppError::Conflict( |
| 682 | "the slot's teacher no longer holds a teaching role", |
| 683 | )); |
| 684 | } |
| 685 | let reason = AppointmentReason::try_new(&req.reason)?; |
| 686 | let appointment = service::appointment::book(&st.db, &slot_id, user.get_id(), reason).await?; |
| 687 | Ok(( |
| 688 | StatusCode::CREATED, |
| 689 | one_appointment(appointment, &st.db).await?, |
| 690 | )) |
| 691 | } |
| 692 | |
| 693 | |
| 694 | |
| 695 | #[derive(Debug, Deserialize, IntoParams)] |
| 696 | struct AppointmentFilter { |
| 697 | |
| 698 | |
| 699 | #[param(example = "pending")] |
| 700 | status: Option<String>, |
| 701 | |
| 702 | #[param(minimum = 0, example = 1_760_000_000_000_i64)] |
| 703 | starts_after: Option<i64>, |
| 704 | |
| 705 | |
| 706 | #[param(minimum = 0, example = 1_760_259_199_999_i64)] |
| 707 | starts_before: Option<i64>, |
| 708 | |
| 709 | |
| 710 | #[param(example = "me")] |
| 711 | teacher: Option<String>, |
| 712 | } |
| 713 | |
| 714 | impl AppointmentFilter { |
| 715 | |
| 716 | |
| 717 | |
| 718 | fn resolve_status(&self) -> Result<Option<AppointmentStatus>, AppError> { |
| 719 | const STATUSES: [AppointmentStatus; 4] = [ |
| 720 | AppointmentStatus::Pending, |
| 721 | AppointmentStatus::Approved, |
| 722 | AppointmentStatus::Rejected, |
| 723 | AppointmentStatus::Cancelled, |
| 724 | ]; |
| 725 | let Some(raw) = self.status.as_deref() else { |
| 726 | return Ok(None); |
| 727 | }; |
| 728 | let word = raw.trim(); |
| 729 | if word.is_empty() { |
| 730 | return Err(AppError::Validation(ValidationError::Invalid { |
| 731 | field: "status", |
| 732 | reason: "must not be empty", |
| 733 | })); |
| 734 | } |
| 735 | STATUSES |
| 736 | .into_iter() |
| 737 | .find(|status| status.as_str() == word) |
| 738 | .map(Some) |
| 739 | .ok_or_else(|| { |
| 740 | AppError::Validation(ValidationError::Invalid { |
| 741 | field: "status", |
| 742 | reason: "must be one of: pending, approved, rejected, cancelled", |
| 743 | }) |
| 744 | }) |
| 745 | } |
| 746 | |
| 747 | fn resolve_starts_after(&self) -> Result<Option<Timestamp>, AppError> { |
| 748 | starts_bound_filter("starts_after", self.starts_after) |
| 749 | } |
| 750 | |
| 751 | fn resolve_starts_before(&self) -> Result<Option<Timestamp>, AppError> { |
| 752 | starts_bound_filter("starts_before", self.starts_before) |
| 753 | } |
| 754 | |
| 755 | fn resolve_teacher(&self, caller: &UserId) -> Result<Option<UserId>, AppError> { |
| 756 | teacher_filter(self.teacher.as_deref(), caller) |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | |
| 761 | |
| 762 | |
| 763 | |
| 764 | |
| 765 | |
| 766 | |
| 767 | |
| 768 | |
| 769 | |
| 770 | |
| 771 | |
| 772 | |
| 773 | |
| 774 | |
| 775 | |
| 776 | #[utoipa::path( |
| 777 | get, |
| 778 | path = "/", |
| 779 | tag = "appointments", |
| 780 | security(("session_cookie" = [])), |
| 781 | params(PageParams, AppointmentFilter), |
| 782 | responses( |
| 783 | (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page<AppointmentResponse>), |
| 784 | (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse), |
| 785 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 786 | ), |
| 787 | )] |
| 788 | async fn list_appointments( |
| 789 | State(st): State<AppState>, |
| 790 | CurrentUser(user): CurrentUser, |
| 791 | Query(page): Query<PageParams>, |
| 792 | Query(filter): Query<AppointmentFilter>, |
| 793 | ) -> Result<Json<Page<AppointmentResponse>>, AppError> { |
| 794 | let (limit, offset) = page.resolve()?; |
| 795 | let status = filter.resolve_status()?; |
| 796 | let starts_after = filter.resolve_starts_after()?; |
| 797 | let starts_before = filter.resolve_starts_before()?; |
| 798 | let narrow_to = filter.resolve_teacher(user.get_id())?; |
| 799 | let (rows, total) = if user.get_role().at_least(Role::Teacher) { |
| 800 | |
| 801 | |
| 802 | |
| 803 | match narrow_to { |
| 804 | Some(other) if other != *user.get_id() => (Vec::new(), 0), |
| 805 | _ => { |
| 806 | service::appointment::list_for_teacher( |
| 807 | &st.db, |
| 808 | user.get_id(), |
| 809 | status, |
| 810 | starts_after, |
| 811 | starts_before, |
| 812 | limit, |
| 813 | offset, |
| 814 | ) |
| 815 | .await? |
| 816 | } |
| 817 | } |
| 818 | } else { |
| 819 | service::appointment::list_for_requester( |
| 820 | &st.db, |
| 821 | user.get_id(), |
| 822 | service::appointment::RequesterListParams { |
| 823 | status, |
| 824 | starts_after, |
| 825 | starts_before, |
| 826 | teacher: narrow_to.as_ref(), |
| 827 | limit, |
| 828 | offset, |
| 829 | }, |
| 830 | ) |
| 831 | .await? |
| 832 | }; |
| 833 | |
| 834 | let items = appointment_responses(&rows, &st.db).await?; |
| 835 | Ok(Json(Page::new(items, total, limit, offset))) |
| 836 | } |
| 837 | |
| 838 | |
| 839 | |
| 840 | |
| 841 | |
| 842 | |
| 843 | |
| 844 | |
| 845 | |
| 846 | |
| 847 | |
| 848 | |
| 849 | #[utoipa::path( |
| 850 | patch, |
| 851 | path = "/{id}/approve", |
| 852 | tag = "appointments", |
| 853 | security(("session_cookie" = [])), |
| 854 | params(("id" = String, Path, description = "Appointment id")), |
| 855 | responses( |
| 856 | (status = 200, description = "Approved", body = AppointmentResponse), |
| 857 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 858 | (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), |
| 859 | (status = 404, description = "Not found", body = ErrorResponse), |
| 860 | (status = 409, description = "No longer pending, a counter-proposal is standing (only the requester can accept it), the time has already started, or it collides with another approved appointment", body = ErrorResponse), |
| 861 | ), |
| 862 | )] |
| 863 | async fn approve( |
| 864 | State(st): State<AppState>, |
| 865 | RequireTeacher(user): RequireTeacher, |
| 866 | Path(id): Path<String>, |
| 867 | ) -> Result<Json<AppointmentResponse>, AppError> { |
| 868 | let id = AppointmentId::from_key(&id); |
| 869 | for_decision(&id, &user, &st.db).await?; |
| 870 | let appointment = service::appointment::approve(&st.db, &id, user.get_id()).await?; |
| 871 | one_appointment(appointment, &st.db).await |
| 872 | } |
| 873 | |
| 874 | |
| 875 | |
| 876 | |
| 877 | #[utoipa::path( |
| 878 | patch, |
| 879 | path = "/{id}/reject", |
| 880 | tag = "appointments", |
| 881 | security(("session_cookie" = [])), |
| 882 | params(("id" = String, Path, description = "Appointment id")), |
| 883 | request_body(content = RejectRequest, description = "Optional rejection reason; the whole body may be omitted"), |
| 884 | responses( |
| 885 | (status = 200, description = "Rejected", body = AppointmentResponse), |
| 886 | (status = 400, description = "Reason is over-long", body = ErrorResponse), |
| 887 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 888 | (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), |
| 889 | (status = 404, description = "Not found", body = ErrorResponse), |
| 890 | (status = 409, description = "No longer pending", body = ErrorResponse), |
| 891 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 892 | ), |
| 893 | )] |
| 894 | async fn reject( |
| 895 | State(st): State<AppState>, |
| 896 | RequireTeacher(user): RequireTeacher, |
| 897 | Path(id): Path<String>, |
| 898 | body: Option<Json<RejectRequest>>, |
| 899 | ) -> Result<Json<AppointmentResponse>, AppError> { |
| 900 | let id = AppointmentId::from_key(&id); |
| 901 | for_decision(&id, &user, &st.db).await?; |
| 902 | |
| 903 | |
| 904 | let reason = match body.and_then(|Json(req)| req.reason) { |
| 905 | Some(reason) if !reason.trim().is_empty() => Some(AppointmentReason::try_new(&reason)?), |
| 906 | _ => None, |
| 907 | }; |
| 908 | let appointment = service::appointment::reject(&st.db, &id, user.get_id(), reason).await?; |
| 909 | one_appointment(appointment, &st.db).await |
| 910 | } |
| 911 | |
| 912 | |
| 913 | |
| 914 | |
| 915 | |
| 916 | |
| 917 | |
| 918 | |
| 919 | |
| 920 | #[utoipa::path( |
| 921 | patch, |
| 922 | path = "/{id}/cancel", |
| 923 | tag = "appointments", |
| 924 | security(("session_cookie" = [])), |
| 925 | params(("id" = String, Path, description = "Appointment id")), |
| 926 | request_body(content = CancelRequest, description = "Optional cancellation reason; the whole body may be omitted"), |
| 927 | responses( |
| 928 | (status = 200, description = "Cancelled", body = AppointmentResponse), |
| 929 | (status = 400, description = "Reason is over-long", body = ErrorResponse), |
| 930 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 931 | (status = 403, description = "Not the requester", body = ErrorResponse), |
| 932 | (status = 404, description = "Not found", body = ErrorResponse), |
| 933 | (status = 409, description = "Already settled, or the appointment has already started", body = ErrorResponse), |
| 934 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 935 | ), |
| 936 | )] |
| 937 | async fn cancel( |
| 938 | State(st): State<AppState>, |
| 939 | CurrentUser(user): CurrentUser, |
| 940 | Path(id): Path<String>, |
| 941 | body: Option<Json<CancelRequest>>, |
| 942 | ) -> Result<Json<AppointmentResponse>, AppError> { |
| 943 | let id = AppointmentId::from_key(&id); |
| 944 | let appointment = service::appointment::read(&st.db, &id) |
| 945 | .await? |
| 946 | .ok_or(AppError::NotFound)?; |
| 947 | |
| 948 | |
| 949 | if appointment.get_requester() != user.get_id() { |
| 950 | return Err(AppError::Forbidden( |
| 951 | "only the requester can cancel this appointment", |
| 952 | )); |
| 953 | } |
| 954 | |
| 955 | |
| 956 | let reason = match body.and_then(|Json(req)| req.reason) { |
| 957 | Some(reason) if !reason.trim().is_empty() => Some(AppointmentReason::try_new(&reason)?), |
| 958 | _ => None, |
| 959 | }; |
| 960 | |
| 961 | |
| 962 | |
| 963 | let appointment = service::appointment::cancel(&st.db, &id, user.get_id(), reason).await?; |
| 964 | one_appointment(appointment, &st.db).await |
| 965 | } |
| 966 | |
| 967 | |
| 968 | |
| 969 | |
| 970 | |
| 971 | |
| 972 | |
| 973 | |
| 974 | |
| 975 | |
| 976 | |
| 977 | |
| 978 | |
| 979 | |
| 980 | #[utoipa::path( |
| 981 | patch, |
| 982 | path = "/{id}/reschedule", |
| 983 | tag = "appointments", |
| 984 | security(("session_cookie" = [])), |
| 985 | params(("id" = String, Path, description = "Appointment id")), |
| 986 | request_body = Reschedule, |
| 987 | responses( |
| 988 | (status = 200, description = "Proposed; the booking is pending again", body = AppointmentResponse), |
| 989 | (status = 400, description = "Invalid time range or times in the past", body = ErrorResponse), |
| 990 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 991 | (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), |
| 992 | (status = 404, description = "Not found", body = ErrorResponse), |
| 993 | (status = 409, description = "The appointment is already settled, or the proposed window has already started", body = ErrorResponse), |
| 994 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 995 | ), |
| 996 | )] |
| 997 | async fn reschedule( |
| 998 | State(st): State<AppState>, |
| 999 | RequireTeacher(user): RequireTeacher, |
| 1000 | Path(id): Path<String>, |
| 1001 | Json(req): Json<Reschedule>, |
| 1002 | ) -> Result<Json<AppointmentResponse>, AppError> { |
| 1003 | let starts_at = Timestamp::from_millis(req.starts_at); |
| 1004 | let ends_at = Timestamp::from_millis(req.ends_at); |
| 1005 | check_not_past("starts_at", Some(starts_at))?; |
| 1006 | check_not_past("ends_at", Some(ends_at))?; |
| 1007 | check_time_range(Some(starts_at), Some(ends_at))?; |
| 1008 | |
| 1009 | let id = AppointmentId::from_key(&id); |
| 1010 | for_decision(&id, &user, &st.db).await?; |
| 1011 | let appointment = |
| 1012 | service::appointment::propose(&st.db, &id, starts_at, ends_at, user.get_id()).await?; |
| 1013 | one_appointment(appointment, &st.db).await |
| 1014 | } |
| 1015 | |
| 1016 | |
| 1017 | |
| 1018 | |
| 1019 | |
| 1020 | |
| 1021 | |
| 1022 | |
| 1023 | |
| 1024 | |
| 1025 | |
| 1026 | |
| 1027 | |
| 1028 | #[utoipa::path( |
| 1029 | patch, |
| 1030 | path = "/{id}/reschedule/accept", |
| 1031 | tag = "appointments", |
| 1032 | security(("session_cookie" = [])), |
| 1033 | params(("id" = String, Path, description = "Appointment id")), |
| 1034 | request_body = AcceptReschedule, |
| 1035 | responses( |
| 1036 | (status = 200, description = "Approved at the proposed time", body = AppointmentResponse), |
| 1037 | (status = 400, description = "Missing or unreadable body", body = ErrorResponse), |
| 1038 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1039 | (status = 403, description = "Not the requester", body = ErrorResponse), |
| 1040 | (status = 404, description = "Not found", body = ErrorResponse), |
| 1041 | (status = 409, description = "No time has been proposed, the proposal has since changed (re-read it), the booking is no longer pending, the proposed time has already started, or it collides with another approved appointment", body = ErrorResponse), |
| 1042 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 1043 | ), |
| 1044 | )] |
| 1045 | async fn accept_reschedule( |
| 1046 | State(st): State<AppState>, |
| 1047 | CurrentUser(user): CurrentUser, |
| 1048 | Path(id): Path<String>, |
| 1049 | Json(req): Json<AcceptReschedule>, |
| 1050 | ) -> Result<Json<AppointmentResponse>, AppError> { |
| 1051 | let id = AppointmentId::from_key(&id); |
| 1052 | ensure_requester(&id, &user, &st.db).await?; |
| 1053 | |
| 1054 | |
| 1055 | |
| 1056 | |
| 1057 | let appointment = service::appointment::accept_proposal( |
| 1058 | &st.db, |
| 1059 | &id, |
| 1060 | user.get_id(), |
| 1061 | Timestamp::from_millis(req.proposed_starts_at), |
| 1062 | Timestamp::from_millis(req.proposed_ends_at), |
| 1063 | ) |
| 1064 | .await?; |
| 1065 | one_appointment(appointment, &st.db).await |
| 1066 | } |
| 1067 | |
| 1068 | |
| 1069 | |
| 1070 | |
| 1071 | |
| 1072 | |
| 1073 | |
| 1074 | #[utoipa::path( |
| 1075 | patch, |
| 1076 | path = "/{id}/reschedule/decline", |
| 1077 | tag = "appointments", |
| 1078 | security(("session_cookie" = [])), |
| 1079 | params(("id" = String, Path, description = "Appointment id")), |
| 1080 | responses( |
| 1081 | (status = 200, description = "Cancelled", body = AppointmentResponse), |
| 1082 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1083 | (status = 403, description = "Not the requester", body = ErrorResponse), |
| 1084 | (status = 404, description = "Not found", body = ErrorResponse), |
| 1085 | (status = 409, description = "No time has been proposed, the booking is already settled, or the meeting's window has already started", body = ErrorResponse), |
| 1086 | ), |
| 1087 | )] |
| 1088 | async fn decline_reschedule( |
| 1089 | State(st): State<AppState>, |
| 1090 | CurrentUser(user): CurrentUser, |
| 1091 | Path(id): Path<String>, |
| 1092 | ) -> Result<Json<AppointmentResponse>, AppError> { |
| 1093 | let id = AppointmentId::from_key(&id); |
| 1094 | let appointment = ensure_requester(&id, &user, &st.db).await?; |
| 1095 | if appointment.get_proposed_starts_at().is_none() { |
| 1096 | return Err(AppError::Conflict("no time has been proposed")); |
| 1097 | } |
| 1098 | let appointment = service::appointment::cancel(&st.db, &id, user.get_id(), None).await?; |
| 1099 | one_appointment(appointment, &st.db).await |
| 1100 | } |
| 1101 | |
| 1102 | |
| 1103 | |
| 1104 | async fn ensure_requester( |
| 1105 | id: &AppointmentId, |
| 1106 | user: &User, |
| 1107 | db: &Database, |
| 1108 | ) -> Result<Appointment, AppError> { |
| 1109 | let appointment = service::appointment::read(db, id) |
| 1110 | .await? |
| 1111 | .ok_or(AppError::NotFound)?; |
| 1112 | if appointment.get_requester() != user.get_id() { |
| 1113 | return Err(AppError::Forbidden( |
| 1114 | "only the requester can answer a counter-proposal", |
| 1115 | )); |
| 1116 | } |
| 1117 | Ok(appointment) |
| 1118 | } |
| 1119 | |
| 1120 | #[cfg(test)] |
| 1121 | mod tests { |
| 1122 | use super::*; |
| 1123 | use crate::database::init_test_db; |
| 1124 | use crate::domain::user::Username; |
| 1125 | |
| 1126 | |
| 1127 | async fn user(username: &str, role: Role, db: &Database) -> User { |
| 1128 | let user = crate::service::user::create(db, Username::try_new(username).unwrap(), None) |
| 1129 | .await |
| 1130 | .unwrap(); |
| 1131 | crate::service::user::set_role(db, user.get_id(), role) |
| 1132 | .await |
| 1133 | .unwrap() |
| 1134 | .0 |
| 1135 | } |
| 1136 | |
| 1137 | |
| 1138 | |
| 1139 | |
| 1140 | #[tokio::test] |
| 1141 | async fn demoted_slot_owner_loses_management() { |
| 1142 | let (db, _leases) = init_test_db().await; |
| 1143 | let owner = user("ogretmen", Role::Teacher, &db).await; |
| 1144 | let slot = service::appointment_slot::create( |
| 1145 | &db, |
| 1146 | owner.get_id(), |
| 1147 | Timestamp::from_millis(1_000), |
| 1148 | Timestamp::from_millis(2_000), |
| 1149 | None, |
| 1150 | ) |
| 1151 | .await |
| 1152 | .unwrap(); |
| 1153 | assert!(can_manage(&slot, &owner)); |
| 1154 | |
| 1155 | for role in [Role::Student, Role::Parent] { |
| 1156 | let demoted = crate::service::user::set_role(&db, owner.get_id(), role) |
| 1157 | .await |
| 1158 | .unwrap() |
| 1159 | .0; |
| 1160 | assert!( |
| 1161 | !can_manage(&slot, &demoted), |
| 1162 | "{role:?} slot owner still decides its bookings" |
| 1163 | ); |
| 1164 | } |
| 1165 | |
| 1166 | let boss = user("mudur", Role::Manager, &db).await; |
| 1167 | assert!(can_manage(&slot, &boss)); |
| 1168 | } |
| 1169 | |
| 1170 | |
| 1171 | |
| 1172 | |
| 1173 | |
| 1174 | async fn a_state(db: &Database) -> AppState { |
| 1175 | AppState { |
| 1176 | db: db.clone(), |
| 1177 | tenants: crate::database::init_test_tenants().await, |
| 1178 | files_path: std::env::temp_dir(), |
| 1179 | cookie_secure: false, |
| 1180 | rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), |
| 1181 | chatbot_limit: Default::default(), |
| 1182 | rag_limit: Default::default(), |
| 1183 | exam_presence: Default::default(), |
| 1184 | board_hub: Default::default(), |
| 1185 | ai: None, |
| 1186 | metrics: crate::telemetry::Metrics::noop(), |
| 1187 | } |
| 1188 | } |
| 1189 | |
| 1190 | |
| 1191 | async fn a_slot(db: &Database, teacher: &UserId, starts_at: i64, ends_at: i64) { |
| 1192 | service::appointment_slot::create( |
| 1193 | db, |
| 1194 | teacher, |
| 1195 | Timestamp::from_millis(starts_at), |
| 1196 | Timestamp::from_millis(ends_at), |
| 1197 | None, |
| 1198 | ) |
| 1199 | .await |
| 1200 | .unwrap(); |
| 1201 | } |
| 1202 | |
| 1203 | |
| 1204 | async fn slots(st: &AppState, who: &User, filter: SlotFilter) -> Page<SlotResponse> { |
| 1205 | list_slots( |
| 1206 | State(st.clone()), |
| 1207 | CurrentUser(who.clone()), |
| 1208 | Query(PageParams { |
| 1209 | limit: None, |
| 1210 | offset: None, |
| 1211 | }), |
| 1212 | Query(filter), |
| 1213 | ) |
| 1214 | .await |
| 1215 | .unwrap() |
| 1216 | .0 |
| 1217 | } |
| 1218 | |
| 1219 | |
| 1220 | async fn bookings( |
| 1221 | st: &AppState, |
| 1222 | who: &User, |
| 1223 | filter: AppointmentFilter, |
| 1224 | ) -> Page<AppointmentResponse> { |
| 1225 | list_appointments( |
| 1226 | State(st.clone()), |
| 1227 | CurrentUser(who.clone()), |
| 1228 | Query(PageParams { |
| 1229 | limit: None, |
| 1230 | offset: None, |
| 1231 | }), |
| 1232 | Query(filter), |
| 1233 | ) |
| 1234 | .await |
| 1235 | .unwrap() |
| 1236 | .0 |
| 1237 | } |
| 1238 | |
| 1239 | |
| 1240 | |
| 1241 | |
| 1242 | #[test] |
| 1243 | fn filter_words_refuse_blank_malformed_and_negative() { |
| 1244 | let caller = UserId::generate(); |
| 1245 | |
| 1246 | for word in ["", " ", "not-a-uuid"] { |
| 1247 | let filter = SlotFilter { |
| 1248 | teacher: Some(word.into()), |
| 1249 | starts_after: None, |
| 1250 | }; |
| 1251 | assert!( |
| 1252 | matches!( |
| 1253 | filter.resolve_teacher(&caller), |
| 1254 | Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "teacher" |
| 1255 | ), |
| 1256 | "`{word}` must refuse as `teacher`" |
| 1257 | ); |
| 1258 | } |
| 1259 | assert_eq!( |
| 1260 | SlotFilter { |
| 1261 | teacher: Some("me".into()), |
| 1262 | starts_after: None, |
| 1263 | } |
| 1264 | .resolve_teacher(&caller) |
| 1265 | .unwrap(), |
| 1266 | Some(caller) |
| 1267 | ); |
| 1268 | let stranger = UserId::generate(); |
| 1269 | assert_eq!( |
| 1270 | SlotFilter { |
| 1271 | teacher: Some(stranger.key()), |
| 1272 | starts_after: None, |
| 1273 | } |
| 1274 | .resolve_teacher(&caller) |
| 1275 | .unwrap(), |
| 1276 | Some(stranger) |
| 1277 | ); |
| 1278 | |
| 1279 | let filter = SlotFilter { |
| 1280 | teacher: None, |
| 1281 | starts_after: Some(-1), |
| 1282 | }; |
| 1283 | assert!(matches!( |
| 1284 | filter.resolve_starts_after(), |
| 1285 | Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "starts_after" |
| 1286 | )); |
| 1287 | assert_eq!( |
| 1288 | SlotFilter { |
| 1289 | teacher: None, |
| 1290 | starts_after: Some(0), |
| 1291 | } |
| 1292 | .resolve_starts_after() |
| 1293 | .unwrap() |
| 1294 | .map(|instant| instant.as_millis()), |
| 1295 | Some(0) |
| 1296 | ); |
| 1297 | |
| 1298 | let filter = AppointmentFilter { |
| 1299 | status: None, |
| 1300 | starts_after: None, |
| 1301 | starts_before: Some(-5), |
| 1302 | teacher: None, |
| 1303 | }; |
| 1304 | assert!(matches!( |
| 1305 | filter.resolve_starts_before(), |
| 1306 | Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "starts_before" |
| 1307 | )); |
| 1308 | |
| 1309 | |
| 1310 | |
| 1311 | let status = |word: Option<&str>| AppointmentFilter { |
| 1312 | status: word.map(str::to_string), |
| 1313 | starts_after: None, |
| 1314 | starts_before: None, |
| 1315 | teacher: None, |
| 1316 | }; |
| 1317 | assert_eq!(status(None).resolve_status().unwrap(), None); |
| 1318 | assert_eq!( |
| 1319 | status(Some(" pending ")).resolve_status().unwrap(), |
| 1320 | Some(AppointmentStatus::Pending) |
| 1321 | ); |
| 1322 | assert_eq!( |
| 1323 | status(Some("cancelled")).resolve_status().unwrap(), |
| 1324 | Some(AppointmentStatus::Cancelled) |
| 1325 | ); |
| 1326 | for word in ["", " ", "APPROVED", "live", "confirmed"] { |
| 1327 | assert!( |
| 1328 | matches!( |
| 1329 | status(Some(word)).resolve_status(), |
| 1330 | Err(AppError::Validation(ValidationError::Invalid { field, .. })) if field == "status" |
| 1331 | ), |
| 1332 | "`{word}` must refuse as `status`" |
| 1333 | ); |
| 1334 | } |
| 1335 | } |
| 1336 | |
| 1337 | |
| 1338 | |
| 1339 | |
| 1340 | |
| 1341 | |
| 1342 | |
| 1343 | #[tokio::test] |
| 1344 | async fn slot_filters_narrow_without_widening() { |
| 1345 | let (db, _leases) = init_test_db().await; |
| 1346 | let st = a_state(&db).await; |
| 1347 | let now = Timestamp::now().as_millis(); |
| 1348 | let ali = user("ali-ogretmen", Role::Teacher, &db).await; |
| 1349 | let ayse = user("ayse-ogretmen", Role::Teacher, &db).await; |
| 1350 | let veli = user("veli-veli", Role::Student, &db).await; |
| 1351 | |
| 1352 | a_slot(&db, ali.get_id(), now - 10_000, now - 5_000).await; |
| 1353 | a_slot(&db, ali.get_id(), now + 5_000, now + 10_000).await; |
| 1354 | a_slot(&db, ali.get_id(), now + 60_000, now + 90_000).await; |
| 1355 | a_slot(&db, ayse.get_id(), now + 30_000, now + 40_000).await; |
| 1356 | |
| 1357 | let none = || SlotFilter { |
| 1358 | teacher: None, |
| 1359 | starts_after: None, |
| 1360 | }; |
| 1361 | let me = || SlotFilter { |
| 1362 | teacher: Some("me".into()), |
| 1363 | starts_after: None, |
| 1364 | }; |
| 1365 | let of = |who: &UserId| SlotFilter { |
| 1366 | teacher: Some(who.key()), |
| 1367 | starts_after: None, |
| 1368 | }; |
| 1369 | |
| 1370 | |
| 1371 | |
| 1372 | let page = slots(&st, &veli, none()).await; |
| 1373 | assert_eq!(page.total, 3); |
| 1374 | let starts: Vec<i64> = page.items.iter().map(|slot| slot.starts_at).collect(); |
| 1375 | let mut sorted = starts.clone(); |
| 1376 | sorted.sort_unstable(); |
| 1377 | assert_eq!(starts, sorted); |
| 1378 | |
| 1379 | |
| 1380 | |
| 1381 | let page = slots(&st, &veli, me()).await; |
| 1382 | assert_eq!((page.items.len(), page.total), (0, 0)); |
| 1383 | |
| 1384 | |
| 1385 | |
| 1386 | let page = slots(&st, &veli, of(ali.get_id())).await; |
| 1387 | assert_eq!(page.total, 2); |
| 1388 | assert!( |
| 1389 | page.items |
| 1390 | .iter() |
| 1391 | .all(|slot| slot.teacher.id == ali.get_id().key() && slot.starts_at > now) |
| 1392 | ); |
| 1393 | |
| 1394 | |
| 1395 | let page = slots(&st, &veli, of(&UserId::generate())).await; |
| 1396 | assert_eq!((page.items.len(), page.total), (0, 0)); |
| 1397 | |
| 1398 | |
| 1399 | |
| 1400 | let page = slots(&st, &ali, none()).await; |
| 1401 | assert_eq!(page.total, 3); |
| 1402 | |
| 1403 | |
| 1404 | let page = slots(&st, &ali, me()).await; |
| 1405 | assert_eq!(page.total, 3); |
| 1406 | |
| 1407 | |
| 1408 | |
| 1409 | let page = slots(&st, &ali, of(ayse.get_id())).await; |
| 1410 | assert_eq!((page.items.len(), page.total), (0, 0)); |
| 1411 | |
| 1412 | |
| 1413 | |
| 1414 | let page = slots( |
| 1415 | &st, |
| 1416 | &ali, |
| 1417 | SlotFilter { |
| 1418 | teacher: None, |
| 1419 | starts_after: Some(now), |
| 1420 | }, |
| 1421 | ) |
| 1422 | .await; |
| 1423 | assert_eq!(page.total, 2); |
| 1424 | assert!(page.items.iter().all(|slot| slot.starts_at >= now)); |
| 1425 | |
| 1426 | |
| 1427 | let page = slots( |
| 1428 | &st, |
| 1429 | &veli, |
| 1430 | SlotFilter { |
| 1431 | teacher: Some(ayse.get_id().key()), |
| 1432 | starts_after: Some(now), |
| 1433 | }, |
| 1434 | ) |
| 1435 | .await; |
| 1436 | assert_eq!(page.total, 1); |
| 1437 | assert_eq!(page.items[0].starts_at, now + 30_000); |
| 1438 | } |
| 1439 | |
| 1440 | |
| 1441 | |
| 1442 | |
| 1443 | |
| 1444 | #[tokio::test] |
| 1445 | async fn booking_filters_narrow_without_widening() { |
| 1446 | let (db, _leases) = init_test_db().await; |
| 1447 | let st = a_state(&db).await; |
| 1448 | let now = Timestamp::now().as_millis(); |
| 1449 | let ali = user("ali-ogretmen", Role::Teacher, &db).await; |
| 1450 | let ayse = user("ayse-ogretmen", Role::Teacher, &db).await; |
| 1451 | let veli = user("veli-veli", Role::Student, &db).await; |
| 1452 | let reason = AppointmentReason::try_new("görüşme").unwrap(); |
| 1453 | |
| 1454 | let ali_slot = service::appointment_slot::create( |
| 1455 | &db, |
| 1456 | ali.get_id(), |
| 1457 | Timestamp::from_millis(now + 60_000), |
| 1458 | Timestamp::from_millis(now + 120_000), |
| 1459 | None, |
| 1460 | ) |
| 1461 | .await |
| 1462 | .unwrap(); |
| 1463 | let ayse_slot = service::appointment_slot::create( |
| 1464 | &db, |
| 1465 | ayse.get_id(), |
| 1466 | Timestamp::from_millis(now + 200_000), |
| 1467 | Timestamp::from_millis(now + 260_000), |
| 1468 | None, |
| 1469 | ) |
| 1470 | .await |
| 1471 | .unwrap(); |
| 1472 | let pending = |
| 1473 | service::appointment::book(&db, ali_slot.get_id(), veli.get_id(), reason.clone()) |
| 1474 | .await |
| 1475 | .unwrap(); |
| 1476 | let approved = |
| 1477 | service::appointment::book(&db, ayse_slot.get_id(), veli.get_id(), reason.clone()) |
| 1478 | .await |
| 1479 | .unwrap(); |
| 1480 | service::appointment::approve(&db, approved.get_id(), ayse.get_id()) |
| 1481 | .await |
| 1482 | .unwrap(); |
| 1483 | |
| 1484 | let none = || AppointmentFilter { |
| 1485 | status: None, |
| 1486 | starts_after: None, |
| 1487 | starts_before: None, |
| 1488 | teacher: None, |
| 1489 | }; |
| 1490 | let status = |word: &str| AppointmentFilter { |
| 1491 | status: Some(word.into()), |
| 1492 | starts_after: None, |
| 1493 | starts_before: None, |
| 1494 | teacher: None, |
| 1495 | }; |
| 1496 | let after = |millis: i64| AppointmentFilter { |
| 1497 | status: None, |
| 1498 | starts_after: Some(millis), |
| 1499 | starts_before: None, |
| 1500 | teacher: None, |
| 1501 | }; |
| 1502 | let with_teacher = |who: &User| AppointmentFilter { |
| 1503 | status: None, |
| 1504 | starts_after: None, |
| 1505 | starts_before: None, |
| 1506 | teacher: Some(who.get_id().key()), |
| 1507 | }; |
| 1508 | |
| 1509 | |
| 1510 | let page = bookings(&st, &veli, none()).await; |
| 1511 | assert_eq!(page.total, 2); |
| 1512 | |
| 1513 | |
| 1514 | let page = bookings(&st, &veli, status("approved")).await; |
| 1515 | assert_eq!(page.total, 1); |
| 1516 | assert_eq!(page.items[0].id, approved.get_id().key()); |
| 1517 | assert_eq!(page.items[0].status, "approved"); |
| 1518 | |
| 1519 | |
| 1520 | let page = bookings(&st, &veli, status("rejected")).await; |
| 1521 | assert_eq!((page.items.len(), page.total), (0, 0)); |
| 1522 | |
| 1523 | |
| 1524 | let page = bookings(&st, &veli, with_teacher(&ali)).await; |
| 1525 | assert_eq!(page.total, 1); |
| 1526 | assert_eq!(page.items[0].id, pending.get_id().key()); |
| 1527 | |
| 1528 | |
| 1529 | |
| 1530 | let page = bookings(&st, &veli, after(now + 150_000)).await; |
| 1531 | assert_eq!(page.total, 1); |
| 1532 | assert_eq!(page.items[0].id, approved.get_id().key()); |
| 1533 | |
| 1534 | |
| 1535 | |
| 1536 | let page = bookings( |
| 1537 | &st, |
| 1538 | &veli, |
| 1539 | AppointmentFilter { |
| 1540 | status: None, |
| 1541 | starts_after: None, |
| 1542 | starts_before: Some(now + 150_000), |
| 1543 | teacher: None, |
| 1544 | }, |
| 1545 | ) |
| 1546 | .await; |
| 1547 | assert_eq!(page.total, 1); |
| 1548 | assert_eq!(page.items[0].id, pending.get_id().key()); |
| 1549 | |
| 1550 | |
| 1551 | let page = bookings(&st, &ali, none()).await; |
| 1552 | assert_eq!(page.total, 1); |
| 1553 | assert_eq!(page.items[0].id, pending.get_id().key()); |
| 1554 | |
| 1555 | |
| 1556 | let page = bookings(&st, &ali, with_teacher(&ali)).await; |
| 1557 | assert_eq!(page.total, 1); |
| 1558 | |
| 1559 | |
| 1560 | let page = bookings(&st, &ali, with_teacher(&ayse)).await; |
| 1561 | assert_eq!((page.items.len(), page.total), (0, 0)); |
| 1562 | |
| 1563 | |
| 1564 | |
| 1565 | let page = bookings(&st, &ali, after(now + 150_000)).await; |
| 1566 | assert_eq!((page.items.len(), page.total), (0, 0)); |
| 1567 | let page = bookings(&st, &ayse, after(now + 150_000)).await; |
| 1568 | assert_eq!(page.total, 1); |
| 1569 | } |
| 1570 | } |