| 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::AttendanceStatus; |
| 14 | use crate::domain::class_course::ClassCourse; |
| 15 | use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; |
| 16 | |
| 17 | use crate::domain::role::Role; |
| 18 | use crate::domain::session_attendance::{SessionAttendance, SessionAttendanceId}; |
| 19 | use crate::domain::timestamp::Timestamp; |
| 20 | use crate::domain::user::{User, UserId}; |
| 21 | use crate::error::{AppError, ErrorResponse}; |
| 22 | use crate::service; |
| 23 | use crate::service::instance::can_manage_instance; |
| 24 | use crate::state::AppState; |
| 25 | |
| 26 | use super::instances::can_view_instance; |
| 27 | use super::{ |
| 28 | CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SessionResponse, check_not_past, |
| 29 | check_time_range, person_map, set_or_clear, |
| 30 | }; |
| 31 | |
| 32 | pub fn routes() -> OpenApiRouter<AppState> { |
| 33 | OpenApiRouter::new() |
| 34 | .routes(routes!(get_session, update_session, delete_session)) |
| 35 | .routes(routes!(mark_roll_call, list_roll_call)) |
| 36 | .routes(routes!(remove_roll_call)) |
| 37 | } |
| 38 | |
| 39 | #[derive(Deserialize, ToSchema)] |
| 40 | struct UpdateSession { |
| 41 | #[schema(max_length = 200)] |
| 42 | topic: Option<String>, |
| 43 | |
| 44 | teacher_id: Option<String>, |
| 45 | |
| 46 | |
| 47 | starts_at: Option<i64>, |
| 48 | |
| 49 | |
| 50 | #[serde(default, deserialize_with = "set_or_clear")] |
| 51 | #[schema(value_type = Option<i64>)] |
| 52 | ends_at: Option<Option<i64>>, |
| 53 | } |
| 54 | |
| 55 | #[derive(Deserialize, ToSchema)] |
| 56 | struct MarkRollCall { |
| 57 | |
| 58 | |
| 59 | #[schema(max_length = 50, example = "present")] |
| 60 | status: String, |
| 61 | |
| 62 | |
| 63 | user_id: String, |
| 64 | } |
| 65 | |
| 66 | #[derive(Serialize, ToSchema)] |
| 67 | struct SessionAttendanceResponse { |
| 68 | id: String, |
| 69 | session: String, |
| 70 | class_course: String, |
| 71 | |
| 72 | user: PersonRef, |
| 73 | status: String, |
| 74 | |
| 75 | marked_by: PersonRef, |
| 76 | } |
| 77 | |
| 78 | impl SessionAttendanceResponse { |
| 79 | fn new(attendance: &SessionAttendance, people: &HashMap<String, PersonRef>) -> Self { |
| 80 | Self { |
| 81 | id: SessionAttendanceId::composite(attendance.get_session(), attendance.get_user()) |
| 82 | .key(), |
| 83 | session: attendance.get_session().key().to_string(), |
| 84 | class_course: attendance.get_class_course().key().to_string(), |
| 85 | user: PersonRef::resolve(people, attendance.get_user()), |
| 86 | status: attendance.get_status().as_str().to_string(), |
| 87 | marked_by: PersonRef::resolve(people, attendance.get_marked_by()), |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | |
| 93 | |
| 94 | async fn session_with_instance( |
| 95 | id: &str, |
| 96 | db: &Database, |
| 97 | ) -> Result<(CourseSession, ClassCourse), AppError> { |
| 98 | let session = service::course_session::read(db, &CourseSessionId::from_key(id)) |
| 99 | .await? |
| 100 | .ok_or(AppError::NotFound)?; |
| 101 | let instance = crate::service::class_course::read(db, session.get_class_course()) |
| 102 | .await? |
| 103 | .ok_or(AppError::NotFound)?; |
| 104 | Ok((session, instance)) |
| 105 | } |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | fn is_live_session_teacher(session: &CourseSession, user: &User) -> bool { |
| 114 | user.get_role().at_least(Role::Teacher) && session.is_teacher(user.get_id()) |
| 115 | } |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | async fn can_roll_call( |
| 121 | session: &CourseSession, |
| 122 | instance: &ClassCourse, |
| 123 | user: &User, |
| 124 | db: &Database, |
| 125 | ) -> Result<bool, AppError> { |
| 126 | Ok(is_live_session_teacher(session, user) |
| 127 | || can_manage_instance(db, instance.get_id(), user).await?) |
| 128 | } |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | #[utoipa::path( |
| 135 | get, |
| 136 | path = "/{id}", |
| 137 | tag = "sessions", |
| 138 | security(("session_cookie" = [])), |
| 139 | params(("id" = String, Path, description = "Session id")), |
| 140 | responses( |
| 141 | (status = 200, description = "The session", body = SessionResponse), |
| 142 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 143 | (status = 403, description = "Not enrolled, not the session's teacher, and without instance rights", body = ErrorResponse), |
| 144 | (status = 404, description = "Not found", body = ErrorResponse), |
| 145 | ), |
| 146 | )] |
| 147 | async fn get_session( |
| 148 | State(st): State<AppState>, |
| 149 | CurrentUser(user): CurrentUser, |
| 150 | Path(id): Path<String>, |
| 151 | ) -> Result<Json<SessionResponse>, AppError> { |
| 152 | let (session, instance) = session_with_instance(&id, &st.db).await?; |
| 153 | if !is_live_session_teacher(&session, &user) |
| 154 | && !can_view_instance(&st.db, instance.get_id(), &user).await? |
| 155 | { |
| 156 | return Err(AppError::Forbidden( |
| 157 | "only the instance's enrolled students, the session's teacher, its teachers, or a manager/admin can view this session", |
| 158 | )); |
| 159 | } |
| 160 | let people = person_map([*session.get_teacher()], &st.db).await?; |
| 161 | Ok(Json(SessionResponse::new(&session, &people))) |
| 162 | } |
| 163 | |
| 164 | |
| 165 | |
| 166 | #[utoipa::path( |
| 167 | patch, |
| 168 | path = "/{id}", |
| 169 | tag = "sessions", |
| 170 | security(("session_cookie" = [])), |
| 171 | params(("id" = String, Path, description = "Session id")), |
| 172 | request_body = UpdateSession, |
| 173 | responses( |
| 174 | (status = 200, description = "Updated session", body = SessionResponse), |
| 175 | (status = 400, description = "Invalid fields, time range, newly set times in the past, or teacher", body = ErrorResponse), |
| 176 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 177 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 178 | (status = 404, description = "Not found", body = ErrorResponse), |
| 179 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 180 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 181 | ), |
| 182 | )] |
| 183 | async fn update_session( |
| 184 | State(st): State<AppState>, |
| 185 | RequireTeacher(user): RequireTeacher, |
| 186 | Path(id): Path<String>, |
| 187 | Json(req): Json<UpdateSession>, |
| 188 | ) -> Result<Json<SessionResponse>, AppError> { |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | let starts_at = req.starts_at.map(Timestamp::from_millis); |
| 194 | check_not_past("starts_at", starts_at)?; |
| 195 | let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis)); |
| 196 | if let Some(ends_at) = ends_at { |
| 197 | check_not_past("ends_at", ends_at)?; |
| 198 | } |
| 199 | let (session, instance) = session_with_instance(&id, &st.db).await?; |
| 200 | if !can_manage_instance(&st.db, instance.get_id(), &user).await? { |
| 201 | return Err(AppError::Forbidden( |
| 202 | "only the instance's teachers, its şube's homeroom teacher, or a manager/admin can edit this session", |
| 203 | )); |
| 204 | } |
| 205 | crate::service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 206 | |
| 207 | let topic = req |
| 208 | .topic |
| 209 | .as_deref() |
| 210 | .map(SessionTopic::try_new) |
| 211 | .transpose()?; |
| 212 | let teacher = match req.teacher_id { |
| 213 | Some(ref key) => Some( |
| 214 | *service::course_session::resolve_session_teacher(Some(key), &user, &st.db) |
| 215 | .await? |
| 216 | .get_id(), |
| 217 | ), |
| 218 | None => None, |
| 219 | }; |
| 220 | |
| 221 | |
| 222 | |
| 223 | check_time_range( |
| 224 | Some(starts_at.unwrap_or_else(|| session.get_starts_at())), |
| 225 | ends_at.unwrap_or_else(|| session.get_ends_at()), |
| 226 | )?; |
| 227 | |
| 228 | let updated = |
| 229 | service::course_session::update(&st.db, session, teacher, topic, starts_at, ends_at) |
| 230 | .await?; |
| 231 | let people = person_map([*updated.get_teacher()], &st.db).await?; |
| 232 | Ok(Json(SessionResponse::new(&updated, &people))) |
| 233 | } |
| 234 | |
| 235 | |
| 236 | |
| 237 | #[utoipa::path( |
| 238 | delete, |
| 239 | path = "/{id}", |
| 240 | tag = "sessions", |
| 241 | security(("session_cookie" = [])), |
| 242 | params(("id" = String, Path, description = "Session id")), |
| 243 | responses( |
| 244 | (status = 204, description = "Deleted"), |
| 245 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 246 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 247 | (status = 404, description = "Not found", body = ErrorResponse), |
| 248 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 249 | ), |
| 250 | )] |
| 251 | async fn delete_session( |
| 252 | State(st): State<AppState>, |
| 253 | RequireTeacher(user): RequireTeacher, |
| 254 | Path(id): Path<String>, |
| 255 | ) -> Result<StatusCode, AppError> { |
| 256 | let (session, instance) = session_with_instance(&id, &st.db).await?; |
| 257 | if !can_manage_instance(&st.db, instance.get_id(), &user).await? { |
| 258 | return Err(AppError::Forbidden( |
| 259 | "only the instance's teachers, its şube's homeroom teacher, or a manager/admin can delete this session", |
| 260 | )); |
| 261 | } |
| 262 | crate::service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 263 | service::course_session::delete(&st.db, session).await?; |
| 264 | Ok(StatusCode::NO_CONTENT) |
| 265 | } |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | #[utoipa::path( |
| 275 | post, |
| 276 | path = "/{id}/attendance", |
| 277 | tag = "sessions", |
| 278 | security(("session_cookie" = [])), |
| 279 | params(("id" = String, Path, description = "Session id")), |
| 280 | request_body = MarkRollCall, |
| 281 | responses( |
| 282 | (status = 200, description = "Roll-call state recorded", body = SessionAttendanceResponse), |
| 283 | (status = 400, description = "Invalid status, unknown user, target not a student, or not on the roster", body = ErrorResponse), |
| 284 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 285 | (status = 403, description = "Not the session's teacher or a manager of its instance; or marking the teacher without manager+", body = ErrorResponse), |
| 286 | (status = 404, description = "Session not found", body = ErrorResponse), |
| 287 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 288 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 289 | ), |
| 290 | )] |
| 291 | async fn mark_roll_call( |
| 292 | State(st): State<AppState>, |
| 293 | RequireTeacher(user): RequireTeacher, |
| 294 | Path(id): Path<String>, |
| 295 | Json(req): Json<MarkRollCall>, |
| 296 | ) -> Result<Json<SessionAttendanceResponse>, AppError> { |
| 297 | let (session, instance) = session_with_instance(&id, &st.db).await?; |
| 298 | if !can_roll_call(&session, &instance, &user, &st.db).await? { |
| 299 | return Err(AppError::Forbidden( |
| 300 | "only the session's teacher or a manager of its instance can take roll call", |
| 301 | )); |
| 302 | } |
| 303 | crate::service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 304 | |
| 305 | let school = service::settings::load(&st.db).await?; |
| 306 | let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; |
| 307 | let target = UserId::from_key(&req.user_id); |
| 308 | |
| 309 | let (attendance, target_user) = |
| 310 | service::session_attendance::mark(&st.db, &session, &user, &target, status).await?; |
| 311 | let people = PersonRef::map_of(&[&target_user, &user]); |
| 312 | Ok(Json(SessionAttendanceResponse::new(&attendance, &people))) |
| 313 | } |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | #[utoipa::path( |
| 321 | get, |
| 322 | path = "/{id}/attendance", |
| 323 | tag = "sessions", |
| 324 | security(("session_cookie" = [])), |
| 325 | params(("id" = String, Path, description = "Session id"), PageParams), |
| 326 | responses( |
| 327 | (status = 200, description = "A page of the roll-call roster (all of it when unpaged)", body = Page<SessionAttendanceResponse>), |
| 328 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 329 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 330 | (status = 403, description = "Not the session's teacher or a manager of its instance", body = ErrorResponse), |
| 331 | (status = 404, description = "Session not found", body = ErrorResponse), |
| 332 | ), |
| 333 | )] |
| 334 | async fn list_roll_call( |
| 335 | State(st): State<AppState>, |
| 336 | RequireTeacher(user): RequireTeacher, |
| 337 | Path(id): Path<String>, |
| 338 | Query(page): Query<PageParams>, |
| 339 | ) -> Result<Json<Page<SessionAttendanceResponse>>, AppError> { |
| 340 | let (limit, offset) = page.resolve()?; |
| 341 | let (session, instance) = session_with_instance(&id, &st.db).await?; |
| 342 | if !can_roll_call(&session, &instance, &user, &st.db).await? { |
| 343 | return Err(AppError::Forbidden( |
| 344 | "only the session's teacher or a manager of its instance can list the roll call", |
| 345 | )); |
| 346 | } |
| 347 | let (rows, total) = |
| 348 | service::session_attendance::list_for_session(&st.db, session.get_id(), limit, offset) |
| 349 | .await?; |
| 350 | |
| 351 | let people = person_map( |
| 352 | rows.iter() |
| 353 | .flat_map(|a| [*a.get_user(), *a.get_marked_by()]), |
| 354 | &st.db, |
| 355 | ) |
| 356 | .await?; |
| 357 | let items = rows |
| 358 | .iter() |
| 359 | .map(|a| SessionAttendanceResponse::new(a, &people)) |
| 360 | .collect(); |
| 361 | Ok(Json(Page::new(items, total, limit, offset))) |
| 362 | } |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | #[utoipa::path( |
| 368 | delete, |
| 369 | path = "/{id}/attendance/{user}", |
| 370 | tag = "sessions", |
| 371 | security(("session_cookie" = [])), |
| 372 | params( |
| 373 | ("id" = String, Path, description = "Session id"), |
| 374 | ("user" = String, Path, description = "User id"), |
| 375 | ), |
| 376 | responses( |
| 377 | (status = 204, description = "Removed"), |
| 378 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 379 | (status = 403, description = "Not the session's teacher or a manager of its instance; or removing a staff row without manager+", body = ErrorResponse), |
| 380 | (status = 404, description = "Not found", body = ErrorResponse), |
| 381 | (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse), |
| 382 | ), |
| 383 | )] |
| 384 | async fn remove_roll_call( |
| 385 | State(st): State<AppState>, |
| 386 | RequireTeacher(user): RequireTeacher, |
| 387 | Path((id, target)): Path<(String, String)>, |
| 388 | ) -> Result<StatusCode, AppError> { |
| 389 | let (session, instance) = session_with_instance(&id, &st.db).await?; |
| 390 | if !can_roll_call(&session, &instance, &user, &st.db).await? { |
| 391 | return Err(AppError::Forbidden( |
| 392 | "only the session's teacher or a manager of its instance can take roll call", |
| 393 | )); |
| 394 | } |
| 395 | crate::service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 396 | let target = UserId::from_key(&target); |
| 397 | service::session_attendance::remove(&st.db, &session, &user, &target).await?; |
| 398 | Ok(StatusCode::NO_CONTENT) |
| 399 | } |