| 1 | use std::collections::HashMap; |
| 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::ToSchema; |
| 9 | use utoipa_axum::router::OpenApiRouter; |
| 10 | use utoipa_axum::routes; |
| 11 | |
| 12 | use crate::database::Database; |
| 13 | use crate::domain::attendance::{Attendance, AttendanceStatus}; |
| 14 | use crate::domain::class_group::ClassGroupId; |
| 15 | use crate::domain::course::CourseId; |
| 16 | use crate::domain::event::{ |
| 17 | Event, EventAudience, EventAudienceKind, EventDescription, EventId, EventTitle, |
| 18 | }; |
| 19 | use crate::domain::role::Role; |
| 20 | use crate::domain::timestamp::Timestamp; |
| 21 | use crate::domain::user::{User, UserId}; |
| 22 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 23 | use crate::service; |
| 24 | use crate::state::AppState; |
| 25 | |
| 26 | use super::{ |
| 27 | CurrentUser, Page, PageParams, PersonRef, RequireTeacher, WindowParams, check_not_past, |
| 28 | check_time_range, paginate, person_map, set_or_clear, |
| 29 | }; |
| 30 | |
| 31 | pub fn routes() -> OpenApiRouter<AppState> { |
| 32 | OpenApiRouter::new() |
| 33 | .routes(routes!(create_event, list_events)) |
| 34 | .routes(routes!(get_event, update_event, delete_event)) |
| 35 | .routes(routes!(mark, list_attendance)) |
| 36 | .routes(routes!(remove_attendance)) |
| 37 | .routes(routes!(roster)) |
| 38 | .routes(routes!(register)) |
| 39 | .routes(routes!(unregister)) |
| 40 | } |
| 41 | |
| 42 | |
| 43 | |
| 44 | #[derive(Serialize, Deserialize, Clone, ToSchema)] |
| 45 | #[serde(tag = "kind", rename_all = "lowercase")] |
| 46 | enum AudienceDto { |
| 47 | |
| 48 | |
| 49 | School, |
| 50 | |
| 51 | |
| 52 | Role { role: String }, |
| 53 | |
| 54 | |
| 55 | Course { course: String }, |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | Class { class: String }, |
| 61 | |
| 62 | |
| 63 | |
| 64 | Registration { |
| 65 | #[serde(default)] |
| 66 | capacity: Option<i64>, |
| 67 | }, |
| 68 | } |
| 69 | |
| 70 | impl AudienceDto { |
| 71 | |
| 72 | |
| 73 | async fn into_domain(self, db: &Database) -> Result<EventAudience, AppError> { |
| 74 | Ok(match self { |
| 75 | AudienceDto::School => EventAudience { |
| 76 | kind: EventAudienceKind::School, |
| 77 | role: None, |
| 78 | course: None, |
| 79 | class: None, |
| 80 | capacity: None, |
| 81 | }, |
| 82 | AudienceDto::Role { role } => EventAudience { |
| 83 | kind: EventAudienceKind::Role, |
| 84 | role: Some(Role::try_from_str(&role)?), |
| 85 | course: None, |
| 86 | class: None, |
| 87 | capacity: None, |
| 88 | }, |
| 89 | AudienceDto::Course { course } => { |
| 90 | let course = CourseId::from_key(&course); |
| 91 | if crate::service::course::read(db, &course).await?.is_none() { |
| 92 | return Err(AppError::Validation(ValidationError::Invalid { |
| 93 | field: "audience", |
| 94 | reason: "course does not exist", |
| 95 | })); |
| 96 | } |
| 97 | EventAudience { |
| 98 | kind: EventAudienceKind::Course, |
| 99 | role: None, |
| 100 | course: Some(course), |
| 101 | class: None, |
| 102 | capacity: None, |
| 103 | } |
| 104 | } |
| 105 | AudienceDto::Class { class } => { |
| 106 | let class = ClassGroupId::from_key(&class); |
| 107 | if crate::service::class_group::read(db, &class) |
| 108 | .await? |
| 109 | .is_none() |
| 110 | { |
| 111 | return Err(AppError::Validation(ValidationError::Invalid { |
| 112 | field: "audience", |
| 113 | reason: "class does not exist", |
| 114 | })); |
| 115 | } |
| 116 | EventAudience { |
| 117 | kind: EventAudienceKind::Class, |
| 118 | role: None, |
| 119 | course: None, |
| 120 | class: Some(class), |
| 121 | capacity: None, |
| 122 | } |
| 123 | } |
| 124 | AudienceDto::Registration { capacity } => { |
| 125 | if capacity.is_some_and(|capacity| capacity < 1) { |
| 126 | return Err(AppError::Validation(ValidationError::Invalid { |
| 127 | field: "audience", |
| 128 | reason: "capacity must be at least 1", |
| 129 | })); |
| 130 | } |
| 131 | EventAudience { |
| 132 | kind: EventAudienceKind::Registration, |
| 133 | role: None, |
| 134 | course: None, |
| 135 | class: None, |
| 136 | capacity, |
| 137 | } |
| 138 | } |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | fn from_domain(audience: &EventAudience) -> Self { |
| 143 | match audience.kind { |
| 144 | EventAudienceKind::School => AudienceDto::School, |
| 145 | EventAudienceKind::Role => AudienceDto::Role { |
| 146 | role: audience |
| 147 | .role |
| 148 | .map(|role| role.as_str().to_string()) |
| 149 | .unwrap_or_default(), |
| 150 | }, |
| 151 | EventAudienceKind::Course => AudienceDto::Course { |
| 152 | course: audience |
| 153 | .course |
| 154 | .as_ref() |
| 155 | .map(|course| course.key()) |
| 156 | .unwrap_or_default(), |
| 157 | }, |
| 158 | EventAudienceKind::Class => AudienceDto::Class { |
| 159 | class: audience |
| 160 | .class |
| 161 | .as_ref() |
| 162 | .map(|class| class.key()) |
| 163 | .unwrap_or_default(), |
| 164 | }, |
| 165 | EventAudienceKind::Registration => AudienceDto::Registration { |
| 166 | capacity: audience.capacity, |
| 167 | }, |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | #[derive(Deserialize, ToSchema)] |
| 173 | struct CreateEvent { |
| 174 | #[schema(max_length = 200, example = "Sprint demo")] |
| 175 | title: String, |
| 176 | #[schema(max_length = 2000)] |
| 177 | description: Option<String>, |
| 178 | |
| 179 | |
| 180 | audience: Option<AudienceDto>, |
| 181 | |
| 182 | #[schema(example = 1_900_000_000_000_i64)] |
| 183 | starts_at: Option<i64>, |
| 184 | ends_at: Option<i64>, |
| 185 | } |
| 186 | |
| 187 | #[derive(Deserialize, ToSchema)] |
| 188 | struct UpdateEvent { |
| 189 | #[schema(max_length = 200)] |
| 190 | title: Option<String>, |
| 191 | #[schema(max_length = 2000)] |
| 192 | description: Option<String>, |
| 193 | |
| 194 | |
| 195 | |
| 196 | audience: Option<AudienceDto>, |
| 197 | |
| 198 | |
| 199 | #[serde(default, deserialize_with = "set_or_clear")] |
| 200 | #[schema(value_type = Option<i64>)] |
| 201 | starts_at: Option<Option<i64>>, |
| 202 | |
| 203 | |
| 204 | #[serde(default, deserialize_with = "set_or_clear")] |
| 205 | #[schema(value_type = Option<i64>)] |
| 206 | ends_at: Option<Option<i64>>, |
| 207 | } |
| 208 | |
| 209 | #[derive(Deserialize, ToSchema)] |
| 210 | struct MarkAttendance { |
| 211 | |
| 212 | |
| 213 | #[schema(max_length = 50, example = "present")] |
| 214 | status: String, |
| 215 | |
| 216 | |
| 217 | user_id: Option<String>, |
| 218 | } |
| 219 | |
| 220 | #[derive(Serialize, ToSchema)] |
| 221 | struct EventResponse { |
| 222 | id: String, |
| 223 | creator: String, |
| 224 | title: String, |
| 225 | description: String, |
| 226 | audience: AudienceDto, |
| 227 | starts_at: Option<i64>, |
| 228 | ends_at: Option<i64>, |
| 229 | } |
| 230 | |
| 231 | impl EventResponse { |
| 232 | fn new(event: &Event) -> Self { |
| 233 | Self { |
| 234 | id: event.get_id().key().to_string(), |
| 235 | creator: event.get_creator().key().to_string(), |
| 236 | title: event.get_title().as_str().to_string(), |
| 237 | description: event.get_description().as_str().to_string(), |
| 238 | audience: AudienceDto::from_domain(&EventAudience::of_row(event)), |
| 239 | starts_at: event.get_starts_at().map(|t| t.as_millis()), |
| 240 | ends_at: event.get_ends_at().map(|t| t.as_millis()), |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | fn can_manage(event: &Event, user: &User) -> bool { |
| 256 | user.get_role().at_least(Role::Teacher) |
| 257 | && (event.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager)) |
| 258 | } |
| 259 | |
| 260 | #[derive(Serialize, ToSchema)] |
| 261 | struct AttendanceResponse { |
| 262 | id: String, |
| 263 | event: String, |
| 264 | |
| 265 | user: PersonRef, |
| 266 | status: String, |
| 267 | |
| 268 | marked_by: PersonRef, |
| 269 | } |
| 270 | |
| 271 | impl AttendanceResponse { |
| 272 | fn new(attendance: &Attendance, people: &HashMap<String, PersonRef>) -> Self { |
| 273 | Self { |
| 274 | id: attendance.get_id().key().to_string(), |
| 275 | event: attendance.get_event().key().to_string(), |
| 276 | user: PersonRef::resolve(people, attendance.get_user()), |
| 277 | status: attendance.get_status().as_str().to_string(), |
| 278 | marked_by: PersonRef::resolve(people, attendance.get_marked_by()), |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | #[utoipa::path( |
| 292 | post, |
| 293 | path = "/", |
| 294 | tag = "events", |
| 295 | security(("session_cookie" = [])), |
| 296 | request_body = CreateEvent, |
| 297 | responses( |
| 298 | (status = 201, description = "Event created", body = EventResponse), |
| 299 | (status = 400, description = "Invalid fields, audience, time range, or times in the past", body = ErrorResponse), |
| 300 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 301 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 302 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 303 | ), |
| 304 | )] |
| 305 | async fn create_event( |
| 306 | State(st): State<AppState>, |
| 307 | RequireTeacher(user): RequireTeacher, |
| 308 | Json(req): Json<CreateEvent>, |
| 309 | ) -> Result<(StatusCode, Json<EventResponse>), AppError> { |
| 310 | let title = EventTitle::try_new(&req.title)?; |
| 311 | let description = EventDescription::try_new(&req.description.unwrap_or_default())?; |
| 312 | let audience = match req.audience { |
| 313 | Some(audience) => audience.into_domain(&st.db).await?, |
| 314 | None => EventAudience { |
| 315 | kind: EventAudienceKind::School, |
| 316 | role: None, |
| 317 | course: None, |
| 318 | class: None, |
| 319 | capacity: None, |
| 320 | }, |
| 321 | }; |
| 322 | let starts_at = req.starts_at.map(Timestamp::from_millis); |
| 323 | let ends_at = req.ends_at.map(Timestamp::from_millis); |
| 324 | check_not_past("starts_at", starts_at)?; |
| 325 | check_not_past("ends_at", ends_at)?; |
| 326 | check_time_range(starts_at, ends_at)?; |
| 327 | let event = service::event::create( |
| 328 | &st.db, |
| 329 | user.get_id(), |
| 330 | title, |
| 331 | description, |
| 332 | audience, |
| 333 | starts_at, |
| 334 | ends_at, |
| 335 | ) |
| 336 | .await?; |
| 337 | Ok((StatusCode::CREATED, Json(EventResponse::new(&event)))) |
| 338 | } |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | #[utoipa::path( |
| 352 | get, |
| 353 | path = "/", |
| 354 | tag = "events", |
| 355 | security(("session_cookie" = [])), |
| 356 | params(WindowParams, PageParams), |
| 357 | responses( |
| 358 | (status = 200, description = "A page of events (all of them when unpaged)", body = Page<EventResponse>), |
| 359 | (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse), |
| 360 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 361 | ), |
| 362 | )] |
| 363 | async fn list_events( |
| 364 | State(st): State<AppState>, |
| 365 | _user: CurrentUser, |
| 366 | Query(window): Query<WindowParams>, |
| 367 | Query(page): Query<PageParams>, |
| 368 | ) -> Result<Json<Page<EventResponse>>, AppError> { |
| 369 | let (limit, offset) = page.resolve()?; |
| 370 | window.validate()?; |
| 371 | |
| 372 | |
| 373 | let (events, total) = service::event::list_windowed( |
| 374 | &st.db, |
| 375 | window.starts_after, |
| 376 | window.ends_after, |
| 377 | window.starts_before, |
| 378 | window.ends_before, |
| 379 | limit, |
| 380 | offset, |
| 381 | ) |
| 382 | .await?; |
| 383 | let items = events.iter().map(EventResponse::new).collect(); |
| 384 | Ok(Json(Page::new(items, total, limit, offset))) |
| 385 | } |
| 386 | |
| 387 | |
| 388 | #[utoipa::path( |
| 389 | get, |
| 390 | path = "/{id}", |
| 391 | tag = "events", |
| 392 | security(("session_cookie" = [])), |
| 393 | params(("id" = String, Path, description = "Event id")), |
| 394 | responses( |
| 395 | (status = 200, description = "The event", body = EventResponse), |
| 396 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 397 | (status = 404, description = "Not found", body = ErrorResponse), |
| 398 | ), |
| 399 | )] |
| 400 | async fn get_event( |
| 401 | State(st): State<AppState>, |
| 402 | _user: CurrentUser, |
| 403 | Path(id): Path<String>, |
| 404 | ) -> Result<Json<EventResponse>, AppError> { |
| 405 | let event = service::event::read(&st.db, &EventId::from_key(&id)) |
| 406 | .await? |
| 407 | .ok_or(AppError::NotFound)?; |
| 408 | Ok(Json(EventResponse::new(&event))) |
| 409 | } |
| 410 | |
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | #[utoipa::path( |
| 418 | patch, |
| 419 | path = "/{id}", |
| 420 | tag = "events", |
| 421 | security(("session_cookie" = [])), |
| 422 | params(("id" = String, Path, description = "Event id")), |
| 423 | request_body = UpdateEvent, |
| 424 | responses( |
| 425 | (status = 200, description = "Updated event", body = EventResponse), |
| 426 | (status = 400, description = "Invalid fields, audience, time range, or times in the past", body = ErrorResponse), |
| 427 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 428 | (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), |
| 429 | (status = 404, description = "Not found", body = ErrorResponse), |
| 430 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 431 | ), |
| 432 | )] |
| 433 | async fn update_event( |
| 434 | State(st): State<AppState>, |
| 435 | RequireTeacher(user): RequireTeacher, |
| 436 | Path(id): Path<String>, |
| 437 | Json(req): Json<UpdateEvent>, |
| 438 | ) -> Result<Json<EventResponse>, AppError> { |
| 439 | |
| 440 | |
| 441 | |
| 442 | let starts_at = req |
| 443 | .starts_at |
| 444 | .map(|update| update.map(Timestamp::from_millis)); |
| 445 | let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis)); |
| 446 | let event = service::event::read(&st.db, &EventId::from_key(&id)) |
| 447 | .await? |
| 448 | .ok_or(AppError::NotFound)?; |
| 449 | if !can_manage(&event, &user) { |
| 450 | return Err(AppError::Forbidden( |
| 451 | "only the creator or a manager/admin can edit this event", |
| 452 | )); |
| 453 | } |
| 454 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | |
| 460 | let title = req.title.as_deref().map(EventTitle::try_new).transpose()?; |
| 461 | let description = req |
| 462 | .description |
| 463 | .as_deref() |
| 464 | .map(EventDescription::try_new) |
| 465 | .transpose()?; |
| 466 | let audience = match req.audience { |
| 467 | Some(audience) => Some(audience.into_domain(&st.db).await?), |
| 468 | None => None, |
| 469 | }; |
| 470 | |
| 471 | |
| 472 | if let Some(starts_at) = starts_at { |
| 473 | check_not_past("starts_at", starts_at)?; |
| 474 | } |
| 475 | if let Some(ends_at) = ends_at { |
| 476 | check_not_past("ends_at", ends_at)?; |
| 477 | } |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | check_time_range( |
| 483 | starts_at.unwrap_or_else(|| event.get_starts_at()), |
| 484 | ends_at.unwrap_or_else(|| event.get_ends_at()), |
| 485 | )?; |
| 486 | |
| 487 | let updated = service::event::update( |
| 488 | &st.db, |
| 489 | event, |
| 490 | title, |
| 491 | description, |
| 492 | audience, |
| 493 | starts_at, |
| 494 | ends_at, |
| 495 | ) |
| 496 | .await?; |
| 497 | Ok(Json(EventResponse::new(&updated))) |
| 498 | } |
| 499 | |
| 500 | |
| 501 | |
| 502 | #[utoipa::path( |
| 503 | delete, |
| 504 | path = "/{id}", |
| 505 | tag = "events", |
| 506 | security(("session_cookie" = [])), |
| 507 | params(("id" = String, Path, description = "Event id")), |
| 508 | responses( |
| 509 | (status = 204, description = "Deleted"), |
| 510 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 511 | (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), |
| 512 | (status = 404, description = "Not found", body = ErrorResponse), |
| 513 | ), |
| 514 | )] |
| 515 | async fn delete_event( |
| 516 | State(st): State<AppState>, |
| 517 | RequireTeacher(user): RequireTeacher, |
| 518 | Path(id): Path<String>, |
| 519 | ) -> Result<StatusCode, AppError> { |
| 520 | let event = service::event::read(&st.db, &EventId::from_key(&id)) |
| 521 | .await? |
| 522 | .ok_or(AppError::NotFound)?; |
| 523 | if !can_manage(&event, &user) { |
| 524 | return Err(AppError::Forbidden( |
| 525 | "only the creator or a manager/admin can delete this event", |
| 526 | )); |
| 527 | } |
| 528 | service::event::delete(&st.db, event).await?; |
| 529 | Ok(StatusCode::NO_CONTENT) |
| 530 | } |
| 531 | |
| 532 | |
| 533 | |
| 534 | |
| 535 | |
| 536 | |
| 537 | #[utoipa::path( |
| 538 | post, |
| 539 | path = "/{id}/attendance", |
| 540 | tag = "events", |
| 541 | security(("session_cookie" = [])), |
| 542 | params(("id" = String, Path, description = "Event id")), |
| 543 | request_body = MarkAttendance, |
| 544 | responses( |
| 545 | (status = 200, description = "Attendance recorded", body = AttendanceResponse), |
| 546 | (status = 400, description = "Invalid status, unknown user, or target outside the event's audience", body = ErrorResponse), |
| 547 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 548 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 549 | (status = 404, description = "Event not found", body = ErrorResponse), |
| 550 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 551 | ), |
| 552 | )] |
| 553 | async fn mark( |
| 554 | State(st): State<AppState>, |
| 555 | RequireTeacher(user): RequireTeacher, |
| 556 | Path(id): Path<String>, |
| 557 | Json(req): Json<MarkAttendance>, |
| 558 | ) -> Result<Json<AttendanceResponse>, AppError> { |
| 559 | let event_id = EventId::from_key(&id); |
| 560 | let event = service::event::read(&st.db, &event_id) |
| 561 | .await? |
| 562 | .ok_or(AppError::NotFound)?; |
| 563 | |
| 564 | let school = service::settings::load(&st.db).await?; |
| 565 | let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; |
| 566 | let target = match req.user_id { |
| 567 | Some(ref key) => UserId::from_key(key), |
| 568 | None => *user.get_id(), |
| 569 | }; |
| 570 | |
| 571 | |
| 572 | let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { |
| 573 | return Err(AppError::Validation(ValidationError::Invalid { |
| 574 | field: "user_id", |
| 575 | reason: "target user does not exist", |
| 576 | })); |
| 577 | }; |
| 578 | |
| 579 | |
| 580 | |
| 581 | if !service::event::includes(&st.db, &event, &target_user).await? { |
| 582 | return Err(AppError::Validation(ValidationError::Invalid { |
| 583 | field: "user_id", |
| 584 | reason: "target user is not in this event's audience", |
| 585 | })); |
| 586 | } |
| 587 | |
| 588 | let attendance = |
| 589 | crate::service::attendance::mark(&st.db, &event_id, &target, status, user.get_id()).await?; |
| 590 | let people = PersonRef::map_of(&[&target_user, &user]); |
| 591 | Ok(Json(AttendanceResponse::new(&attendance, &people))) |
| 592 | } |
| 593 | |
| 594 | |
| 595 | |
| 596 | |
| 597 | |
| 598 | #[utoipa::path( |
| 599 | get, |
| 600 | path = "/{id}/attendance", |
| 601 | tag = "events", |
| 602 | security(("session_cookie" = [])), |
| 603 | params(("id" = String, Path, description = "Event id"), PageParams), |
| 604 | responses( |
| 605 | (status = 200, description = "A page of the attendance roster (all of it when unpaged)", body = Page<AttendanceResponse>), |
| 606 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 607 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 608 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 609 | (status = 404, description = "Event not found", body = ErrorResponse), |
| 610 | ), |
| 611 | )] |
| 612 | async fn list_attendance( |
| 613 | State(st): State<AppState>, |
| 614 | _teacher: RequireTeacher, |
| 615 | Path(id): Path<String>, |
| 616 | Query(page): Query<PageParams>, |
| 617 | ) -> Result<Json<Page<AttendanceResponse>>, AppError> { |
| 618 | let (limit, offset) = page.resolve()?; |
| 619 | let event_id = EventId::from_key(&id); |
| 620 | |
| 621 | service::event::read(&st.db, &event_id) |
| 622 | .await? |
| 623 | .ok_or(AppError::NotFound)?; |
| 624 | let (rows, total) = |
| 625 | crate::service::attendance::list_for_event(&st.db, &event_id, limit, offset).await?; |
| 626 | |
| 627 | let people = person_map( |
| 628 | rows.iter() |
| 629 | .flat_map(|a| [*a.get_user(), *a.get_marked_by()]), |
| 630 | &st.db, |
| 631 | ) |
| 632 | .await?; |
| 633 | let items = rows |
| 634 | .iter() |
| 635 | .map(|a| AttendanceResponse::new(a, &people)) |
| 636 | .collect(); |
| 637 | Ok(Json(Page::new(items, total, limit, offset))) |
| 638 | } |
| 639 | |
| 640 | |
| 641 | #[utoipa::path( |
| 642 | delete, |
| 643 | path = "/{id}/attendance/{user}", |
| 644 | tag = "events", |
| 645 | security(("session_cookie" = [])), |
| 646 | params( |
| 647 | ("id" = String, Path, description = "Event id"), |
| 648 | ("user" = String, Path, description = "User id"), |
| 649 | ), |
| 650 | responses( |
| 651 | (status = 204, description = "Removed"), |
| 652 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 653 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 654 | (status = 404, description = "Not found", body = ErrorResponse), |
| 655 | ), |
| 656 | )] |
| 657 | async fn remove_attendance( |
| 658 | State(st): State<AppState>, |
| 659 | _teacher: RequireTeacher, |
| 660 | Path((id, target)): Path<(String, String)>, |
| 661 | ) -> Result<StatusCode, AppError> { |
| 662 | let removed = crate::service::attendance::remove( |
| 663 | &st.db, |
| 664 | &EventId::from_key(&id), |
| 665 | &UserId::from_key(&target), |
| 666 | ) |
| 667 | .await?; |
| 668 | if removed.is_none() { |
| 669 | return Err(AppError::NotFound); |
| 670 | } |
| 671 | Ok(StatusCode::NO_CONTENT) |
| 672 | } |
| 673 | |
| 674 | |
| 675 | |
| 676 | |
| 677 | |
| 678 | #[derive(Serialize, ToSchema)] |
| 679 | struct RosterEntry { |
| 680 | user: PersonRef, |
| 681 | |
| 682 | |
| 683 | status: Option<String>, |
| 684 | |
| 685 | marked_by: Option<PersonRef>, |
| 686 | } |
| 687 | |
| 688 | |
| 689 | |
| 690 | |
| 691 | |
| 692 | |
| 693 | |
| 694 | |
| 695 | |
| 696 | #[utoipa::path( |
| 697 | get, |
| 698 | path = "/{id}/roster", |
| 699 | tag = "events", |
| 700 | security(("session_cookie" = [])), |
| 701 | params(("id" = String, Path, description = "Event id"), PageParams), |
| 702 | responses( |
| 703 | (status = 200, description = "A page of the expected-attendee roster (all of it when unpaged)", body = Page<RosterEntry>), |
| 704 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 705 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 706 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 707 | (status = 404, description = "Event not found", body = ErrorResponse), |
| 708 | ), |
| 709 | )] |
| 710 | async fn roster( |
| 711 | State(st): State<AppState>, |
| 712 | _teacher: RequireTeacher, |
| 713 | Path(id): Path<String>, |
| 714 | Query(page): Query<PageParams>, |
| 715 | ) -> Result<Json<Page<RosterEntry>>, AppError> { |
| 716 | let (limit, offset) = page.resolve()?; |
| 717 | let event_id = EventId::from_key(&id); |
| 718 | let event = service::event::read(&st.db, &event_id) |
| 719 | .await? |
| 720 | .ok_or(AppError::NotFound)?; |
| 721 | |
| 722 | let mut members = service::event::members(&st.db, &event).await?; |
| 723 | |
| 724 | members.sort_by_key(|a| a.key()); |
| 725 | let (marks, _) = crate::service::attendance::list_for_event(&st.db, &event_id, None, 0).await?; |
| 726 | let by_user: HashMap<String, &Attendance> = marks |
| 727 | .iter() |
| 728 | .map(|attendance| (attendance.get_user().key(), attendance)) |
| 729 | .collect(); |
| 730 | |
| 731 | let total = members.len() as i64; |
| 732 | |
| 733 | |
| 734 | let window = paginate(&members, limit, offset); |
| 735 | let ids = window.iter().cloned().chain(window.iter().filter_map(|m| { |
| 736 | by_user |
| 737 | .get(m.key().as_str()) |
| 738 | .map(|attendance| *attendance.get_marked_by()) |
| 739 | })); |
| 740 | let people = person_map(ids, &st.db).await?; |
| 741 | let items = window |
| 742 | .iter() |
| 743 | .map(|member| { |
| 744 | let mark = by_user.get(member.key().as_str()); |
| 745 | RosterEntry { |
| 746 | user: PersonRef::resolve(&people, member), |
| 747 | status: mark.map(|attendance| attendance.get_status().as_str().to_string()), |
| 748 | marked_by: mark |
| 749 | .map(|attendance| PersonRef::resolve(&people, attendance.get_marked_by())), |
| 750 | } |
| 751 | }) |
| 752 | .collect(); |
| 753 | Ok(Json(Page::new(items, total, limit, offset))) |
| 754 | } |
| 755 | |
| 756 | |
| 757 | |
| 758 | #[derive(Deserialize, ToSchema)] |
| 759 | struct RegisterUser { |
| 760 | |
| 761 | |
| 762 | user_id: Option<String>, |
| 763 | } |
| 764 | |
| 765 | #[derive(Serialize, ToSchema)] |
| 766 | struct RegistrationResponse { |
| 767 | event: String, |
| 768 | |
| 769 | user: PersonRef, |
| 770 | |
| 771 | registered_by: PersonRef, |
| 772 | } |
| 773 | |
| 774 | |
| 775 | |
| 776 | |
| 777 | |
| 778 | |
| 779 | |
| 780 | |
| 781 | #[utoipa::path( |
| 782 | post, |
| 783 | path = "/{id}/register", |
| 784 | tag = "events", |
| 785 | security(("session_cookie" = [])), |
| 786 | params(("id" = String, Path, description = "Event id")), |
| 787 | request_body = RegisterUser, |
| 788 | responses( |
| 789 | (status = 200, description = "Seat taken (or already held)", body = RegistrationResponse), |
| 790 | (status = 400, description = "Not a registration event, or the target is unknown", body = ErrorResponse), |
| 791 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 792 | (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), |
| 793 | (status = 404, description = "Event not found", body = ErrorResponse), |
| 794 | (status = 409, description = "The event is full, or it already started or ended", body = ErrorResponse), |
| 795 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 796 | ), |
| 797 | )] |
| 798 | async fn register( |
| 799 | State(st): State<AppState>, |
| 800 | RequireTeacher(user): RequireTeacher, |
| 801 | Path(id): Path<String>, |
| 802 | Json(req): Json<RegisterUser>, |
| 803 | ) -> Result<Json<RegistrationResponse>, AppError> { |
| 804 | let event_id = EventId::from_key(&id); |
| 805 | let event = service::event::read(&st.db, &event_id) |
| 806 | .await? |
| 807 | .ok_or(AppError::NotFound)?; |
| 808 | |
| 809 | |
| 810 | event.registration_capacity()?; |
| 811 | |
| 812 | let target = match req.user_id { |
| 813 | Some(ref key) => UserId::from_key(key), |
| 814 | None => *user.get_id(), |
| 815 | }; |
| 816 | let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { |
| 817 | return Err(AppError::Validation(ValidationError::Invalid { |
| 818 | field: "user_id", |
| 819 | reason: "target user does not exist", |
| 820 | })); |
| 821 | }; |
| 822 | |
| 823 | if &target != user.get_id() && target_user.get_role() != Role::Student { |
| 824 | return Err(AppError::Forbidden( |
| 825 | "staff register themselves — only students can be registered for", |
| 826 | )); |
| 827 | } |
| 828 | |
| 829 | let registration = |
| 830 | crate::service::registration::register(&st.db, &event_id, &target, user.get_id()).await?; |
| 831 | |
| 832 | |
| 833 | |
| 834 | let people = person_map( |
| 835 | [*registration.get_user(), *registration.get_registered_by()], |
| 836 | &st.db, |
| 837 | ) |
| 838 | .await?; |
| 839 | Ok(Json(RegistrationResponse { |
| 840 | event: registration.get_event().key().to_string(), |
| 841 | user: PersonRef::resolve(&people, registration.get_user()), |
| 842 | registered_by: PersonRef::resolve(&people, registration.get_registered_by()), |
| 843 | })) |
| 844 | } |
| 845 | |
| 846 | |
| 847 | |
| 848 | |
| 849 | |
| 850 | |
| 851 | |
| 852 | |
| 853 | #[utoipa::path( |
| 854 | delete, |
| 855 | path = "/{id}/register/{user}", |
| 856 | tag = "events", |
| 857 | security(("session_cookie" = [])), |
| 858 | params( |
| 859 | ("id" = String, Path, description = "Event id"), |
| 860 | ("user" = String, Path, description = "User id"), |
| 861 | ), |
| 862 | responses( |
| 863 | (status = 204, description = "Seat freed"), |
| 864 | (status = 400, description = "Not a registration event", body = ErrorResponse), |
| 865 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 866 | (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), |
| 867 | (status = 404, description = "Event not found, or the user holds no seat", body = ErrorResponse), |
| 868 | (status = 409, description = "The event already started or ended", body = ErrorResponse), |
| 869 | ), |
| 870 | )] |
| 871 | async fn unregister( |
| 872 | State(st): State<AppState>, |
| 873 | RequireTeacher(user): RequireTeacher, |
| 874 | Path((id, target)): Path<(String, String)>, |
| 875 | ) -> Result<StatusCode, AppError> { |
| 876 | let event_id = EventId::from_key(&id); |
| 877 | let event = service::event::read(&st.db, &event_id) |
| 878 | .await? |
| 879 | .ok_or(AppError::NotFound)?; |
| 880 | event.registration_capacity()?; |
| 881 | |
| 882 | let target = UserId::from_key(&target); |
| 883 | |
| 884 | |
| 885 | |
| 886 | |
| 887 | |
| 888 | |
| 889 | if &target != user.get_id() |
| 890 | && let Some(target_user) = crate::service::user::read(&st.db, &target).await? |
| 891 | && target_user.get_role().at_least(Role::Teacher) |
| 892 | { |
| 893 | return Err(AppError::Forbidden( |
| 894 | "staff unregister themselves — only students' seats can be freed", |
| 895 | )); |
| 896 | } |
| 897 | |
| 898 | if crate::service::registration::remove(&st.db, &event_id, &target) |
| 899 | .await? |
| 900 | .is_none() |
| 901 | { |
| 902 | return Err(AppError::NotFound); |
| 903 | } |
| 904 | Ok(StatusCode::NO_CONTENT) |
| 905 | } |
| 906 | |
| 907 | #[cfg(test)] |
| 908 | mod tests { |
| 909 | use super::*; |
| 910 | use crate::database::init_test_db; |
| 911 | use crate::domain::user::Username; |
| 912 | |
| 913 | |
| 914 | async fn user(username: &str, role: Role, db: &Database) -> User { |
| 915 | let user = crate::service::user::create(db, Username::try_new(username).unwrap(), None) |
| 916 | .await |
| 917 | .unwrap(); |
| 918 | crate::service::user::set_role(db, user.get_id(), role) |
| 919 | .await |
| 920 | .unwrap() |
| 921 | .0 |
| 922 | } |
| 923 | |
| 924 | |
| 925 | |
| 926 | |
| 927 | #[tokio::test] |
| 928 | async fn demoted_event_creator_loses_management() { |
| 929 | let (db, _leases) = init_test_db().await; |
| 930 | let creator = user("ogretmen", Role::Teacher, &db).await; |
| 931 | let event = service::event::create( |
| 932 | &db, |
| 933 | creator.get_id(), |
| 934 | EventTitle::try_new("Gezi").unwrap(), |
| 935 | EventDescription::try_new("").unwrap(), |
| 936 | EventAudience { |
| 937 | kind: EventAudienceKind::School, |
| 938 | role: None, |
| 939 | course: None, |
| 940 | class: None, |
| 941 | capacity: None, |
| 942 | }, |
| 943 | None, |
| 944 | None, |
| 945 | ) |
| 946 | .await |
| 947 | .unwrap(); |
| 948 | assert!(can_manage(&event, &creator)); |
| 949 | |
| 950 | for role in [Role::Student, Role::Parent] { |
| 951 | let demoted = crate::service::user::set_role(&db, creator.get_id(), role) |
| 952 | .await |
| 953 | .unwrap() |
| 954 | .0; |
| 955 | assert!( |
| 956 | !can_manage(&event, &demoted), |
| 957 | "{role:?} creator still manages the event" |
| 958 | ); |
| 959 | } |
| 960 | |
| 961 | let boss = user("mudur", Role::Manager, &db).await; |
| 962 | assert!(can_manage(&event, &boss)); |
| 963 | } |
| 964 | } |