forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

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

user.rs1333 lines, 56.6 KiBHistoryRawDownload
1//! The `app_user` table: the row mint (with the duplicate-username mapping),
2//! row reads and listings, the role cascade transaction (admin floor and all
3//! sweeps included), and the field-scoped writers. The workflow that drives
4//! the cascade lives in [`crate::service::user`].
5//!
6//! The compile-time macros map columns by name and check each decoded type
7//! against the prepare schema, so the eighteen user columns are spelled
8//! out — newtype overrides included — in every static statement below. The
9//! repetitions are the check.
10
11use crate::database::{Database, check_violation, tx_with_retry, unique_violation};
12use crate::db::field_update::FieldUpdate;
13use crate::db::page::{PagedList, Param};
14use crate::domain::board::{Board, BoardId, BoardTitle};
15use crate::domain::note_file::FileContentType;
16use crate::domain::person::PersonId;
17use crate::domain::preferences::{Language, PaletteColor, Theme};
18use crate::domain::profile::{Address, Bio, BirthDate, DisplayName, Email, Gender, PersonName, Phone};
19use crate::domain::role::Role;
20use crate::domain::text_fold::{search_fold, search_fold_sql};
21use crate::domain::timestamp::Timestamp;
22use crate::domain::user::{StudentNumber, User, UserId, Username};
23use crate::error::AppError;
24
25/// The answer a duplicate `student_number` gets, from both write paths that
26/// can raise one (the mint and the profile writer). One spelling so the two
27/// cannot drift, and `ConflictCoded` because the frontend branches on the
28/// cause — the number is refused by the partial unique index
29/// (`app_user_student_number`), not by anything the message could name.
30fn number_taken() -> AppError {
31 AppError::ConflictCoded {
32 code: "student_number_taken",
33 message: "student number already taken".to_owned(),
34 }
35}
36
37/// Register a new school account for the control-plane `person` whose
38/// credential login verifies — `person` is the join key, `None` only where the
39/// caller cannot know it yet (tests, the boot seed's row-first order — see
40/// [`crate::service::user::ensure_admin`]). New users always start as
41/// [`Role::Student`]; elevation is a separate, admin-only action
42/// (see [`crate::service::user::set_role`]).
43pub async fn create(
44 db: &Database,
45 username: Username,
46 person: Option<PersonId>,
47) -> Result<User, AppError> {
48 create_with_role(db, username, person, Role::Student, None).await
49}
50
51/// The one row-minting path. `role` is written *with* the row rather than
52/// patched on afterwards, which is what makes the admin seed atomic: a
53/// create-then-promote pair can be interrupted between its halves (a SIGKILL,
54/// or a cancelled future), and the row left behind is an ordinary student
55/// account that [`crate::service::user::ensure_admin`] must then refuse to
56/// touch — a deployment with no admin and no way for a later boot to repair it.
57///
58/// The unique index on `username` is the whole availability check. The old
59/// pre-check-and-recheck dance existed because the old store could not name
60/// the constraint a racing insert had violated; here the violated
61/// constraint's name answers directly (`app_user_username`), and the loser
62/// of a race gets the same 409 the sequential duplicate always got.
63///
64/// The row carries its `created_at` mint stamp and, when the caller knows it,
65/// the `person` id the credential lives on. `student_number` binds as handed:
66/// the *role* rule ("only a student may hold one") is the web layer's gate —
67/// it is the layer that resolves the requested role — while the *uniqueness*
68/// rule is the partial unique index, and its violation answers the same 409
69/// the duplicate username does.
70pub async fn create_with_role(
71 db: &Database,
72 username: Username,
73 person: Option<PersonId>,
74 role: Role,
75 student_number: Option<StudentNumber>,
76) -> Result<User, AppError> {
77 debug_assert!(
78 student_number.is_none() || role == Role::Student,
79 "only a student row may be born with a student number"
80 );
81 let id = UserId::generate();
82 match sqlx::query_as!(
83 User,
84 r#"INSERT INTO app_user (id, username, person, role, student_number, created_at)
85 VALUES ($1, $2, $3, $4, $5, $6)
86 RETURNING id AS "id: UserId",
87 username AS "username: Username",
88 person AS "person: PersonId",
89 role AS "role: Role",
90 name AS "name: PersonName",
91 surname AS "surname: PersonName",
92 email AS "email: Email",
93 phone AS "phone: Phone",
94 birth_date AS "birth_date: BirthDate",
95 gender AS "gender: Gender",
96 address AS "address: Address",
97 emergency_contact_name AS "emergency_contact_name: PersonName",
98 emergency_contact_phone AS "emergency_contact_phone: Phone",
99 theme AS "theme: Theme",
100 language AS "language: Language",
101 palette_color AS "palette_color: PaletteColor",
102 display_name AS "display_name: DisplayName",
103 bio AS "bio: Bio",
104 avatar_file,
105 avatar_content_type AS "avatar_content_type: FileContentType",
106 branch,
107 student_number AS "student_number: StudentNumber",
108 avatar_size"#,
109 id.uuid(),
110 username.as_str(),
111 person.as_ref().map(PersonId::uuid),
112 role.as_str(),
113 student_number.as_ref().map(StudentNumber::as_str),
114 Timestamp::now().as_millis(),
115 )
116 .fetch_one(db)
117 .await
118 {
119 Ok(user) => {
120 debug_assert_eq!(
121 user.get_person().map(PersonId::uuid),
122 person.as_ref().map(PersonId::uuid)
123 );
124 Ok(user)
125 }
126 Err(err) if unique_violation(&err) == Some("app_user_username") => {
127 Err(AppError::Conflict("username already taken"))
128 }
129 Err(err) if unique_violation(&err) == Some("app_user_student_number") => {
130 Err(number_taken())
131 }
132 // The row's own CHECK: this path already debug-asserts the rule, and
133 // in a release build the database is what says no.
134 Err(err) if check_violation(&err) == Some("app_user_student_number_student") => {
135 Err(StudentNumber::non_student_refusal().into())
136 }
137 Err(err) => Err(err.into()),
138 }
139}
140
141pub async fn read(db: &Database, id: &UserId) -> Result<Option<User>, AppError> {
142 let user = sqlx::query_as!(
143 User,
144 r#"SELECT id AS "id: UserId",
145 username AS "username: Username",
146 person AS "person: PersonId",
147 role AS "role: Role",
148 name AS "name: PersonName",
149 surname AS "surname: PersonName",
150 email AS "email: Email",
151 phone AS "phone: Phone",
152 birth_date AS "birth_date: BirthDate",
153 gender AS "gender: Gender",
154 address AS "address: Address",
155 emergency_contact_name AS "emergency_contact_name: PersonName",
156 emergency_contact_phone AS "emergency_contact_phone: Phone",
157 theme AS "theme: Theme",
158 language AS "language: Language",
159 palette_color AS "palette_color: PaletteColor",
160 display_name AS "display_name: DisplayName",
161 bio AS "bio: Bio",
162 avatar_file,
163 avatar_content_type AS "avatar_content_type: FileContentType",
164 branch,
165 student_number AS "student_number: StudentNumber",
166 avatar_size
167 FROM app_user WHERE id = $1"#,
168 id.uuid()
169 )
170 .fetch_optional(db)
171 .await?;
172 Ok(user)
173}
174
175/// Every account, newest first — the web layer's paging read — or, when
176/// `roles` is `Some`, only the rows whose role is in the set (the admin
177/// directory's tabs; `manager,admin` is one OR, not an AND). The narrowing
178/// is the `WHERE` itself, so [`PagedList`] counts the filtered set and a
179/// later page stays inside it: page and `total` share this one predicate.
180pub async fn list_all(
181 db: &Database,
182 roles: Option<&[Role]>,
183 limit: Option<i64>,
184 offset: i64,
185) -> Result<(Vec<User>, i64), AppError> {
186 let list = match roles {
187 None => PagedList::new("app_user", "ORDER BY id DESC"),
188 Some(roles) => PagedList::new("app_user WHERE role = ANY($1)", "ORDER BY id DESC").bind(
189 Param::Texts(
190 roles
191 .iter()
192 .map(|role| role.as_str().to_string())
193 .collect(),
194 ),
195 ),
196 };
197 list.run(limit, offset, db).await
198}
199
200/// Fetch the users behind `ids` in one query. Ids with no row are simply
201/// absent from the result — the caller decides how to degrade.
202pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result<Vec<User>, AppError> {
203 if ids.is_empty() {
204 return Ok(Vec::new());
205 }
206 let ids: Vec<uuid::Uuid> = ids.iter().map(UserId::uuid).collect();
207 let users = sqlx::query_as!(
208 User,
209 r#"SELECT id AS "id: UserId",
210 username AS "username: Username",
211 person AS "person: PersonId",
212 role AS "role: Role",
213 name AS "name: PersonName",
214 surname AS "surname: PersonName",
215 email AS "email: Email",
216 phone AS "phone: Phone",
217 birth_date AS "birth_date: BirthDate",
218 gender AS "gender: Gender",
219 address AS "address: Address",
220 emergency_contact_name AS "emergency_contact_name: PersonName",
221 emergency_contact_phone AS "emergency_contact_phone: Phone",
222 theme AS "theme: Theme",
223 language AS "language: Language",
224 palette_color AS "palette_color: PaletteColor",
225 display_name AS "display_name: DisplayName",
226 bio AS "bio: Bio",
227 avatar_file,
228 avatar_content_type AS "avatar_content_type: FileContentType",
229 branch,
230 student_number AS "student_number: StudentNumber",
231 avatar_size
232 FROM app_user WHERE id = ANY($1)"#,
233 &ids
234 )
235 .fetch_all(db)
236 .await?;
237 Ok(users)
238}
239
240/// Every user holding exactly `role` — e.g. the roster of a role-targeted
241/// event. Exact match, not `at_least`: "all teachers" means teachers, not
242/// managers and admins too.
243pub async fn list_by_role(db: &Database, role: Role) -> Result<Vec<User>, AppError> {
244 let users = sqlx::query_as!(
245 User,
246 r#"SELECT id AS "id: UserId",
247 username AS "username: Username",
248 person AS "person: PersonId",
249 role AS "role: Role",
250 name AS "name: PersonName",
251 surname AS "surname: PersonName",
252 email AS "email: Email",
253 phone AS "phone: Phone",
254 birth_date AS "birth_date: BirthDate",
255 gender AS "gender: Gender",
256 address AS "address: Address",
257 emergency_contact_name AS "emergency_contact_name: PersonName",
258 emergency_contact_phone AS "emergency_contact_phone: Phone",
259 theme AS "theme: Theme",
260 language AS "language: Language",
261 palette_color AS "palette_color: PaletteColor",
262 display_name AS "display_name: DisplayName",
263 bio AS "bio: Bio",
264 avatar_file,
265 avatar_content_type AS "avatar_content_type: FileContentType",
266 branch,
267 student_number AS "student_number: StudentNumber",
268 avatar_size
269 FROM app_user WHERE role = $1 ORDER BY id DESC"#,
270 role.as_str()
271 )
272 .fetch_all(db)
273 .await?;
274 Ok(users)
275}
276
277/// Case- and diacritic-insensitive fragment search over username, name,
278/// and surname. Needle and columns both go through
279/// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back —
280/// backs the user pickers. `role` narrows to one role (e.g. only students
281/// for an enroll picker); `None` searches everyone. `allowed_roles`
282/// narrows the *visible* set (the roles a non-staff caller may message —
283/// see [`Role::messageable_roles`]); it is part of the query, not a
284/// post-filter, so `total` counts only what the caller may see. A blank
285/// `query` matches everyone visible: blank alone is the caller's whole
286/// directory, blank + `role` a role-scoped listing. Returns
287/// every match, ordered by username; the HTTP layer pages the result like
288/// any other list (no built-in cap — an over-broad fragment is windowed
289/// by `?limit`).
290pub async fn search(
291 db: &Database,
292 query: &str,
293 role: Option<Role>,
294 allowed_roles: Option<&[Role]>,
295 limit: Option<i64>,
296 offset: i64,
297) -> Result<(Vec<User>, i64), AppError> {
298 let needle = search_fold(query.trim());
299 // Placeholders are positional, and every clause is optional, so the
300 // numbering is assigned as the clauses are added. Containment is spelled
301 // `position(...) > 0` rather than `LIKE` so the needle's `%` and `_`
302 // stay literal characters — the fold does not escape, and a query for
303 // `100%` must not grow a wildcard.
304 let mut binds: Vec<Param> = Vec::new();
305 let mut clauses: Vec<String> = Vec::new();
306 if !needle.is_empty() {
307 let n = binds.len() + 1;
308 clauses.push(format!(
309 "(position(${n} in {}) > 0 \
310 OR position(${n} in {}) > 0 \
311 OR position(${n} in {}) > 0)",
312 search_fold_sql("username"),
313 search_fold_sql("coalesce(name, '')"),
314 search_fold_sql("coalesce(surname, '')"),
315 ));
316 binds.push(Param::Text(needle));
317 }
318 if let Some(role) = role {
319 let n = binds.len() + 1;
320 clauses.push(format!("role = ${n}"));
321 binds.push(Param::Text(role.as_str().to_string()));
322 }
323 if let Some(allowed) = allowed_roles {
324 let n = binds.len() + 1;
325 clauses.push(format!("role = ANY(${n})"));
326 binds.push(Param::Texts(
327 allowed
328 .iter()
329 .map(|role| role.as_str().to_string())
330 .collect(),
331 ));
332 }
333 let where_clause = if clauses.is_empty() {
334 "TRUE".to_string()
335 } else {
336 clauses.join(" AND ")
337 };
338 let mut list = PagedList::new(
339 format!("app_user WHERE {where_clause}"),
340 "ORDER BY username",
341 );
342 for bind in binds {
343 list = list.bind(bind);
344 }
345 list.run(limit, offset, db).await
346}
347
348/// The role write and every sweep it owes, in one transaction — the
349/// statement list behind [`crate::service::user::set_role`]; see there for
350/// the floor that guards it and the arm-by-arm reasoning. What follows is
351/// the store side.
352///
353/// Writes *only* the `role` field of the user row — plus `student_number`,
354/// cleared in that same statement whenever the new role is not `student`
355/// (see the statement's own note) — never the whole row: the row mixes
356/// admin-owned (role) and self-service (profile, preferences) fields, and
357/// each writer starts from a snapshot read at request start. A whole-row
358/// write would carry the snapshot's copy of the *other* group back over a
359/// concurrent edit — an in-flight profile save silently reverting an
360/// admin's demotion, or this write erasing a profile edit that raced it.
361/// [`set_profile`] and [`set_preferences`] are scoped for the same reason.
362///
363/// What is swept, and why the conditions differ:
364///
365/// * **Non-student** sheds class memberships, *every* enrollment row
366/// (hand-placed ones included — only students enroll, and a kept row
367/// would grant nothing and count a seat) and the parent links observing
368/// them. Memberships and enrollments were already one transaction and
369/// still are: released apart, an enrollment row could be left tagged with
370/// a class whose counters had been given back, so the class passed its
371/// zero-zero delete guard and no sweep could ever reach the row again.
372/// * **Parent** additionally frees event seats, comes off every whiteboard
373/// roster and has the boards they *created* closed — permanently
374/// read-only, rows kept, because a room whose creator is demoted is
375/// commandable by nobody at all (see the statement's own note). The seat
376/// is the one thing on a signup list nothing
377/// else could remove: staff free their own by hand (`unregister` allows
378/// the self case) but a parent can reach no such door, so a promotion
379/// strands nothing and only this demotion does. A list that has already
380/// **frozen** (an audience-`registration` event whose start-or-end time
381/// has passed — the same predicate
382/// [`crate::domain::registration`]'s Rust check enforces) is left exactly
383/// as it stands — past the freeze it is historical record,
384/// re-registering answers 409, and rewriting it here would be
385/// irrecoverable. A signup whose event record is *gone* has no seat to
386/// hand back and no list that can freeze, so it is deleted rather than
387/// skipped: skipped, it is stranded forever (`unregister` 404s on the
388/// missing event).
389/// * **Below teacher** gives up course staffing and homeroom-teacher
390/// columns — only teacher+ may hold either — and the published
391/// appointment calendar, whose live bookings are cancelled in the same
392/// breath. Nothing else could ever reach those: a slot is listed only on
393/// its own teacher's calendar and deleted only by a teacher+, so after the
394/// demotion neither its owner nor a manager has a route that yields its
395/// id, and a booking on it can be neither decided (teacher+ only) nor
396/// cancelled once its window opens — leaving the slot's `occupied` seat
397/// pinned at one and the slot itself undeletable forever. The requester
398/// keeps the row, `cancelled`, with the teacher on `cancelled_by` and the
399/// reason on `cancel_reason`; the slot it pointed at is gone (the
400/// `ON DELETE SET NULL` link carries the delete), so the booking renders
401/// without a window
402/// ([`crate::domain::appointment::Appointment`]'s reader already treats a
403/// vanished slot that way). There is no notification anywhere in
404/// this crate, so a settled row the person can read is the strongest
405/// defined end available — and the alternative, deleting it, would make a
406/// confirmed meeting vanish with no trace at all.
407///
408/// The returned boards are the rooms whose roster this changed, plus those
409/// the user created — whose roster is untouched but which are now closed,
410/// and they carry that stamp because the close is written first. Publishing
411/// to them is the caller's job: an in-process
412/// fan-out cannot sit inside a database transaction, and a room told before
413/// the commit would re-read the pre-commit state.
414///
415/// **The admin floor is the role write's own `WHERE`.** The old guard was a
416/// count read under a process-wide lock held across the whole cascade,
417/// because the old store could not serialize a cross-record count against a
418/// concurrent update (write-skew). Here the count rides the very row write
419/// it guards — a demotion that would leave no other admin writes zero rows
420/// — so two racing demotions contend on row locks and exactly one lands.
421/// Zero rows therefore means the floor refused; the missing-row reading of
422/// zero rows is unreachable (no route deletes a user row, and the caller's
423/// 404 pre-read answers that case first anyway).
424pub async fn set_role_cascade(
425 db: &Database,
426 target: &UserId,
427 role: Role,
428) -> Result<(User, Vec<Board>), AppError> {
429 // One wall-clock read for the whole cascade, bound by every stamping
430 // statement — the old batch's single `$now`.
431 let now = Timestamp::now().as_millis();
432 // Owned capture: an `async move` closure holding a `&UserId` fails the
433 // higher-ranked `Send` check `tx_with_retry`'s future must pass.
434 let target = *target;
435 tx_with_retry(db, true, async move |tx| {
436 // The floor's serialization point: a demotion takes the admin set's
437 // row locks *before* the write, so two same-instant demotions of
438 // each other cannot both count the other as the surviving admin —
439 // the loser re-counts against the winner's commit and refuses
440 // here. (The predicate on the `UPDATE` below stays as the write's
441 // own guard; under these locks it can no longer be raced past.)
442 if role != Role::Admin {
443 let current = sqlx::query!(
444 r#"SELECT role AS "role: Role" FROM app_user WHERE id = $1"#,
445 target.uuid()
446 )
447 .fetch_optional(&mut *tx)
448 .await?
449 .map(|row| row.role);
450 if current == Some(Role::Admin) {
451 let admins = sqlx::query_as::<_, (uuid::Uuid,)>(
452 "SELECT id FROM app_user WHERE role = 'admin' FOR UPDATE",
453 )
454 .fetch_all(&mut *tx)
455 .await?;
456 if admins.len() <= 1 {
457 return Err(AppError::Conflict(
458 "the school must keep at least one admin — promote another account first",
459 ));
460 }
461 }
462 }
463
464 // The role write, floor guard included. `$2 <> 'admin'` arms the
465 // guard only for a demotion: a promotion or a same-role rewrite can
466 // never orphan the admins. `student_number` rides the same statement:
467 // the number names a student of this school, so the write that stops
468 // being one is the write that drops it — a re-stated `student` keeps
469 // it, everything else clears it, and no window exists where a
470 // promoted account still holds one.
471 let updated = sqlx::query_as!(
472 User,
473 r#"UPDATE app_user
474 SET role = $2,
475 student_number = CASE WHEN $2 = 'student' THEN student_number ELSE NULL END
476 WHERE id = $1
477 AND NOT (role = 'admin'
478 AND $2 <> 'admin'
479 AND (SELECT count(*) FROM app_user
480 WHERE role = 'admin' AND id <> $1) = 0)
481 RETURNING id AS "id: UserId",
482 username AS "username: Username",
483 person AS "person: PersonId",
484 role AS "role: Role",
485 name AS "name: PersonName",
486 surname AS "surname: PersonName",
487 email AS "email: Email",
488 phone AS "phone: Phone",
489 birth_date AS "birth_date: BirthDate",
490 gender AS "gender: Gender",
491 address AS "address: Address",
492 emergency_contact_name AS "emergency_contact_name: PersonName",
493 emergency_contact_phone AS "emergency_contact_phone: Phone",
494 theme AS "theme: Theme",
495 language AS "language: Language",
496 palette_color AS "palette_color: PaletteColor",
497 display_name AS "display_name: DisplayName",
498 bio AS "bio: Bio",
499 avatar_file,
500 avatar_content_type AS "avatar_content_type: FileContentType",
501 branch,
502 student_number AS "student_number: StudentNumber",
503 avatar_size"#,
504 target.uuid(),
505 role.as_str(),
506 )
507 .fetch_optional(&mut *tx)
508 .await?;
509 let Some(updated) = updated else {
510 return Err(AppError::Conflict(
511 "the school must keep at least one admin — promote another account first",
512 ));
513 };
514
515 if role != Role::Student {
516 // Class memberships go *soft*: the live stint is stamped, not
517 // deleted — membership history survives a demotion, and the
518 // partial unique index leaves the pair free to rejoin if the
519 // account is promoted back — while each class they were live in
520 // gets its seat back (the counter counts live rows). One live row
521 // per (class, user), so one decrement each.
522 sqlx::query!(
523 r#"WITH gone AS (
524 UPDATE class_member SET left_at = $2
525 WHERE app_user = $1 AND left_at IS NULL
526 RETURNING class
527 )
528 UPDATE class_group
529 SET class_member_count = GREATEST(class_member_count - 1, 0)
530 WHERE id IN (SELECT gone.class FROM gone)"#,
531 target.uuid(),
532 now,
533 )
534 .execute(&mut *tx)
535 .await?;
536 // Every enrollment row — hand-placed included — and each
537 // *instance's* roster count with it (the roster counter lives on
538 // the class×course instance now).
539 sqlx::query!(
540 r#"WITH gone AS (
541 DELETE FROM enrollment WHERE app_user = $1 RETURNING class_course
542 )
543 UPDATE class_course
544 SET enrollment_count = GREATEST(enrollment_count - 1, 0)
545 WHERE id IN (SELECT gone.class_course FROM gone)"#,
546 target.uuid(),
547 )
548 .execute(&mut *tx)
549 .await?;
550 // The individual club/supervised-study memberships go with them: a demoted
551 // account may hold no seat in a school-scoped course either, and
552 // each course gets its membership count back.
553 sqlx::query!(
554 r#"WITH gone AS (
555 DELETE FROM course_membership WHERE app_user = $1 RETURNING course
556 )
557 UPDATE course
558 SET course_membership_count = GREATEST(course_membership_count - 1, 0)
559 WHERE id IN (SELECT gone.course FROM gone)"#,
560 target.uuid(),
561 )
562 .execute(&mut *tx)
563 .await?;
564 sqlx::query!("DELETE FROM parent_link WHERE student = $1", target.uuid())
565 .execute(&mut *tx)
566 .await?;
567 }
568
569 if role == Role::Parent {
570 // Signups whose event is gone: no seat to hand back, no list
571 // that could freeze — delete the stray row outright.
572 sqlx::query!(
573 r#"DELETE FROM registration r
574 WHERE r.app_user = $1
575 AND NOT EXISTS (SELECT 1 FROM event e WHERE e.id = r.event)"#,
576 target.uuid(),
577 )
578 .execute(&mut *tx)
579 .await?;
580 // Row and seat move together per signup, the way `unregister`
581 // does: the seats are independent facts on unrelated events. A
582 // frozen list keeps its rows exactly as they stand; every other
583 // list — including a registration event with no dates at all,
584 // which never freezes — releases the seat.
585 sqlx::query!(
586 r#"WITH gone AS (
587 DELETE FROM registration r
588 USING event e
589 WHERE r.event = e.id
590 AND r.app_user = $1
591 AND NOT (e.audience_kind = 'registration'
592 AND COALESCE(e.starts_at, e.ends_at) IS NOT NULL
593 AND COALESCE(e.starts_at, e.ends_at) <= $2)
594 RETURNING r.event AS event_id
595 )
596 UPDATE event
597 SET registration_count = GREATEST(registration_count - 1, 0)
598 WHERE id IN (SELECT gone.event_id FROM gone)"#,
599 target.uuid(),
600 now,
601 )
602 .execute(&mut *tx)
603 .await?;
604 // A room whose *creator* is demoted can never be ended by anyone:
605 // the whiteboard is closed to parents outright, so the creator is
606 // 404'd off their own board, `clear`/`lock`/`close`/`delete` are
607 // creator-only for everyone else, and
608 // `crate::db::board::list_for_user` is the crate's only
609 // enumeration — no manager or admin can so much as find the id.
610 // Its participants meanwhile keep drawing (the room re-derives
611 // membership per frame and they still pass), into a board only
612 // the 50 000-stroke lifetime cap could ever retire. So the
613 // demotion retires it, with the same compare-and-set
614 // [`crate::db::board::close`] uses: an already-closed board
615 // keeps its first stamp. Closed and not deleted because the
616 // marks are the participants' work too — they keep reading the
617 // board and its whole history, and the creator's `board_count`
618 // seat stays taken, which is correct while the row it counts
619 // exists. Stamped *before* the roster strip so the strip's
620 // read-back below carries the closed row the caller fans out.
621 // The strip itself is the junction's: the demoted user's roster
622 // rows are deleted and their board ids collected from
623 // RETURNING, then the affected rooms are read back in the same
624 // transaction — the junction delete cannot return the whole
625 // row the way the old `array_remove` `UPDATE` did.
626 sqlx::query!(
627 "UPDATE board SET closed_at = $2 WHERE creator = $1 AND closed_at IS NULL",
628 target.uuid(),
629 now,
630 )
631 .execute(&mut *tx)
632 .await?;
633 let stripped = sqlx::query!(
634 "DELETE FROM board_participant WHERE participant = $1 RETURNING board",
635 target.uuid(),
636 )
637 .fetch_all(&mut *tx)
638 .await?;
639 let stripped_boards: Vec<uuid::Uuid> =
640 stripped.into_iter().map(|row| row.board).collect();
641 let boards = sqlx::query_as!(
642 Board,
643 r#"SELECT b.id AS "id: BoardId", b.creator AS "creator: UserId",
644 b.title AS "title: BoardTitle",
645 ARRAY(SELECT p.participant FROM board_participant p
646 WHERE p.board = b.id ORDER BY p.participant)
647 AS "participants!: Vec<UserId>",
648 b.locked, b.locked_by AS "locked_by: UserId",
649 b.locked_at AS "locked_at: Timestamp", b.epoch,
650 b.closed_at AS "closed_at: Timestamp",
651 b.created_at AS "created_at: Timestamp"
652 FROM board b
653 WHERE b.id = ANY($1::uuid[]) OR b.creator = $2
654 ORDER BY b.id"#,
655 &stripped_boards,
656 target.uuid(),
657 )
658 .fetch_all(&mut *tx)
659 .await?;
660 return Ok((updated, boards));
661 }
662
663 if role != Role::Parent {
664 sqlx::query!("DELETE FROM parent_link WHERE parent = $1", target.uuid())
665 .execute(&mut *tx)
666 .await?;
667 }
668
669 if !role.at_least(Role::Teacher) {
670 // Instance staffing goes — only teacher+ may hold a seat, and the
671 // seat is a `class_course_teacher` row now (D6 moved assignment
672 // onto the instance): one `DELETE` by its `teacher` index takes
673 // every assignment.
674 sqlx::query!(
675 "DELETE FROM class_course_teacher WHERE teacher = $1",
676 target.uuid(),
677 )
678 .execute(&mut *tx)
679 .await?;
680 sqlx::query!(
681 "UPDATE class_group SET teacher = NULL WHERE teacher = $1",
682 target.uuid(),
683 )
684 .execute(&mut *tx)
685 .await?;
686 // The published calendar goes too, and the bookings on it are
687 // settled first: a slot only its own teacher can list and only a
688 // teacher+ can delete is reachable by nobody once that teacher is
689 // demoted, and a live booking on one is worse — nobody can
690 // approve, reject or (past its start) cancel it, so it pins the
691 // slot's `occupied` seat forever. Cancelled rather than deleted
692 // so the person who asked is left with a settled booking they can
693 // still read, carrying who dropped it and why; the slot row (and
694 // with it the seat) goes, which is what makes this convergent.
695 sqlx::query!(
696 r#"UPDATE appointment
697 SET status = 'cancelled', cancelled_by = $1, cancel_reason = $2
698 WHERE slot IN (SELECT id FROM appointment_slot WHERE teacher = $1)
699 AND status IN ('pending', 'approved')"#,
700 target.uuid(),
701 "the teacher no longer holds a teaching role",
702 )
703 .execute(&mut *tx)
704 .await?;
705 // Deleting the slots is also what makes a *concurrent* booking
706 // safe: `Appointment::book` claims the slot row this deletes, so
707 // the two collide in the store. A slot *published* concurrently
708 // shares no key with any of this, which is why the publish path
709 // claims the user row instead. The settled booking rows survive
710 // the delete with `slot = NULL` (`ON DELETE SET NULL`) — still
711 // readable, windowless.
712 sqlx::query!(
713 "DELETE FROM appointment_slot WHERE teacher = $1",
714 target.uuid(),
715 )
716 .execute(&mut *tx)
717 .await?;
718 }
719
720 Ok((updated, Vec::new()))
721 })
722 .await
723}
724
725/// Write the personal-info and public-profile fields the request actually
726/// carried — everything a person edits about themselves except the avatar
727/// blob, which needs its own writer ([`set_avatar`]). Every
728/// column is nullable, so each argument is an outer/inner `Option`: `None`
729/// = omitted (not written at all), `Some(None)` = cleared, `Some(Some(v))`
730/// = set. Merging the request against the current row is the HTTP layer's
731/// job; the caller authorizes.
732///
733/// Request-scoped, not merely field-scoped: nothing guards the row across
734/// the handler's read and this write, so re-sending the snapshot's value
735/// for an omitted field would revert a concurrent PATCH of that field —
736/// two profile edits (a name and a phone) used to lose each other. See
737/// [`set_role_cascade`] for why no writer here touches the whole row.
738///
739/// `student_number` is the one column here whose write can be *violated*
740/// rather than merely refused: the partial unique index is its whole
741/// availability check, so a duplicate the caller did not pre-check (and
742/// could not — a pre-check races) comes back as the index's 23505 and is
743/// mapped to the same 409 the duplicate-username path answers. The role
744/// gate ("only a student holds one") stays at the web layer, which holds
745/// the row it read.
746// One argument per nullable column is the point: folding them into a struct
747// would just re-spell the HTTP DTO here and cost the compiler's check that
748// every column was considered at the call site.
749#[allow(clippy::too_many_arguments)]
750pub async fn set_profile(
751 db: &Database,
752 id: &UserId,
753 name: Option<Option<PersonName>>,
754 surname: Option<Option<PersonName>>,
755 email: Option<Option<Email>>,
756 phone: Option<Option<Phone>>,
757 birth_date: Option<Option<BirthDate>>,
758 display_name: Option<Option<DisplayName>>,
759 bio: Option<Option<Bio>>,
760 gender: Option<Option<Gender>>,
761 address: Option<Option<Address>>,
762 emergency_contact_name: Option<Option<PersonName>>,
763 emergency_contact_phone: Option<Option<Phone>>,
764 branch: Option<Option<String>>,
765 student_number: Option<Option<StudentNumber>>,
766) -> Result<User, AppError> {
767 // `Some(None)` must bind an explicit NULL and `Some(Some(v))` a value:
768 // `Param::OptText` carries both shapes of one nullable TEXT column.
769 fn text(value: Option<Option<&str>>) -> Option<Param> {
770 value.map(|inner| Param::OptText(inner.map(str::to_string)))
771 }
772 FieldUpdate::new("app_user", id.uuid())
773 .set(
774 "name",
775 text(name.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))),
776 )
777 .set(
778 "surname",
779 text(surname.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))),
780 )
781 .set(
782 "email",
783 text(email.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))),
784 )
785 .set(
786 "phone",
787 text(phone.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))),
788 )
789 .set(
790 "birth_date",
791 text(birth_date.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))),
792 )
793 .set(
794 "display_name",
795 text(
796 display_name
797 .as_ref()
798 .map(|n| n.as_ref().map(|x| x.as_str())),
799 ),
800 )
801 .set(
802 "bio",
803 text(bio.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))),
804 )
805 .set(
806 "gender",
807 text(gender.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))),
808 )
809 .set(
810 "address",
811 text(address.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))),
812 )
813 .set(
814 "emergency_contact_name",
815 text(
816 emergency_contact_name
817 .as_ref()
818 .map(|n| n.as_ref().map(|x| x.as_str())),
819 ),
820 )
821 .set(
822 "emergency_contact_phone",
823 text(
824 emergency_contact_phone
825 .as_ref()
826 .map(|n| n.as_ref().map(|x| x.as_str())),
827 ),
828 )
829 // The subject area is plain text, not a newtype: the school's own list is
830 // settings data, so its membership check belongs to the write path
831 // that holds that list (the web layer), not to a row type.
832 .set(
833 "branch",
834 text(branch.as_ref().map(|n| n.as_ref().map(String::as_str))),
835 )
836 .set(
837 "student_number",
838 text(
839 student_number
840 .as_ref()
841 .map(|n| n.as_ref().map(StudentNumber::as_str)),
842 ),
843 )
844 .run(db)
845 .await
846 .map_err(|err| match err {
847 // The index's own refusal, named. A `SELECT`-then-write pre-check
848 // would race (two students claim the same number, both read free);
849 // the partial unique index is the serialization point, so this is
850 // the only place the collision is knowable.
851 AppError::Db(sqlx_err)
852 if unique_violation(&sqlx_err) == Some("app_user_student_number") =>
853 {
854 number_taken()
855 }
856 // The other half of the rule, and the one only the database can
857 // hold: this write carried a number from a snapshot that said
858 // `student`, while the role write committed first. The CHECK sees
859 // the row as it is *now*, and the caller gets the same 400 the
860 // web pre-check answers.
861 AppError::Db(sqlx_err)
862 if check_violation(&sqlx_err) == Some("app_user_student_number_student") =>
863 {
864 StudentNumber::non_student_refusal().into()
865 }
866 other => other,
867 })
868}
869
870/// Point the row at a freshly uploaded avatar blob, returning the row *as
871/// it was* — the caller deletes `before.get_avatar_file()` off disk. Losing
872/// the pre-image here strands the replaced blob forever: no route ever
873/// deletes a user, so nothing else would collect it.
874///
875/// Field-scoped for the same reason as [`set_profile`]: an avatar
876/// upload must not carry a stale snapshot's role back over an admin's
877/// change. `None` means the row is gone.
878///
879/// The row is locked across the pre-image read and the write (`FOR
880/// UPDATE`), so two racing uploads each collect the blob *they* actually
881/// replaced — the read and the write are one unit, not a guess that stayed
882/// true.
883pub async fn set_avatar(
884 db: &Database,
885 id: &UserId,
886 file: &str,
887 content_type: &FileContentType,
888 size: i64,
889) -> Result<Option<User>, AppError> {
890 // Owned captures, same `Send` rule as every `tx_with_retry` closure.
891 let id = *id;
892 let file = file.to_string();
893 let content_type = content_type.clone();
894 tx_with_retry(db, false, async move |tx| {
895 let before = sqlx::query_as!(
896 User,
897 r#"SELECT id AS "id: UserId",
898 username AS "username: Username",
899 person AS "person: PersonId",
900 role AS "role: Role",
901 name AS "name: PersonName",
902 surname AS "surname: PersonName",
903 email AS "email: Email",
904 phone AS "phone: Phone",
905 birth_date AS "birth_date: BirthDate",
906 gender AS "gender: Gender",
907 address AS "address: Address",
908 emergency_contact_name AS "emergency_contact_name: PersonName",
909 emergency_contact_phone AS "emergency_contact_phone: Phone",
910 theme AS "theme: Theme",
911 language AS "language: Language",
912 palette_color AS "palette_color: PaletteColor",
913 display_name AS "display_name: DisplayName",
914 bio AS "bio: Bio",
915 avatar_file,
916 avatar_content_type AS "avatar_content_type: FileContentType",
917 branch,
918 student_number AS "student_number: StudentNumber",
919 avatar_size
920 FROM app_user WHERE id = $1 FOR UPDATE"#,
921 id.uuid()
922 )
923 .fetch_optional(&mut *tx)
924 .await?;
925 let Some(before) = before else {
926 return Ok(None);
927 };
928 sqlx::query!(
929 r#"UPDATE app_user
930 SET avatar_file = $2, avatar_content_type = $3, avatar_size = $4
931 WHERE id = $1"#,
932 id.uuid(),
933 file.as_str(),
934 content_type.as_str(),
935 size,
936 )
937 .execute(&mut *tx)
938 .await?;
939 Ok(Some(before))
940 })
941 .await
942}
943
944/// Drop the avatar, returning the row as it was so the caller can delete
945/// the blob. Same pre-image contract as [`set_avatar`].
946pub async fn clear_avatar(db: &Database, id: &UserId) -> Result<Option<User>, AppError> {
947 let id = *id;
948 tx_with_retry(db, false, async move |tx| {
949 let before = sqlx::query_as!(
950 User,
951 r#"SELECT id AS "id: UserId",
952 username AS "username: Username",
953 person AS "person: PersonId",
954 role AS "role: Role",
955 name AS "name: PersonName",
956 surname AS "surname: PersonName",
957 email AS "email: Email",
958 phone AS "phone: Phone",
959 birth_date AS "birth_date: BirthDate",
960 gender AS "gender: Gender",
961 address AS "address: Address",
962 emergency_contact_name AS "emergency_contact_name: PersonName",
963 emergency_contact_phone AS "emergency_contact_phone: Phone",
964 theme AS "theme: Theme",
965 language AS "language: Language",
966 palette_color AS "palette_color: PaletteColor",
967 display_name AS "display_name: DisplayName",
968 bio AS "bio: Bio",
969 avatar_file,
970 avatar_content_type AS "avatar_content_type: FileContentType",
971 branch,
972 student_number AS "student_number: StudentNumber",
973 avatar_size
974 FROM app_user WHERE id = $1 FOR UPDATE"#,
975 id.uuid()
976 )
977 .fetch_optional(&mut *tx)
978 .await?;
979 let Some(before) = before else {
980 return Ok(None);
981 };
982 sqlx::query!(
983 r#"UPDATE app_user
984 SET avatar_file = NULL, avatar_content_type = NULL, avatar_size = NULL
985 WHERE id = $1"#,
986 id.uuid(),
987 )
988 .execute(&mut *tx)
989 .await?;
990 Ok(Some(before))
991 })
992 .await
993}
994
995/// Write the UI-preference fields the request actually carried. Same
996/// contract as [`set_profile`]: `None` = omitted (not written),
997/// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set.
998pub async fn set_preferences(
999 db: &Database,
1000 id: &UserId,
1001 theme: Option<Option<Theme>>,
1002 language: Option<Option<Language>>,
1003 palette_color: Option<Option<PaletteColor>>,
1004) -> Result<User, AppError> {
1005 let theme = theme.map(|t| Param::OptText(t.map(|v| v.as_str().to_string())));
1006 let language = language.map(|l| Param::OptText(l.map(|v| v.as_str().to_string())));
1007 let palette_color = palette_color.map(|p| Param::OptText(p.map(|v| v.as_str().to_string())));
1008 FieldUpdate::new("app_user", id.uuid())
1009 .set("theme", theme)
1010 .set("language", language)
1011 .set("palette_color", palette_color)
1012 .run(db)
1013 .await
1014}
1015
1016pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<User>, AppError> {
1017 let user = sqlx::query_as!(
1018 User,
1019 r#"SELECT id AS "id: UserId",
1020 username AS "username: Username",
1021 person AS "person: PersonId",
1022 role AS "role: Role",
1023 name AS "name: PersonName",
1024 surname AS "surname: PersonName",
1025 email AS "email: Email",
1026 phone AS "phone: Phone",
1027 birth_date AS "birth_date: BirthDate",
1028 gender AS "gender: Gender",
1029 address AS "address: Address",
1030 emergency_contact_name AS "emergency_contact_name: PersonName",
1031 emergency_contact_phone AS "emergency_contact_phone: Phone",
1032 theme AS "theme: Theme",
1033 language AS "language: Language",
1034 palette_color AS "palette_color: PaletteColor",
1035 display_name AS "display_name: DisplayName",
1036 bio AS "bio: Bio",
1037 avatar_file,
1038 avatar_content_type AS "avatar_content_type: FileContentType",
1039 branch,
1040 student_number AS "student_number: StudentNumber",
1041 avatar_size
1042 FROM app_user WHERE username = $1"#,
1043 username
1044 )
1045 .fetch_optional(db)
1046 .await?;
1047 Ok(user)
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052 use super::*;
1053 use crate::database::init_test_db;
1054
1055 fn png() -> FileContentType {
1056 FileContentType::try_new("image/png").unwrap()
1057 }
1058
1059 async fn a_user(username: &str, db: &Database) -> User {
1060 create(db, Username::try_new(username).unwrap(), None)
1061 .await
1062 .unwrap()
1063 }
1064
1065 #[tokio::test]
1066 async fn a_stale_profile_write_cannot_revert_a_role_change() {
1067 let (db, _leases) = init_test_db().await;
1068 let user = a_user("aysenur", &db).await;
1069
1070 // A PATCH /users/me handler reads its snapshot (role = student)...
1071 let stale = read(&db, user.get_id()).await.unwrap().unwrap();
1072
1073 // ...then an admin's role change commits before the profile save runs.
1074 crate::service::user::set_role(&db, user.get_id(), Role::Teacher)
1075 .await
1076 .unwrap();
1077
1078 // The in-flight save lands from the stale snapshot. It must write only
1079 // the profile fields — not carry the snapshot's old role back over the
1080 // admin's change.
1081 let name = PersonName::try_new("name", "Ayşenur").unwrap();
1082 set_profile(
1083 &db,
1084 stale.get_id(),
1085 Some(Some(name.clone())),
1086 None,
1087 None,
1088 None,
1089 None,
1090 None,
1091 None,
1092 None,
1093 None,
1094 None,
1095 None,
1096 None,
1097 None,
1098 )
1099 .await
1100 .unwrap();
1101
1102 let after = read(&db, user.get_id()).await.unwrap().unwrap();
1103 assert_eq!(
1104 after.get_role(),
1105 Role::Teacher,
1106 "the role change must survive the racing profile write"
1107 );
1108 assert_eq!(
1109 after.get_name(),
1110 Some(&name),
1111 "the profile edit itself lands"
1112 );
1113 }
1114
1115 /// The role rule is the *database's*, not only the handler's: a profile
1116 /// write carrying a number read from a `student` snapshot must be refused
1117 /// when a promotion committed in between — exactly as the web pre-check
1118 /// would have refused it a moment earlier. Without the row's own `CHECK`
1119 /// this write lands and leaves a teacher holding a student number, which
1120 /// every later read would serve.
1121 #[tokio::test]
1122 async fn a_stale_number_write_cannot_outrun_a_promotion() {
1123 let (db, _leases) = init_test_db().await;
1124 let user = a_user("selin", &db).await;
1125 let number = StudentNumber::try_new("9-B/17").unwrap();
1126 // Numbered while a student.
1127 set_profile(
1128 &db,
1129 user.get_id(),
1130 None, None, None, None, None, None, None, None, // name..bio
1131 None, None, None, None, // gender..emergency_contact_phone
1132 Some(Some(number.clone())),
1133 )
1134 .await
1135 .unwrap();
1136
1137 // The handler reads its snapshot (role = student, number set)...
1138 let stale = read(&db, user.get_id()).await.unwrap().unwrap();
1139 // ...the promotion commits, clearing the number...
1140 crate::service::user::set_role(&db, user.get_id(), Role::Teacher)
1141 .await
1142 .unwrap();
1143 // ...and the in-flight save lands from the stale snapshot.
1144 let refused = set_profile(
1145 &db,
1146 stale.get_id(),
1147 None, None, None, None, None, None, None, None, // name..bio
1148 None, None, None, None, // gender..emergency_contact_phone
1149 Some(Some(number)),
1150 )
1151 .await;
1152 match refused {
1153 Err(AppError::Validation(crate::error::ValidationError::Invalid { field, .. })) => {
1154 assert_eq!(field, "student_number")
1155 }
1156 other => panic!("the database must refuse a number on a promoted row: {other:?}"),
1157 }
1158 let after = read(&db, user.get_id()).await.unwrap().unwrap();
1159 assert_eq!(after.get_role(), Role::Teacher);
1160 assert_eq!(
1161 after.get_student_number(),
1162 None,
1163 "a promoted row holds no number"
1164 );
1165 }
1166
1167 #[tokio::test]
1168 async fn an_avatar_upload_cannot_revert_a_role_change() {
1169 let (db, _leases) = init_test_db().await;
1170 let user = a_user("berk", &db).await;
1171
1172 // The upload handler holds its snapshot (role = student)...
1173 let stale = read(&db, user.get_id()).await.unwrap().unwrap();
1174
1175 // ...an admin promotes and the person edits their bio, both while the
1176 // blob is still being written...
1177 crate::service::user::set_role(&db, user.get_id(), Role::Teacher)
1178 .await
1179 .unwrap();
1180 let display_name = DisplayName::try_new("Berk").unwrap();
1181 set_profile(
1182 &db,
1183 user.get_id(),
1184 None,
1185 None,
1186 None,
1187 None,
1188 None,
1189 Some(Some(display_name.clone())),
1190 None,
1191 None,
1192 None,
1193 None,
1194 None,
1195 None,
1196 None,
1197 )
1198 .await
1199 .unwrap();
1200
1201 // ...and only then does the avatar land, from the stale row's id.
1202 set_avatar(&db, stale.get_id(), "blob-1", &png(), 42)
1203 .await
1204 .unwrap()
1205 .expect("the row exists");
1206
1207 let after = read(&db, user.get_id()).await.unwrap().unwrap();
1208 assert_eq!(
1209 after.get_role(),
1210 Role::Teacher,
1211 "the role change must survive the racing avatar write"
1212 );
1213 assert_eq!(
1214 after.get_display_name(),
1215 Some(&display_name),
1216 "and so must every other column the avatar write never named"
1217 );
1218 assert_eq!(after.get_avatar_file(), Some("blob-1"));
1219 assert_eq!(after.get_avatar_content_type(), Some(&png()));
1220 assert_eq!(after.get_avatar_size(), Some(42));
1221 }
1222
1223 /// The blob cleanup is built on the pre-image: without the old
1224 /// `avatar_file` coming back, every replace strands a file on disk that
1225 /// no route ever collects.
1226 #[tokio::test]
1227 async fn the_avatar_writers_return_the_replaced_blob() {
1228 let (db, _leases) = init_test_db().await;
1229 let user = a_user("ceyda", &db).await;
1230
1231 let before = set_avatar(&db, user.get_id(), "blob-1", &png(), 10)
1232 .await
1233 .unwrap()
1234 .expect("the row exists");
1235 assert_eq!(before.get_avatar_file(), None, "no blob to collect yet");
1236
1237 let before = set_avatar(&db, user.get_id(), "blob-2", &png(), 20)
1238 .await
1239 .unwrap()
1240 .expect("the row exists");
1241 assert_eq!(
1242 before.get_avatar_file(),
1243 Some("blob-1"),
1244 "the replaced blob is what the caller must delete"
1245 );
1246
1247 let before = clear_avatar(&db, user.get_id())
1248 .await
1249 .unwrap()
1250 .expect("the row exists");
1251 assert_eq!(before.get_avatar_file(), Some("blob-2"));
1252
1253 let after = read(&db, user.get_id()).await.unwrap().unwrap();
1254 assert_eq!(after.get_avatar_file(), None);
1255 assert_eq!(after.get_avatar_content_type(), None);
1256 assert_eq!(after.get_avatar_size(), None);
1257
1258 assert!(
1259 clear_avatar(&db, &UserId::from_key("yok"))
1260 .await
1261 .unwrap()
1262 .is_none(),
1263 "a missing row is None, not an error"
1264 );
1265 }
1266
1267 /// The admin directory's role tabs: `roles` is the query's `WHERE`, so
1268 /// the page and the `total` share one filtered predicate — a window
1269 /// never leaks another role, and `total` counts the filtered set, not
1270 /// the roster.
1271 #[tokio::test]
1272 async fn the_roles_filter_is_one_where_across_page_and_total() {
1273 let (db, _leases) = init_test_db().await;
1274 let admin = a_user("tabor-admin", &db).await;
1275 crate::service::user::set_role(&db, admin.get_id(), Role::Admin)
1276 .await
1277 .unwrap();
1278 let manager = a_user("tabor-mgr", &db).await;
1279 crate::service::user::set_role(&db, manager.get_id(), Role::Manager)
1280 .await
1281 .unwrap();
1282 let _student1 = a_user("tabor-s1", &db).await;
1283 let _student2 = a_user("tabor-s2", &db).await;
1284
1285 // Matched: only the staff pair, `total` = the filtered count.
1286 let (staff, total) =
1287 list_all(&db, Some(&[Role::Manager, Role::Admin]), None, 0)
1288 .await
1289 .unwrap();
1290 assert_eq!(total, 2, "total counts the filtered set, not the roster");
1291 assert!(
1292 staff
1293 .iter()
1294 .all(|user| matches!(user.get_role(), Role::Manager | Role::Admin)),
1295 "no student may ride a staff tab"
1296 );
1297
1298 // Unmatched: a well-formed set naming nobody is an empty page, not
1299 // an error.
1300 let (none, total) = list_all(&db, Some(&[Role::Parent]), None, 0)
1301 .await
1302 .unwrap();
1303 assert!(none.is_empty());
1304 assert_eq!(total, 0);
1305
1306 // Absent: the whole roster, exactly the unfiltered read.
1307 let (all, total) = list_all(&db, None, None, 0).await.unwrap();
1308 assert_eq!(total, 4);
1309 assert_eq!(all.len(), 4);
1310
1311 // The window applies AFTER the filter: a page of 1 inside the staff
1312 // set still counts 2, and walking the windows collects exactly the
1313 // staff pair — never a student.
1314 let (page1, total) =
1315 list_all(&db, Some(&[Role::Manager, Role::Admin]), Some(1), 0)
1316 .await
1317 .unwrap();
1318 assert_eq!(total, 2);
1319 assert_eq!(page1.len(), 1);
1320 let (page2, _) =
1321 list_all(&db, Some(&[Role::Manager, Role::Admin]), Some(1), 1)
1322 .await
1323 .unwrap();
1324 assert_eq!(page2.len(), 1);
1325 let mut both: Vec<_> = page1
1326 .iter()
1327 .chain(page2.iter())
1328 .map(|user| user.get_role())
1329 .collect();
1330 both.sort();
1331 assert_eq!(both, vec![Role::Manager, Role::Admin]);
1332 }
1333}