forge
Explore
Log in

Don't you dare go Hollow

Registration audience replaces hand-picked users

Browse files at this commit

31e155aa3bc532176f525ec15230a65c9ef1e49cAhmet Kaan GümüşParent: bd9e7d8
  • feat
    • registration audience replaces hand-picked users
Show full message
✨ feat(events)!: registration audience replaces hand-picked users

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.mdmodified+29 -13
@@ -7,10 +7,13 @@ Session-cookie auth with four hierarchical roles (`student < teacher < manager
7 …): blobs live on disk next to the database, metadata in the database, and the7 …): blobs live on disk next to the database, metadata in the database, and the
8 per-file size cap is school policy in settings (`max_file_bytes`, default8 per-file size cap is school policy in settings (`max_file_bytes`, default
9 5 MiB). Attendance is event + attendees: create an event with an **audience**9 5 MiB). Attendance is event + attendees: create an event with an **audience**
10-(the whole school, one role, a course's enrollment, or a hand-picked list —10+(the whole school, one role, a course's enrollment, or a **registration**
11-omit for school-wide), then teachers mark the expected attendees present /11+signup list — omit for school-wide), then teachers mark the expected attendees
12-absent / late / excused (students never self-mark), and a **roster report**12+present / absent / late / excused (students never self-mark), and a **roster
13-shows who was expected and who missed. Every event stays visible to everyone —13+report** shows who was expected and who missed. Registration lists fill seat
14+by seat: teachers register students (never the other way round), staff
15+register only themselves, an optional `capacity` caps the seats, and the list
16+closes the moment the event starts. Every event stays visible to everyone —
14 the audience is a roster, not a wall. Marks are course-shaped17 the audience is a roster, not a wall. Marks are course-shaped
15 (Google Classroom style): a teacher creates a course, enrolls students, adds18 (Google Classroom style): a teacher creates a course, enrolls students, adds
16 exams inside it, and grades — enrolling, sitting exams, roll call, and marks are19 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).
169 | Register / login / view own account | (any) | Registration always creates a `student` |172 | Register / login / view own account | (any) | Registration always creates a `student` |
170 | 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 |173 | 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 |
171 | 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 |174 | 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 |
172-| Create events | teacher | The audience (school / role / course / user list) is set at creation and editable later |175+| Create events | teacher | The audience (school / role / course / registration) is set at creation and editable later |
176+| 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 |
173 | List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report |177 | List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report |
174 | Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |178 | Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |
175 | View a course's sessions | student | Only inside **visible** courses: enrolled, creator, or `manager`+ |179 | 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
292 | GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) · paged |296 | GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) · paged |
293 | GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` · paged |297 | GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` · paged |
294 | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |298 | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |
299+| 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 |
300+| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |
295 | POST | `/courses` | teacher | `{title, description?}` (creator manages it) |301 | POST | `/courses` | teacher | `{title, description?}` (creator manages it) |
296 | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged |302 | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged |
297 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |303 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |
@@ -380,14 +386,24 @@ explicit `null` clears it.
380 An event's `audience` is a tagged object — `{"kind": "school"}` (the default),386 An event's `audience` is a tagged object — `{"kind": "school"}` (the default),
381 `{"kind": "role", "role": "student"}` (that exact role, no "and above"),387 `{"kind": "role", "role": "student"}` (that exact role, no "and above"),
382 `{"kind": "course", "course": "<id>"}` (the course's current enrollment), or388 `{"kind": "course", "course": "<id>"}` (the course's current enrollment), or
383-`{"kind": "users", "users": ["<id>", …]}` (hand-picked, ≤ 100, deduplicated) —389+`{"kind": "registration", "capacity": 30}` (a signup list; `capacity` optional,
384-and is the event's **expected-attendee roster**, resolved live at read time:390+`null` = unlimited) — and is the event's **expected-attendee roster**, resolved
385-role changes and (un)enrollments move people in and out by themselves. It never391+live at read time: role changes, (un)enrollments, and (un)registrations move
386-hides the event — everyone sees every event. Only audience members can be392+people in and out by themselves. It never hides the event — everyone sees every
387-marked; `GET /events/{id}/roster` joins the live roster with the recorded marks393+event. Only audience members can be marked; `GET /events/{id}/roster` joins the
388-(`status: null` = expected but never marked). Attendance rows for people a394+live roster with the recorded marks (`status: null` = expected but never
389-later audience edit (or unenrollment / role change) dropped stay stored and395+marked). Attendance rows for people a later audience edit (or unenrollment /
390-listed under `/events/{id}/attendance`, but leave the roster report.396+role change) dropped stay stored and listed under `/events/{id}/attendance`,
397+but leave the roster report.
398+A registration list fills through `POST /events/{id}/register`: teachers place
399+students (a student never registers, not even themselves) and take seats only
400+for themselves — registering another staff member is refused. Re-registering
401+someone is a no-op, a full list is a `409`, and the list freezes the moment
402+the event starts (register and unregister both). Signup rows survive an
403+audience switch inertly and resurface if the event returns to the registration
404+kind; deleting the event deletes them. Pre-existing hand-picked (`users`)
405+audiences convert on boot: each listed user becomes a signup row credited to
406+the event's creator, and the audience becomes an uncapped registration list.
391 Reading a child collection of a missing parent (`/events/{id}/attendance`,407 Reading a child collection of a missing parent (`/events/{id}/attendance`,
392 `/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`,408 `/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`,
393 `/courses/{id}/sessions`, `/sessions/{id}/attendance`) is a `404`, not an409 `/courses/{id}/sessions`, `/sessions/{id}/attendance`) is a `404`, not an
src/constant.rsmodified+0 -6
@@ -58,12 +58,6 @@ pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024;
58 pub const MAX_EVENT_TITLE_LEN: usize = 200;58 pub const MAX_EVENT_TITLE_LEN: usize = 200;
59 pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000;59 pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000;
60 60
61-/// How many users a hand-picked (`kind: "users"`) event audience may list.
62-/// Bigger groups have a broader kind: a whole role or a course's enrollment.
63-/// The "100" wording in `web::events`' rejection reason and the `AudienceDto`
64-/// docs mirrors this literal — keep them in step.
65-pub const MAX_EVENT_AUDIENCE_USERS: usize = 100;
66-
67 pub const MAX_EXAM_TITLE_LEN: usize = 200;61 pub const MAX_EXAM_TITLE_LEN: usize = 200;
68 pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000;62 pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000;
69 63
src/database.rsmodified+43 -6
@@ -14,6 +14,7 @@ pub const NOTE_TABLE: &str = "note";
14 pub const NOTE_FILE_TABLE: &str = "note_file";14 pub const NOTE_FILE_TABLE: &str = "note_file";
15 pub const EVENT_TABLE: &str = "event";15 pub const EVENT_TABLE: &str = "event";
16 pub const ATTENDANCE_TABLE: &str = "attendance";16 pub const ATTENDANCE_TABLE: &str = "attendance";
17+pub const REGISTRATION_TABLE: &str = "registration";
17 pub const EXAM_TABLE: &str = "exam";18 pub const EXAM_TABLE: &str = "exam";
18 pub const EXAM_RESULT_TABLE: &str = "exam_result";19 pub const EXAM_RESULT_TABLE: &str = "exam_result";
19 pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt";20 pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt";
@@ -29,9 +30,12 @@ pub const TERM_TABLE: &str = "term";
29 30
30 /// SCHEMAFULL schema: every column is typed, references use `record<..>`.31 /// SCHEMAFULL schema: every column is typed, references use `record<..>`.
31 /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the32 /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the
32-/// definitions, the backfill `UPDATE ... WHERE <field> = NONE` lines only33+/// definitions and `REMOVE ... IF EXISTS` retires schema (like the
33-/// touch rows written before their column existed, and `REMOVE ... IF EXISTS`34+/// single-attempt unique index) exactly once. DDL only — data backfills live
34-/// retires schema (like the single-attempt unique index) exactly once.35+/// in `BACKFILL`, which runs as a *separate* query: statements inside one
36+/// batch see the schema as it stood when the batch started, so an UPDATE next
37+/// to a fresh `DEFINE FIELD audience.*` writes against the old field set and
38+/// SCHEMAFULL silently strips the very keys being backfilled.
35 const MIGRATION: &str = "39 const MIGRATION: &str = "
36 DEFINE TABLE IF NOT EXISTS user SCHEMAFULL;40 DEFINE TABLE IF NOT EXISTS user SCHEMAFULL;
37 DEFINE FIELD IF NOT EXISTS username ON user TYPE string;41 DEFINE FIELD IF NOT EXISTS username ON user TYPE string;
@@ -45,7 +49,6 @@ const MIGRATION: &str = "
45 DEFINE FIELD IF NOT EXISTS theme ON user TYPE option<string>;49 DEFINE FIELD IF NOT EXISTS theme ON user TYPE option<string>;
46 DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>;50 DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>;
47 DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;51 DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;
48- UPDATE user SET role = 'student' WHERE role = NONE;
49 52
50 DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;53 DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;
51 DEFINE FIELD IF NOT EXISTS user ON session TYPE record<user>;54 DEFINE FIELD IF NOT EXISTS user ON session TYPE record<user>;
@@ -75,10 +78,10 @@ const MIGRATION: &str = "
75 DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string;78 DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string;
76 DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option<string>;79 DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option<string>;
77 DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option<record<course>>;80 DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option<record<course>>;
78- DEFINE FIELD IF NOT EXISTS audience.users ON event TYPE option<array<record<user>>>;81+ DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option<int>;
82+ REMOVE FIELD IF EXISTS audience.users ON TABLE event;
79 DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option<int>;83 DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option<int>;
80 DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option<int>;84 DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option<int>;
81- UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE;
82 85
83 DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL;86 DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL;
84 DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record<event>;87 DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record<event>;
@@ -88,6 +91,13 @@ const MIGRATION: &str = "
88 DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE;91 DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE;
89 DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user;92 DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user;
90 93
94+ DEFINE TABLE IF NOT EXISTS registration SCHEMAFULL;
95+ DEFINE FIELD IF NOT EXISTS event ON registration TYPE record<event>;
96+ DEFINE FIELD IF NOT EXISTS user ON registration TYPE record<user>;
97+ DEFINE FIELD IF NOT EXISTS registered_by ON registration TYPE record<user>;
98+ DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE;
99+ DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event;
100+
91 DEFINE TABLE IF NOT EXISTS term SCHEMAFULL;101 DEFINE TABLE IF NOT EXISTS term SCHEMAFULL;
92 DEFINE FIELD IF NOT EXISTS name ON term TYPE string;102 DEFINE FIELD IF NOT EXISTS name ON term TYPE string;
93 DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int;103 DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int;
@@ -193,6 +203,32 @@ const MIGRATION: &str = "
193 DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>;203 DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>;
194 ";204 ";
195 205
206+/// Data backfills for rows written by older binaries. Runs *after* (and apart
207+/// from) the DDL batch so every statement sees the freshly defined schema —
208+/// see the `MIGRATION` doc for why sharing the batch corrupts the writes.
209+/// Idempotent: each backfill's `WHERE` only matches unconverted rows.
210+const BACKFILL: &str = "
211+ UPDATE user SET role = 'student' WHERE role = NONE;
212+
213+ UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};
214+
215+ -- The hand-picked `users` audience retired into `registration` (2026-07-16):
216+ -- each listed user becomes a signup row credited to the event's creator, and
217+ -- the event becomes an uncapped registration list. Runs once — converted
218+ -- events no longer match the `kind = 'users'` filter. (`?? []`: an empty
219+ -- statement-subquery evaluates to NONE, which FOR refuses to iterate.)
220+ FOR $ev IN ((SELECT id, creator, audience FROM event WHERE audience.kind = 'users') ?? []) {
221+ FOR $usr IN ($ev.audience.users ?? []) {
222+ UPSERT type::record('registration', string::concat(record::id($ev.id), '_', record::id($usr))) CONTENT {
223+ event: $ev.id,
224+ user: $usr,
225+ registered_by: $ev.creator,
226+ };
227+ };
228+ UPDATE $ev.id SET audience = { kind: 'registration' };
229+ };
230+";
231+
196 /// Open the file-backed database and apply the schema.232 /// Open the file-backed database and apply the schema.
197 pub async fn init(cfg: &Config) -> Result<Database, AppError> {233 pub async fn init(cfg: &Config) -> Result<Database, AppError> {
198 let db = Surreal::new::<SurrealKv>(cfg.db_path.clone()).await?;234 let db = Surreal::new::<SurrealKv>(cfg.db_path.clone()).await?;
@@ -213,5 +249,6 @@ pub async fn init_mem() -> Result<Database, AppError> {
213 249
214 async fn migrate(db: &Database) -> Result<(), AppError> {250 async fn migrate(db: &Database) -> Result<(), AppError> {
215 db.query(MIGRATION).await?.check()?;251 db.query(MIGRATION).await?.check()?;
252+ db.query(BACKFILL).await?.check()?;
216 Ok(())253 Ok(())
217 }254 }
src/domain/event.rsmodified+63 -24
@@ -7,6 +7,7 @@ use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};
7 use crate::database::{Database, EVENT_TABLE};7 use crate::database::{Database, EVENT_TABLE};
8 use crate::domain::course::CourseId;8 use crate::domain::course::CourseId;
9 use crate::domain::enrollment::Enrollment;9 use crate::domain::enrollment::Enrollment;
10+use crate::domain::registration::Registration;
10 use crate::domain::role::Role;11 use crate::domain::role::Role;
11 use crate::domain::timestamp::Timestamp;12 use crate::domain::timestamp::Timestamp;
12 use crate::domain::user::{User, UserId};13 use crate::domain::user::{User, UserId};
@@ -66,13 +67,14 @@ impl EventDescription {
66 }67 }
67 68
68 /// Who an event is aimed at: the expected-attendee roster. Membership is69 /// Who an event is aimed at: the expected-attendee roster. Membership is
69-/// resolved live against today's users/enrollments — never snapshotted — so a70+/// resolved live against today's users/enrollments/registrations — never
70-/// role change or (un)enrollment moves people in and out of rosters by itself.71+/// snapshotted — so a role change, (un)enrollment, or (un)registration moves
71-/// The audience does not gate *seeing* the event (the calendar stays72+/// people in and out of rosters by itself. The audience does not gate *seeing*
72-/// school-visible); it defines who counts as expected and who may be marked.73+/// the event (the calendar stays school-visible); it defines who counts as
74+/// expected and who may be marked.
73 ///75 ///
74 /// Stored internally tagged: `{kind: 'school'}`, `{kind: 'role', role: 'student'}`,76 /// Stored internally tagged: `{kind: 'school'}`, `{kind: 'role', role: 'student'}`,
75-/// `{kind: 'course', course: course:…}`, `{kind: 'users', users: [user:…]}`.77+/// `{kind: 'course', course: course:…}`, `{kind: 'registration', capacity: 30}`.
76 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]78 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
77 #[surreal(tag = "kind", rename_all = "lowercase")]79 #[surreal(tag = "kind", rename_all = "lowercase")]
78 pub enum EventAudience {80 pub enum EventAudience {
@@ -81,17 +83,26 @@ pub enum EventAudience {
81 /// Every user holding exactly this role ("all students", "all teachers").83 /// Every user holding exactly this role ("all students", "all teachers").
82 Role { role: Role },84 Role { role: Role },
83 /// A course's enrolled students. Staff running the course are not implied85 /// A course's enrolled students. Staff running the course are not implied
84- /// members — a mixed gathering wants `Users` or a role audience.86+ /// members — a mixed gathering wants a registration or role audience.
85 Course { course: CourseId },87 Course { course: CourseId },
86- /// A hand-picked list. Bounded by `MAX_EVENT_AUDIENCE_USERS` at the web88+ /// A signup list built one person at a time through the register
87- /// layer; a member row deleted later simply stops resolving.89+ /// endpoints — teachers place students, staff take their own seat. The
88- Users { users: Vec<UserId> },90+ /// list is capped at `capacity` seats when set (`None` = unlimited) and
91+ /// closes once the event starts. Rows survive an audience change inertly.
92+ Registration { capacity: Option<i64> },
89 }93 }
90 94
91 impl EventAudience {95 impl EventAudience {
92- /// Is `user` in the roster right now? The point check behind marking —96+ /// Is `user` in `event`'s roster right now? The point check behind
93- /// cheaper than resolving the whole roster when the target is known.97+ /// marking — cheaper than resolving the whole roster when the target is
94- pub async fn includes(&self, user: &User, db: &Database) -> Result<bool, AppError> {98+ /// known. `event` must be the event this audience came from: the
99+ /// registration kind resolves against that event's signup rows.
100+ pub async fn includes(
101+ &self,
102+ event: &EventId,
103+ user: &User,
104+ db: &Database,
105+ ) -> Result<bool, AppError> {
95 match self {106 match self {
96 EventAudience::School => Ok(true),107 EventAudience::School => Ok(true),
97 EventAudience::Role { role } => Ok(user.get_role() == *role),108 EventAudience::Role { role } => Ok(user.get_role() == *role),
@@ -100,14 +111,18 @@ impl EventAudience {
100 .await?111 .await?
101 .is_some())112 .is_some())
102 }113 }
103- EventAudience::Users { users } => Ok(users.contains(user.get_id())),114+ EventAudience::Registration { .. } => {
115+ Ok(Registration::read_for_user(event, user.get_id(), db)
116+ .await?
117+ .is_some())
118+ }
104 }119 }
105 }120 }
106 121
107- /// The full roster, as it stands right now — the who-missed report's122+ /// `event`'s full roster, as it stands right now — the who-missed
108- /// backbone. `Users` ids that no longer resolve to a row are kept; the123+ /// report's backbone. Registered ids that no longer resolve to a user row
109- /// caller degrades their display like any stale reference.124+ /// are kept; the caller degrades their display like any stale reference.
110- pub async fn members(&self, db: &Database) -> Result<Vec<UserId>, AppError> {125+ pub async fn members(&self, event: &EventId, db: &Database) -> Result<Vec<UserId>, AppError> {
111 match self {126 match self {
112 EventAudience::School => Ok(User::list_all(db)127 EventAudience::School => Ok(User::list_all(db)
113 .await?128 .await?
@@ -124,7 +139,11 @@ impl EventAudience {
124 .iter()139 .iter()
125 .map(|enrollment| enrollment.get_user().clone())140 .map(|enrollment| enrollment.get_user().clone())
126 .collect()),141 .collect()),
127- EventAudience::Users { users } => Ok(users.clone()),142+ EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db)
143+ .await?
144+ .iter()
145+ .map(|registration| registration.get_user().clone())
146+ .collect()),
128 }147 }
129 }148 }
130 }149 }
@@ -225,9 +244,9 @@ impl Event {
225 updated.ok_or(AppError::NotFound)244 updated.ok_or(AppError::NotFound)
226 }245 }
227 246
228- /// Delete the event and cascade-remove its attendance rows.247+ /// Delete the event and cascade-remove its attendance and signup rows.
229 pub async fn delete(self, db: &Database) -> Result<Event, AppError> {248 pub async fn delete(self, db: &Database) -> Result<Event, AppError> {
230- db.query("DELETE attendance WHERE event = $ev")249+ db.query("DELETE attendance WHERE event = $ev; DELETE registration WHERE event = $ev;")
231 .bind(("ev", self.id.record()))250 .bind(("ev", self.id.record()))
232 .await?251 .await?
233 .check()?;252 .check()?;
@@ -275,10 +294,12 @@ mod tests {
275 "course",294 "course",
276 ),295 ),
277 (296 (
278- EventAudience::Users {297+ EventAudience::Registration { capacity: Some(30) },
279- users: vec![UserId::from_key("u1"), UserId::from_key("u2")],298+ "registration",
280- },299+ ),
281- "users",300+ (
301+ EventAudience::Registration { capacity: None },
302+ "registration",
282 ),303 ),
283 ];304 ];
284 for (audience, kind) in cases {305 for (audience, kind) in cases {
@@ -294,4 +315,22 @@ mod tests {
294 assert_eq!(EventAudience::from_value(value).unwrap(), audience);315 assert_eq!(EventAudience::from_value(value).unwrap(), audience);
295 }316 }
296 }317 }
318+
319+ /// The database strips `NONE`-valued optional columns and the boot
320+ /// conversion writes a bare `{kind: 'registration'}` — an object with no
321+ /// `capacity` key at all must decode as an uncapped registration.
322+ #[tokio::test]
323+ async fn registration_audience_decodes_without_capacity_key() {
324+ use surrealdb::types::Value;
325+
326+ let value = EventAudience::Registration { capacity: None }.into_value();
327+ let Value::Object(mut object) = value else {
328+ panic!("audience must encode as an object, got {value:?}");
329+ };
330+ object.remove("capacity");
331+ assert_eq!(
332+ EventAudience::from_value(Value::Object(object)).unwrap(),
333+ EventAudience::Registration { capacity: None }
334+ );
335+ }
297 }336 }
src/domain/mod.rsmodified+1 -0
@@ -16,6 +16,7 @@ pub mod note;
16 pub mod note_file;16 pub mod note_file;
17 pub mod preferences;17 pub mod preferences;
18 pub mod profile;18 pub mod profile;
19+pub mod registration;
19 pub mod role;20 pub mod role;
20 pub mod session;21 pub mod session;
21 pub mod session_attendance;22 pub mod session_attendance;
src/domain/registration.rsadded+156 -0
@@ -0,0 +1,156 @@
1+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2+
3+use crate::database::{Database, REGISTRATION_TABLE};
4+use crate::domain::event::EventId;
5+use crate::domain::user::UserId;
6+use crate::error::AppError;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
9+pub struct RegistrationId(RecordId);
10+
11+impl RegistrationId {
12+ /// A deterministic id for the (event, user) pair — the same pair always
13+ /// maps to the same record id, so registering is one atomic UPSERT with
14+ /// no find-then-insert race and one-row-per-pair by construction (the
15+ /// enrollment trick). ULID keys are alphanumeric, so `_` is unambiguous.
16+ pub fn composite(event: &EventId, user: &UserId) -> Self {
17+ Self(RecordId::new(
18+ REGISTRATION_TABLE,
19+ format!("{}_{}", event.key(), user.key()),
20+ ))
21+ }
22+
23+ pub fn record(&self) -> RecordId {
24+ self.0.clone()
25+ }
26+
27+ pub fn key(&self) -> &str {
28+ match &self.0.key {
29+ RecordIdKey::String(key) => key,
30+ _ => "",
31+ }
32+ }
33+}
34+
35+/// A seat on a registration-audience event's signup list. The list *is* the
36+/// event's roster: whoever holds a row is expected (and markable), everyone
37+/// else is not. Rows survive audience changes inertly — switching the event
38+/// away from the registration kind hides them without deleting them.
39+#[derive(Debug, Clone, SurrealValue)]
40+pub struct Registration {
41+ id: RegistrationId,
42+ event: EventId,
43+ user: UserId,
44+ registered_by: UserId,
45+}
46+
47+impl Registration {
48+ pub fn get_id(&self) -> &RegistrationId {
49+ &self.id
50+ }
51+
52+ pub fn get_event(&self) -> &EventId {
53+ &self.event
54+ }
55+
56+ pub fn get_user(&self) -> &UserId {
57+ &self.user
58+ }
59+
60+ pub fn get_registered_by(&self) -> &UserId {
61+ &self.registered_by
62+ }
63+
64+ /// Register (idempotently) `user` onto `event`, refusing when a `capacity`
65+ /// cap is set and every seat is taken. The seat count is re-read inside the
66+ /// transaction and the THROW cancels the UPSERT, so a full event never
67+ /// over-admits through the check-then-write gap; re-registering someone
68+ /// already listed never counts against the cap (and returns their row).
69+ pub async fn register(
70+ event: &EventId,
71+ user: &UserId,
72+ registered_by: &UserId,
73+ capacity: Option<i64>,
74+ db: &Database,
75+ ) -> Result<Registration, AppError> {
76+ let registration = Registration {
77+ id: RegistrationId::composite(event, user),
78+ event: event.clone(),
79+ user: user.clone(),
80+ registered_by: registered_by.clone(),
81+ };
82+ let mut result = db
83+ .query(
84+ "BEGIN TRANSACTION;
85+ LET $already = (SELECT VALUE id FROM registration WHERE event = $ev AND user = $usr);
86+ LET $count = (SELECT count() FROM registration WHERE event = $ev GROUP ALL)[0].count ?? 0;
87+ IF $cap != NONE AND array::len($already) = 0 AND $count >= $cap { THROW 'event_full' };
88+ UPSERT $id CONTENT $registration;
89+ COMMIT TRANSACTION;",
90+ )
91+ .bind(("ev", event.record()))
92+ .bind(("usr", user.record()))
93+ .bind(("cap", capacity))
94+ .bind(("id", registration.id.record()))
95+ .bind(("registration", registration))
96+ .await?;
97+ // An aborted transaction errors *every* slot, most with a generic
98+ // "not executed" — only the THROW's own slot names the reason, so scan
99+ // them all for the marker instead of trusting the first (`check`-style)
100+ // error.
101+ let mut errors = result.take_errors();
102+ if errors
103+ .values()
104+ .any(|error| error.to_string().contains("event_full"))
105+ {
106+ return Err(AppError::Conflict("the event is full"));
107+ }
108+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
109+ return Err(error.into());
110+ }
111+ // Statement slots count BEGIN and the LETs too: the UPSERT is slot 4.
112+ let saved: Option<Registration> = result.take::<Vec<Registration>>(4)?.into_iter().next();
113+ saved.ok_or_else(|| AppError::Internal("failed to register user".into()))
114+ }
115+
116+ /// Some(_) iff `user` holds a seat on `event` — the audience point check.
117+ pub async fn read_for_user(
118+ event: &EventId,
119+ user: &UserId,
120+ db: &Database,
121+ ) -> Result<Option<Registration>, AppError> {
122+ let mut result = db
123+ .query("SELECT * FROM registration WHERE event = $ev AND user = $usr LIMIT 1")
124+ .bind(("ev", event.record()))
125+ .bind(("usr", user.record()))
126+ .await?
127+ .check()?;
128+ Ok(result.take::<Vec<Registration>>(0)?.into_iter().next())
129+ }
130+
131+ pub async fn list_for_event(
132+ event: &EventId,
133+ db: &Database,
134+ ) -> Result<Vec<Registration>, AppError> {
135+ let mut result = db
136+ .query("SELECT * FROM registration WHERE event = $ev ORDER BY id DESC")
137+ .bind(("ev", event.record()))
138+ .await?
139+ .check()?;
140+ Ok(result.take::<Vec<Registration>>(0)?)
141+ }
142+
143+ pub async fn remove(
144+ event: &EventId,
145+ user: &UserId,
146+ db: &Database,
147+ ) -> Result<Option<Registration>, AppError> {
148+ let mut result = db
149+ .query("DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE")
150+ .bind(("ev", event.record()))
151+ .bind(("usr", user.record()))
152+ .await?
153+ .check()?;
154+ Ok(result.take::<Vec<Registration>>(0)?.into_iter().next())
155+ }
156+}
src/lib.rsmodified+2 -2
@@ -32,7 +32,7 @@ use crate::state::AppState;
32 info(32 info(
33 title = "Hezarfen Backend API",33 title = "Hezarfen Backend API",
34 version = env!("CARGO_PKG_VERSION"),34 version = env!("CARGO_PKG_VERSION"),
35- 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.",35+ 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.",
36 ),36 ),
37 modifiers(&SecurityAddon),37 modifiers(&SecurityAddon),
38 tags(38 tags(
@@ -40,7 +40,7 @@ use crate::state::AppState;
40 (name = "auth", description = "Registration, login, session lifecycle"),40 (name = "auth", description = "Registration, login, session lifecycle"),
41 (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)"),41 (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)"),
42 (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`)"),42 (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`)"),
43- (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"),43+ (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"),
44 (name = "courses", description = "Courses, enrollment (students only), course exams, and course sessions"),44 (name = "courses", description = "Courses, enrollment (students only), course exams, and course sessions"),
45 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),45 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
46 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),46 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
src/web/events.rsmodified+185 -36
@@ -8,11 +8,11 @@ use utoipa::ToSchema;
8 use utoipa_axum::router::OpenApiRouter;8 use utoipa_axum::router::OpenApiRouter;
9 use utoipa_axum::routes;9 use utoipa_axum::routes;
10 10
11-use crate::constant::MAX_EVENT_AUDIENCE_USERS;
12 use crate::database::Database;11 use crate::database::Database;
13 use crate::domain::attendance::{Attendance, AttendanceStatus};12 use crate::domain::attendance::{Attendance, AttendanceStatus};
14 use crate::domain::course::{Course, CourseId};13 use crate::domain::course::{Course, CourseId};
15 use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};14 use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};
15+use crate::domain::registration::Registration;
16 use crate::domain::role::Role;16 use crate::domain::role::Role;
17 use crate::domain::settings::Settings;17 use crate::domain::settings::Settings;
18 use crate::domain::timestamp::Timestamp;18 use crate::domain::timestamp::Timestamp;
@@ -32,6 +32,8 @@ pub fn routes() -> OpenApiRouter<AppState> {
32 .routes(routes!(mark, list_attendance))32 .routes(routes!(mark, list_attendance))
33 .routes(routes!(remove_attendance))33 .routes(routes!(remove_attendance))
34 .routes(routes!(roster))34 .routes(routes!(roster))
35+ .routes(routes!(register))
36+ .routes(routes!(unregister))
35 }37 }
36 38
37 /// An event's audience on the wire — who is expected to attend. Tagged by39 /// An event's audience on the wire — who is expected to attend. Tagged by
@@ -48,14 +50,18 @@ enum AudienceDto {
48 /// The students currently enrolled in this course (live — enrollment50 /// The students currently enrolled in this course (live — enrollment
49 /// changes move people in and out).51 /// changes move people in and out).
50 Course { course: String },52 Course { course: String },
51- /// A hand-picked list of user ids (at most `100`, deduplicated).53+ /// A signup list built through `POST /events/{id}/register` — teachers
52- Users { users: Vec<String> },54+ /// place students, staff take their own seat. `capacity` caps the seats;
55+ /// `null` or omitted = unlimited. The list closes when the event starts.
56+ Registration {
57+ #[serde(default)]
58+ capacity: Option<i64>,
59+ },
53 }60 }
54 61
55 impl AudienceDto {62 impl AudienceDto {
56 /// Validate the wire form into the domain audience: the role must parse,63 /// Validate the wire form into the domain audience: the role must parse,
57- /// the course must exist, and a `users` list must be non-empty, within the64+ /// the course must exist, and a registration capacity must be positive.
58- /// cap, and name only existing users.
59 async fn into_domain(self, db: &Database) -> Result<EventAudience, AppError> {65 async fn into_domain(self, db: &Database) -> Result<EventAudience, AppError> {
60 match self {66 match self {
61 AudienceDto::School => Ok(EventAudience::School),67 AudienceDto::School => Ok(EventAudience::School),
@@ -72,32 +78,14 @@ impl AudienceDto {
72 }78 }
73 Ok(EventAudience::Course { course })79 Ok(EventAudience::Course { course })
74 }80 }
75- AudienceDto::Users { users } => {81+ AudienceDto::Registration { capacity } => {
76- let mut seen = std::collections::HashSet::new();82+ if capacity.is_some_and(|capacity| capacity < 1) {
77- let users: Vec<UserId> = users
78- .iter()
79- .filter(|key| seen.insert(key.as_str()))
80- .map(|key| UserId::from_key(key))
81- .collect();
82- if users.is_empty() {
83 return Err(AppError::Validation(ValidationError::Invalid {83 return Err(AppError::Validation(ValidationError::Invalid {
84 field: "audience",84 field: "audience",
85- reason: "users must not be empty",85+ reason: "capacity must be at least 1",
86 }));86 }));
87 }87 }
88- if users.len() > MAX_EVENT_AUDIENCE_USERS {88+ Ok(EventAudience::Registration { capacity })
89- return Err(AppError::Validation(ValidationError::Invalid {
90- field: "audience",
91- reason: "users lists more than 100 people — target a role or course instead",
92- }));
93- }
94- if User::list_by_ids(&users, db).await?.len() != users.len() {
95- return Err(AppError::Validation(ValidationError::Invalid {
96- field: "audience",
97- reason: "users lists a user that does not exist",
98- }));
99- }
100- Ok(EventAudience::Users { users })
101 }89 }
102 }90 }
103 }91 }
@@ -111,8 +99,8 @@ impl AudienceDto {
111 EventAudience::Course { course } => AudienceDto::Course {99 EventAudience::Course { course } => AudienceDto::Course {
112 course: course.key().to_string(),100 course: course.key().to_string(),
113 },101 },
114- EventAudience::Users { users } => AudienceDto::Users {102+ EventAudience::Registration { capacity } => AudienceDto::Registration {
115- users: users.iter().map(|user| user.key().to_string()).collect(),103+ capacity: *capacity,
116 },104 },
117 }105 }
118 }106 }
@@ -222,8 +210,9 @@ impl AttendanceResponse {
222 210
223 /// Create an event owned by the current user. Requires the `teacher` role or211 /// Create an event owned by the current user. Requires the `teacher` role or
224 /// higher. `audience` targets it at a role, a course's enrollment, or a212 /// higher. `audience` targets it at a role, a course's enrollment, or a
225-/// hand-picked user list; omitted it is school-wide. Everyone still sees every213+/// registration list (filled via `POST /events/{id}/register`); omitted it is
226-/// event — the audience is the expected-attendee roster, not a visibility wall.214+/// school-wide. Everyone still sees every event — the audience is the
215+/// expected-attendee roster, not a visibility wall.
227 #[utoipa::path(216 #[utoipa::path(
228 post,217 post,
229 path = "/",218 path = "/",
@@ -322,8 +311,9 @@ async fn get_event(
322 /// Update an event. Requires teacher+; the creator may edit their own event and311 /// Update an event. Requires teacher+; the creator may edit their own event and
323 /// managers/admins may edit anyone's. Omitted fields keep their value; an312 /// managers/admins may edit anyone's. Omitted fields keep their value; an
324 /// explicit `null` clears `starts_at`/`ends_at`. A provided `audience` replaces313 /// explicit `null` clears `starts_at`/`ends_at`. A provided `audience` replaces
325-/// the current one wholesale — attendance rows for people it drops stay stored314+/// the current one wholesale — attendance and signup rows for people it drops
326-/// but leave the roster report.315+/// stay stored but leave the roster report (signups resurface if the event is
316+/// switched back to the registration kind).
327 #[utoipa::path(317 #[utoipa::path(
328 patch,318 patch,
329 path = "/{id}",319 path = "/{id}",
@@ -473,7 +463,11 @@ async fn mark(
473 463
474 // Only expected attendees can be marked. The marker needn't be in the464 // Only expected attendees can be marked. The marker needn't be in the
475 // audience — a teacher takes roll of a student-targeted event.465 // audience — a teacher takes roll of a student-targeted event.
476- if !event.get_audience().includes(&target_user, &st.db).await? {466+ if !event
467+ .get_audience()
468+ .includes(event.get_id(), &target_user, &st.db)
469+ .await?
470+ {
477 return Err(AppError::Validation(ValidationError::Invalid {471 return Err(AppError::Validation(ValidationError::Invalid {
478 field: "user_id",472 field: "user_id",
479 reason: "target user is not in this event's audience",473 reason: "target user is not in this event's audience",
@@ -578,7 +572,8 @@ struct RosterEntry {
578 572
579 /// The event's expected-attendee roster joined with its attendance marks — the573 /// The event's expected-attendee roster joined with its attendance marks — the
580 /// who-came/who-missed report. Resolved live from the audience (today's role574 /// who-came/who-missed report. Resolved live from the audience (today's role
581-/// holders, current enrollment), so it always reflects the present roster;575+/// holders, current enrollment, the current signup list), so it always reflects
576+/// the present roster;
582 /// attendance rows for people no longer in the audience are omitted here (they577 /// attendance rows for people no longer in the audience are omitted here (they
583 /// remain in `GET /events/{id}/attendance`). Requires teacher+. Paged via578 /// remain in `GET /events/{id}/attendance`). Requires teacher+. Paged via
584 /// `?limit=&offset=` (omit `limit` for the whole roster).579 /// `?limit=&offset=` (omit `limit` for the whole roster).
@@ -608,7 +603,7 @@ async fn roster(
608 .await?603 .await?
609 .ok_or(AppError::NotFound)?;604 .ok_or(AppError::NotFound)?;
610 605
611- let mut members = event.get_audience().members(&st.db).await?;606+ let mut members = event.get_audience().members(event.get_id(), &st.db).await?;
612 // ULID keys sort by creation instant — a stable order keeps pages coherent.607 // ULID keys sort by creation instant — a stable order keeps pages coherent.
613 members.sort_by(|a, b| a.key().cmp(b.key()));608 members.sort_by(|a, b| a.key().cmp(b.key()));
614 let marks = Attendance::list_for_event(&event_id, &st.db).await?;609 let marks = Attendance::list_for_event(&event_id, &st.db).await?;
@@ -640,3 +635,157 @@ async fn roster(
640 .collect();635 .collect();
641 Ok(Json(Page::new(items, total, limit, offset)))636 Ok(Json(Page::new(items, total, limit, offset)))
642 }637 }
638+
639+// ---- registration ---------------------------------------------------------
640+
641+#[derive(Deserialize, ToSchema)]
642+struct RegisterUser {
643+ /// Target user id — must name a student (staff take seats only for
644+ /// themselves). Defaults to the caller when omitted.
645+ user_id: Option<String>,
646+}
647+
648+#[derive(Serialize, ToSchema)]
649+struct RegistrationResponse {
650+ event: String,
651+ /// Who holds the seat.
652+ user: PersonRef,
653+ /// Who placed them on the list.
654+ registered_by: PersonRef,
655+}
656+
657+/// The shared gate for touching a signup list: the event must carry the
658+/// registration audience, and the list must still be open — it closes the
659+/// moment the event starts (a timeless event never closes). Returns the seat
660+/// cap for the register path.
661+fn check_registration_open(event: &Event) -> Result<Option<i64>, AppError> {
662+ let EventAudience::Registration { capacity } = event.get_audience() else {
663+ return Err(AppError::Validation(ValidationError::Invalid {
664+ field: "audience",
665+ reason: "this event does not take registrations",
666+ }));
667+ };
668+ if let Some(starts_at) = event.get_starts_at()
669+ && Timestamp::now().as_millis() >= starts_at.as_millis()
670+ {
671+ return Err(AppError::Conflict(
672+ "registration closed when the event started",
673+ ));
674+ }
675+ Ok(*capacity)
676+}
677+
678+/// Put a user on a registration-audience event's signup list. Requires
679+/// teacher+. `user_id` must name a student — students are placed by staff and
680+/// never register themselves; omit it to take a seat yourself (staff
681+/// self-serve, so registering another teacher/manager is refused). Registering
682+/// the same person twice is a no-op returning the existing seat. The list
683+/// closes when the event starts and refuses to grow past `capacity`.
684+#[utoipa::path(
685+ post,
686+ path = "/{id}/register",
687+ tag = "events",
688+ security(("session_cookie" = [])),
689+ params(("id" = String, Path, description = "Event id")),
690+ request_body = RegisterUser,
691+ responses(
692+ (status = 200, description = "Seat taken (or already held)", body = RegistrationResponse),
693+ (status = 400, description = "Not a registration event, or the target is unknown", body = ErrorResponse),
694+ (status = 401, description = "Not authenticated", body = ErrorResponse),
695+ (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse),
696+ (status = 404, description = "Event not found", body = ErrorResponse),
697+ (status = 409, description = "The event is full, or it already started", body = ErrorResponse),
698+ ),
699+)]
700+async fn register(
701+ State(st): State<AppState>,
702+ RequireTeacher(user): RequireTeacher,
703+ Path(id): Path<String>,
704+ Json(req): Json<RegisterUser>,
705+) -> Result<Json<RegistrationResponse>, AppError> {
706+ let event_id = EventId::from_key(&id);
707+ let event = Event::read(&event_id, &st.db)
708+ .await?
709+ .ok_or(AppError::NotFound)?;
710+ let capacity = check_registration_open(&event)?;
711+
712+ let target = match req.user_id {
713+ Some(ref key) => UserId::from_key(key),
714+ None => user.get_id().clone(),
715+ };
716+ let Some(target_user) = User::read(&target, &st.db).await? else {
717+ return Err(AppError::Validation(ValidationError::Invalid {
718+ field: "user_id",
719+ reason: "target user does not exist",
720+ }));
721+ };
722+ // Students are placed by staff; staff hold only their own seat.
723+ if &target != user.get_id() && target_user.get_role() != Role::Student {
724+ return Err(AppError::Forbidden(
725+ "staff register themselves — only students can be registered for",
726+ ));
727+ }
728+
729+ let registration =
730+ Registration::register(&event_id, &target, user.get_id(), capacity, &st.db).await?;
731+ let people = PersonRef::map_of(&[&target_user, &user]);
732+ Ok(Json(RegistrationResponse {
733+ event: registration.get_event().key().to_string(),
734+ user: PersonRef::resolve(&people, registration.get_user()),
735+ registered_by: PersonRef::resolve(&people, registration.get_registered_by()),
736+ }))
737+}
738+
739+/// Take a user off the signup list — the register rules mirrored: teacher+,
740+/// students' seats or your own (another staff member's seat only if their
741+/// account no longer exists), and only while the list is open (the event
742+/// hasn't started). Attendance already marked stays recorded.
743+#[utoipa::path(
744+ delete,
745+ path = "/{id}/register/{user}",
746+ tag = "events",
747+ security(("session_cookie" = [])),
748+ params(
749+ ("id" = String, Path, description = "Event id"),
750+ ("user" = String, Path, description = "User id"),
751+ ),
752+ responses(
753+ (status = 204, description = "Seat freed"),
754+ (status = 400, description = "Not a registration event", body = ErrorResponse),
755+ (status = 401, description = "Not authenticated", body = ErrorResponse),
756+ (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse),
757+ (status = 404, description = "Event not found, or the user holds no seat", body = ErrorResponse),
758+ (status = 409, description = "The event already started", body = ErrorResponse),
759+ ),
760+)]
761+async fn unregister(
762+ State(st): State<AppState>,
763+ RequireTeacher(user): RequireTeacher,
764+ Path((id, target)): Path<(String, String)>,
765+) -> Result<StatusCode, AppError> {
766+ let event_id = EventId::from_key(&id);
767+ let event = Event::read(&event_id, &st.db)
768+ .await?
769+ .ok_or(AppError::NotFound)?;
770+ check_registration_open(&event)?;
771+
772+ let target = UserId::from_key(&target);
773+ // A deleted account's leftover seat is fair game for any teacher+; a
774+ // living staff member's seat is theirs alone.
775+ if &target != user.get_id()
776+ && let Some(target_user) = User::read(&target, &st.db).await?
777+ && target_user.get_role() != Role::Student
778+ {
779+ return Err(AppError::Forbidden(
780+ "staff unregister themselves — only students' seats can be freed",
781+ ));
782+ }
783+
784+ if Registration::remove(&event_id, &target, &st.db)
785+ .await?
786+ .is_none()
787+ {
788+ return Err(AppError::NotFound);
789+ }
790+ Ok(StatusCode::NO_CONTENT)
791+}
tests/integration.rsmodified+371 -23
@@ -1217,8 +1217,6 @@ async fn event_timestamps_echo_and_validate() {
1217 async fn event_audience_defaults_validates_and_echoes() {1217 async fn event_audience_defaults_validates_and_echoes() {
1218 let (app, db) = app_and_db().await;1218 let (app, db) = app_and_db().await;
1219 let ali = login_as(&app, &db, "ali", "teacher").await;1219 let ali = login_as(&app, &db, "ali", "teacher").await;
1220- let veli = login(&app, "veli").await; // student
1221- let veli_id = me_id(&app, &veli).await;
1222 1220
1223 // Omitted audience = school-wide, and it echoes on every read.1221 // Omitted audience = school-wide, and it echoes on every read.
1224 let ev = send(1222 let ev = send(
@@ -1260,22 +1258,32 @@ async fn event_audience_defaults_validates_and_echoes() {
1260 "PATCH",1258 "PATCH",
1261 &format!("/events/{event_id}"),1259 &format!("/events/{event_id}"),
1262 Some(&ali),1260 Some(&ali),
1263- Some(json!({ "audience": { "kind": "users", "users": [veli_id, veli_id] } })),1261+ Some(json!({ "audience": { "kind": "registration", "capacity": 5 } })),
1264 )1262 )
1265 .await;1263 .await;
1266 assert_eq!(res.status, StatusCode::OK);1264 assert_eq!(res.status, StatusCode::OK);
1267- // The duplicated id collapsed to one entry.1265+ assert_eq!(res.body["audience"]["capacity"], 5);
1268- assert_eq!(res.body["audience"]["users"].as_array().unwrap().len(), 1);
1269 1266
1270- // Invalid audiences are rejected: unknown role, ghost course, ghost user,1267+ // An omitted capacity echoes as null: an uncapped signup list.
1271- // an empty hand-picked list, and one past the 100-user cap.1268+ let res = send(
1269+ &app,
1270+ "POST",
1271+ "/events",
1272+ Some(&ali),
1273+ Some(json!({ "title": "trip", "audience": { "kind": "registration" } })),
1274+ )
1275+ .await;
1276+ assert_eq!(res.status, StatusCode::CREATED);
1277+ assert_eq!(res.body["audience"]["kind"], "registration");
1278+ assert!(res.body["audience"]["capacity"].is_null());
1279+
1280+ // Invalid audiences are rejected: unknown role, ghost course, and
1281+ // non-positive capacities.
1272 for audience in [1282 for audience in [
1273 json!({ "kind": "role", "role": "wizard" }),1283 json!({ "kind": "role", "role": "wizard" }),
1274 json!({ "kind": "course", "course": "nope" }),1284 json!({ "kind": "course", "course": "nope" }),
1275- json!({ "kind": "users", "users": ["ghost"] }),1285+ json!({ "kind": "registration", "capacity": 0 }),
1276- json!({ "kind": "users", "users": [] }),1286+ json!({ "kind": "registration", "capacity": -3 }),
1277- json!({ "kind": "users",
1278- "users": (0..101).map(|n| format!("u{n}")).collect::<Vec<_>>() }),
1279 ] {1287 ] {
1280 let res = send(1288 let res = send(
1281 &app,1289 &app,
@@ -1287,16 +1295,22 @@ async fn event_audience_defaults_validates_and_echoes() {
1287 .await;1295 .await;
1288 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{audience}");1296 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{audience}");
1289 }1297 }
1290- // An unknown kind never deserializes.1298+ // An unknown kind never deserializes — including the retired hand-picked
1291- let res = send(1299+ // `users` kind, gone in the registration clean break.
1292- &app,1300+ for audience in [
1293- "POST",1301+ json!({ "kind": "galaxy" }),
1294- "/events",1302+ json!({ "kind": "users", "users": ["ghost"] }),
1295- Some(&ali),1303+ ] {
1296- Some(json!({ "title": "bad", "audience": { "kind": "galaxy" } })),1304+ let res = send(
1297- )1305+ &app,
1298- .await;1306+ "POST",
1299- assert!(res.status.is_client_error(), "{}", res.status);1307+ "/events",
1308+ Some(&ali),
1309+ Some(json!({ "title": "bad", "audience": audience })),
1310+ )
1311+ .await;
1312+ assert!(res.status.is_client_error(), "{audience}: {}", res.status);
1313+ }
1300 }1314 }
1301 1315
1302 #[tokio::test]1316 #[tokio::test]
@@ -1373,8 +1387,17 @@ async fn event_audience_gates_marking() {
1373 StatusCode::BAD_REQUEST1387 StatusCode::BAD_REQUEST
1374 );1388 );
1375 1389
1376- // Hand-picked audience: the list is the roster.1390+ // Registration audience: the signup list is the roster.
1377- let ev = create(json!({ "kind": "users", "users": [mina_id.clone()] })).await;1391+ let ev = create(json!({ "kind": "registration" })).await;
1392+ let res = send(
1393+ &app,
1394+ "POST",
1395+ &format!("/events/{ev}/register"),
1396+ Some(&ali),
1397+ Some(json!({ "user_id": mina_id })),
1398+ )
1399+ .await;
1400+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1378 assert_eq!(mark(ev.clone(), mina_id.clone()).await, StatusCode::OK);1401 assert_eq!(mark(ev.clone(), mina_id.clone()).await, StatusCode::OK);
1379 assert_eq!(1402 assert_eq!(
1380 mark(ev.clone(), veli_id.clone()).await,1403 mark(ev.clone(), veli_id.clone()).await,
@@ -3071,6 +3094,331 @@ async fn students_never_mark_attendance() {
3071 );3094 );
3072 }3095 }
3073 3096
3097+/// Registration seats follow the placement rule — teachers seat students and
3098+/// themselves, never other staff; students never touch the endpoints — and a
3099+/// repeat register is a no-op on the same single row. Deleting the event
3100+/// removes its signup rows with it.
3101+#[tokio::test]
3102+async fn event_registration_follows_placement_rules() {
3103+ let (app, db) = app_and_db().await;
3104+ let ali = login_as(&app, &db, "ali", "teacher").await;
3105+ let deniz = login_as(&app, &db, "deniz", "teacher").await;
3106+ let veli = login(&app, "veli").await; // student
3107+ let veli_id = me_id(&app, &veli).await;
3108+ let ali_id = me_id(&app, &ali).await;
3109+ let deniz_id = me_id(&app, &deniz).await;
3110+
3111+ let res = send(
3112+ &app,
3113+ "POST",
3114+ "/events",
3115+ Some(&ali),
3116+ Some(json!({ "title": "seminar", "audience": { "kind": "registration" } })),
3117+ )
3118+ .await;
3119+ assert_eq!(res.status, StatusCode::CREATED);
3120+ let ev = id_of(&res.body);
3121+ let register_uri = format!("/events/{ev}/register");
3122+
3123+ // Students can't register — not even themselves.
3124+ let res = send(&app, "POST", &register_uri, Some(&veli), Some(json!({}))).await;
3125+ assert_eq!(res.status, StatusCode::FORBIDDEN);
3126+
3127+ // A teacher seats a student; the row names who placed whom.
3128+ let res = send(
3129+ &app,
3130+ "POST",
3131+ &register_uri,
3132+ Some(&ali),
3133+ Some(json!({ "user_id": veli_id })),
3134+ )
3135+ .await;
3136+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
3137+ assert_eq!(res.body["user"]["id"], veli_id);
3138+ assert_eq!(res.body["registered_by"]["id"], ali_id);
3139+
3140+ // Registering the same student again is a no-op on the same seat.
3141+ let res = send(
3142+ &app,
3143+ "POST",
3144+ &register_uri,
3145+ Some(&deniz),
3146+ Some(json!({ "user_id": veli_id })),
3147+ )
3148+ .await;
3149+ assert_eq!(res.status, StatusCode::OK);
3150+ let roster = send(
3151+ &app,
3152+ "GET",
3153+ &format!("/events/{ev}/roster"),
3154+ Some(&ali),
3155+ None,
3156+ )
3157+ .await;
3158+ assert_eq!(common::total(&roster.body), 1, "upsert keeps a single seat");
3159+
3160+ // A teacher takes their own seat by omitting the target…
3161+ let res = send(&app, "POST", &register_uri, Some(&ali), Some(json!({}))).await;
3162+ assert_eq!(res.status, StatusCode::OK);
3163+ // …but never seats another staff member, and ghosts don't register.
3164+ let res = send(
3165+ &app,
3166+ "POST",
3167+ &register_uri,
3168+ Some(&ali),
3169+ Some(json!({ "user_id": deniz_id })),
3170+ )
3171+ .await;
3172+ assert_eq!(res.status, StatusCode::FORBIDDEN);
3173+ let res = send(
3174+ &app,
3175+ "POST",
3176+ &register_uri,
3177+ Some(&ali),
3178+ Some(json!({ "user_id": "ghost" })),
3179+ )
3180+ .await;
3181+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
3182+
3183+ // Non-registration events refuse the endpoint outright.
3184+ let school = send(
3185+ &app,
3186+ "POST",
3187+ "/events",
3188+ Some(&ali),
3189+ Some(json!({ "title": "assembly" })),
3190+ )
3191+ .await;
3192+ let res = send(
3193+ &app,
3194+ "POST",
3195+ &format!("/events/{}/register", id_of(&school.body)),
3196+ Some(&ali),
3197+ Some(json!({})),
3198+ )
3199+ .await;
3200+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
3201+
3202+ // Unregistering mirrors the rule: students never, staff seats are their
3203+ // own, students' seats are anyone's (teacher+) to free.
3204+ let res = send(
3205+ &app,
3206+ "DELETE",
3207+ &format!("{register_uri}/{ali_id}"),
3208+ Some(&veli),
3209+ None,
3210+ )
3211+ .await;
3212+ assert_eq!(res.status, StatusCode::FORBIDDEN);
3213+ let res = send(
3214+ &app,
3215+ "DELETE",
3216+ &format!("{register_uri}/{ali_id}"),
3217+ Some(&deniz),
3218+ None,
3219+ )
3220+ .await;
3221+ assert_eq!(
3222+ res.status,
3223+ StatusCode::FORBIDDEN,
3224+ "staff seat is not deniz's"
3225+ );
3226+ let res = send(
3227+ &app,
3228+ "DELETE",
3229+ &format!("{register_uri}/{veli_id}"),
3230+ Some(&deniz),
3231+ None,
3232+ )
3233+ .await;
3234+ assert_eq!(res.status, StatusCode::NO_CONTENT);
3235+ let res = send(
3236+ &app,
3237+ "DELETE",
3238+ &format!("{register_uri}/{veli_id}"),
3239+ Some(&deniz),
3240+ None,
3241+ )
3242+ .await;
3243+ assert_eq!(res.status, StatusCode::NOT_FOUND, "seat already freed");
3244+
3245+ // Deleting the event cascades its signup rows away.
3246+ let res = send(&app, "DELETE", &format!("/events/{ev}"), Some(&ali), None).await;
3247+ assert_eq!(res.status, StatusCode::NO_CONTENT);
3248+ let left: Vec<hezarfen_backend::domain::registration::Registration> =
3249+ db.select("registration").await.unwrap();
3250+ assert!(left.is_empty(), "event delete leaves no seats behind");
3251+}
3252+
3253+/// A capacity caps live seats, not history: re-registering never double-counts,
3254+/// freeing a seat reopens it, and shrinking the cap below the current count
3255+/// only blocks new seats.
3256+#[tokio::test]
3257+async fn event_registration_capacity_caps_seats() {
3258+ let (app, db) = app_and_db().await;
3259+ let ali = login_as(&app, &db, "ali", "teacher").await;
3260+ let veli = login(&app, "veli").await;
3261+ let mina = login(&app, "mina").await;
3262+ let veli_id = me_id(&app, &veli).await;
3263+ let mina_id = me_id(&app, &mina).await;
3264+
3265+ let res = send(
3266+ &app,
3267+ "POST",
3268+ "/events",
3269+ Some(&ali),
3270+ Some(json!({ "title": "workshop",
3271+ "audience": { "kind": "registration", "capacity": 1 } })),
3272+ )
3273+ .await;
3274+ let ev = id_of(&res.body);
3275+ let register_uri = format!("/events/{ev}/register");
3276+ let register = |user: String| {
3277+ let app = &app;
3278+ let ali = &ali;
3279+ let uri = &register_uri;
3280+ async move {
3281+ send(
3282+ app,
3283+ "POST",
3284+ uri,
3285+ Some(ali),
3286+ Some(json!({ "user_id": user })),
3287+ )
3288+ .await
3289+ .status
3290+ }
3291+ };
3292+
3293+ assert_eq!(register(veli_id.clone()).await, StatusCode::OK);
3294+ assert_eq!(
3295+ register(mina_id.clone()).await,
3296+ StatusCode::CONFLICT,
3297+ "full"
3298+ );
3299+ assert_eq!(
3300+ register(veli_id.clone()).await,
3301+ StatusCode::OK,
3302+ "re-register of a seated user never counts against the cap"
3303+ );
3304+
3305+ // Freeing the seat reopens the list.
3306+ let res = send(
3307+ &app,
3308+ "DELETE",
3309+ &format!("{register_uri}/{veli_id}"),
3310+ Some(&ali),
3311+ None,
3312+ )
3313+ .await;
3314+ assert_eq!(res.status, StatusCode::NO_CONTENT);
3315+ assert_eq!(register(mina_id.clone()).await, StatusCode::OK);
3316+
3317+ // Shrinking the cap under the current count keeps the seats and only
3318+ // refuses growth.
3319+ assert_eq!(
3320+ send(
3321+ &app,
3322+ "PATCH",
3323+ &format!("/events/{ev}"),
3324+ Some(&ali),
3325+ Some(json!({ "audience": { "kind": "registration", "capacity": 2 } })),
3326+ )
3327+ .await
3328+ .status,
3329+ StatusCode::OK
3330+ );
3331+ assert_eq!(register(veli_id.clone()).await, StatusCode::OK);
3332+ assert_eq!(
3333+ send(
3334+ &app,
3335+ "PATCH",
3336+ &format!("/events/{ev}"),
3337+ Some(&ali),
3338+ Some(json!({ "audience": { "kind": "registration", "capacity": 1 } })),
3339+ )
3340+ .await
3341+ .status,
3342+ StatusCode::OK
3343+ );
3344+ let roster = send(
3345+ &app,
3346+ "GET",
3347+ &format!("/events/{ev}/roster"),
3348+ Some(&ali),
3349+ None,
3350+ )
3351+ .await;
3352+ assert_eq!(
3353+ common::total(&roster.body),
3354+ 2,
3355+ "shrink keeps existing seats"
3356+ );
3357+}
3358+
3359+/// The signup list freezes the moment the event starts — both directions.
3360+/// (The create-time no-past grace lets a just-started event exist, which is
3361+/// exactly a closed list.)
3362+#[tokio::test]
3363+async fn event_registration_closes_at_start() {
3364+ let (app, db) = app_and_db().await;
3365+ let ali = login_as(&app, &db, "ali", "teacher").await;
3366+ let veli = login(&app, "veli").await;
3367+ let veli_id = me_id(&app, &veli).await;
3368+ let now = Timestamp::now().as_millis();
3369+
3370+ // Started 30s ago: inside the scheduling grace, so creation passes — but
3371+ // the list is already closed.
3372+ let res = send(
3373+ &app,
3374+ "POST",
3375+ "/events",
3376+ Some(&ali),
3377+ Some(json!({ "title": "underway", "starts_at": now - 30_000,
3378+ "audience": { "kind": "registration" } })),
3379+ )
3380+ .await;
3381+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
3382+ let ev = id_of(&res.body);
3383+ let res = send(
3384+ &app,
3385+ "POST",
3386+ &format!("/events/{ev}/register"),
3387+ Some(&ali),
3388+ Some(json!({ "user_id": veli_id })),
3389+ )
3390+ .await;
3391+ assert_eq!(res.status, StatusCode::CONFLICT);
3392+ let res = send(
3393+ &app,
3394+ "DELETE",
3395+ &format!("/events/{ev}/register/{veli_id}"),
3396+ Some(&ali),
3397+ None,
3398+ )
3399+ .await;
3400+ assert_eq!(res.status, StatusCode::CONFLICT, "unregister freezes too");
3401+
3402+ // A future or timeless event keeps its list open.
3403+ for body in [
3404+ json!({ "title": "later", "starts_at": now + 3_600_000,
3405+ "audience": { "kind": "registration" } }),
3406+ json!({ "title": "whenever", "audience": { "kind": "registration" } }),
3407+ ] {
3408+ let res = send(&app, "POST", "/events", Some(&ali), Some(body)).await;
3409+ let ev = id_of(&res.body);
3410+ let res = send(
3411+ &app,
3412+ "POST",
3413+ &format!("/events/{ev}/register"),
3414+ Some(&ali),
3415+ Some(json!({ "user_id": veli_id })),
3416+ )
3417+ .await;
3418+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
3419+ }
3420+}
3421+
3074 #[tokio::test]3422 #[tokio::test]
3075 async fn event_management_follows_hierarchy() {3423 async fn event_management_follows_hierarchy() {
3076 let (app, db) = app_and_db().await;3424 let (app, db) = app_and_db().await;
tests/persistence.rsmodified+107 -0
@@ -593,3 +593,110 @@ async fn legacy_events_backfill_to_school_audience() {
593 assert_eq!(res.status, StatusCode::OK);593 assert_eq!(res.status, StatusCode::OK);
594 assert_eq!(common::total(&res.body), 1, "whole school = the one user");594 assert_eq!(common::total(&res.body), 1, "whole school = the one user");
595 }595 }
596+
597+/// Event rows carrying the retired hand-picked (`users`) audience convert on
598+/// the next boot: the audience becomes an uncapped registration list and each
599+/// listed user gets a signup row credited to the event's creator — the old
600+/// roster survives the clean break byte for byte.
601+#[tokio::test]
602+async fn legacy_users_audiences_convert_to_registrations() {
603+ let dir = tempfile::tempdir().unwrap();
604+ let cfg = config_at(&dir);
605+ let creds = json!({ "username": "ali", "password": "secret1" });
606+ let event_id;
607+ let student_id;
608+
609+ // First boot: a registration-audience event — then rewrite it into the
610+ // shape an old binary left behind: restore the `audience.users` column
611+ // definition and store a hand-picked list on the row.
612+ {
613+ let db = database::init(&cfg).await.expect("first open");
614+ let app = build_router(state(db.clone(), &cfg));
615+ assert_eq!(
616+ send(&app, "POST", "/auth/register", None, Some(creds.clone()))
617+ .await
618+ .status,
619+ StatusCode::CREATED
620+ );
621+ set_role(&db, "ali", "teacher").await;
622+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone()))
623+ .await
624+ .cookie
625+ .unwrap();
626+ let student = json!({ "username": "veli", "password": "secret1" });
627+ assert_eq!(
628+ send(&app, "POST", "/auth/register", None, Some(student.clone()))
629+ .await
630+ .status,
631+ StatusCode::CREATED
632+ );
633+ let student_cookie = send(&app, "POST", "/auth/login", None, Some(student))
634+ .await
635+ .cookie
636+ .unwrap();
637+ student_id = common::me_id(&app, &student_cookie).await;
638+
639+ let res = send(
640+ &app,
641+ "POST",
642+ "/events",
643+ Some(&cookie),
644+ Some(json!({ "title": "trip", "audience": { "kind": "registration" } })),
645+ )
646+ .await;
647+ assert_eq!(res.status, StatusCode::CREATED);
648+ event_id = common::id_of(&res.body);
649+
650+ db.query(format!(
651+ "DEFINE FIELD OVERWRITE audience.users ON TABLE event TYPE option<array<record<user>>>;
652+ UPDATE event SET audience = {{ kind: 'users', users: [type::record('user', $usr)] }}
653+ WHERE id = type::record('event', '{event_id}');"
654+ ))
655+ .bind(("usr", student_id.clone()))
656+ .await
657+ .expect("rewrite to legacy users audience")
658+ .check()
659+ .expect("rewrite check");
660+ }
661+
662+ // Second boot runs the conversion: the audience reads back as an uncapped
663+ // registration list, the listed student holds a seat credited to the
664+ // creator, and the roster (and marking gate) see them.
665+ let db = reopen(&cfg).await;
666+ let app = build_router(state(db, &cfg));
667+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds))
668+ .await
669+ .cookie
670+ .unwrap();
671+ let res = send(
672+ &app,
673+ "GET",
674+ &format!("/events/{event_id}"),
675+ Some(&cookie),
676+ None,
677+ )
678+ .await;
679+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
680+ assert_eq!(res.body["audience"]["kind"], "registration");
681+ assert!(res.body["audience"]["capacity"].is_null());
682+ let res = send(
683+ &app,
684+ "GET",
685+ &format!("/events/{event_id}/roster"),
686+ Some(&cookie),
687+ None,
688+ )
689+ .await;
690+ assert_eq!(res.status, StatusCode::OK);
691+ assert_eq!(common::total(&res.body), 1, "the listed user became a seat");
692+ assert_eq!(common::items(&res.body)[0]["user"]["id"], student_id);
693+ let res = send(
694+ &app,
695+ "POST",
696+ &format!("/events/{event_id}/attendance"),
697+ Some(&cookie),
698+ Some(json!({ "status": "present", "user_id": student_id })),
699+ )
700+ .await;
701+ assert_eq!(res.status, StatusCode::OK, "converted seat is markable");
702+}