forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

events.rs964 lines, 37.6 KiBHistoryRawDownload
1use std::collections::HashMap;
2
3use crate::web::tenant_state::State;
4use axum::Json;
5use axum::extract::{Path, Query};
6use axum::http::StatusCode;
7use serde::{Deserialize, Serialize};
8use utoipa::ToSchema;
9use utoipa_axum::router::OpenApiRouter;
10use utoipa_axum::routes;
11
12use crate::database::Database;
13use crate::domain::attendance::{Attendance, AttendanceStatus};
14use crate::domain::class_group::ClassGroupId;
15use crate::domain::course::CourseId;
16use crate::domain::event::{
17 Event, EventAudience, EventAudienceKind, EventDescription, EventId, EventTitle,
18};
19use crate::domain::role::Role;
20use crate::domain::timestamp::Timestamp;
21use crate::domain::user::{User, UserId};
22use crate::error::{AppError, ErrorResponse, ValidationError};
23use crate::service;
24use crate::state::AppState;
25
26use super::{
27 CurrentUser, Page, PageParams, PersonRef, RequireTeacher, WindowParams, check_not_past,
28 check_time_range, paginate, person_map, set_or_clear,
29};
30
31pub 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/// An event's audience on the wire — who is expected to attend. Tagged by
43/// `kind`; the extra field each kind needs rides alongside it.
44#[derive(Serialize, Deserialize, Clone, ToSchema)]
45#[serde(tag = "kind", rename_all = "lowercase")]
46enum AudienceDto {
47 /// Everybody in the school. The default when a create request omits
48 /// `audience` entirely.
49 School,
50 /// Every user holding exactly this role — `parent`, `student`, `teacher`,
51 /// `manager`, or `admin` (no implied "and above").
52 Role { role: String },
53 /// The students currently enrolled in this course (live — enrollment
54 /// changes move people in and out).
55 Course { course: String },
56 /// The students currently in this class section — live, so adding
57 /// or removing a member moves them in and out. The homeroom teacher is not
58 /// implied. If the class is later deleted the event survives with an empty
59 /// roster.
60 Class { class: String },
61 /// A signup list built through `POST /events/{id}/register` — teachers
62 /// place students, staff take their own seat. `capacity` caps the seats;
63 /// `null` or omitted = unlimited. The list closes when the event starts.
64 Registration {
65 #[serde(default)]
66 capacity: Option<i64>,
67 },
68}
69
70impl AudienceDto {
71 /// Validate the wire form into the domain audience: the role must parse,
72 /// the course must exist, and a registration capacity must be positive.
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)]
173struct CreateEvent {
174 #[schema(max_length = 200, example = "Sprint demo")]
175 title: String,
176 #[schema(max_length = 2000)]
177 description: Option<String>,
178 /// Who the event is for (its expected-attendee roster). Omit for a
179 /// school-wide event.
180 audience: Option<AudienceDto>,
181 /// Unix-millisecond timestamps. Must not be in the past.
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)]
188struct UpdateEvent {
189 #[schema(max_length = 200)]
190 title: Option<String>,
191 #[schema(max_length = 2000)]
192 description: Option<String>,
193 /// Replaces the audience wholesale when present; omit to keep the current
194 /// one. Attendance rows for people the change drops out of the roster stay
195 /// stored — they just stop appearing on the roster report.
196 audience: Option<AudienceDto>,
197 /// Unix-millisecond timestamp. Omit to keep the current value; send `null`
198 /// to clear it. A newly set value must not be in the past.
199 #[serde(default, deserialize_with = "set_or_clear")]
200 #[schema(value_type = Option<i64>)]
201 starts_at: Option<Option<i64>>,
202 /// Unix-millisecond timestamp. Omit to keep the current value; send `null`
203 /// to clear it. A newly set value must not be in the past.
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)]
210struct MarkAttendance {
211 /// One of the school's attendance statuses (`GET /settings`; the core
212 /// four are `present`, `absent`, `late`, `excused`).
213 #[schema(max_length = 50, example = "present")]
214 status: String,
215 /// Target user id — must be in the event's audience. Defaults to the
216 /// caller when omitted.
217 user_id: Option<String>,
218}
219
220#[derive(Serialize, ToSchema)]
221struct 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
231impl 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/// Who may edit/delete a specific event: its creator, or anyone `manager` and
246/// above (who can manage any event regardless of ownership) — in both cases
247/// only while the caller is *still* `teacher` or above.
248///
249/// The `teacher` floor is enforced here, not left to the extractors: `creator`
250/// is a historical column no demotion sweeps, so a grant read off it has to
251/// re-read the live role or it outlives the role that earned it. This helper
252/// deliberately does not trust its callers to have cleared the bar — the same
253/// assumption, written into the same comment, is what let a demoted course
254/// creator keep course-management rights (see `courses::can_manage_course`).
255fn 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)]
261struct AttendanceResponse {
262 id: String,
263 event: String,
264 /// Whose attendance this row records.
265 user: PersonRef,
266 status: String,
267 /// Who recorded it.
268 marked_by: PersonRef,
269}
270
271impl 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// ---- events -------------------------------------------------------------
284
285/// Create an event owned by the current user. Requires the `teacher` role or
286/// higher. `audience` targets it at a role, a course's enrollment, a class
287/// section's roster, or a registration list (filled via
288/// `POST /events/{id}/register`); omitted it is
289/// school-wide. Everyone still sees every event — the audience is the
290/// expected-attendee roster, not a visibility wall.
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)]
305async 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/// List all events, newest first. Paged via `?limit=&offset=` (omit `limit`
341/// for every event); returns a `{items, total, limit, offset}` envelope.
342///
343/// The optional `?starts_after=&ends_after=` schedule window (unix
344/// milliseconds) narrows the list to upcoming/unfinished events and flips the
345/// order to ascending by schedule, so `?ends_after=<now>&limit=20` returns the
346/// twenty *soonest* events rather than the twenty newest-created. Events with
347/// no schedule are excluded by either parameter. `?starts_before=` /
348/// `?ends_before=` are the mirror bounds (strictly before); with any bound
349/// set the page, the count, and the window share one SQL `WHERE`, so a
350/// filtered page never decodes the events it skips.
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)]
363async 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 // The window and the page are one SQL statement; `total` is a count over
372 // the same WHERE, so a filtered page never loads the rows it skips.
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/// Fetch a single event by id.
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)]
400async 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/// Update an event. Requires teacher+; the creator may edit their own event and
412/// managers/admins may edit anyone's. Omitted fields keep their value; an
413/// explicit `null` clears `starts_at`/`ends_at`. A provided `audience` replaces
414/// the current one wholesale — attendance and signup rows for people it drops
415/// stay stored but leave the roster report (signups resurface if the event is
416/// switched back to the registration kind).
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)]
433async 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 // The schedule columns are nullable, so they keep the outer/inner
440 // distinction: a provided value sets the field, an explicit `null` clears
441 // it, and an omitted one is left alone.
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 // Only what the request carried: an omitted field stays `None` and is
456 // never written, so a concurrent PATCH of another field survives. (A JSON
457 // `null` deserializes to `None` for title/description/audience too —
458 // those columns are not nullable, so "omitted" and "null" both mean
459 // "keep".)
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 // Only set schedule values are held to the no-past rule — a kept time of
471 // an event already underway may be past.
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 // The range CHECK needs both ends: whichever the request omitted comes
479 // from the stored row. Read for the check only — the omitted side is
480 // never written back. Pre-flight only: the UPDATE's own `WHERE` re-makes
481 // this check, so a concurrent move of the omitted end loses.
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/// Delete an event. Requires teacher+; the creator may delete their own event
501/// and managers/admins may delete anyone's.
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)]
515async 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// ---- attendance ---------------------------------------------------------
533
534/// Mark attendance for a user on an event (defaults to the caller). Taking
535/// attendance is a teacher+ action — students never mark, not even themselves —
536/// and the target must be in the event's audience.
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)]
553async 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 // Target user must exist.
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 // Only expected attendees can be marked. The marker needn't be in the
580 // audience — a teacher takes roll of a student-targeted event.
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/// List the attendance roster for an event, paged via `?limit=&offset=` (omit
595/// `limit` for the whole roster). Requires teacher+ — students see their own
596/// tallies via `GET /attendance/me`. Returns a `{items, total, limit, offset}`
597/// envelope.
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)]
612async 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 // Event must exist — a missing event is a 404, not an empty roster.
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 // Join people onto the page alone — the lookup shrinks with the window.
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/// Remove a user's attendance record from an event. Requires teacher+.
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)]
657async 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// ---- roster ---------------------------------------------------------------
675
676/// One expected attendee on the roster report: who they are and how (whether)
677/// they were marked.
678#[derive(Serialize, ToSchema)]
679struct RosterEntry {
680 user: PersonRef,
681 /// The recorded attendance status; `null` = expected but never marked —
682 /// the "missed" signal once the event is over.
683 status: Option<String>,
684 /// Who recorded it; `null` while unmarked.
685 marked_by: Option<PersonRef>,
686}
687
688/// The event's expected-attendee roster joined with its attendance marks — the
689/// who-came/who-missed report. Resolved live from the audience (today's role
690/// holders, current enrollment, the current class roster, the current signup
691/// list), so it always reflects
692/// the present roster;
693/// attendance rows for people no longer in the audience are omitted here (they
694/// remain in `GET /events/{id}/attendance`). Requires teacher+. Paged via
695/// `?limit=&offset=` (omit `limit` for the whole roster).
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)]
710async 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 // ULID keys sort by creation instant — a stable order keeps pages coherent.
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 // Join people onto the page alone — the lookup shrinks with the window.
733 // Paged in the web layer: the audience is resolved in Rust.
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// ---- registration ---------------------------------------------------------
757
758#[derive(Deserialize, ToSchema)]
759struct RegisterUser {
760 /// Target user id — must name a student (staff take seats only for
761 /// themselves). Defaults to the caller when omitted.
762 user_id: Option<String>,
763}
764
765#[derive(Serialize, ToSchema)]
766struct RegistrationResponse {
767 event: String,
768 /// Who holds the seat.
769 user: PersonRef,
770 /// Who placed them on the list.
771 registered_by: PersonRef,
772}
773
774/// Put a user on a registration-audience event's signup list. Requires
775/// teacher+. `user_id` must name a student — students are placed by staff and
776/// never register themselves; omit it to take a seat yourself (staff
777/// self-serve, so registering another teacher/manager is refused). Registering
778/// the same person twice is a no-op returning the existing seat. The list
779/// closes when the event starts (or its ends_at-only deadline passes) and
780/// refuses to grow past `capacity`.
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)]
798async 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 // Fast-fail gate; the authoritative re-check runs inside
809 // `service::registration::register` under its lock.
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 // Students are placed by staff; staff hold only their own seat.
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 // Resolve from the row, not the request: a re-register returns the
832 // existing seat, whose registered_by is the *original* placer — someone
833 // the {target, caller} pair may not contain.
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/// Take a user off the signup list — the register rules mirrored: teacher+,
847/// students' seats or your own (another *staff* member's seat only if their
848/// account no longer exists), and only while the list is open (the event
849/// hasn't started or, ends_at-only, passed). A seat held by a `parent` is
850/// freeable by any teacher+ as well: no route lets that account free it
851/// itself, so a stranded seat needs a door. Attendance already marked stays
852/// recorded.
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)]
871async 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 // A deleted account's leftover seat is fair game for any teacher+; a living
884 // staff member's seat is theirs alone. The bar is *staff*, not "a student":
885 // a parent holds no seat any route can reach — they cannot get past
886 // `RequireTeacher` to free their own — so a seat under that role is
887 // stranded, and a volume written before `service::registration::register` claimed
888 // the holder's row already carries some.
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)]
908mod tests {
909 use super::*;
910 use crate::database::init_test_db;
911 use crate::domain::user::Username;
912
913 /// A user at `role`, minted through the real create path.
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 /// `can_manage` is only reached behind `RequireTeacher` today, so this is
925 /// pinned at the helper — the level where the floor is observable. The
926 /// helper is what must hold when a future route arrives with `CurrentUser`.
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 // ...and the event is never orphaned: manager+ still reaches it.
961 let boss = user("mudur", Role::Manager, &db).await;
962 assert!(can_manage(&event, &boss));
963 }
964}