//! The `event` table: row reads and listings, the cascading delete, and the //! audience's live membership resolution — the point check behind marking //! ([`includes`]) and the who-missed report's backbone ([`members`]). use crate::database::{Database, tx_with_retry}; use crate::db::field_update::FieldUpdate; use crate::db::page::{PagedList, Param}; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; use crate::domain::event::{ Event, EventAudience, EventAudienceKind, EventDescription, EventId, EventTitle, }; use crate::domain::role::Role; use crate::domain::timestamp::{Timestamp, range_error}; use crate::domain::user::{User, UserId}; use crate::error::AppError; use sqlx::query_as; /// Is `user` in this event's audience roster right now? The point check /// behind marking — cheaper than resolving the whole roster when the target /// is known. The audience comes off the row itself: the registration kind /// resolves against that event's signup rows. pub async fn includes(db: &Database, event: &Event, user: &User) -> Result { match event.get_audience_kind() { crate::domain::event::EventAudienceKind::School => Ok(true), crate::domain::event::EventAudienceKind::Role => { Ok(Some(user.get_role()) == event.get_audience_role()) } crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() { Some(course) => { Ok(crate::db::enrollment::user_is_in_course(db, course, user.get_id()).await?) } None => Ok(false), }, // The (class, user) pair is the membership row's own key, so the point // check is one existence probe — and `left_at IS NULL` makes it the // *live* stint's, the row the partial unique index // `class_member_live_pair` carries: a student who left the section is // history, not audience, and a stale probe would let them be marked // present at (and counted by) an event their section no longer // attends. crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() { Some(class) => { let row = sqlx::query!( "SELECT EXISTS(SELECT 1 FROM class_member WHERE class = $1 AND app_user = $2 AND left_at IS NULL) AS \"present!\"", class.uuid(), user.get_id().uuid() ) .fetch_one(db) .await?; Ok(row.present) } None => Ok(false), }, crate::domain::event::EventAudienceKind::Registration => Ok( crate::db::registration::read_for_user(db, event.get_id(), user.get_id()) .await? .is_some(), ), } } /// The event's full roster, as it stands right now — the who-missed /// report's backbone. Registered ids that no longer resolve to a user row /// are kept; the caller degrades their display like any stale reference. pub async fn members(db: &Database, event: &Event) -> Result, AppError> { match event.get_audience_kind() { crate::domain::event::EventAudienceKind::School => { Ok(crate::db::user::list_all(db, None, None, 0) .await? .0 .iter() .map(|user| *user.get_id()) .collect()) } crate::domain::event::EventAudienceKind::Role => match event.get_audience_role() { Some(role) => Ok(crate::db::user::list_by_role(db, role) .await? .iter() .map(|user| *user.get_id()) .collect()), None => Ok(Vec::new()), }, crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() { Some(course) => Ok(crate::db::enrollment::list_users_for_course(db, course).await?), None => Ok(Vec::new()), }, crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() { Some(class) => Ok(crate::db::class_member::list_for_class(db, class, None, 0) .await? .0 .iter() .map(|member| *member.get_user()) .collect()), None => Ok(Vec::new()), }, crate::domain::event::EventAudienceKind::Registration => { Ok(crate::db::registration::list_for_event(db, event.get_id()) .await? .iter() .map(|registration| *registration.get_user()) .collect()) } } } pub async fn create( db: &Database, creator: &UserId, title: EventTitle, description: EventDescription, audience: EventAudience, starts_at: Option, ends_at: Option, ) -> Result { // The audience payload moves as one unit with its kind; the validated // bundle guarantees only the matching payload is ever non-NULL. let created = query_as!( Event, "INSERT INTO event (id, creator, title, description, audience_kind, audience_role, \ audience_course, audience_class, audience_capacity, starts_at, ends_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \ audience_kind AS \"audience_kind: EventAudienceKind\", \ audience_role AS \"audience_role: Role\", \ audience_course AS \"audience_course: CourseId\", \ audience_class AS \"audience_class: ClassGroupId\", \ audience_capacity, starts_at AS \"starts_at: Timestamp\", \ ends_at AS \"ends_at: Timestamp\"", EventId::generate().uuid(), creator.uuid(), title.as_str(), description.as_str(), audience.kind.as_str(), audience.role.map(|r| r.as_str().to_string()), audience.course.map(|c| c.uuid()), audience.class.map(|c| c.uuid()), audience.capacity, starts_at.map(|t| t.as_millis()), ends_at.map(|t| t.as_millis()), ) .fetch_one(db) .await?; Ok(created) } pub async fn read(db: &Database, id: &EventId) -> Result, AppError> { let event = query_as!( Event, "SELECT id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \ audience_kind AS \"audience_kind: EventAudienceKind\", \ audience_role AS \"audience_role: Role\", \ audience_course AS \"audience_course: CourseId\", \ audience_class AS \"audience_class: ClassGroupId\", \ audience_capacity, starts_at AS \"starts_at: Timestamp\", \ ends_at AS \"ends_at: Timestamp\" \ FROM event WHERE id = $1", id.uuid() ) .fetch_optional(db) .await?; Ok(event) } /// The event list behind `GET /events`, paged by the database — the window is /// `LIMIT/OFFSET` in SQL, and `total` a `count(*)` over the same `WHERE`, so /// a schedule query never decodes the whole table to slice ten rows off it. /// /// The four optional bounds are [`crate::web::page::WindowParams`]'s schedule /// window, validated upstream. All four absent is the unfiltered read, /// `ORDER BY id DESC` (newest first). Any bound set drops schedule-less rows /// (every predicate is `NULL`-rejecting) and flips the order to ascending by /// schedule — `starts_at`, falling back to `ends_at`, ties by id — the same /// order `WindowParams::apply` used to produce in Rust. pub async fn list_windowed( db: &Database, starts_after: Option, ends_after: Option, starts_before: Option, ends_before: Option, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { // Conditions and binds move together: each bound appends its predicate // with the placeholder number its bind position lands on. let mut conds: Vec = Vec::new(); let mut bounds: Vec = Vec::new(); let mut bound = |column: &str, op: &str, value: Option| { if let Some(value) = value { conds.push(format!("{column} {op} ${}", bounds.len() + 1)); bounds.push(value); } }; bound("starts_at", ">", starts_after); bound("starts_at", "<", starts_before); bound("COALESCE(ends_at, starts_at)", ">", ends_after); bound("COALESCE(ends_at, starts_at)", "<", ends_before); let windowed = !conds.is_empty(); let from_where = if windowed { format!("event WHERE {}", conds.join(" AND ")) } else { "event".to_owned() }; let order = if windowed { "ORDER BY COALESCE(starts_at, ends_at) ASC, id ASC" } else { "ORDER BY id DESC" }; let mut list = PagedList::new(from_where, order); for value in bounds { list = list.bind(value); } list.run::(limit, offset, db).await } /// Request-scoped: the handler reads the event, then awaits the clock and a /// course lookup before saving, holding no lock, so an omitted field /// (`None`) is not written at all. Passing the snapshot's value back /// instead would revert a concurrent edit of that field — scoping the `SET` /// alone does not prevent that, the values have to come from the request. /// The schedule columns are nullable, so they take the outer/inner /// `Option>`: `None` = omitted (keep), `Some(None)` = clear. /// /// The audience is five columns moving as one unit: when the request /// carries an audience, all five are written (the non-matching payload as /// NULL); when it carries none, none are. pub async fn update( db: &Database, event: Event, title: Option, description: Option, audience: Option, starts_at: Option>, ends_at: Option>, ) -> Result { FieldUpdate::new("event", event.get_id().uuid()) .set( "title", title.map(|title| Param::Text(title.as_str().to_string())), ) .set( "description", description.map(|d| Param::Text(d.as_str().to_string())), ) .set( "audience_kind", audience .as_ref() .map(|a| Param::Text(a.kind.as_str().to_string())), ) .set( "audience_role", audience .as_ref() .map(|a| Param::OptText(a.role.map(|r| r.as_str().to_string()))), ) .set( "audience_course", audience .as_ref() .map(|a| Param::OptUuid(a.course.as_ref().map(|c| c.uuid()))), ) .set( "audience_class", audience .as_ref() .map(|a| Param::OptUuid(a.class.as_ref().map(|c| c.uuid()))), ) .set( "audience_capacity", audience.as_ref().map(|a| Param::OptI64(a.capacity)), ) .set( "starts_at", starts_at.map(|at| Param::OptI64(at.map(|at| at.as_millis()))), ) .set( "ends_at", ends_at.map(|at| Param::OptI64(at.map(|at| at.as_millis()))), ) .ordered("starts_at", "ends_at", range_error()) .run::(db) .await } /// Delete the event and cascade-remove its attendance and signup rows. /// /// Children first, all of it in one guarded transaction: run as separate /// statements, a registration or a mark committing in between would outlive /// its event — an orphan no read path can ever reach and no delete can ever /// reclaim, since every one of them is keyed on the event that is now gone. /// /// `cascade` retry: a mark landing while the cascade is in flight contends /// for the event row (its insert's foreign key proves the event the moment /// it lands), so a lost round re-sends instead of answering 500. pub async fn delete(db: &Database, event: Event) -> Result { tx_with_retry(db, true, async move |tx| { sqlx::query!("DELETE FROM attendance WHERE event = $1", event.get_id().uuid()) .execute(&mut *tx) .await?; sqlx::query!( "DELETE FROM registration WHERE event = $1", event.get_id().uuid() ) .execute(&mut *tx) .await?; let gone = query_as!( Event, "DELETE FROM event WHERE id = $1 \ RETURNING id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \ audience_kind AS \"audience_kind: EventAudienceKind\", \ audience_role AS \"audience_role: Role\", \ audience_course AS \"audience_course: CourseId\", \ audience_class AS \"audience_class: ClassGroupId\", \ audience_capacity, starts_at AS \"starts_at: Timestamp\", \ ends_at AS \"ends_at: Timestamp\"", event.get_id().uuid() ) .fetch_optional(&mut *tx) .await?; gone.ok_or(AppError::NotFound) }) .await } #[cfg(test)] mod tests { use super::*; /// A real `app_user` row: the creator is a foreign key now. async fn a_person(db: &Database, label: &str) -> UserId { let user = UserId::generate(); sqlx::query( "INSERT INTO app_user (id, username, created_at, role) \ VALUES ($1, $2, 0, 'teacher')", ) .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) .execute(db) .await .unwrap(); user } /// The forcing function behind the one rule with two spellings: the freeze /// this file decides in Rust ([`Event::registration_capacity`]) and the /// demotion sweep's SQL predicate, which `service::user::set_role` carries /// because it frees a demoted parent's seats inside a transaction and /// cannot call Rust from there. The predicate is copied here test-side on /// purpose: the sweep lives in user.rs, and this test pins the copy. /// /// Every schedule shape is put to both, including the three the SQL is most /// likely to get wrong: the ends_at-only event (`COALESCE` must fall through to /// it), the boundary itself (closed *at* the instant, not after it — `>=` in /// Rust, `<=` in SQL, and the two read opposite ways round; `now` is bound /// to that exact instant so the boundary is really exercised), and an event /// that takes no registrations at all, which Rust refuses one arm *earlier* /// — so the SQL must not report it frozen, or a stray row on it would be /// preserved forever instead of swept. #[tokio::test] async fn the_sql_freeze_guard_matches_the_rust_one() { let (db, _leases) = crate::database::init_test_db().await; let creator = a_person(&db, "event-guard").await; // `audience_class` is a foreign key too: the class case needs a real group. let class = ClassGroupId::generate(); sqlx::query("INSERT INTO class_group (id, name, creator, grade_level) VALUES ($1, 'g1', $2, 9)") .bind(class.uuid()) .bind(creator.uuid()) .execute(&db) .await .unwrap(); let no_payload = |kind| EventAudience { kind, role: None, course: None, class: None, capacity: None, }; let now = Timestamp::now().as_millis(); let past = Some(Timestamp::from_millis(now - 60_000)); let future = Some(Timestamp::from_millis(now + 3_600_000)); let later = Some(Timestamp::from_millis(now + 7_200_000)); let signup = no_payload(EventAudienceKind::Registration); let cases = [ ("timeless", signup.clone(), None, None), ("deadline ahead", signup.clone(), None, future), ("deadline passed", signup.clone(), None, past), ("starts later", signup.clone(), future, later), ("already started", signup.clone(), past, None), ("started, ends later", signup.clone(), past, future), ( "closing this instant", signup.clone(), Some(Timestamp::from_millis(now)), None, ), // No signup list to freeze: `registration_capacity` refuses these on // the audience, before it ever looks at the clock. ( "started school event", no_payload(EventAudienceKind::School), past, None, ), ( "started class event", EventAudience { class: Some(class), ..no_payload(EventAudienceKind::Class) }, past, None, ), ]; for (name, audience, starts_at, ends_at) in cases { let event = create( &db, &creator, EventTitle::try_new(name).unwrap(), EventDescription::try_new("").unwrap(), audience, starts_at, ends_at, ) .await .unwrap(); let rust = matches!( event.registration_capacity(), Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) ); // Test-side copy of the sweep predicate in `service::user::set_role` // (src/db/user.rs): true == frozen, i.e. the demotion sweep would // leave the signup rows exactly as they stand. let sql = sqlx::query_scalar::<_, bool>( "SELECT audience_kind = 'registration' \ AND COALESCE(starts_at, ends_at) IS NOT NULL \ AND COALESCE(starts_at, ends_at) <= $2 \ FROM event WHERE id = $1", ) .bind(event.get_id().uuid()) .bind(now) .fetch_one(&db) .await .unwrap(); assert_eq!( sql, rust, "the SQL freeze guard and registration_capacity disagree on a \ {name} event — the role cascade would rewrite a closed signup \ list, or strand a seat on an open one" ); } } /// Four schedule shapes; creation order is id order (uuidv7), so the /// unfiltered read is exactly the reverse of the creation order. async fn four_events(db: &Database) -> (UserId, [EventId; 4]) { let creator = a_person(db, "event-window").await; let school = EventAudience { kind: EventAudienceKind::School, role: None, course: None, class: None, capacity: None, }; let now = Timestamp::now().as_millis(); let past = Timestamp::from_millis(now - 60_000); let soon = Timestamp::from_millis(now + 30 * 60_000); let future = Timestamp::from_millis(now + 3_600_000); let later = Timestamp::from_millis(now + 2 * 3_600_000); let mut ids = Vec::new(); for (starts_at, ends_at) in [ (None, None), // timeless — never survives a window (Some(past), None), // already started (Some(soon), None), // ends-only deadline... starts soon (Some(future), Some(later)), // fully scheduled ahead ] { ids.push( create( db, &creator, EventTitle::try_new("window").unwrap(), EventDescription::try_new("").unwrap(), school.clone(), starts_at, ends_at, ) .await .unwrap() .get_id() .clone(), ); } (creator, ids.try_into().unwrap()) } #[tokio::test] async fn absent_window_is_the_unfiltered_newest_first_read() { let (db, _leases) = crate::database::init_test_db().await; let (_, ids) = four_events(&db).await; let (events, total) = list_windowed(&db, None, None, None, None, None, 0) .await .unwrap(); assert_eq!(total, 4); let listed: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect(); let expected: Vec<_> = ids.iter().rev().cloned().collect(); assert_eq!(listed, expected); } #[tokio::test] async fn the_window_filters_and_orders_in_sql_with_a_filtered_total() { let (db, _leases) = crate::database::init_test_db().await; let (_, ids) = four_events(&db).await; let [_, started, soon, ahead] = &ids; let now = Timestamp::now().as_millis(); // ends_after: the timeless and the already-started drop; the ends-only // event survives on its `ends_at` COALESCE fallback. let (events, total) = list_windowed(&db, None, Some(now), None, None, None, 0) .await .unwrap(); assert_eq!(total, 2); let keys: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect(); assert_eq!(keys, vec![soon.clone(), ahead.clone()]); // A limit applies after the filter: one row out, total still two. let (events, total) = list_windowed(&db, None, Some(now), None, None, Some(1), 0) .await .unwrap(); assert_eq!((events.len(), total), (1, 2)); assert_eq!(events[0].get_id(), soon); // Offset runs inside the filtered set, not past it. let (events, total) = list_windowed(&db, None, Some(now), None, None, None, 1) .await .unwrap(); assert_eq!((events.len(), total), (1, 2)); assert_eq!(events[0].get_id(), ahead); // starts_before drops the start-less rows and everything starting at // or after the cut (strict): the cut sits between `soon` (+30 min) // and `ahead` (+1 h), so `started` and `soon` survive, schedule // ascending. let (events, total) = list_windowed( &db, None, None, Some(now + 45 * 60_000), None, None, 0, ) .await .unwrap(); assert_eq!(total, 2); let keys: Vec<_> = events.iter().map(|event| event.get_id()).cloned().collect(); assert_eq!(keys, vec![started.clone(), soon.clone()]); // ends_before: only the already-started, on its starts_at fallback. let (_, total) = list_windowed(&db, None, None, None, Some(now - 30_000), None, 0) .await .unwrap(); assert_eq!(total, 1); // A well-formed instant naming no row is an empty page, not an error. let (events, total) = list_windowed(&db, Some(now + 30 * 86_400_000), None, None, None, None, 0) .await .unwrap(); assert!((events.is_empty()) && total == 0); } }