From 31e155aa3bc532176f525ec15230a65c9ef1e49c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 16 Jul 2026 18:19:55 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(events)!:=20registration=20aud?= =?UTF-8?q?ience=20replaces=20hand-picked=20users?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Events gain a `registration` audience: a signup list built one seat at a time — teachers place students (students never register, not even themselves), staff take only their own seat, never another's. An optional capacity caps the list (seat count re-checked inside the insert transaction), and the list freezes the moment the event starts, both directions. Seats resolve live like every audience: roster, marking gate, and who-missed report inherit unchanged. - POST /events/{id}/register {user_id?}: idempotent seat upsert (enrollment's composite-id trick); 409 when full or started - DELETE /events/{id}/register/{user}: same self-or-student rule; a deleted account's leftover seat is any teacher's to free - event delete cascades signup rows; audience switches leave them inert (they resurface if the kind returns) - migration split into DDL + backfill queries: statements in one batch see the batch-start schema, so a backfill next to a fresh DEFINE FIELD silently lost the keys it wrote (audience became {}) BREAKING CHANGE: the hand-picked `users` audience kind is gone — requests naming it are rejected. Existing users-audience events convert on boot: each listed user becomes a registration row credited to the event creator and the audience becomes an uncapped registration list. --- README.md | 42 ++-- src/constant.rs | 6 - src/database.rs | 49 ++++- src/domain/event.rs | 87 +++++--- src/domain/mod.rs | 1 + src/domain/registration.rs | 156 +++++++++++++++ src/lib.rs | 4 +- src/web/events.rs | 221 +++++++++++++++++---- tests/integration.rs | 394 ++++++++++++++++++++++++++++++++++--- tests/persistence.rs | 107 ++++++++++ 10 files changed, 957 insertions(+), 110 deletions(-) create mode 100644 src/domain/registration.rs diff --git a/README.md b/README.md index c1670dd..d2d583c 100644 --- a/README.md +++ b/README.md @@ -7,10 +7,13 @@ Session-cookie auth with four hierarchical roles (`student < teacher < manager …): blobs live on disk next to the database, metadata in the database, and the per-file size cap is school policy in settings (`max_file_bytes`, default 5 MiB). Attendance is event + attendees: create an event with an **audience** -(the whole school, one role, a course's enrollment, or a hand-picked list — -omit for school-wide), then teachers mark the expected attendees present / -absent / late / excused (students never self-mark), and a **roster report** -shows who was expected and who missed. Every event stays visible to everyone — +(the whole school, one role, a course's enrollment, or a **registration** +signup list — omit for school-wide), then teachers mark the expected attendees +present / absent / late / excused (students never self-mark), and a **roster +report** shows who was expected and who missed. Registration lists fill seat +by seat: teachers register students (never the other way round), staff +register only themselves, an optional `capacity` caps the seats, and the list +closes the moment the event starts. Every event stays visible to everyone — the audience is a roster, not a wall. Marks are course-shaped (Google Classroom style): a teacher creates a course, enrolls students, adds exams inside it, and grades — enrolling, sitting exams, roll call, and marks are @@ -169,7 +172,8 @@ effect on the user's very next call (no re-login). | Register / login / view own account | (any) | Registration always creates a `student` | | View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves | | Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark — a teacher+ may mark anyone expected, themselves included | -| Create events | teacher | The audience (school / role / course / user list) is set at creation and editable later | +| Create events | teacher | The audience (school / role / course / registration) is set at creation and editable later | +| Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** — never for another staff member. Unregistering mirrors the same rule | | List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report | | Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event | | View a course's sessions | student | Only inside **visible** courses: enrolled, creator, or `manager`+ | @@ -292,6 +296,8 @@ their existing shapes: the student exam-room reads | GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) · paged | | GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` · paged | | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance | +| POST | `/events/{id}/register` | teacher | `{user_id?}` — seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started | +| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started | | POST | `/courses` | teacher | `{title, description?}` (creator manages it) | | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged | | GET | `/courses/me` | student | The caller's **enrolled** courses · paged | @@ -380,14 +386,24 @@ explicit `null` clears it. An event's `audience` is a tagged object — `{"kind": "school"}` (the default), `{"kind": "role", "role": "student"}` (that exact role, no "and above"), `{"kind": "course", "course": ""}` (the course's current enrollment), or -`{"kind": "users", "users": ["", …]}` (hand-picked, ≤ 100, deduplicated) — -and is the event's **expected-attendee roster**, resolved live at read time: -role changes and (un)enrollments move people in and out by themselves. It never -hides the event — everyone sees every event. Only audience members can be -marked; `GET /events/{id}/roster` joins the live roster with the recorded marks -(`status: null` = expected but never marked). Attendance rows for people a -later audience edit (or unenrollment / role change) dropped stay stored and -listed under `/events/{id}/attendance`, but leave the roster report. +`{"kind": "registration", "capacity": 30}` (a signup list; `capacity` optional, +`null` = unlimited) — and is the event's **expected-attendee roster**, resolved +live at read time: role changes, (un)enrollments, and (un)registrations move +people in and out by themselves. It never hides the event — everyone sees every +event. Only audience members can be marked; `GET /events/{id}/roster` joins the +live roster with the recorded marks (`status: null` = expected but never +marked). Attendance rows for people a later audience edit (or unenrollment / +role change) dropped stay stored and listed under `/events/{id}/attendance`, +but leave the roster report. +A registration list fills through `POST /events/{id}/register`: teachers place +students (a student never registers, not even themselves) and take seats only +for themselves — registering another staff member is refused. Re-registering +someone is a no-op, a full list is a `409`, and the list freezes the moment +the event starts (register and unregister both). Signup rows survive an +audience switch inertly and resurface if the event returns to the registration +kind; deleting the event deletes them. Pre-existing hand-picked (`users`) +audiences convert on boot: each listed user becomes a signup row credited to +the event's creator, and the audience becomes an uncapped registration list. Reading a child collection of a missing parent (`/events/{id}/attendance`, `/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`, `/courses/{id}/sessions`, `/sessions/{id}/attendance`) is a `404`, not an diff --git a/src/constant.rs b/src/constant.rs index e31ec28..39c43ef 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -58,12 +58,6 @@ pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024; pub const MAX_EVENT_TITLE_LEN: usize = 200; pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; -/// How many users a hand-picked (`kind: "users"`) event audience may list. -/// Bigger groups have a broader kind: a whole role or a course's enrollment. -/// The "100" wording in `web::events`' rejection reason and the `AudienceDto` -/// docs mirrors this literal — keep them in step. -pub const MAX_EVENT_AUDIENCE_USERS: usize = 100; - pub const MAX_EXAM_TITLE_LEN: usize = 200; pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; diff --git a/src/database.rs b/src/database.rs index 9018c0d..deb5a3c 100644 --- a/src/database.rs +++ b/src/database.rs @@ -14,6 +14,7 @@ pub const NOTE_TABLE: &str = "note"; pub const NOTE_FILE_TABLE: &str = "note_file"; pub const EVENT_TABLE: &str = "event"; pub const ATTENDANCE_TABLE: &str = "attendance"; +pub const REGISTRATION_TABLE: &str = "registration"; pub const EXAM_TABLE: &str = "exam"; pub const EXAM_RESULT_TABLE: &str = "exam_result"; pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt"; @@ -29,9 +30,12 @@ pub const TERM_TABLE: &str = "term"; /// SCHEMAFULL schema: every column is typed, references use `record<..>`. /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the -/// definitions, the backfill `UPDATE ... WHERE = NONE` lines only -/// touch rows written before their column existed, and `REMOVE ... IF EXISTS` -/// retires schema (like the single-attempt unique index) exactly once. +/// definitions and `REMOVE ... IF EXISTS` retires schema (like the +/// single-attempt unique index) exactly once. DDL only — data backfills live +/// in `BACKFILL`, which runs as a *separate* query: statements inside one +/// batch see the schema as it stood when the batch started, so an UPDATE next +/// to a fresh `DEFINE FIELD audience.*` writes against the old field set and +/// SCHEMAFULL silently strips the very keys being backfilled. const MIGRATION: &str = " DEFINE TABLE IF NOT EXISTS user SCHEMAFULL; DEFINE FIELD IF NOT EXISTS username ON user TYPE string; @@ -45,7 +49,6 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS theme ON user TYPE option; DEFINE FIELD IF NOT EXISTS language ON user TYPE option; DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; - UPDATE user SET role = 'student' WHERE role = NONE; DEFINE TABLE IF NOT EXISTS session SCHEMAFULL; DEFINE FIELD IF NOT EXISTS user ON session TYPE record; @@ -75,10 +78,10 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string; DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option; DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option>; - DEFINE FIELD IF NOT EXISTS audience.users ON event TYPE option>>; + DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option; + REMOVE FIELD IF EXISTS audience.users ON TABLE event; DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option; DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option; - UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE; DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL; DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record; @@ -88,6 +91,13 @@ const MIGRATION: &str = " DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user; + DEFINE TABLE IF NOT EXISTS registration SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS event ON registration TYPE record; + DEFINE FIELD IF NOT EXISTS user ON registration TYPE record; + DEFINE FIELD IF NOT EXISTS registered_by ON registration TYPE record; + DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE; + DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event; + DEFINE TABLE IF NOT EXISTS term SCHEMAFULL; DEFINE FIELD IF NOT EXISTS name ON term TYPE string; DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int; @@ -193,6 +203,32 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option; "; +/// Data backfills for rows written by older binaries. Runs *after* (and apart +/// from) the DDL batch so every statement sees the freshly defined schema — +/// see the `MIGRATION` doc for why sharing the batch corrupts the writes. +/// Idempotent: each backfill's `WHERE` only matches unconverted rows. +const BACKFILL: &str = " + UPDATE user SET role = 'student' WHERE role = NONE; + + UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; + + -- The hand-picked `users` audience retired into `registration` (2026-07-16): + -- each listed user becomes a signup row credited to the event's creator, and + -- the event becomes an uncapped registration list. Runs once — converted + -- events no longer match the `kind = 'users'` filter. (`?? []`: an empty + -- statement-subquery evaluates to NONE, which FOR refuses to iterate.) + FOR $ev IN ((SELECT id, creator, audience FROM event WHERE audience.kind = 'users') ?? []) { + FOR $usr IN ($ev.audience.users ?? []) { + UPSERT type::record('registration', string::concat(record::id($ev.id), '_', record::id($usr))) CONTENT { + event: $ev.id, + user: $usr, + registered_by: $ev.creator, + }; + }; + UPDATE $ev.id SET audience = { kind: 'registration' }; + }; +"; + /// Open the file-backed database and apply the schema. pub async fn init(cfg: &Config) -> Result { let db = Surreal::new::(cfg.db_path.clone()).await?; @@ -213,5 +249,6 @@ pub async fn init_mem() -> Result { async fn migrate(db: &Database) -> Result<(), AppError> { db.query(MIGRATION).await?.check()?; + db.query(BACKFILL).await?.check()?; Ok(()) } diff --git a/src/domain/event.rs b/src/domain/event.rs index 12823ac..c9efd61 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -7,6 +7,7 @@ use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; use crate::database::{Database, EVENT_TABLE}; use crate::domain::course::CourseId; use crate::domain::enrollment::Enrollment; +use crate::domain::registration::Registration; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; @@ -66,13 +67,14 @@ impl EventDescription { } /// Who an event is aimed at: the expected-attendee roster. Membership is -/// resolved live against today's users/enrollments — never snapshotted — so a -/// role change or (un)enrollment moves people in and out of rosters by itself. -/// The audience does not gate *seeing* the event (the calendar stays -/// school-visible); it defines who counts as expected and who may be marked. +/// resolved live against today's users/enrollments/registrations — never +/// snapshotted — so a role change, (un)enrollment, or (un)registration moves +/// people in and out of rosters by itself. The audience does not gate *seeing* +/// the event (the calendar stays school-visible); it defines who counts as +/// expected and who may be marked. /// /// Stored internally tagged: `{kind: 'school'}`, `{kind: 'role', role: 'student'}`, -/// `{kind: 'course', course: course:…}`, `{kind: 'users', users: [user:…]}`. +/// `{kind: 'course', course: course:…}`, `{kind: 'registration', capacity: 30}`. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] #[surreal(tag = "kind", rename_all = "lowercase")] pub enum EventAudience { @@ -81,17 +83,26 @@ pub enum EventAudience { /// Every user holding exactly this role ("all students", "all teachers"). Role { role: Role }, /// A course's enrolled students. Staff running the course are not implied - /// members — a mixed gathering wants `Users` or a role audience. + /// members — a mixed gathering wants a registration or role audience. Course { course: CourseId }, - /// A hand-picked list. Bounded by `MAX_EVENT_AUDIENCE_USERS` at the web - /// layer; a member row deleted later simply stops resolving. - Users { users: Vec }, + /// A signup list built one person at a time through the register + /// endpoints — teachers place students, staff take their own seat. The + /// list is capped at `capacity` seats when set (`None` = unlimited) and + /// closes once the event starts. Rows survive an audience change inertly. + Registration { capacity: Option }, } impl EventAudience { - /// Is `user` in the roster right now? The point check behind marking — - /// cheaper than resolving the whole roster when the target is known. - pub async fn includes(&self, user: &User, db: &Database) -> Result { + /// Is `user` in `event`'s roster right now? The point check behind + /// marking — cheaper than resolving the whole roster when the target is + /// known. `event` must be the event this audience came from: the + /// registration kind resolves against that event's signup rows. + pub async fn includes( + &self, + event: &EventId, + user: &User, + db: &Database, + ) -> Result { match self { EventAudience::School => Ok(true), EventAudience::Role { role } => Ok(user.get_role() == *role), @@ -100,14 +111,18 @@ impl EventAudience { .await? .is_some()) } - EventAudience::Users { users } => Ok(users.contains(user.get_id())), + EventAudience::Registration { .. } => { + Ok(Registration::read_for_user(event, user.get_id(), db) + .await? + .is_some()) + } } } - /// The full roster, as it stands right now — the who-missed report's - /// backbone. `Users` ids that no longer resolve to a row are kept; the - /// caller degrades their display like any stale reference. - pub async fn members(&self, db: &Database) -> Result, AppError> { + /// `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(&self, event: &EventId, db: &Database) -> Result, AppError> { match self { EventAudience::School => Ok(User::list_all(db) .await? @@ -124,7 +139,11 @@ impl EventAudience { .iter() .map(|enrollment| enrollment.get_user().clone()) .collect()), - EventAudience::Users { users } => Ok(users.clone()), + EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db) + .await? + .iter() + .map(|registration| registration.get_user().clone()) + .collect()), } } } @@ -225,9 +244,9 @@ impl Event { updated.ok_or(AppError::NotFound) } - /// Delete the event and cascade-remove its attendance rows. + /// Delete the event and cascade-remove its attendance and signup rows. pub async fn delete(self, db: &Database) -> Result { - db.query("DELETE attendance WHERE event = $ev") + db.query("DELETE attendance WHERE event = $ev; DELETE registration WHERE event = $ev;") .bind(("ev", self.id.record())) .await? .check()?; @@ -275,10 +294,12 @@ mod tests { "course", ), ( - EventAudience::Users { - users: vec![UserId::from_key("u1"), UserId::from_key("u2")], - }, - "users", + EventAudience::Registration { capacity: Some(30) }, + "registration", + ), + ( + EventAudience::Registration { capacity: None }, + "registration", ), ]; for (audience, kind) in cases { @@ -294,4 +315,22 @@ mod tests { assert_eq!(EventAudience::from_value(value).unwrap(), audience); } } + + /// The database strips `NONE`-valued optional columns and the boot + /// conversion writes a bare `{kind: 'registration'}` — an object with no + /// `capacity` key at all must decode as an uncapped registration. + #[tokio::test] + async fn registration_audience_decodes_without_capacity_key() { + use surrealdb::types::Value; + + let value = EventAudience::Registration { capacity: None }.into_value(); + let Value::Object(mut object) = value else { + panic!("audience must encode as an object, got {value:?}"); + }; + object.remove("capacity"); + assert_eq!( + EventAudience::from_value(Value::Object(object)).unwrap(), + EventAudience::Registration { capacity: None } + ); + } } diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 85910a6..7f231cb 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -16,6 +16,7 @@ pub mod note; pub mod note_file; pub mod preferences; pub mod profile; +pub mod registration; pub mod role; pub mod session; pub mod session_attendance; diff --git a/src/domain/registration.rs b/src/domain/registration.rs new file mode 100644 index 0000000..0536136 --- /dev/null +++ b/src/domain/registration.rs @@ -0,0 +1,156 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::database::{Database, REGISTRATION_TABLE}; +use crate::domain::event::EventId; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct RegistrationId(RecordId); + +impl RegistrationId { + /// A deterministic id for the (event, user) pair — the same pair always + /// maps to the same record id, so registering is one atomic UPSERT with + /// no find-then-insert race and one-row-per-pair by construction (the + /// enrollment trick). ULID keys are alphanumeric, so `_` is unambiguous. + pub fn composite(event: &EventId, user: &UserId) -> Self { + Self(RecordId::new( + REGISTRATION_TABLE, + format!("{}_{}", event.key(), user.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A seat on a registration-audience event's signup list. The list *is* the +/// event's roster: whoever holds a row is expected (and markable), everyone +/// else is not. Rows survive audience changes inertly — switching the event +/// away from the registration kind hides them without deleting them. +#[derive(Debug, Clone, SurrealValue)] +pub struct Registration { + id: RegistrationId, + event: EventId, + user: UserId, + registered_by: UserId, +} + +impl Registration { + pub fn get_id(&self) -> &RegistrationId { + &self.id + } + + pub fn get_event(&self) -> &EventId { + &self.event + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_registered_by(&self) -> &UserId { + &self.registered_by + } + + /// Register (idempotently) `user` onto `event`, refusing when a `capacity` + /// cap is set and every seat is taken. The seat count is re-read inside the + /// transaction and the THROW cancels the UPSERT, so a full event never + /// over-admits through the check-then-write gap; re-registering someone + /// already listed never counts against the cap (and returns their row). + pub async fn register( + event: &EventId, + user: &UserId, + registered_by: &UserId, + capacity: Option, + db: &Database, + ) -> Result { + let registration = Registration { + id: RegistrationId::composite(event, user), + event: event.clone(), + user: user.clone(), + registered_by: registered_by.clone(), + }; + let mut result = db + .query( + "BEGIN TRANSACTION; + LET $already = (SELECT VALUE id FROM registration WHERE event = $ev AND user = $usr); + LET $count = (SELECT count() FROM registration WHERE event = $ev GROUP ALL)[0].count ?? 0; + IF $cap != NONE AND array::len($already) = 0 AND $count >= $cap { THROW 'event_full' }; + UPSERT $id CONTENT $registration; + COMMIT TRANSACTION;", + ) + .bind(("ev", event.record())) + .bind(("usr", user.record())) + .bind(("cap", capacity)) + .bind(("id", registration.id.record())) + .bind(("registration", registration)) + .await?; + // An aborted transaction errors *every* slot, most with a generic + // "not executed" — only the THROW's own slot names the reason, so scan + // them all for the marker instead of trusting the first (`check`-style) + // error. + let mut errors = result.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains("event_full")) + { + return Err(AppError::Conflict("the event is full")); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Statement slots count BEGIN and the LETs too: the UPSERT is slot 4. + let saved: Option = result.take::>(4)?.into_iter().next(); + saved.ok_or_else(|| AppError::Internal("failed to register user".into())) + } + + /// Some(_) iff `user` holds a seat on `event` — the audience point check. + pub async fn read_for_user( + event: &EventId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM registration WHERE event = $ev AND user = $usr LIMIT 1") + .bind(("ev", event.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + pub async fn list_for_event( + event: &EventId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM registration WHERE event = $ev ORDER BY id DESC") + .bind(("ev", event.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn remove( + event: &EventId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE") + .bind(("ev", event.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } +} diff --git a/src/lib.rs b/src/lib.rs index 675c4cd..1a80c38 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a hand-picked list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", ), modifiers(&SecurityAddon), tags( @@ -40,7 +40,7 @@ use crate::state::AppState; (name = "auth", description = "Registration, login, session lifecycle"), (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only)"), (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), - (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a hand-picked user list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed"), + (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts"), (name = "courses", description = "Courses, enrollment (students only), course exams, and course sessions"), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), diff --git a/src/web/events.rs b/src/web/events.rs index 5698ac5..0debaee 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -8,11 +8,11 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::MAX_EVENT_AUDIENCE_USERS; use crate::database::Database; use crate::domain::attendance::{Attendance, AttendanceStatus}; use crate::domain::course::{Course, CourseId}; use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; +use crate::domain::registration::Registration; use crate::domain::role::Role; use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; @@ -32,6 +32,8 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(mark, list_attendance)) .routes(routes!(remove_attendance)) .routes(routes!(roster)) + .routes(routes!(register)) + .routes(routes!(unregister)) } /// An event's audience on the wire — who is expected to attend. Tagged by @@ -48,14 +50,18 @@ enum AudienceDto { /// The students currently enrolled in this course (live — enrollment /// changes move people in and out). Course { course: String }, - /// A hand-picked list of user ids (at most `100`, deduplicated). - Users { users: Vec }, + /// A signup list built through `POST /events/{id}/register` — teachers + /// place students, staff take their own seat. `capacity` caps the seats; + /// `null` or omitted = unlimited. The list closes when the event starts. + Registration { + #[serde(default)] + capacity: Option, + }, } impl AudienceDto { /// Validate the wire form into the domain audience: the role must parse, - /// the course must exist, and a `users` list must be non-empty, within the - /// cap, and name only existing users. + /// the course must exist, and a registration capacity must be positive. async fn into_domain(self, db: &Database) -> Result { match self { AudienceDto::School => Ok(EventAudience::School), @@ -72,32 +78,14 @@ impl AudienceDto { } Ok(EventAudience::Course { course }) } - AudienceDto::Users { users } => { - let mut seen = std::collections::HashSet::new(); - let users: Vec = users - .iter() - .filter(|key| seen.insert(key.as_str())) - .map(|key| UserId::from_key(key)) - .collect(); - if users.is_empty() { + AudienceDto::Registration { capacity } => { + if capacity.is_some_and(|capacity| capacity < 1) { return Err(AppError::Validation(ValidationError::Invalid { field: "audience", - reason: "users must not be empty", + reason: "capacity must be at least 1", })); } - if users.len() > MAX_EVENT_AUDIENCE_USERS { - return Err(AppError::Validation(ValidationError::Invalid { - field: "audience", - reason: "users lists more than 100 people — target a role or course instead", - })); - } - if User::list_by_ids(&users, db).await?.len() != users.len() { - return Err(AppError::Validation(ValidationError::Invalid { - field: "audience", - reason: "users lists a user that does not exist", - })); - } - Ok(EventAudience::Users { users }) + Ok(EventAudience::Registration { capacity }) } } } @@ -111,8 +99,8 @@ impl AudienceDto { EventAudience::Course { course } => AudienceDto::Course { course: course.key().to_string(), }, - EventAudience::Users { users } => AudienceDto::Users { - users: users.iter().map(|user| user.key().to_string()).collect(), + EventAudience::Registration { capacity } => AudienceDto::Registration { + capacity: *capacity, }, } } @@ -222,8 +210,9 @@ impl AttendanceResponse { /// Create an event owned by the current user. Requires the `teacher` role or /// higher. `audience` targets it at a role, a course's enrollment, or a -/// hand-picked user list; omitted it is school-wide. Everyone still sees every -/// event — the audience is the expected-attendee roster, not a visibility wall. +/// registration list (filled via `POST /events/{id}/register`); omitted it is +/// school-wide. Everyone still sees every event — the audience is the +/// expected-attendee roster, not a visibility wall. #[utoipa::path( post, path = "/", @@ -322,8 +311,9 @@ async fn get_event( /// Update an event. Requires teacher+; the creator may edit their own event and /// managers/admins may edit anyone's. Omitted fields keep their value; an /// explicit `null` clears `starts_at`/`ends_at`. A provided `audience` replaces -/// the current one wholesale — attendance rows for people it drops stay stored -/// but leave the roster report. +/// the current one wholesale — attendance and signup rows for people it drops +/// stay stored but leave the roster report (signups resurface if the event is +/// switched back to the registration kind). #[utoipa::path( patch, path = "/{id}", @@ -473,7 +463,11 @@ async fn mark( // Only expected attendees can be marked. The marker needn't be in the // audience — a teacher takes roll of a student-targeted event. - if !event.get_audience().includes(&target_user, &st.db).await? { + if !event + .get_audience() + .includes(event.get_id(), &target_user, &st.db) + .await? + { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "target user is not in this event's audience", @@ -578,7 +572,8 @@ struct RosterEntry { /// The event's expected-attendee roster joined with its attendance marks — the /// who-came/who-missed report. Resolved live from the audience (today's role -/// holders, current enrollment), so it always reflects the present roster; +/// holders, current enrollment, the current signup list), so it always reflects +/// the present roster; /// attendance rows for people no longer in the audience are omitted here (they /// remain in `GET /events/{id}/attendance`). Requires teacher+. Paged via /// `?limit=&offset=` (omit `limit` for the whole roster). @@ -608,7 +603,7 @@ async fn roster( .await? .ok_or(AppError::NotFound)?; - let mut members = event.get_audience().members(&st.db).await?; + let mut members = event.get_audience().members(event.get_id(), &st.db).await?; // ULID keys sort by creation instant — a stable order keeps pages coherent. members.sort_by(|a, b| a.key().cmp(b.key())); let marks = Attendance::list_for_event(&event_id, &st.db).await?; @@ -640,3 +635,157 @@ async fn roster( .collect(); Ok(Json(Page::new(items, total, limit, offset))) } + +// ---- registration --------------------------------------------------------- + +#[derive(Deserialize, ToSchema)] +struct RegisterUser { + /// Target user id — must name a student (staff take seats only for + /// themselves). Defaults to the caller when omitted. + user_id: Option, +} + +#[derive(Serialize, ToSchema)] +struct RegistrationResponse { + event: String, + /// Who holds the seat. + user: PersonRef, + /// Who placed them on the list. + registered_by: PersonRef, +} + +/// The shared gate for touching a signup list: the event must carry the +/// registration audience, and the list must still be open — it closes the +/// moment the event starts (a timeless event never closes). Returns the seat +/// cap for the register path. +fn check_registration_open(event: &Event) -> Result, AppError> { + let EventAudience::Registration { capacity } = event.get_audience() else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "audience", + reason: "this event does not take registrations", + })); + }; + if let Some(starts_at) = event.get_starts_at() + && Timestamp::now().as_millis() >= starts_at.as_millis() + { + return Err(AppError::Conflict( + "registration closed when the event started", + )); + } + Ok(*capacity) +} + +/// Put a user on a registration-audience event's signup list. Requires +/// teacher+. `user_id` must name a student — students are placed by staff and +/// never register themselves; omit it to take a seat yourself (staff +/// self-serve, so registering another teacher/manager is refused). Registering +/// the same person twice is a no-op returning the existing seat. The list +/// closes when the event starts and refuses to grow past `capacity`. +#[utoipa::path( + post, + path = "/{id}/register", + tag = "events", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Event id")), + request_body = RegisterUser, + responses( + (status = 200, description = "Seat taken (or already held)", body = RegistrationResponse), + (status = 400, description = "Not a registration event, or the target is unknown", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), + (status = 404, description = "Event not found", body = ErrorResponse), + (status = 409, description = "The event is full, or it already started", body = ErrorResponse), + ), +)] +async fn register( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let event_id = EventId::from_key(&id); + let event = Event::read(&event_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let capacity = check_registration_open(&event)?; + + let target = match req.user_id { + Some(ref key) => UserId::from_key(key), + None => user.get_id().clone(), + }; + let Some(target_user) = User::read(&target, &st.db).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + }; + // Students are placed by staff; staff hold only their own seat. + if &target != user.get_id() && target_user.get_role() != Role::Student { + return Err(AppError::Forbidden( + "staff register themselves — only students can be registered for", + )); + } + + let registration = + Registration::register(&event_id, &target, user.get_id(), capacity, &st.db).await?; + let people = PersonRef::map_of(&[&target_user, &user]); + Ok(Json(RegistrationResponse { + event: registration.get_event().key().to_string(), + user: PersonRef::resolve(&people, registration.get_user()), + registered_by: PersonRef::resolve(&people, registration.get_registered_by()), + })) +} + +/// Take a user off the signup list — the register rules mirrored: teacher+, +/// students' seats or your own (another staff member's seat only if their +/// account no longer exists), and only while the list is open (the event +/// hasn't started). Attendance already marked stays recorded. +#[utoipa::path( + delete, + path = "/{id}/register/{user}", + tag = "events", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Event id"), + ("user" = String, Path, description = "User id"), + ), + responses( + (status = 204, description = "Seat freed"), + (status = 400, description = "Not a registration event", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), + (status = 404, description = "Event not found, or the user holds no seat", body = ErrorResponse), + (status = 409, description = "The event already started", body = ErrorResponse), + ), +)] +async fn unregister( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, target)): Path<(String, String)>, +) -> Result { + let event_id = EventId::from_key(&id); + let event = Event::read(&event_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + check_registration_open(&event)?; + + let target = UserId::from_key(&target); + // A deleted account's leftover seat is fair game for any teacher+; a + // living staff member's seat is theirs alone. + if &target != user.get_id() + && let Some(target_user) = User::read(&target, &st.db).await? + && target_user.get_role() != Role::Student + { + return Err(AppError::Forbidden( + "staff unregister themselves — only students' seats can be freed", + )); + } + + if Registration::remove(&event_id, &target, &st.db) + .await? + .is_none() + { + return Err(AppError::NotFound); + } + Ok(StatusCode::NO_CONTENT) +} diff --git a/tests/integration.rs b/tests/integration.rs index aa2abff..e658b6f 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -1217,8 +1217,6 @@ async fn event_timestamps_echo_and_validate() { async fn event_audience_defaults_validates_and_echoes() { let (app, db) = app_and_db().await; let ali = login_as(&app, &db, "ali", "teacher").await; - let veli = login(&app, "veli").await; // student - let veli_id = me_id(&app, &veli).await; // Omitted audience = school-wide, and it echoes on every read. let ev = send( @@ -1260,22 +1258,32 @@ async fn event_audience_defaults_validates_and_echoes() { "PATCH", &format!("/events/{event_id}"), Some(&ali), - Some(json!({ "audience": { "kind": "users", "users": [veli_id, veli_id] } })), + Some(json!({ "audience": { "kind": "registration", "capacity": 5 } })), ) .await; assert_eq!(res.status, StatusCode::OK); - // The duplicated id collapsed to one entry. - assert_eq!(res.body["audience"]["users"].as_array().unwrap().len(), 1); + assert_eq!(res.body["audience"]["capacity"], 5); - // Invalid audiences are rejected: unknown role, ghost course, ghost user, - // an empty hand-picked list, and one past the 100-user cap. + // An omitted capacity echoes as null: an uncapped signup list. + let res = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "trip", "audience": { "kind": "registration" } })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + assert_eq!(res.body["audience"]["kind"], "registration"); + assert!(res.body["audience"]["capacity"].is_null()); + + // Invalid audiences are rejected: unknown role, ghost course, and + // non-positive capacities. for audience in [ json!({ "kind": "role", "role": "wizard" }), json!({ "kind": "course", "course": "nope" }), - json!({ "kind": "users", "users": ["ghost"] }), - json!({ "kind": "users", "users": [] }), - json!({ "kind": "users", - "users": (0..101).map(|n| format!("u{n}")).collect::>() }), + json!({ "kind": "registration", "capacity": 0 }), + json!({ "kind": "registration", "capacity": -3 }), ] { let res = send( &app, @@ -1287,16 +1295,22 @@ async fn event_audience_defaults_validates_and_echoes() { .await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{audience}"); } - // An unknown kind never deserializes. - let res = send( - &app, - "POST", - "/events", - Some(&ali), - Some(json!({ "title": "bad", "audience": { "kind": "galaxy" } })), - ) - .await; - assert!(res.status.is_client_error(), "{}", res.status); + // An unknown kind never deserializes — including the retired hand-picked + // `users` kind, gone in the registration clean break. + for audience in [ + json!({ "kind": "galaxy" }), + json!({ "kind": "users", "users": ["ghost"] }), + ] { + let res = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "bad", "audience": audience })), + ) + .await; + assert!(res.status.is_client_error(), "{audience}: {}", res.status); + } } #[tokio::test] @@ -1373,8 +1387,17 @@ async fn event_audience_gates_marking() { StatusCode::BAD_REQUEST ); - // Hand-picked audience: the list is the roster. - let ev = create(json!({ "kind": "users", "users": [mina_id.clone()] })).await; + // Registration audience: the signup list is the roster. + let ev = create(json!({ "kind": "registration" })).await; + let res = send( + &app, + "POST", + &format!("/events/{ev}/register"), + Some(&ali), + Some(json!({ "user_id": mina_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(mark(ev.clone(), mina_id.clone()).await, StatusCode::OK); assert_eq!( mark(ev.clone(), veli_id.clone()).await, @@ -3071,6 +3094,331 @@ async fn students_never_mark_attendance() { ); } +/// Registration seats follow the placement rule — teachers seat students and +/// themselves, never other staff; students never touch the endpoints — and a +/// repeat register is a no-op on the same single row. Deleting the event +/// removes its signup rows with it. +#[tokio::test] +async fn event_registration_follows_placement_rules() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let deniz = login_as(&app, &db, "deniz", "teacher").await; + let veli = login(&app, "veli").await; // student + let veli_id = me_id(&app, &veli).await; + let ali_id = me_id(&app, &ali).await; + let deniz_id = me_id(&app, &deniz).await; + + let res = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "seminar", "audience": { "kind": "registration" } })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + let ev = id_of(&res.body); + let register_uri = format!("/events/{ev}/register"); + + // Students can't register — not even themselves. + let res = send(&app, "POST", ®ister_uri, Some(&veli), Some(json!({}))).await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + + // A teacher seats a student; the row names who placed whom. + let res = send( + &app, + "POST", + ®ister_uri, + Some(&ali), + Some(json!({ "user_id": veli_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["user"]["id"], veli_id); + assert_eq!(res.body["registered_by"]["id"], ali_id); + + // Registering the same student again is a no-op on the same seat. + let res = send( + &app, + "POST", + ®ister_uri, + Some(&deniz), + Some(json!({ "user_id": veli_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + let roster = send( + &app, + "GET", + &format!("/events/{ev}/roster"), + Some(&ali), + None, + ) + .await; + assert_eq!(common::total(&roster.body), 1, "upsert keeps a single seat"); + + // A teacher takes their own seat by omitting the target… + let res = send(&app, "POST", ®ister_uri, Some(&ali), Some(json!({}))).await; + assert_eq!(res.status, StatusCode::OK); + // …but never seats another staff member, and ghosts don't register. + let res = send( + &app, + "POST", + ®ister_uri, + Some(&ali), + Some(json!({ "user_id": deniz_id })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + let res = send( + &app, + "POST", + ®ister_uri, + Some(&ali), + Some(json!({ "user_id": "ghost" })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); + + // Non-registration events refuse the endpoint outright. + let school = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "assembly" })), + ) + .await; + let res = send( + &app, + "POST", + &format!("/events/{}/register", id_of(&school.body)), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); + + // Unregistering mirrors the rule: students never, staff seats are their + // own, students' seats are anyone's (teacher+) to free. + let res = send( + &app, + "DELETE", + &format!("{register_uri}/{ali_id}"), + Some(&veli), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + let res = send( + &app, + "DELETE", + &format!("{register_uri}/{ali_id}"), + Some(&deniz), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "staff seat is not deniz's" + ); + let res = send( + &app, + "DELETE", + &format!("{register_uri}/{veli_id}"), + Some(&deniz), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + let res = send( + &app, + "DELETE", + &format!("{register_uri}/{veli_id}"), + Some(&deniz), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "seat already freed"); + + // Deleting the event cascades its signup rows away. + let res = send(&app, "DELETE", &format!("/events/{ev}"), Some(&ali), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + let left: Vec = + db.select("registration").await.unwrap(); + assert!(left.is_empty(), "event delete leaves no seats behind"); +} + +/// A capacity caps live seats, not history: re-registering never double-counts, +/// freeing a seat reopens it, and shrinking the cap below the current count +/// only blocks new seats. +#[tokio::test] +async fn event_registration_capacity_caps_seats() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let veli = login(&app, "veli").await; + let mina = login(&app, "mina").await; + let veli_id = me_id(&app, &veli).await; + let mina_id = me_id(&app, &mina).await; + + let res = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "workshop", + "audience": { "kind": "registration", "capacity": 1 } })), + ) + .await; + let ev = id_of(&res.body); + let register_uri = format!("/events/{ev}/register"); + let register = |user: String| { + let app = &app; + let ali = &ali; + let uri = ®ister_uri; + async move { + send( + app, + "POST", + uri, + Some(ali), + Some(json!({ "user_id": user })), + ) + .await + .status + } + }; + + assert_eq!(register(veli_id.clone()).await, StatusCode::OK); + assert_eq!( + register(mina_id.clone()).await, + StatusCode::CONFLICT, + "full" + ); + assert_eq!( + register(veli_id.clone()).await, + StatusCode::OK, + "re-register of a seated user never counts against the cap" + ); + + // Freeing the seat reopens the list. + let res = send( + &app, + "DELETE", + &format!("{register_uri}/{veli_id}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + assert_eq!(register(mina_id.clone()).await, StatusCode::OK); + + // Shrinking the cap under the current count keeps the seats and only + // refuses growth. + assert_eq!( + send( + &app, + "PATCH", + &format!("/events/{ev}"), + Some(&ali), + Some(json!({ "audience": { "kind": "registration", "capacity": 2 } })), + ) + .await + .status, + StatusCode::OK + ); + assert_eq!(register(veli_id.clone()).await, StatusCode::OK); + assert_eq!( + send( + &app, + "PATCH", + &format!("/events/{ev}"), + Some(&ali), + Some(json!({ "audience": { "kind": "registration", "capacity": 1 } })), + ) + .await + .status, + StatusCode::OK + ); + let roster = send( + &app, + "GET", + &format!("/events/{ev}/roster"), + Some(&ali), + None, + ) + .await; + assert_eq!( + common::total(&roster.body), + 2, + "shrink keeps existing seats" + ); +} + +/// The signup list freezes the moment the event starts — both directions. +/// (The create-time no-past grace lets a just-started event exist, which is +/// exactly a closed list.) +#[tokio::test] +async fn event_registration_closes_at_start() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let veli = login(&app, "veli").await; + let veli_id = me_id(&app, &veli).await; + let now = Timestamp::now().as_millis(); + + // Started 30s ago: inside the scheduling grace, so creation passes — but + // the list is already closed. + let res = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "underway", "starts_at": now - 30_000, + "audience": { "kind": "registration" } })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let ev = id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/events/{ev}/register"), + Some(&ali), + Some(json!({ "user_id": veli_id })), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT); + let res = send( + &app, + "DELETE", + &format!("/events/{ev}/register/{veli_id}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "unregister freezes too"); + + // A future or timeless event keeps its list open. + for body in [ + json!({ "title": "later", "starts_at": now + 3_600_000, + "audience": { "kind": "registration" } }), + json!({ "title": "whenever", "audience": { "kind": "registration" } }), + ] { + let res = send(&app, "POST", "/events", Some(&ali), Some(body)).await; + let ev = id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/events/{ev}/register"), + Some(&ali), + Some(json!({ "user_id": veli_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + } +} + #[tokio::test] async fn event_management_follows_hierarchy() { let (app, db) = app_and_db().await; diff --git a/tests/persistence.rs b/tests/persistence.rs index 1bbb362..d58fdf7 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -593,3 +593,110 @@ async fn legacy_events_backfill_to_school_audience() { assert_eq!(res.status, StatusCode::OK); assert_eq!(common::total(&res.body), 1, "whole school = the one user"); } + +/// Event rows carrying the retired hand-picked (`users`) audience convert on +/// the next boot: the audience becomes an uncapped registration list and each +/// listed user gets a signup row credited to the event's creator — the old +/// roster survives the clean break byte for byte. +#[tokio::test] +async fn legacy_users_audiences_convert_to_registrations() { + let dir = tempfile::tempdir().unwrap(); + let cfg = config_at(&dir); + let creds = json!({ "username": "ali", "password": "secret1" }); + let event_id; + let student_id; + + // First boot: a registration-audience event — then rewrite it into the + // shape an old binary left behind: restore the `audience.users` column + // definition and store a hand-picked list on the row. + { + let db = database::init(&cfg).await.expect("first open"); + let app = build_router(state(db.clone(), &cfg)); + assert_eq!( + send(&app, "POST", "/auth/register", None, Some(creds.clone())) + .await + .status, + StatusCode::CREATED + ); + set_role(&db, "ali", "teacher").await; + let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) + .await + .cookie + .unwrap(); + let student = json!({ "username": "veli", "password": "secret1" }); + assert_eq!( + send(&app, "POST", "/auth/register", None, Some(student.clone())) + .await + .status, + StatusCode::CREATED + ); + let student_cookie = send(&app, "POST", "/auth/login", None, Some(student)) + .await + .cookie + .unwrap(); + student_id = common::me_id(&app, &student_cookie).await; + + let res = send( + &app, + "POST", + "/events", + Some(&cookie), + Some(json!({ "title": "trip", "audience": { "kind": "registration" } })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + event_id = common::id_of(&res.body); + + db.query(format!( + "DEFINE FIELD OVERWRITE audience.users ON TABLE event TYPE option>>; + UPDATE event SET audience = {{ kind: 'users', users: [type::record('user', $usr)] }} + WHERE id = type::record('event', '{event_id}');" + )) + .bind(("usr", student_id.clone())) + .await + .expect("rewrite to legacy users audience") + .check() + .expect("rewrite check"); + } + + // Second boot runs the conversion: the audience reads back as an uncapped + // registration list, the listed student holds a seat credited to the + // creator, and the roster (and marking gate) see them. + let db = reopen(&cfg).await; + let app = build_router(state(db, &cfg)); + let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) + .await + .cookie + .unwrap(); + let res = send( + &app, + "GET", + &format!("/events/{event_id}"), + Some(&cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["audience"]["kind"], "registration"); + assert!(res.body["audience"]["capacity"].is_null()); + let res = send( + &app, + "GET", + &format!("/events/{event_id}/roster"), + Some(&cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(common::total(&res.body), 1, "the listed user became a seat"); + assert_eq!(common::items(&res.body)[0]["user"]["id"], student_id); + let res = send( + &app, + "POST", + &format!("/events/{event_id}/attendance"), + Some(&cookie), + Some(json!({ "status": "present", "user_id": student_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "converted seat is markable"); +}