From f820c368f6c2bfc9b01b1d9f0f040645edf06fa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 14:25:07 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20message/parent?= =?UTF-8?q?=5Flink/registration=20into=20domain/db/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/meal_booking.rs | 2 +- src/db/message.rs | 230 +++++++++++++++++++++++++++++++++ src/db/mod.rs | 3 + src/db/parent_link.rs | 59 +++++++++ src/db/registration.rs | 55 ++++++++ src/domain/event.rs | 21 +-- src/domain/message.rs | 249 +++--------------------------------- src/domain/parent_link.rs | 68 +--------- src/domain/registration.rs | 151 ++-------------------- src/service/message.rs | 69 ++++++++++ src/service/mod.rs | 3 + src/service/parent_link.rs | 107 ++++++++++++++++ src/service/registration.rs | 103 +++++++++++++++ src/web/attendance.rs | 3 +- src/web/classes.rs | 5 +- src/web/events.rs | 15 ++- src/web/homework.rs | 3 +- src/web/marks.rs | 3 +- src/web/meals.rs | 24 ++-- src/web/messages.rs | 17 +-- src/web/mod.rs | 34 +---- src/web/payments.rs | 12 +- src/web/pomodoro.rs | 3 +- src/web/users.rs | 74 +++++------ tests/regress_role_sweep.rs | 10 +- 25 files changed, 757 insertions(+), 566 deletions(-) create mode 100644 src/db/message.rs create mode 100644 src/db/parent_link.rs create mode 100644 src/db/registration.rs create mode 100644 src/service/message.rs create mode 100644 src/service/parent_link.rs create mode 100644 src/service/registration.rs diff --git a/src/db/meal_booking.rs b/src/db/meal_booking.rs index 34d3c4f..49e95f1 100644 --- a/src/db/meal_booking.rs +++ b/src/db/meal_booking.rs @@ -46,7 +46,7 @@ pub async fn list_for_menu( /// parent whose link was revoked (by an unlink or by the student-side role /// sweep) would otherwise keep a live view of the child's seat, watching /// cancellations made long after the link died — exactly what -/// [`ensure_can_observe`](crate::web::ensure_can_observe) refuses. The +/// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The /// caller re-derives the list from the links on every read, so the view /// dies with the link. pub async fn list_for_students( diff --git a/src/db/message.rs b/src/db/message.rs new file mode 100644 index 0000000..1bd1aa9 --- /dev/null +++ b/src/db/message.rs @@ -0,0 +1,230 @@ +//! The `message` table: the send-side create, the folder listings, the +//! party-scoped read, and the field-scoped writes each party makes to its own +//! copy. The folder arithmetic on a row's values lives in +//! [`crate::domain::message`]. + +use crate::database::Database; +use crate::db::page::PagedList; +use crate::domain::message::{ + Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject, +}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn send( + db: &Database, + sender: &UserId, + recipient: &UserId, + subject: MessageSubject, + body: MessageBody, + label: Option, +) -> Result { + let message = Message { + id: MessageId::generate(), + sender: sender.clone(), + recipient: recipient.clone(), + subject, + body, + label, + sent_at: Timestamp::now(), + read: false, + sender_folder: Folder::Sent, + recipient_folder: Folder::Inbox, + sender_origin: None, + recipient_origin: None, + }; + let created: Option = db.create(message.id.record()).content(message).await?; + created.ok_or_else(|| AppError::Internal("failed to create message".into())) +} + +/// One folder view for `user`, newest first. `inbox` is recipient-side, +/// `sent` is sender-side, and `archive`/`trash` are each the union of both +/// sides' filed copies (either party may archive or trash their own copy). +/// `read` narrows to that flag state (`false` on the inbox is the unread +/// view; on `sent`, receipts pending) — the folder condition is +/// parenthesized because `archive`'s and `trash`'s are ORs. +pub async fn list_folder( + db: &Database, + user: &UserId, + folder: Folder, + read: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + let condition = match folder { + Folder::Sent => "sender = $usr AND sender_folder = 'sent'", + Folder::Archive => { + "(recipient = $usr AND recipient_folder = 'archive') \ + OR (sender = $usr AND sender_folder = 'archive')" + } + Folder::Trash => { + "(recipient = $usr AND recipient_folder = 'trash') \ + OR (sender = $usr AND sender_folder = 'trash')" + } + _ => "recipient = $usr AND recipient_folder = $folder", + }; + let read_clause = if read.is_some() { + " AND read = $read" + } else { + "" + }; + PagedList::new( + format!("message WHERE ({condition}){read_clause}"), + "ORDER BY id DESC", + ) + .bind("usr", user.record()) + .bind("folder", folder.as_str().to_string()) + .bind("read", read.unwrap_or_default()) + .run(limit, offset, db) + .await +} + +/// Read a message only if `user` is its sender or recipient and their +/// side hasn't been permanently deleted. +pub async fn read_for( + db: &Database, + id: &MessageId, + user: &UserId, +) -> Result, AppError> { + let message: Option = db.select(id.record()).await?; + Ok(message.filter(|message| { + (&message.sender == user || &message.recipient == user) + && message.folder_of(user) != Folder::Deleted + })) +} + +/// Flip the recipient's read flag. Field-scoped write: the sender may be +/// filing their side concurrently, and a whole-row save would clobber it. +pub async fn set_read(db: &Database, message: Message, read: bool) -> Result { + let mut result = db + .query("UPDATE $id SET read = $read RETURN AFTER") + .bind(("id", message.id.record())) + .bind(("read", read)) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +/// File `user`'s side into `folder` (already validated against that +/// side's allowed set), stamping where the copy came from so it can be +/// restored. Only the caller's two fields are written — field-scoped for +/// the same race reason as [`set_read`]. +/// +/// Filing away remembers the folder being left, so `inbox → archive → +/// trash` restores to `archive` and that back to `inbox`. Two folders are +/// never stamped: the trash (`trash → archive` would leave the copy +/// pointing back at the discard pile — it falls back to the home folder) +/// and the target itself (a no-op move keeps the memory it had). Moving +/// back to a home folder clears it. +pub async fn move_to( + db: &Database, + message: Message, + user: &UserId, + folder: Folder, +) -> Result { + let current = message.folder_of(user); + let (field, origin_field) = if message.is_sender(user) { + ("sender_folder", "sender_origin") + } else { + ("recipient_folder", "recipient_origin") + }; + let origin = match folder { + _ if !folder.is_filed() => None, + _ if current == folder => message.origin_of(user), + _ if current.is_restore_target() => Some(current), + _ => None, + }; + let mut result = db + .query(format!( + "UPDATE $id SET {field} = $folder, {origin_field} = $origin RETURN AFTER" + )) + .bind(("id", message.id.record())) + .bind(("folder", folder.as_str().to_string())) + .bind(("origin", origin.map(|origin| origin.as_str().to_string()))) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +/// Permanently drop `user`'s side — only if that side currently sits in +/// the trash; the gate rides in the `UPDATE`'s `WHERE` so a concurrent +/// move back to the inbox can't slip past a check-then-act window. The +/// row itself is removed once both sides are gone — judged on the +/// post-write row, so two concurrent deletes can't leak an all-deleted +/// row. +pub async fn delete_for(db: &Database, message: Message, user: &UserId) -> Result<(), AppError> { + let (field, origin_field) = if message.is_sender(user) { + ("sender_folder", "sender_origin") + } else { + ("recipient_folder", "recipient_origin") + }; + let mut result = db + .query(format!( + "UPDATE $id SET {field} = $deleted, {origin_field} = NONE \ + WHERE {field} = $trash RETURN AFTER" + )) + .bind(("id", message.id.record())) + .bind(("deleted", Folder::Deleted.as_str().to_string())) + .bind(("trash", Folder::Trash.as_str().to_string())) + .await? + .check()?; + let Some(after) = result.take::>(0)?.into_iter().next() else { + return Err(AppError::Conflict( + "only messages in the trash can be permanently deleted", + )); + }; + if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted { + let _: Option = db.delete(after.id.record()).await?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The `next_ulid` hazard: an inbox is documented newest-first and sorts + /// `id DESC`, so messages sent inside one millisecond must come back in + /// exact reverse write order, not at random (src/domain/monotonic_id.rs). + /// Asserts the *stored* order, not the mint order. + #[tokio::test] + async fn inbox_is_newest_first_within_a_millisecond() { + let db = crate::database::init_mem().await.unwrap(); + let sender = UserId::from_key("a"); + let recipient = UserId::from_key("b"); + let mut sent = Vec::new(); + for i in 0..25 { + let message = send( + &db, + &sender, + &recipient, + MessageSubject::try_new(&format!("s{i}")).unwrap(), + MessageBody::try_new("").unwrap(), + None, + ) + .await + .unwrap(); + sent.push(message.get_id().key().to_string()); + } + + let (listed, total) = list_folder(&db, &recipient, Folder::Inbox, None, None, 0) + .await + .unwrap(); + assert_eq!(total, 25); + sent.reverse(); + let read_back: Vec = listed + .iter() + .map(|row| row.get_id().key().to_string()) + .collect(); + assert_eq!(read_back, sent); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index e164f1b..871cfa7 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -12,9 +12,12 @@ pub mod exam_attempt; pub mod exam_question; pub mod field_update; pub mod meal_booking; +pub mod message; pub mod note; pub mod page; +pub mod parent_link; pub mod payment_ledger; +pub mod registration; pub mod session; pub mod settings; pub mod user; diff --git a/src/db/parent_link.rs b/src/db/parent_link.rs new file mode 100644 index 0000000..367cd34 --- /dev/null +++ b/src/db/parent_link.rs @@ -0,0 +1,59 @@ +//! The `parent_link` table: the composite-id upsert, the existence probe, +//! the per-parent listing, and the delete. The *decisions* over these rows +//! — who may be tied, and which reads a live link grants — live in +//! [`crate::service::parent_link`]. + +use crate::database::Database; +use crate::domain::parent_link::{ParentLink, ParentLinkId}; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn link( + db: &Database, + parent: &UserId, + student: &UserId, + linked_by: &UserId, +) -> Result { + let link = ParentLink { + id: ParentLinkId::composite(parent, student), + parent: parent.clone(), + student: student.clone(), + linked_by: linked_by.clone(), + }; + let saved: Option = db.upsert(link.id.record()).content(link).await?; + saved.ok_or_else(|| AppError::Internal("failed to link student to parent".into())) +} + +/// True iff a link row exists for the (parent, student) pair — the storage +/// half of the grant. The live half (the student side still holding the +/// role) is [`crate::service::parent_link::links_live`]. +pub async fn exists(db: &Database, parent: &UserId, student: &UserId) -> Result { + let found: Option = db + .select(ParentLinkId::composite(parent, student).record()) + .await?; + Ok(found.is_some()) +} + +/// Every student `parent` observes, newest link first. +pub async fn list_for_parent(db: &Database, parent: &UserId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM parent_link WHERE parent = $parent ORDER BY id DESC") + .bind(("parent", parent.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +pub async fn remove( + db: &Database, + parent: &UserId, + student: &UserId, +) -> Result, AppError> { + let mut result = db + .query("DELETE parent_link WHERE parent = $parent AND student = $student RETURN BEFORE") + .bind(("parent", parent.record())) + .bind(("student", student.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} diff --git a/src/db/registration.rs b/src/db/registration.rs new file mode 100644 index 0000000..207ba4e --- /dev/null +++ b/src/db/registration.rs @@ -0,0 +1,55 @@ +//! The `registration` table: the seat reads, the per-event listing, and +//! the delete that returns the seat in the same transaction. The register +//! workflow itself (the cap claim and its conflict mapping) lives in +//! [`crate::service::registration`]. + +use crate::database::Database; +use crate::domain::event::EventId; +use crate::domain::registration::Registration; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Some(_) iff `user` holds a seat on `event` — the audience point check. +pub async fn read_for_user( + db: &Database, + event: &EventId, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM registration WHERE event = $ev AND user = $usr LIMIT 1") + .bind(("ev", event.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +pub async fn list_for_event(db: &Database, event: &EventId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM registration WHERE event = $ev ORDER BY id DESC") + .bind(("ev", event.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +pub async fn remove( + db: &Database, + event: &EventId, + user: &UserId, +) -> Result, AppError> { + // The seat comes back in the same transaction as the row that held it. + let mut result = db + .query( + "BEGIN TRANSACTION; + LET $gone = (DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE); + UPDATE $ev SET registration_count = math::max([(registration_count ?? 0) - array::len($gone), 0]); + RETURN $gone; + COMMIT TRANSACTION;", + ) + .bind(("ev", event.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(3)?.into_iter().next()) +} diff --git a/src/domain/event.rs b/src/domain/event.rs index 2094333..d4ae240 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -9,7 +9,6 @@ use crate::domain::class_group::ClassGroupId; use crate::domain::class_member::{ClassMember, ClassMemberId}; use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_ulid; -use crate::domain::registration::Registration; use crate::domain::role::Role; use crate::domain::timestamp::{Timestamp, range_error}; use crate::domain::user::{User, UserId}; @@ -135,9 +134,11 @@ impl EventAudience { Ok(member.is_some()) } EventAudience::Registration { .. } => { - Ok(Registration::read_for_user(event, user.get_id(), db) - .await? - .is_some()) + Ok( + crate::db::registration::read_for_user(db, event, user.get_id()) + .await? + .is_some(), + ) } } } @@ -172,11 +173,13 @@ impl EventAudience { .iter() .map(|member| member.get_user().clone()) .collect()), - EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db) - .await? - .iter() - .map(|registration| registration.get_user().clone()) - .collect()), + EventAudience::Registration { .. } => { + Ok(crate::db::registration::list_for_event(db, event) + .await? + .iter() + .map(|registration| registration.get_user().clone()) + .collect()) + } } } } diff --git a/src/domain/message.rs b/src/domain/message.rs index 0d245ae..9d2dc0d 100644 --- a/src/domain/message.rs +++ b/src/domain/message.rs @@ -12,12 +12,10 @@ use crate::constant::{ MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, MESSAGE_TABLE, RECIPIENT_FOLDERS, SENDER_FOLDERS, }; -use crate::database::Database; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; /// The mailbox folders a copy can sit in — the single source of folder names @@ -36,7 +34,7 @@ pub enum Folder { Archive, Trash, /// The hidden "my copy is gone" folder; never a valid move or list - /// target — reached only through [`Message::delete_for`]. + /// target — reached only through [`crate::db::message::delete_for`]. Deleted, } @@ -86,14 +84,14 @@ impl Folder { } /// A filed-away copy — one that has somewhere to be restored to. - fn is_filed(self) -> bool { + pub(crate) fn is_filed(self) -> bool { matches!(self, Folder::Archive | Folder::Trash) } /// Whether this folder is worth remembering as a restore target. The /// trash is not: pulling a copy out of the trash and into the archive /// must not leave it pointing back at the trash. - fn is_restore_target(self) -> bool { + pub(crate) fn is_restore_target(self) -> bool { matches!(self, Folder::Inbox | Folder::Sent | Folder::Archive) } } @@ -103,7 +101,8 @@ pub struct MessageId(RecordId); impl MessageId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: - /// the folder listings sort `id DESC` (newest first, [`Message::list_folder`]), + /// the folder listings sort `id DESC` (newest first, + /// [`crate::db::message::list_folder`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(RecordId::new(MESSAGE_TABLE, next_ulid().to_string())) @@ -171,20 +170,20 @@ impl MessageLabel { #[derive(Debug, Clone, SurrealValue)] pub struct Message { - id: MessageId, - sender: UserId, - recipient: UserId, - subject: MessageSubject, - body: MessageBody, - label: Option, - sent_at: Timestamp, - read: bool, - sender_folder: Folder, - recipient_folder: Folder, + pub(crate) id: MessageId, + pub(crate) sender: UserId, + pub(crate) recipient: UserId, + pub(crate) subject: MessageSubject, + pub(crate) body: MessageBody, + pub(crate) label: Option, + pub(crate) sent_at: Timestamp, + pub(crate) read: bool, + pub(crate) sender_folder: Folder, + pub(crate) recipient_folder: Folder, /// Where each side's copy sat before it was filed into archive/trash — /// the restore target. `None` while the copy sits in its home folder. - sender_origin: Option, - recipient_origin: Option, + pub(crate) sender_origin: Option, + pub(crate) recipient_origin: Option, } impl Message { @@ -243,182 +242,6 @@ impl Message { self.recipient_origin } } - - pub async fn send( - sender: &UserId, - recipient: &UserId, - subject: MessageSubject, - body: MessageBody, - label: Option, - db: &Database, - ) -> Result { - let message = Message { - id: MessageId::generate(), - sender: sender.clone(), - recipient: recipient.clone(), - subject, - body, - label, - sent_at: Timestamp::now(), - read: false, - sender_folder: Folder::Sent, - recipient_folder: Folder::Inbox, - sender_origin: None, - recipient_origin: None, - }; - let created: Option = db.create(message.id.record()).content(message).await?; - created.ok_or_else(|| AppError::Internal("failed to create message".into())) - } - - /// One folder view for `user`, newest first. `inbox` is recipient-side, - /// `sent` is sender-side, and `archive`/`trash` are each the union of both - /// sides' filed copies (either party may archive or trash their own copy). - /// `read` narrows to that flag state (`false` on the inbox is the unread - /// view; on `sent`, receipts pending) — the folder condition is - /// parenthesized because `archive`'s and `trash`'s are ORs. - pub async fn list_folder( - user: &UserId, - folder: Folder, - read: Option, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - let condition = match folder { - Folder::Sent => "sender = $usr AND sender_folder = 'sent'", - Folder::Archive => { - "(recipient = $usr AND recipient_folder = 'archive') \ - OR (sender = $usr AND sender_folder = 'archive')" - } - Folder::Trash => { - "(recipient = $usr AND recipient_folder = 'trash') \ - OR (sender = $usr AND sender_folder = 'trash')" - } - _ => "recipient = $usr AND recipient_folder = $folder", - }; - let read_clause = if read.is_some() { - " AND read = $read" - } else { - "" - }; - PagedList::new( - format!("message WHERE ({condition}){read_clause}"), - "ORDER BY id DESC", - ) - .bind("usr", user.record()) - .bind("folder", folder.as_str().to_string()) - .bind("read", read.unwrap_or_default()) - .run(limit, offset, db) - .await - } - - /// Read a message only if `user` is its sender or recipient and their - /// side hasn't been permanently deleted. - pub async fn read_for( - id: &MessageId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let message: Option = db.select(id.record()).await?; - Ok(message.filter(|message| { - (&message.sender == user || &message.recipient == user) - && message.folder_of(user) != Folder::Deleted - })) - } - - /// Flip the recipient's read flag. Field-scoped write: the sender may be - /// filing their side concurrently, and a whole-row save would clobber it. - pub async fn set_read(self, read: bool, db: &Database) -> Result { - let mut result = db - .query("UPDATE $id SET read = $read RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("read", read)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - - /// File `user`'s side into `folder` (already validated against that - /// side's allowed set), stamping where the copy came from so it can be - /// restored. Only the caller's two fields are written — field-scoped for - /// the same race reason as [`Message::set_read`]. - /// - /// Filing away remembers the folder being left, so `inbox → archive → - /// trash` restores to `archive` and that back to `inbox`. Two folders are - /// never stamped: the trash (`trash → archive` would leave the copy - /// pointing back at the discard pile — it falls back to the home folder) - /// and the target itself (a no-op move keeps the memory it had). Moving - /// back to a home folder clears it. - pub async fn move_to( - self, - user: &UserId, - folder: Folder, - db: &Database, - ) -> Result { - let current = self.folder_of(user); - let (field, origin_field) = if self.is_sender(user) { - ("sender_folder", "sender_origin") - } else { - ("recipient_folder", "recipient_origin") - }; - let origin = match folder { - _ if !folder.is_filed() => None, - _ if current == folder => self.origin_of(user), - _ if current.is_restore_target() => Some(current), - _ => None, - }; - let mut result = db - .query(format!( - "UPDATE $id SET {field} = $folder, {origin_field} = $origin RETURN AFTER" - )) - .bind(("id", self.id.record())) - .bind(("folder", folder.as_str().to_string())) - .bind(("origin", origin.map(|origin| origin.as_str().to_string()))) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - - /// Permanently drop `user`'s side — only if that side currently sits in - /// the trash; the gate rides in the `UPDATE`'s `WHERE` so a concurrent - /// move back to the inbox can't slip past a check-then-act window. The - /// row itself is removed once both sides are gone — judged on the - /// post-write row, so two concurrent deletes can't leak an all-deleted - /// row. - pub async fn delete_for(self, user: &UserId, db: &Database) -> Result<(), AppError> { - let (field, origin_field) = if self.is_sender(user) { - ("sender_folder", "sender_origin") - } else { - ("recipient_folder", "recipient_origin") - }; - let mut result = db - .query(format!( - "UPDATE $id SET {field} = $deleted, {origin_field} = NONE \ - WHERE {field} = $trash RETURN AFTER" - )) - .bind(("id", self.id.record())) - .bind(("deleted", Folder::Deleted.as_str().to_string())) - .bind(("trash", Folder::Trash.as_str().to_string())) - .await? - .check()?; - let Some(after) = result.take::>(0)?.into_iter().next() else { - return Err(AppError::Conflict( - "only messages in the trash can be permanently deleted", - )); - }; - if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted { - let _: Option = db.delete(after.id.record()).await?; - } - Ok(()) - } } #[cfg(test)] @@ -432,42 +255,6 @@ mod tests { assert_eq!(MessageBody::try_new("").unwrap().as_str(), ""); } - /// The `next_ulid` hazard: an inbox is documented newest-first and sorts - /// `id DESC`, so messages sent inside one millisecond must come back in - /// exact reverse write order, not at random (src/domain/monotonic_id.rs). - /// Asserts the *stored* order, not the mint order. - #[tokio::test] - async fn inbox_is_newest_first_within_a_millisecond() { - let db = crate::database::init_mem().await.unwrap(); - let sender = UserId::from_key("a"); - let recipient = UserId::from_key("b"); - let mut sent = Vec::new(); - for i in 0..25 { - let message = Message::send( - &sender, - &recipient, - MessageSubject::try_new(&format!("s{i}")).unwrap(), - MessageBody::try_new("").unwrap(), - None, - &db, - ) - .await - .unwrap(); - sent.push(message.get_id().key().to_string()); - } - - let (listed, total) = Message::list_folder(&recipient, Folder::Inbox, None, None, 0, &db) - .await - .unwrap(); - assert_eq!(total, 25); - sent.reverse(); - let read_back: Vec = listed - .iter() - .map(|row| row.get_id().key().to_string()) - .collect(); - assert_eq!(read_back, sent); - } - #[tokio::test] async fn folder_sides_resolve_by_membership() { let sender = UserId::from_key("a"); diff --git a/src/domain/parent_link.rs b/src/domain/parent_link.rs index 21bbdf7..df36ed4 100644 --- a/src/domain/parent_link.rs +++ b/src/domain/parent_link.rs @@ -1,9 +1,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::PARENT_LINK_TABLE; -use crate::database::Database; use crate::domain::user::UserId; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ParentLinkId(RecordId); @@ -39,10 +37,10 @@ impl ParentLinkId { /// is a parent's job and a small child cannot do it themselves. #[derive(Debug, Clone, SurrealValue)] pub struct ParentLink { - id: ParentLinkId, - parent: UserId, - student: UserId, - linked_by: UserId, + pub(crate) id: ParentLinkId, + pub(crate) parent: UserId, + pub(crate) student: UserId, + pub(crate) linked_by: UserId, } impl ParentLink { @@ -62,64 +60,6 @@ impl ParentLink { &self.linked_by } - /// Tie (idempotently) `student` to `parent`. One row per pair, keyed by the - /// deterministic composite id, so concurrent links converge on one row. The - /// caller validates the roles — this only stores the pair. - pub async fn link( - parent: &UserId, - student: &UserId, - linked_by: &UserId, - db: &Database, - ) -> Result { - let link = ParentLink { - id: ParentLinkId::composite(parent, student), - parent: parent.clone(), - student: student.clone(), - linked_by: linked_by.clone(), - }; - let saved: Option = db.upsert(link.id.record()).content(link).await?; - saved.ok_or_else(|| AppError::Internal("failed to link student to parent".into())) - } - - /// True iff `parent` holds a link to `student` — the observation gate. - pub async fn exists( - parent: &UserId, - student: &UserId, - db: &Database, - ) -> Result { - let found: Option = db - .select(ParentLinkId::composite(parent, student).record()) - .await?; - Ok(found.is_some()) - } - - /// Every student `parent` observes, newest link first. - pub async fn list_for_parent( - parent: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM parent_link WHERE parent = $parent ORDER BY id DESC") - .bind(("parent", parent.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - pub async fn remove( - parent: &UserId, - student: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("DELETE parent_link WHERE parent = $parent AND student = $student RETURN BEFORE") - .bind(("parent", parent.record())) - .bind(("student", student.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - // Both role-change sweeps (the observed student leaving `student`, the // observing parent leaving `parent`) live in // [`crate::service::user::set_role`]: they commit with the role write diff --git a/src/domain/registration.rs b/src/domain/registration.rs index 14dd932..4896976 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -1,12 +1,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE}; -use crate::database::Database; -use crate::db::cap; -use crate::domain::event::{Event, EventId}; -use crate::domain::role::Role; +use crate::constant::REGISTRATION_TABLE; +use crate::domain::event::EventId; use crate::domain::user::UserId; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct RegistrationId(RecordId); @@ -41,10 +37,10 @@ impl RegistrationId { /// away from the registration kind hides them without deleting them. #[derive(Debug, Clone, SurrealValue)] pub struct Registration { - id: RegistrationId, - event: EventId, - user: UserId, - registered_by: UserId, + pub(crate) id: RegistrationId, + pub(crate) event: EventId, + pub(crate) user: UserId, + pub(crate) registered_by: UserId, } impl Registration { @@ -64,139 +60,12 @@ impl Registration { &self.registered_by } - /// Register (idempotently) `user` onto `event`, refusing when a capacity - /// cap is set and every seat is taken. Someone already listed gets their - /// existing row back untouched — a true no-op that never counts against - /// the cap and never rewrites who placed them. The seat is taken by - /// [`cap::claim_live_and_create`] on the event row — an atomic single-record - /// conditional write that reads `audience.capacity` off that same row as it - /// decides, so neither a racing registration nor a concurrent PATCH - /// *lowering* the capacity can over-admit. Bound as a number instead, the - /// snapshot below would admit every request already in flight when the - /// lower cap landed. - /// - /// The seat is claimed on the event row, so the same statement says nothing - /// about the *user* it is for — and a fall to `parent` is the one demotion - /// whose sweep ([`crate::service::user::set_role`]) can miss a seat and - /// leave it unfreeable: `unregister` refuses a non-student target and a - /// parent cannot reach the route at all. So the transaction also claims the - /// holder's own record ([`cap::role_claim`]), which is the key that - /// demotion writes: either the sweep sees this seat, or this write sees the - /// parent and takes it back. - pub async fn register( - event: &EventId, - user: &UserId, - registered_by: &UserId, - db: &Database, - ) -> Result { - if let Some(existing) = Self::read_for_user(event, user, db).await? { - return Ok(existing); - } - // Read for its refusals only — the audience kind and the closing time. - // The seat count itself is re-read by the claim. - Event::read(event, db) - .await? - .ok_or(AppError::NotFound)? - .registration_capacity()?; - let registration = Registration { - id: RegistrationId::composite(event, user), - event: event.clone(), - user: user.clone(), - registered_by: registered_by.clone(), - }; - match cap::claim_live_and_create( - &event.record(), - REGISTRATION_COUNT_FIELD, - // An uncapped registration list stores no `capacity` key at all - // (SurrealDB drops a `NONE`-valued object key), so the coalesce is - // what "unlimited" reads as. - "audience.capacity ?? $num", - cap::UNLIMITED, - // Staff hold their own seats, so the bar is not "still a student" - // but "still someone who can be taken off the list". - Some((&user.record(), &format!("= '{}'", Role::Parent.as_str()))), - (®istration.id.record(), ®istration), - db, - ) - .await? - { - cap::Claimed::Made(created) => Ok(created), - // A concurrent placement of the same pair got there first: hand its - // row over, the same no-op the early return above would have made, - // and with no seat spent either way. - cap::Claimed::Duplicate => Self::read_for_user(event, user, db) - .await? - .ok_or_else(|| AppError::Internal("failed to register user".into())), - // Full, the event was deleted between the read and the claim, or - // the holder fell to parent while this ran — the conditional writes - // match nothing (or throw) either way, and only this path pays for - // the reads that tell them apart. - cap::Claimed::Full => match Event::read(event, db).await? { - None => Err(AppError::NotFound), - Some(_) => match crate::db::user::read(db, user).await? { - Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden( - "that account was demoted to parent while this request ran — \ - only students can be registered for", - )), - _ => Err(AppError::Conflict("the event is full")), - }, - }, - } - } - - /// Some(_) iff `user` holds a seat on `event` — the audience point check. - pub async fn read_for_user( - event: &EventId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM registration WHERE event = $ev AND user = $usr LIMIT 1") - .bind(("ev", event.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - pub async fn list_for_event( - event: &EventId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM registration WHERE event = $ev ORDER BY id DESC") - .bind(("ev", event.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - pub async fn remove( - event: &EventId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - // The seat comes back in the same transaction as the row that held it. - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $gone = (DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE); - UPDATE $ev SET registration_count = math::max([(registration_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - ) - .bind(("ev", event.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(3)?.into_iter().next()) - } - // The demotion sweep — freeing every seat a fall to `parent` would strand, // and leaving a list that has already frozen exactly as it stands — is an // arm of [`crate::service::user::set_role`], so the seat comes back in // the same transaction as the role that invalidated it. The freeze it obeys - // is [`Event::registration_capacity`]'s `Conflict` arm, re-spelled for - // SurrealQL as [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it - // by `event::tests::the_sql_freeze_guard_matches_the_rust_one`. + // is [`crate::domain::event::Event::registration_capacity`]'s `Conflict` + // arm, re-spelled for SurrealQL as + // [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it by + // `event::tests::the_sql_freeze_guard_matches_the_rust_one`. } diff --git a/src/service/message.rs b/src/service/message.rs new file mode 100644 index 0000000..0c15040 --- /dev/null +++ b/src/service/message.rs @@ -0,0 +1,69 @@ +//! Message workflows. Every persistence step here is a single atomic +//! record write ([`crate::db::message`]) whose rule rides in its own +//! `WHERE` clause, so there is no multi-call lock to hold and no policy of +//! its own — the handler validates the DTO, gates on the row it just read, +//! and sequences these calls. They live in the service so the web layer +//! never names the db layer. + +use crate::database::Database; +use crate::db::message; +use crate::domain::message::{ + Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject, +}; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn send( + db: &Database, + sender: &UserId, + recipient: &UserId, + subject: MessageSubject, + body: MessageBody, + label: Option, +) -> Result { + message::send(db, sender, recipient, subject, body, label).await +} + +pub async fn list_folder( + db: &Database, + user: &UserId, + folder: Folder, + read: Option, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + message::list_folder(db, user, folder, read, limit, offset).await +} + +pub async fn read_for( + db: &Database, + id: &MessageId, + user: &UserId, +) -> Result, AppError> { + message::read_for(db, id, user).await +} + +pub async fn set_read( + db: &Database, + message_row: Message, + read: bool, +) -> Result { + message::set_read(db, message_row, read).await +} + +pub async fn move_to( + db: &Database, + message_row: Message, + user: &UserId, + folder: Folder, +) -> Result { + message::move_to(db, message_row, user, folder).await +} + +pub async fn delete_for( + db: &Database, + message_row: Message, + user: &UserId, +) -> Result<(), AppError> { + message::delete_for(db, message_row, user).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 691aa94..ccb48dd 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -11,8 +11,11 @@ pub mod exam; pub mod exam_attempt; pub mod exam_question; pub mod meal_booking; +pub mod message; pub mod note; +pub mod parent_link; pub mod payment_ledger; +pub mod registration; pub mod session; pub mod settings; pub mod user; diff --git a/src/service/parent_link.rs b/src/service/parent_link.rs new file mode 100644 index 0000000..399ddf4 --- /dev/null +++ b/src/service/parent_link.rs @@ -0,0 +1,107 @@ +//! Parent-link decisions: who may be tied to whom (the admin's `link`), +//! and what a link grants. A link row alone is never the grant — every +//! parent-side permission re-derives it against the student's *live* role +//! through [`links_live`], because the demotion sweeps in +//! [`crate::service::user::set_role`] run once over the rows that exist at +//! that moment and a sweep can lose a race with `link`. The row-storage +//! itself is [`crate::db::parent_link`]. + +use crate::database::Database; +use crate::db::parent_link; +use crate::domain::parent_link::ParentLink; +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ValidationError}; + +/// Tie (idempotently) `student` to `parent`. The gate is the school-office +/// rule: `{id}` must hold the `parent` role and `user_id` the `student` +/// role. A stale-link race cannot start here — a target demoted between +/// this check and the upsert fails the role gate again on the next call, +/// and the sweeps treat the fresh row like any other. +/// +/// Returns the tie plus the two accounts it was judged on, so the caller +/// can render the response without re-reading either. +pub async fn link( + db: &Database, + parent: &UserId, + student: &UserId, + linked_by: &UserId, +) -> Result<(ParentLink, User, User), AppError> { + let parent = crate::service::user::read(db, parent) + .await? + .ok_or(AppError::NotFound)?; + if parent.get_role() != Role::Parent { + return Err(AppError::Validation(ValidationError::Invalid { + field: "id", + reason: "students can only be tied to a parent account", + })); + } + let Some(student) = crate::service::user::read(db, student).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + }; + if student.get_role() != Role::Student { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can be tied to a parent", + })); + } + let link = parent_link::link(db, parent.get_id(), student.get_id(), linked_by).await?; + Ok((link, parent, student)) +} + +/// True iff `parent` holds a *live* link to `student`: the row exists AND +/// the student side still holds the student role. The link row alone is +/// not the grant — like a stale enrollment, a link whose student side +/// changed role must be inert, so the target's live role is re-read here. +/// A missing or non-student target reads as `false`, so a parent never +/// gets an existence oracle. +pub async fn links_live( + db: &Database, + parent: &UserId, + student: &UserId, +) -> Result { + Ok(parent_link::exists(db, parent, student).await? + && crate::service::user::read(db, student) + .await? + .is_some_and(|student| student.get_role() == Role::Student)) +} + +/// May `caller` read `target`'s per-student reports (marks, attendance, +/// pomodoro)? Teacher+ always may (per-endpoint narrowing is the caller's +/// business); a parent may exactly when a `parent_link` row ties them to the +/// target *and* the target still holds the student role. Everyone else — +/// students included — gets a 403 (self-reads go through the `/me` endpoints). +pub async fn ensure_can_observe( + caller: &User, + target: &UserId, + db: &Database, +) -> Result<(), AppError> { + if caller.get_role().at_least(Role::Teacher) { + return Ok(()); + } + if caller.get_role() == Role::Parent && links_live(db, caller.get_id(), target).await? { + return Ok(()); + } + Err(AppError::Forbidden( + "requires teacher role or higher, or a parent link to this student", + )) +} + +/// Every student `parent` observes, newest link first. Rows, not a live +/// filter — callers re-derive each student's live role themselves when the +/// grant matters (the inert-row filter lives with each reader). +pub async fn list_for_parent(db: &Database, parent: &UserId) -> Result, AppError> { + parent_link::list_for_parent(db, parent).await +} + +/// Untie a student from a parent — `Some` iff a tie existed. +pub async fn remove( + db: &Database, + parent: &UserId, + student: &UserId, +) -> Result, AppError> { + parent_link::remove(db, parent, student).await +} diff --git a/src/service/registration.rs b/src/service/registration.rs new file mode 100644 index 0000000..9550723 --- /dev/null +++ b/src/service/registration.rs @@ -0,0 +1,103 @@ +//! The registration workflow: taking a seat on a registration-audience +//! event. The reads and the seat-returning delete are +//! [`crate::db::registration`]; the seat itself is [`cap`]'s +//! claim-on-the-event-row. + +use crate::constant::REGISTRATION_COUNT_FIELD; +use crate::database::Database; +use crate::db::cap; +use crate::db::registration; +use crate::domain::event::{Event, EventId}; +use crate::domain::registration::{Registration, RegistrationId}; +use crate::domain::role::Role; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Register (idempotently) `user` onto `event`, refusing when a capacity +/// cap is set and every seat is taken. Someone already listed gets their +/// existing row back untouched — a true no-op that never counts against +/// the cap and never rewrites who placed them. The seat is taken by +/// [`cap::claim_live_and_create`] on the event row — an atomic single-record +/// conditional write that reads `audience.capacity` off that same row as it +/// decides, so neither a racing registration nor a concurrent PATCH +/// *lowering* the capacity can over-admit. Bound as a number instead, the +/// snapshot below would admit every request already in flight when the +/// lower cap landed. +/// +/// The seat is claimed on the event row, so the same statement says nothing +/// about the *user* it is for — and a fall to `parent` is the one demotion +/// whose sweep ([`crate::service::user::set_role`]) can miss a seat and +/// leave it unfreeable: `unregister` refuses a non-student target and a +/// parent cannot reach the route at all. So the transaction also claims the +/// holder's own record ([`cap::role_claim`]), which is the key that +/// demotion writes: either the sweep sees this seat, or this write sees the +/// parent and takes it back. +pub async fn register( + db: &Database, + event: &EventId, + user: &UserId, + registered_by: &UserId, +) -> Result { + if let Some(existing) = registration::read_for_user(db, event, user).await? { + return Ok(existing); + } + // Read for its refusals only — the audience kind and the closing time. + // The seat count itself is re-read by the claim. + Event::read(event, db) + .await? + .ok_or(AppError::NotFound)? + .registration_capacity()?; + let registration_row = Registration { + id: RegistrationId::composite(event, user), + event: event.clone(), + user: user.clone(), + registered_by: registered_by.clone(), + }; + match cap::claim_live_and_create( + &event.record(), + REGISTRATION_COUNT_FIELD, + // An uncapped registration list stores no `capacity` key at all + // (SurrealDB drops a `NONE`-valued object key), so the coalesce is + // what "unlimited" reads as. + "audience.capacity ?? $num", + cap::UNLIMITED, + // Staff hold their own seats, so the bar is not "still a student" + // but "still someone who can be taken off the list". + Some((&user.record(), &format!("= '{}'", Role::Parent.as_str()))), + (®istration_row.id.record(), ®istration_row), + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + // A concurrent placement of the same pair got there first: hand its + // row over, the same no-op the early return above would have made, + // and with no seat spent either way. + cap::Claimed::Duplicate => registration::read_for_user(db, event, user) + .await? + .ok_or_else(|| AppError::Internal("failed to register user".into())), + // Full, the event was deleted between the read and the claim, or + // the holder fell to parent while this ran — the conditional writes + // match nothing (or throw) either way, and only this path pays for + // the reads that tell them apart. + cap::Claimed::Full => match Event::read(event, db).await? { + None => Err(AppError::NotFound), + Some(_) => match crate::db::user::read(db, user).await? { + Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden( + "that account was demoted to parent while this request ran — \ + only students can be registered for", + )), + _ => Err(AppError::Conflict("the event is full")), + }, + }, + } +} + +/// Take a user off the list; `Some` iff they held a seat. +pub async fn remove( + db: &Database, + event: &EventId, + user: &UserId, +) -> Result, AppError> { + registration::remove(db, event, user).await +} diff --git a/src/web/attendance.rs b/src/web/attendance.rs index 90a6fb5..b11b9ab 100644 --- a/src/web/attendance.rs +++ b/src/web/attendance.rs @@ -15,10 +15,11 @@ use crate::domain::role::Role; use crate::domain::session_attendance::SessionAttendance; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; +use crate::service::parent_link::ensure_can_observe; use crate::state::AppState; use super::courses::can_manage_course; -use super::{CourseResponse, CurrentUser, course_people, ensure_can_observe, person_map}; +use super::{CourseResponse, CurrentUser, course_people, person_map}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() diff --git a/src/web/classes.rs b/src/web/classes.rs index 31a01cb..dc88ebd 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -26,13 +26,14 @@ use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service::class_blueprint; +use crate::service::parent_link::ensure_can_observe; use crate::state::AppState; use super::courses::can_manage_course; use super::terms::resolve_term; use super::{ - CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, ensure_can_observe, - person_map, set_or_clear, undo_if_demoted, + CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map, + set_or_clear, undo_if_demoted, }; pub fn routes() -> OpenApiRouter { diff --git a/src/web/events.rs b/src/web/events.rs index 68c82cd..39ee473 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -14,7 +14,6 @@ use crate::domain::attendance::{Attendance, AttendanceStatus}; use crate::domain::class_group::{ClassGroup, ClassGroupId}; use crate::domain::course::CourseId; use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; -use crate::domain::registration::Registration; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; @@ -752,7 +751,7 @@ async fn register( .await? .ok_or(AppError::NotFound)?; // Fast-fail gate; the authoritative re-check runs inside - // `Registration::register` under its lock. + // `service::registration::register` under its lock. event.registration_capacity()?; let target = match req.user_id { @@ -772,7 +771,8 @@ async fn register( )); } - let registration = Registration::register(&event_id, &target, user.get_id(), &st.db).await?; + let registration = + crate::service::registration::register(&st.db, &event_id, &target, user.get_id()).await?; // Resolve from the row, not the request: a re-register returns the // existing seat, whose registered_by is the *original* placer — someone // the {target, caller} pair may not contain. @@ -832,7 +832,7 @@ async fn unregister( // staff member's seat is theirs alone. The bar is *staff*, not "a student": // a parent holds no seat any route can reach — they cannot get past // `RequireTeacher` to free their own — so a seat under that role is - // stranded, and a volume written before `Registration::register` claimed + // stranded, and a volume written before `service::registration::register` claimed // the holder's row already carries some. if &target != user.get_id() && let Some(target_user) = crate::service::user::read(&st.db, &target).await? @@ -843,7 +843,7 @@ async fn unregister( )); } - if Registration::remove(&event_id, &target, &st.db) + if crate::service::registration::remove(&st.db, &event_id, &target) .await? .is_none() { @@ -868,7 +868,10 @@ mod tests { let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) .await .unwrap(); - crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 + crate::service::user::set_role(db, user.get_id(), role) + .await + .unwrap() + .0 } /// `can_manage` is only reached behind `RequireTeacher` today, so this is diff --git a/src/web/homework.rs b/src/web/homework.rs index cc5f4b3..325e61a 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -34,6 +34,7 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service; +use crate::service::parent_link::ensure_can_observe; use crate::state::AppState; use super::courses::{can_manage_course, can_view_course, visible_courses}; @@ -41,7 +42,7 @@ use super::notes::content_disposition; use super::subjects::subject_in_course; use super::{ CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, - check_not_past, ensure_can_observe, paginate, read_upload, remove_blob, set_or_clear, + check_not_past, paginate, read_upload, remove_blob, set_or_clear, }; /// Serializes the homework subsystem's cross-record check-then-writes, which diff --git a/src/web/marks.rs b/src/web/marks.rs index 901bdf4..4e8e67a 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -16,10 +16,11 @@ use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; use crate::service; +use crate::service::parent_link::ensure_can_observe; use crate::state::AppState; use super::courses::can_manage_course; -use super::{CourseResponse, CurrentUser, course_people, ensure_can_observe, person_map}; +use super::{CourseResponse, CurrentUser, course_people, person_map}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() diff --git a/src/web/meals.rs b/src/web/meals.rs index 08398d9..70fd059 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -28,7 +28,6 @@ use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot, validate_ use crate::domain::menu_dish::{ DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, }; -use crate::domain::parent_link::ParentLink; // The same idempotence key `/payments/credits` takes — one grammar, one type. use crate::domain::payment_ledger::PaymentRequestKey; use crate::domain::role::Role; @@ -802,11 +801,7 @@ async fn booking_target( reason: "a parent must name the student the seat is for", }, ))?); - if ParentLink::exists(caller.get_id(), &target, db).await? - && crate::service::user::read(db, &target) - .await? - .is_some_and(|target| target.get_role() == Role::Student) - { + if crate::service::parent_link::links_live(db, caller.get_id(), &target).await? { return Ok(target); } Err(AppError::Forbidden( @@ -903,7 +898,7 @@ async fn my_bookings( let mut students = vec![user.get_id().clone()]; if user.get_role() == Role::Parent { students.extend( - ParentLink::list_for_parent(user.get_id(), &st.db) + crate::service::parent_link::list_for_parent(&st.db, user.get_id()) .await? .iter() .map(|link| link.get_student().clone()), @@ -1146,7 +1141,10 @@ async fn mark_attendance( let student = UserId::from_key(&req.student_id); // The target must exist; no booking is required, since a walk-in was still // served and the record is operationally true. - if crate::service::user::read(&st.db, &student).await?.is_none() { + if crate::service::user::read(&st.db, &student) + .await? + .is_none() + { return Err(AppError::Validation(ValidationError::Invalid { field: "student_id", reason: "target user does not exist", @@ -1318,7 +1316,8 @@ async fn balance_response( /// Reading someone else's meal record — money, attendance, dietary profile: /// teacher+, or a parent linked to the student. Reading your *own* is always /// allowed, since every `{user}` route here accepts the caller's own id; that -/// is the one way this gate differs from [`super::ensure_can_observe`], which +/// is the one way this gate differs from +/// [`crate::service::parent_link::ensure_can_observe`], which /// 403s a self-read because its subjects have their own `/me` routes. async fn ensure_can_read_student( caller: &User, @@ -1328,7 +1327,7 @@ async fn ensure_can_read_student( if caller.get_id() == target { return Ok(()); } - super::ensure_can_observe(caller, target, db).await + crate::service::parent_link::ensure_can_observe(caller, target, db).await } /// May `caller` read `target`'s meal *money* — balance and ledger? Own always; @@ -1351,10 +1350,7 @@ async fn ensure_can_read_money( // role must be inert, so the target's live role is re-read. A missing or // non-student target falls through to the same 403 — a parent never gets an if caller.get_role() == Role::Parent - && ParentLink::exists(caller.get_id(), target, db).await? - && crate::service::user::read(db, target) - .await? - .is_some_and(|target| target.get_role() == Role::Student) + && crate::service::parent_link::links_live(db, caller.get_id(), target).await? { return Ok(()); } diff --git a/src/web/messages.rs b/src/web/messages.rs index e5647d6..10a6bfb 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -15,6 +15,7 @@ use crate::domain::message::{ }; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service::message; use crate::state::AppState; use super::dto::Role; @@ -206,13 +207,13 @@ async fn send_message( )); } - let message = Message::send( + let message = message::send( + &st.db, user.get_id(), recipient.get_id(), subject, body, label, - &st.db, ) .await?; let people = people_of([&user, &recipient]); @@ -250,7 +251,7 @@ async fn list( }; let (messages, total) = - Message::list_folder(user.get_id(), folder, filter.read, limit, offset, &st.db).await?; + message::list_folder(&st.db, user.get_id(), folder, filter.read, limit, offset).await?; let people = load_people(&messages, &st.db).await?; let items = messages .iter() @@ -288,7 +289,7 @@ async fn update_message( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let mut message = Message::read_for(&MessageId::from_key(&id), user.get_id(), &st.db) + let mut message = message::read_for(&st.db, &MessageId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; @@ -313,10 +314,10 @@ async fn update_message( None => None, }; if let Some(read) = req.read { - message = message.set_read(read, &st.db).await?; + message = message::set_read(&st.db, message, read).await?; } if let Some(folder) = folder { - message = message.move_to(user.get_id(), folder, &st.db).await?; + message = message::move_to(&st.db, message, user.get_id(), folder).await?; } let people = load_people(std::slice::from_ref(&message), &st.db).await?; @@ -344,9 +345,9 @@ async fn delete_message( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result { - let message = Message::read_for(&MessageId::from_key(&id), user.get_id(), &st.db) + let message = message::read_for(&st.db, &MessageId::from_key(&id), user.get_id()) .await? .ok_or(AppError::NotFound)?; - message.delete_for(user.get_id(), &st.db).await?; + message::delete_for(&st.db, message, user.get_id()).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/mod.rs b/src/web/mod.rs index eaa93cc..ab98370 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -72,43 +72,11 @@ use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS}; use crate::database::Database; use crate::domain::exam_question::{Choice, ChoiceInput}; use crate::domain::note_file::FileContentType; -use crate::domain::parent_link::ParentLink; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; -use crate::domain::user::{User, UserId}; +use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// May `caller` read `target`'s per-student reports (marks, attendance, -/// pomodoro)? Teacher+ always may (per-endpoint narrowing is the caller's -/// business); a parent may exactly when a `parent_link` row ties them to the -/// target *and* the target still holds the student role. Everyone else — -/// students included — gets a 403 (self-reads go through the `/me` endpoints). -pub(crate) async fn ensure_can_observe( - caller: &User, - target: &UserId, - db: &Database, -) -> Result<(), AppError> { - if caller.get_role().at_least(Role::Teacher) { - return Ok(()); - } - // The link row alone is not the grant: like stale enrollments, a link - // whose student side changed role (a sweep lost a race with link_student) - // must be inert, so the target's live role is re-read here. Missing or - // non-student targets fall through to the same 403 — a parent never gets - // an existence oracle. - if caller.get_role() == Role::Parent - && ParentLink::exists(caller.get_id(), target, db).await? - && crate::service::user::read(db, target) - .await? - .is_some_and(|target| target.get_role() == Role::Student) - { - return Ok(()); - } - Err(AppError::Forbidden( - "requires teacher role or higher, or a parent link to this student", - )) -} - /// Close the window between "this account is teacher+" and the write that /// records a teacher-only assignment (a class's homeroom teacher, a course's /// teacher list). Call it *after* the write, with the account it named. diff --git a/src/web/payments.rs b/src/web/payments.rs index 5f0f13a..4ae491d 100644 --- a/src/web/payments.rs +++ b/src/web/payments.rs @@ -3,7 +3,8 @@ //! //! Every write here is manager+ — money is school administration, and a teacher //! has no business in it. The read gate is deliberately *narrower* than the -//! per-student reports elsewhere ([`super::ensure_can_observe`]): a student sees +//! per-student reports elsewhere +//! ([`crate::service::parent_link::ensure_can_observe`]): a student sees //! their own record, a parent a linked student's, manager+ everyone's, and a //! teacher nothing at all. //! @@ -26,7 +27,6 @@ use crate::constant::{MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES}; use crate::database::Database; use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment}; use crate::domain::fee_plan_assignment::FeePlanAssignment; -use crate::domain::parent_link::ParentLink; use crate::domain::payment_ledger::{ LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind, PaymentRequestKey, @@ -775,7 +775,8 @@ async fn record_reversal( /// May `caller` read `target`'s payment record? Own always; a parent only for a /// student they hold a live link to; manager+ for anyone. /// -/// Deliberately narrower than [`super::ensure_can_observe`]: **a teacher sees no +/// Deliberately narrower than +/// [`crate::service::parent_link::ensure_can_observe`]: **a teacher sees no /// money**. What a family owes the school is not classroom information. async fn ensure_can_read_payments( caller: &User, @@ -790,10 +791,7 @@ async fn ensure_can_read_payments( // non-student target falls through to the same 403 — a parent never gets an // existence oracle. if caller.get_role() == Role::Parent - && ParentLink::exists(caller.get_id(), target, db).await? - && crate::service::user::read(db, target) - .await? - .is_some_and(|target| target.get_role() == Role::Student) + && crate::service::parent_link::links_live(db, caller.get_id(), target).await? { return Ok(()); } diff --git a/src/web/pomodoro.rs b/src/web/pomodoro.rs index 377a67e..b733fab 100644 --- a/src/web/pomodoro.rs +++ b/src/web/pomodoro.rs @@ -11,9 +11,10 @@ use crate::domain::pomodoro::PomodoroSession; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; +use crate::service::parent_link::ensure_can_observe; use crate::state::AppState; -use super::{CurrentUser, PageParams, ensure_can_observe, paginate}; +use super::{CurrentUser, PageParams, paginate}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() diff --git a/src/web/users.rs b/src/web/users.rs index aaab134..673b54b 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -17,20 +17,20 @@ use crate::domain::badge::{self, BadgeAward}; use crate::domain::class_group::{ClassGroup, ClassGroupId}; use crate::domain::class_member::ClassMember; -use crate::domain::parent_link::ParentLink; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats}; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service::parent_link::ensure_can_observe; use crate::state::AppState; use super::courses::visible_courses; use super::dto::AssignableRole; use super::dto::Role as RoleSchema; use super::{ - CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse, - ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob, store_blob, + CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse, paginate, + read_image_upload, remove_blob, serve_inline_blob, store_blob, }; pub fn routes() -> OpenApiRouter { @@ -174,14 +174,9 @@ async fn apply_preferences( let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?; let language = merge_field(req.language.as_deref(), Language::try_from_str)?; let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?; - let updated = crate::service::user::set_preferences( - db, - user.get_id(), - theme, - language, - palette_color, - ) - .await?; + let updated = + crate::service::user::set_preferences(db, user.get_id(), theme, language, palette_color) + .await?; Ok(UserResponse::new(&updated)) } @@ -541,7 +536,7 @@ async fn students_page( db: &Database, ) -> Result, AppError> { let (limit, offset) = page.resolve()?; - let links = ParentLink::list_for_parent(parent, db).await?; + let links = crate::service::parent_link::list_for_parent(db, parent).await?; let ids: Vec = links .iter() .map(|link| link.get_student().clone()) @@ -593,30 +588,13 @@ async fn link_student( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let parent = crate::service::user::read(&st.db, &UserId::from_key(&id)) - .await? - .ok_or(AppError::NotFound)?; - if parent.get_role() != Role::Parent { - return Err(AppError::Validation(ValidationError::Invalid { - field: "id", - reason: "students can only be tied to a parent account", - })); - } - let Some(student) = - crate::service::user::read(&st.db, &UserId::from_key(&req.user_id)).await? - else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "target user does not exist", - })); - }; - if student.get_role() != Role::Student { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "only students can be tied to a parent", - })); - } - let link = ParentLink::link(parent.get_id(), student.get_id(), admin.get_id(), &st.db).await?; + let (link, parent, student) = crate::service::parent_link::link( + &st.db, + &UserId::from_key(&id), + &UserId::from_key(&req.user_id), + admin.get_id(), + ) + .await?; let people = PersonRef::map_of(&[&parent, &student, &admin]); Ok(Json(ParentLinkResponse { parent: PersonRef::resolve(&people, link.get_parent()), @@ -678,9 +656,13 @@ async fn unlink_student( _admin: RequireAdmin, Path((id, student)): Path<(String, String)>, ) -> Result { - if ParentLink::remove(&UserId::from_key(&id), &UserId::from_key(&student), &st.db) - .await? - .is_none() + if crate::service::parent_link::remove( + &st.db, + &UserId::from_key(&id), + &UserId::from_key(&student), + ) + .await? + .is_none() { return Err(AppError::NotFound); } @@ -1070,7 +1052,9 @@ async fn ensure_may_read_profile( async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result { let target = UserId::from_key(id); ensure_may_read_profile(caller, &target, &st.db).await?; - crate::service::user::read(&st.db, &target).await?.ok_or(AppError::NotFound) + crate::service::user::read(&st.db, &target) + .await? + .ok_or(AppError::NotFound) } /// The caller's own public profile — what everyone else sees of them. @@ -1165,7 +1149,15 @@ async fn upload_my_avatar( let file = ulid::Ulid::new().to_string(); store_blob(&st, &file, &upload.data, || async { - match crate::service::user::set_avatar(&st.db, user.get_id(), &file, &upload.content_type, size).await? { + match crate::service::user::set_avatar( + &st.db, + user.get_id(), + &file, + &upload.content_type, + size, + ) + .await? + { // Row written; the picture this one replaced comes off disk. Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))), // The account went away mid-upload — the fresh blob is an orphan. diff --git a/tests/regress_role_sweep.rs b/tests/regress_role_sweep.rs index d467e37..c71649e 100644 --- a/tests/regress_role_sweep.rs +++ b/tests/regress_role_sweep.rs @@ -26,10 +26,10 @@ use hezarfen_backend::domain::class_group::{ClassGroup, ClassGroupId, ClassName} use hezarfen_backend::domain::class_member::ClassMember; use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::event::EventId; -use hezarfen_backend::domain::registration::Registration; use hezarfen_backend::domain::role::Role; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; +use hezarfen_backend::service::registration; use serde_json::json; /// How many rows `sql` selects ids for. @@ -165,7 +165,7 @@ async fn a_seat_is_refused_once_the_holder_is_a_parent() { let event = a_registration_event(&app, &teacher, 1).await; demote(&student, Role::Parent, &db).await; - let refused = Registration::register(&event, &student, &UserId::from_key("staff"), &db).await; + let refused = registration::register(&db, &event, &student, &UserId::from_key("staff")).await; assert!( refused.is_err(), "a parent may not be given a seat: {refused:?}" @@ -190,7 +190,7 @@ async fn a_seat_never_survives_the_demotion_it_raced() { let event = a_registration_event(&app, &teacher, 1).await; // The bait: a seat the sweep will delete, which is what holds it open. let earlier = a_registration_event(&app, &teacher, 1).await; - Registration::register(&earlier, &student, &UserId::from_key("staff"), &db) + registration::register(&db, &earlier, &student, &UserId::from_key("staff")) .await .unwrap(); hold_the_sweep("registration", &db).await; @@ -198,7 +198,7 @@ async fn a_seat_never_survives_the_demotion_it_raced() { // The seat is written inside the held window: past the sweep's snapshot, // before the commit. let demoting = demote_in_the_window(&student, Role::Parent, &db).await; - let seat = Registration::register(&event, &student, &UserId::from_key("staff"), &db).await; + let seat = registration::register(&db, &event, &student, &UserId::from_key("staff")).await; still_running(&demoting); demoting.await.unwrap(); @@ -226,7 +226,7 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() { let (app, db) = app_and_db().await; let (teacher, student) = a_school(&app, &db).await; let event = a_registration_event(&app, &teacher, 1).await; - Registration::register(&event, &student, &UserId::from_key("staff"), &db) + registration::register(&db, &event, &student, &UserId::from_key("staff")) .await .unwrap(); // The state the old race left: the seat stands, the account is a parent,