forge
Explore
Log in

Don't you dare go Hollow

Split message/parent_link/registration into domain/db/service layers

Browse files at this commit

f820c368f6c2bfc9b01b1d9f0f040645edf06fa0Ahmet Kaan GümüşParent: 387eb31
  • chore
    • split message/parent_link/registration into domain/db/service layers
Show full message
🧹 chore: split message/parent_link/registration into domain/db/service layers
src/db/meal_booking.rsmodified+1 -1
@@ -46,7 +46,7 @@ pub async fn list_for_menu(
46 /// parent whose link was revoked (by an unlink or by the student-side role46 /// parent whose link was revoked (by an unlink or by the student-side role
47 /// sweep) would otherwise keep a live view of the child's seat, watching47 /// sweep) would otherwise keep a live view of the child's seat, watching
48 /// cancellations made long after the link died — exactly what48 /// cancellations made long after the link died — exactly what
49-/// [`ensure_can_observe`](crate::web::ensure_can_observe) refuses. The49+/// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The
50 /// caller re-derives the list from the links on every read, so the view50 /// caller re-derives the list from the links on every read, so the view
51 /// dies with the link.51 /// dies with the link.
52 pub async fn list_for_students(52 pub async fn list_for_students(
src/db/message.rsadded+230 -0
@@ -0,0 +1,230 @@
1+//! The `message` table: the send-side create, the folder listings, the
2+//! party-scoped read, and the field-scoped writes each party makes to its own
3+//! copy. The folder arithmetic on a row's values lives in
4+//! [`crate::domain::message`].
5+
6+use crate::database::Database;
7+use crate::db::page::PagedList;
8+use crate::domain::message::{
9+ Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject,
10+};
11+use crate::domain::timestamp::Timestamp;
12+use crate::domain::user::UserId;
13+use crate::error::AppError;
14+
15+pub async fn send(
16+ db: &Database,
17+ sender: &UserId,
18+ recipient: &UserId,
19+ subject: MessageSubject,
20+ body: MessageBody,
21+ label: Option<MessageLabel>,
22+) -> Result<Message, AppError> {
23+ let message = Message {
24+ id: MessageId::generate(),
25+ sender: sender.clone(),
26+ recipient: recipient.clone(),
27+ subject,
28+ body,
29+ label,
30+ sent_at: Timestamp::now(),
31+ read: false,
32+ sender_folder: Folder::Sent,
33+ recipient_folder: Folder::Inbox,
34+ sender_origin: None,
35+ recipient_origin: None,
36+ };
37+ let created: Option<Message> = db.create(message.id.record()).content(message).await?;
38+ created.ok_or_else(|| AppError::Internal("failed to create message".into()))
39+}
40+
41+/// One folder view for `user`, newest first. `inbox` is recipient-side,
42+/// `sent` is sender-side, and `archive`/`trash` are each the union of both
43+/// sides' filed copies (either party may archive or trash their own copy).
44+/// `read` narrows to that flag state (`false` on the inbox is the unread
45+/// view; on `sent`, receipts pending) — the folder condition is
46+/// parenthesized because `archive`'s and `trash`'s are ORs.
47+pub async fn list_folder(
48+ db: &Database,
49+ user: &UserId,
50+ folder: Folder,
51+ read: Option<bool>,
52+ limit: Option<i64>,
53+ offset: i64,
54+) -> Result<(Vec<Message>, i64), AppError> {
55+ let condition = match folder {
56+ Folder::Sent => "sender = $usr AND sender_folder = 'sent'",
57+ Folder::Archive => {
58+ "(recipient = $usr AND recipient_folder = 'archive') \
59+ OR (sender = $usr AND sender_folder = 'archive')"
60+ }
61+ Folder::Trash => {
62+ "(recipient = $usr AND recipient_folder = 'trash') \
63+ OR (sender = $usr AND sender_folder = 'trash')"
64+ }
65+ _ => "recipient = $usr AND recipient_folder = $folder",
66+ };
67+ let read_clause = if read.is_some() {
68+ " AND read = $read"
69+ } else {
70+ ""
71+ };
72+ PagedList::new(
73+ format!("message WHERE ({condition}){read_clause}"),
74+ "ORDER BY id DESC",
75+ )
76+ .bind("usr", user.record())
77+ .bind("folder", folder.as_str().to_string())
78+ .bind("read", read.unwrap_or_default())
79+ .run(limit, offset, db)
80+ .await
81+}
82+
83+/// Read a message only if `user` is its sender or recipient and their
84+/// side hasn't been permanently deleted.
85+pub async fn read_for(
86+ db: &Database,
87+ id: &MessageId,
88+ user: &UserId,
89+) -> Result<Option<Message>, AppError> {
90+ let message: Option<Message> = db.select(id.record()).await?;
91+ Ok(message.filter(|message| {
92+ (&message.sender == user || &message.recipient == user)
93+ && message.folder_of(user) != Folder::Deleted
94+ }))
95+}
96+
97+/// Flip the recipient's read flag. Field-scoped write: the sender may be
98+/// filing their side concurrently, and a whole-row save would clobber it.
99+pub async fn set_read(db: &Database, message: Message, read: bool) -> Result<Message, AppError> {
100+ let mut result = db
101+ .query("UPDATE $id SET read = $read RETURN AFTER")
102+ .bind(("id", message.id.record()))
103+ .bind(("read", read))
104+ .await?
105+ .check()?;
106+ result
107+ .take::<Vec<Message>>(0)?
108+ .into_iter()
109+ .next()
110+ .ok_or(AppError::NotFound)
111+}
112+
113+/// File `user`'s side into `folder` (already validated against that
114+/// side's allowed set), stamping where the copy came from so it can be
115+/// restored. Only the caller's two fields are written — field-scoped for
116+/// the same race reason as [`set_read`].
117+///
118+/// Filing away remembers the folder being left, so `inbox → archive →
119+/// trash` restores to `archive` and that back to `inbox`. Two folders are
120+/// never stamped: the trash (`trash → archive` would leave the copy
121+/// pointing back at the discard pile — it falls back to the home folder)
122+/// and the target itself (a no-op move keeps the memory it had). Moving
123+/// back to a home folder clears it.
124+pub async fn move_to(
125+ db: &Database,
126+ message: Message,
127+ user: &UserId,
128+ folder: Folder,
129+) -> Result<Message, AppError> {
130+ let current = message.folder_of(user);
131+ let (field, origin_field) = if message.is_sender(user) {
132+ ("sender_folder", "sender_origin")
133+ } else {
134+ ("recipient_folder", "recipient_origin")
135+ };
136+ let origin = match folder {
137+ _ if !folder.is_filed() => None,
138+ _ if current == folder => message.origin_of(user),
139+ _ if current.is_restore_target() => Some(current),
140+ _ => None,
141+ };
142+ let mut result = db
143+ .query(format!(
144+ "UPDATE $id SET {field} = $folder, {origin_field} = $origin RETURN AFTER"
145+ ))
146+ .bind(("id", message.id.record()))
147+ .bind(("folder", folder.as_str().to_string()))
148+ .bind(("origin", origin.map(|origin| origin.as_str().to_string())))
149+ .await?
150+ .check()?;
151+ result
152+ .take::<Vec<Message>>(0)?
153+ .into_iter()
154+ .next()
155+ .ok_or(AppError::NotFound)
156+}
157+
158+/// Permanently drop `user`'s side — only if that side currently sits in
159+/// the trash; the gate rides in the `UPDATE`'s `WHERE` so a concurrent
160+/// move back to the inbox can't slip past a check-then-act window. The
161+/// row itself is removed once both sides are gone — judged on the
162+/// post-write row, so two concurrent deletes can't leak an all-deleted
163+/// row.
164+pub async fn delete_for(db: &Database, message: Message, user: &UserId) -> Result<(), AppError> {
165+ let (field, origin_field) = if message.is_sender(user) {
166+ ("sender_folder", "sender_origin")
167+ } else {
168+ ("recipient_folder", "recipient_origin")
169+ };
170+ let mut result = db
171+ .query(format!(
172+ "UPDATE $id SET {field} = $deleted, {origin_field} = NONE \
173+ WHERE {field} = $trash RETURN AFTER"
174+ ))
175+ .bind(("id", message.id.record()))
176+ .bind(("deleted", Folder::Deleted.as_str().to_string()))
177+ .bind(("trash", Folder::Trash.as_str().to_string()))
178+ .await?
179+ .check()?;
180+ let Some(after) = result.take::<Vec<Message>>(0)?.into_iter().next() else {
181+ return Err(AppError::Conflict(
182+ "only messages in the trash can be permanently deleted",
183+ ));
184+ };
185+ if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted {
186+ let _: Option<Message> = db.delete(after.id.record()).await?;
187+ }
188+ Ok(())
189+}
190+
191+#[cfg(test)]
192+mod tests {
193+ use super::*;
194+
195+ /// The `next_ulid` hazard: an inbox is documented newest-first and sorts
196+ /// `id DESC`, so messages sent inside one millisecond must come back in
197+ /// exact reverse write order, not at random (src/domain/monotonic_id.rs).
198+ /// Asserts the *stored* order, not the mint order.
199+ #[tokio::test]
200+ async fn inbox_is_newest_first_within_a_millisecond() {
201+ let db = crate::database::init_mem().await.unwrap();
202+ let sender = UserId::from_key("a");
203+ let recipient = UserId::from_key("b");
204+ let mut sent = Vec::new();
205+ for i in 0..25 {
206+ let message = send(
207+ &db,
208+ &sender,
209+ &recipient,
210+ MessageSubject::try_new(&format!("s{i}")).unwrap(),
211+ MessageBody::try_new("").unwrap(),
212+ None,
213+ )
214+ .await
215+ .unwrap();
216+ sent.push(message.get_id().key().to_string());
217+ }
218+
219+ let (listed, total) = list_folder(&db, &recipient, Folder::Inbox, None, None, 0)
220+ .await
221+ .unwrap();
222+ assert_eq!(total, 25);
223+ sent.reverse();
224+ let read_back: Vec<String> = listed
225+ .iter()
226+ .map(|row| row.get_id().key().to_string())
227+ .collect();
228+ assert_eq!(read_back, sent);
229+ }
230+}
src/db/mod.rsmodified+3 -0
@@ -12,9 +12,12 @@ pub mod exam_attempt;
12 pub mod exam_question;12 pub mod exam_question;
13 pub mod field_update;13 pub mod field_update;
14 pub mod meal_booking;14 pub mod meal_booking;
15+pub mod message;
15 pub mod note;16 pub mod note;
16 pub mod page;17 pub mod page;
18+pub mod parent_link;
17 pub mod payment_ledger;19 pub mod payment_ledger;
20+pub mod registration;
18 pub mod session;21 pub mod session;
19 pub mod settings;22 pub mod settings;
20 pub mod user;23 pub mod user;
src/db/parent_link.rsadded+59 -0
@@ -0,0 +1,59 @@
1+//! The `parent_link` table: the composite-id upsert, the existence probe,
2+//! the per-parent listing, and the delete. The *decisions* over these rows
3+//! — who may be tied, and which reads a live link grants — live in
4+//! [`crate::service::parent_link`].
5+
6+use crate::database::Database;
7+use crate::domain::parent_link::{ParentLink, ParentLinkId};
8+use crate::domain::user::UserId;
9+use crate::error::AppError;
10+
11+pub async fn link(
12+ db: &Database,
13+ parent: &UserId,
14+ student: &UserId,
15+ linked_by: &UserId,
16+) -> Result<ParentLink, AppError> {
17+ let link = ParentLink {
18+ id: ParentLinkId::composite(parent, student),
19+ parent: parent.clone(),
20+ student: student.clone(),
21+ linked_by: linked_by.clone(),
22+ };
23+ let saved: Option<ParentLink> = db.upsert(link.id.record()).content(link).await?;
24+ saved.ok_or_else(|| AppError::Internal("failed to link student to parent".into()))
25+}
26+
27+/// True iff a link row exists for the (parent, student) pair — the storage
28+/// half of the grant. The live half (the student side still holding the
29+/// role) is [`crate::service::parent_link::links_live`].
30+pub async fn exists(db: &Database, parent: &UserId, student: &UserId) -> Result<bool, AppError> {
31+ let found: Option<ParentLink> = db
32+ .select(ParentLinkId::composite(parent, student).record())
33+ .await?;
34+ Ok(found.is_some())
35+}
36+
37+/// Every student `parent` observes, newest link first.
38+pub async fn list_for_parent(db: &Database, parent: &UserId) -> Result<Vec<ParentLink>, AppError> {
39+ let mut result = db
40+ .query("SELECT * FROM parent_link WHERE parent = $parent ORDER BY id DESC")
41+ .bind(("parent", parent.record()))
42+ .await?
43+ .check()?;
44+ Ok(result.take::<Vec<ParentLink>>(0)?)
45+}
46+
47+pub async fn remove(
48+ db: &Database,
49+ parent: &UserId,
50+ student: &UserId,
51+) -> Result<Option<ParentLink>, AppError> {
52+ let mut result = db
53+ .query("DELETE parent_link WHERE parent = $parent AND student = $student RETURN BEFORE")
54+ .bind(("parent", parent.record()))
55+ .bind(("student", student.record()))
56+ .await?
57+ .check()?;
58+ Ok(result.take::<Vec<ParentLink>>(0)?.into_iter().next())
59+}
src/db/registration.rsadded+55 -0
@@ -0,0 +1,55 @@
1+//! The `registration` table: the seat reads, the per-event listing, and
2+//! the delete that returns the seat in the same transaction. The register
3+//! workflow itself (the cap claim and its conflict mapping) lives in
4+//! [`crate::service::registration`].
5+
6+use crate::database::Database;
7+use crate::domain::event::EventId;
8+use crate::domain::registration::Registration;
9+use crate::domain::user::UserId;
10+use crate::error::AppError;
11+
12+/// Some(_) iff `user` holds a seat on `event` — the audience point check.
13+pub async fn read_for_user(
14+ db: &Database,
15+ event: &EventId,
16+ user: &UserId,
17+) -> Result<Option<Registration>, AppError> {
18+ let mut result = db
19+ .query("SELECT * FROM registration WHERE event = $ev AND user = $usr LIMIT 1")
20+ .bind(("ev", event.record()))
21+ .bind(("usr", user.record()))
22+ .await?
23+ .check()?;
24+ Ok(result.take::<Vec<Registration>>(0)?.into_iter().next())
25+}
26+
27+pub async fn list_for_event(db: &Database, event: &EventId) -> Result<Vec<Registration>, AppError> {
28+ let mut result = db
29+ .query("SELECT * FROM registration WHERE event = $ev ORDER BY id DESC")
30+ .bind(("ev", event.record()))
31+ .await?
32+ .check()?;
33+ Ok(result.take::<Vec<Registration>>(0)?)
34+}
35+
36+pub async fn remove(
37+ db: &Database,
38+ event: &EventId,
39+ user: &UserId,
40+) -> Result<Option<Registration>, AppError> {
41+ // The seat comes back in the same transaction as the row that held it.
42+ let mut result = db
43+ .query(
44+ "BEGIN TRANSACTION;
45+ LET $gone = (DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE);
46+ UPDATE $ev SET registration_count = math::max([(registration_count ?? 0) - array::len($gone), 0]);
47+ RETURN $gone;
48+ COMMIT TRANSACTION;",
49+ )
50+ .bind(("ev", event.record()))
51+ .bind(("usr", user.record()))
52+ .await?
53+ .check()?;
54+ Ok(result.take::<Vec<Registration>>(3)?.into_iter().next())
55+}
src/domain/event.rsmodified+12 -9
@@ -9,7 +9,6 @@ use crate::domain::class_group::ClassGroupId;
9 use crate::domain::class_member::{ClassMember, ClassMemberId};9 use crate::domain::class_member::{ClassMember, ClassMemberId};
10 use crate::domain::course::CourseId;10 use crate::domain::course::CourseId;
11 use crate::domain::monotonic_id::next_ulid;11 use crate::domain::monotonic_id::next_ulid;
12-use crate::domain::registration::Registration;
13 use crate::domain::role::Role;12 use crate::domain::role::Role;
14 use crate::domain::timestamp::{Timestamp, range_error};13 use crate::domain::timestamp::{Timestamp, range_error};
15 use crate::domain::user::{User, UserId};14 use crate::domain::user::{User, UserId};
@@ -135,9 +134,11 @@ impl EventAudience {
135 Ok(member.is_some())134 Ok(member.is_some())
136 }135 }
137 EventAudience::Registration { .. } => {136 EventAudience::Registration { .. } => {
138- Ok(Registration::read_for_user(event, user.get_id(), db)137+ Ok(
139- .await?138+ crate::db::registration::read_for_user(db, event, user.get_id())
140- .is_some())139+ .await?
140+ .is_some(),
141+ )
141 }142 }
142 }143 }
143 }144 }
@@ -172,11 +173,13 @@ impl EventAudience {
172 .iter()173 .iter()
173 .map(|member| member.get_user().clone())174 .map(|member| member.get_user().clone())
174 .collect()),175 .collect()),
175- EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db)176+ EventAudience::Registration { .. } => {
176- .await?177+ Ok(crate::db::registration::list_for_event(db, event)
177- .iter()178+ .await?
178- .map(|registration| registration.get_user().clone())179+ .iter()
179- .collect()),180+ .map(|registration| registration.get_user().clone())
181+ .collect())
182+ }
180 }183 }
181 }184 }
182 }185 }
src/domain/message.rsmodified+18 -231
@@ -12,12 +12,10 @@ use crate::constant::{
12 MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, MESSAGE_TABLE,12 MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, MESSAGE_TABLE,
13 RECIPIENT_FOLDERS, SENDER_FOLDERS,13 RECIPIENT_FOLDERS, SENDER_FOLDERS,
14 };14 };
15-use crate::database::Database;
16 use crate::domain::monotonic_id::next_ulid;15 use crate::domain::monotonic_id::next_ulid;
17-use crate::db::page::PagedList;
18 use crate::domain::timestamp::Timestamp;16 use crate::domain::timestamp::Timestamp;
19 use crate::domain::user::UserId;17 use crate::domain::user::UserId;
20-use crate::error::{AppError, ValidationError};18+use crate::error::ValidationError;
21 use crate::validate::{validate_optional, validate_required};19 use crate::validate::{validate_optional, validate_required};
22 20
23 /// The mailbox folders a copy can sit in — the single source of folder names21 /// The mailbox folders a copy can sit in — the single source of folder names
@@ -36,7 +34,7 @@ pub enum Folder {
36 Archive,34 Archive,
37 Trash,35 Trash,
38 /// The hidden "my copy is gone" folder; never a valid move or list36 /// The hidden "my copy is gone" folder; never a valid move or list
39- /// target — reached only through [`Message::delete_for`].37+ /// target — reached only through [`crate::db::message::delete_for`].
40 Deleted,38 Deleted,
41 }39 }
42 40
@@ -86,14 +84,14 @@ impl Folder {
86 }84 }
87 85
88 /// A filed-away copy — one that has somewhere to be restored to.86 /// A filed-away copy — one that has somewhere to be restored to.
89- fn is_filed(self) -> bool {87+ pub(crate) fn is_filed(self) -> bool {
90 matches!(self, Folder::Archive | Folder::Trash)88 matches!(self, Folder::Archive | Folder::Trash)
91 }89 }
92 90
93 /// Whether this folder is worth remembering as a restore target. The91 /// Whether this folder is worth remembering as a restore target. The
94 /// trash is not: pulling a copy out of the trash and into the archive92 /// trash is not: pulling a copy out of the trash and into the archive
95 /// must not leave it pointing back at the trash.93 /// must not leave it pointing back at the trash.
96- fn is_restore_target(self) -> bool {94+ pub(crate) fn is_restore_target(self) -> bool {
97 matches!(self, Folder::Inbox | Folder::Sent | Folder::Archive)95 matches!(self, Folder::Inbox | Folder::Sent | Folder::Archive)
98 }96 }
99 }97 }
@@ -103,7 +101,8 @@ pub struct MessageId(RecordId);
103 101
104 impl MessageId {102 impl MessageId {
105 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:103 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:
106- /// the folder listings sort `id DESC` (newest first, [`Message::list_folder`]),104+ /// the folder listings sort `id DESC` (newest first,
105+ /// [`crate::db::message::list_folder`]),
107 /// and a random low half scrambles rows minted in the same millisecond.106 /// and a random low half scrambles rows minted in the same millisecond.
108 pub fn generate() -> Self {107 pub fn generate() -> Self {
109 Self(RecordId::new(MESSAGE_TABLE, next_ulid().to_string()))108 Self(RecordId::new(MESSAGE_TABLE, next_ulid().to_string()))
@@ -171,20 +170,20 @@ impl MessageLabel {
171 170
172 #[derive(Debug, Clone, SurrealValue)]171 #[derive(Debug, Clone, SurrealValue)]
173 pub struct Message {172 pub struct Message {
174- id: MessageId,173+ pub(crate) id: MessageId,
175- sender: UserId,174+ pub(crate) sender: UserId,
176- recipient: UserId,175+ pub(crate) recipient: UserId,
177- subject: MessageSubject,176+ pub(crate) subject: MessageSubject,
178- body: MessageBody,177+ pub(crate) body: MessageBody,
179- label: Option<MessageLabel>,178+ pub(crate) label: Option<MessageLabel>,
180- sent_at: Timestamp,179+ pub(crate) sent_at: Timestamp,
181- read: bool,180+ pub(crate) read: bool,
182- sender_folder: Folder,181+ pub(crate) sender_folder: Folder,
183- recipient_folder: Folder,182+ pub(crate) recipient_folder: Folder,
184 /// Where each side's copy sat before it was filed into archive/trash —183 /// Where each side's copy sat before it was filed into archive/trash —
185 /// the restore target. `None` while the copy sits in its home folder.184 /// the restore target. `None` while the copy sits in its home folder.
186- sender_origin: Option<Folder>,185+ pub(crate) sender_origin: Option<Folder>,
187- recipient_origin: Option<Folder>,186+ pub(crate) recipient_origin: Option<Folder>,
188 }187 }
189 188
190 impl Message {189 impl Message {
@@ -243,182 +242,6 @@ impl Message {
243 self.recipient_origin242 self.recipient_origin
244 }243 }
245 }244 }
246-
247- pub async fn send(
248- sender: &UserId,
249- recipient: &UserId,
250- subject: MessageSubject,
251- body: MessageBody,
252- label: Option<MessageLabel>,
253- db: &Database,
254- ) -> Result<Message, AppError> {
255- let message = Message {
256- id: MessageId::generate(),
257- sender: sender.clone(),
258- recipient: recipient.clone(),
259- subject,
260- body,
261- label,
262- sent_at: Timestamp::now(),
263- read: false,
264- sender_folder: Folder::Sent,
265- recipient_folder: Folder::Inbox,
266- sender_origin: None,
267- recipient_origin: None,
268- };
269- let created: Option<Message> = db.create(message.id.record()).content(message).await?;
270- created.ok_or_else(|| AppError::Internal("failed to create message".into()))
271- }
272-
273- /// One folder view for `user`, newest first. `inbox` is recipient-side,
274- /// `sent` is sender-side, and `archive`/`trash` are each the union of both
275- /// sides' filed copies (either party may archive or trash their own copy).
276- /// `read` narrows to that flag state (`false` on the inbox is the unread
277- /// view; on `sent`, receipts pending) — the folder condition is
278- /// parenthesized because `archive`'s and `trash`'s are ORs.
279- pub async fn list_folder(
280- user: &UserId,
281- folder: Folder,
282- read: Option<bool>,
283- limit: Option<i64>,
284- offset: i64,
285- db: &Database,
286- ) -> Result<(Vec<Message>, i64), AppError> {
287- let condition = match folder {
288- Folder::Sent => "sender = $usr AND sender_folder = 'sent'",
289- Folder::Archive => {
290- "(recipient = $usr AND recipient_folder = 'archive') \
291- OR (sender = $usr AND sender_folder = 'archive')"
292- }
293- Folder::Trash => {
294- "(recipient = $usr AND recipient_folder = 'trash') \
295- OR (sender = $usr AND sender_folder = 'trash')"
296- }
297- _ => "recipient = $usr AND recipient_folder = $folder",
298- };
299- let read_clause = if read.is_some() {
300- " AND read = $read"
301- } else {
302- ""
303- };
304- PagedList::new(
305- format!("message WHERE ({condition}){read_clause}"),
306- "ORDER BY id DESC",
307- )
308- .bind("usr", user.record())
309- .bind("folder", folder.as_str().to_string())
310- .bind("read", read.unwrap_or_default())
311- .run(limit, offset, db)
312- .await
313- }
314-
315- /// Read a message only if `user` is its sender or recipient and their
316- /// side hasn't been permanently deleted.
317- pub async fn read_for(
318- id: &MessageId,
319- user: &UserId,
320- db: &Database,
321- ) -> Result<Option<Message>, AppError> {
322- let message: Option<Message> = db.select(id.record()).await?;
323- Ok(message.filter(|message| {
324- (&message.sender == user || &message.recipient == user)
325- && message.folder_of(user) != Folder::Deleted
326- }))
327- }
328-
329- /// Flip the recipient's read flag. Field-scoped write: the sender may be
330- /// filing their side concurrently, and a whole-row save would clobber it.
331- pub async fn set_read(self, read: bool, db: &Database) -> Result<Message, AppError> {
332- let mut result = db
333- .query("UPDATE $id SET read = $read RETURN AFTER")
334- .bind(("id", self.id.record()))
335- .bind(("read", read))
336- .await?
337- .check()?;
338- result
339- .take::<Vec<Message>>(0)?
340- .into_iter()
341- .next()
342- .ok_or(AppError::NotFound)
343- }
344-
345- /// File `user`'s side into `folder` (already validated against that
346- /// side's allowed set), stamping where the copy came from so it can be
347- /// restored. Only the caller's two fields are written — field-scoped for
348- /// the same race reason as [`Message::set_read`].
349- ///
350- /// Filing away remembers the folder being left, so `inbox → archive →
351- /// trash` restores to `archive` and that back to `inbox`. Two folders are
352- /// never stamped: the trash (`trash → archive` would leave the copy
353- /// pointing back at the discard pile — it falls back to the home folder)
354- /// and the target itself (a no-op move keeps the memory it had). Moving
355- /// back to a home folder clears it.
356- pub async fn move_to(
357- self,
358- user: &UserId,
359- folder: Folder,
360- db: &Database,
361- ) -> Result<Message, AppError> {
362- let current = self.folder_of(user);
363- let (field, origin_field) = if self.is_sender(user) {
364- ("sender_folder", "sender_origin")
365- } else {
366- ("recipient_folder", "recipient_origin")
367- };
368- let origin = match folder {
369- _ if !folder.is_filed() => None,
370- _ if current == folder => self.origin_of(user),
371- _ if current.is_restore_target() => Some(current),
372- _ => None,
373- };
374- let mut result = db
375- .query(format!(
376- "UPDATE $id SET {field} = $folder, {origin_field} = $origin RETURN AFTER"
377- ))
378- .bind(("id", self.id.record()))
379- .bind(("folder", folder.as_str().to_string()))
380- .bind(("origin", origin.map(|origin| origin.as_str().to_string())))
381- .await?
382- .check()?;
383- result
384- .take::<Vec<Message>>(0)?
385- .into_iter()
386- .next()
387- .ok_or(AppError::NotFound)
388- }
389-
390- /// Permanently drop `user`'s side — only if that side currently sits in
391- /// the trash; the gate rides in the `UPDATE`'s `WHERE` so a concurrent
392- /// move back to the inbox can't slip past a check-then-act window. The
393- /// row itself is removed once both sides are gone — judged on the
394- /// post-write row, so two concurrent deletes can't leak an all-deleted
395- /// row.
396- pub async fn delete_for(self, user: &UserId, db: &Database) -> Result<(), AppError> {
397- let (field, origin_field) = if self.is_sender(user) {
398- ("sender_folder", "sender_origin")
399- } else {
400- ("recipient_folder", "recipient_origin")
401- };
402- let mut result = db
403- .query(format!(
404- "UPDATE $id SET {field} = $deleted, {origin_field} = NONE \
405- WHERE {field} = $trash RETURN AFTER"
406- ))
407- .bind(("id", self.id.record()))
408- .bind(("deleted", Folder::Deleted.as_str().to_string()))
409- .bind(("trash", Folder::Trash.as_str().to_string()))
410- .await?
411- .check()?;
412- let Some(after) = result.take::<Vec<Message>>(0)?.into_iter().next() else {
413- return Err(AppError::Conflict(
414- "only messages in the trash can be permanently deleted",
415- ));
416- };
417- if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted {
418- let _: Option<Message> = db.delete(after.id.record()).await?;
419- }
420- Ok(())
421- }
422 }245 }
423 246
424 #[cfg(test)]247 #[cfg(test)]
@@ -432,42 +255,6 @@ mod tests {
432 assert_eq!(MessageBody::try_new("").unwrap().as_str(), "");255 assert_eq!(MessageBody::try_new("").unwrap().as_str(), "");
433 }256 }
434 257
435- /// The `next_ulid` hazard: an inbox is documented newest-first and sorts
436- /// `id DESC`, so messages sent inside one millisecond must come back in
437- /// exact reverse write order, not at random (src/domain/monotonic_id.rs).
438- /// Asserts the *stored* order, not the mint order.
439- #[tokio::test]
440- async fn inbox_is_newest_first_within_a_millisecond() {
441- let db = crate::database::init_mem().await.unwrap();
442- let sender = UserId::from_key("a");
443- let recipient = UserId::from_key("b");
444- let mut sent = Vec::new();
445- for i in 0..25 {
446- let message = Message::send(
447- &sender,
448- &recipient,
449- MessageSubject::try_new(&format!("s{i}")).unwrap(),
450- MessageBody::try_new("").unwrap(),
451- None,
452- &db,
453- )
454- .await
455- .unwrap();
456- sent.push(message.get_id().key().to_string());
457- }
458-
459- let (listed, total) = Message::list_folder(&recipient, Folder::Inbox, None, None, 0, &db)
460- .await
461- .unwrap();
462- assert_eq!(total, 25);
463- sent.reverse();
464- let read_back: Vec<String> = listed
465- .iter()
466- .map(|row| row.get_id().key().to_string())
467- .collect();
468- assert_eq!(read_back, sent);
469- }
470-
471 #[tokio::test]258 #[tokio::test]
472 async fn folder_sides_resolve_by_membership() {259 async fn folder_sides_resolve_by_membership() {
473 let sender = UserId::from_key("a");260 let sender = UserId::from_key("a");
src/domain/parent_link.rsmodified+4 -64
@@ -1,9 +1,7 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3 use crate::constant::PARENT_LINK_TABLE;3 use crate::constant::PARENT_LINK_TABLE;
4-use crate::database::Database;
5 use crate::domain::user::UserId;4 use crate::domain::user::UserId;
6-use crate::error::AppError;
7 5
8 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]6 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
9 pub struct ParentLinkId(RecordId);7 pub struct ParentLinkId(RecordId);
@@ -39,10 +37,10 @@ impl ParentLinkId {
39 /// is a parent's job and a small child cannot do it themselves.37 /// is a parent's job and a small child cannot do it themselves.
40 #[derive(Debug, Clone, SurrealValue)]38 #[derive(Debug, Clone, SurrealValue)]
41 pub struct ParentLink {39 pub struct ParentLink {
42- id: ParentLinkId,40+ pub(crate) id: ParentLinkId,
43- parent: UserId,41+ pub(crate) parent: UserId,
44- student: UserId,42+ pub(crate) student: UserId,
45- linked_by: UserId,43+ pub(crate) linked_by: UserId,
46 }44 }
47 45
48 impl ParentLink {46 impl ParentLink {
@@ -62,64 +60,6 @@ impl ParentLink {
62 &self.linked_by60 &self.linked_by
63 }61 }
64 62
65- /// Tie (idempotently) `student` to `parent`. One row per pair, keyed by the
66- /// deterministic composite id, so concurrent links converge on one row. The
67- /// caller validates the roles — this only stores the pair.
68- pub async fn link(
69- parent: &UserId,
70- student: &UserId,
71- linked_by: &UserId,
72- db: &Database,
73- ) -> Result<ParentLink, AppError> {
74- let link = ParentLink {
75- id: ParentLinkId::composite(parent, student),
76- parent: parent.clone(),
77- student: student.clone(),
78- linked_by: linked_by.clone(),
79- };
80- let saved: Option<ParentLink> = db.upsert(link.id.record()).content(link).await?;
81- saved.ok_or_else(|| AppError::Internal("failed to link student to parent".into()))
82- }
83-
84- /// True iff `parent` holds a link to `student` — the observation gate.
85- pub async fn exists(
86- parent: &UserId,
87- student: &UserId,
88- db: &Database,
89- ) -> Result<bool, AppError> {
90- let found: Option<ParentLink> = db
91- .select(ParentLinkId::composite(parent, student).record())
92- .await?;
93- Ok(found.is_some())
94- }
95-
96- /// Every student `parent` observes, newest link first.
97- pub async fn list_for_parent(
98- parent: &UserId,
99- db: &Database,
100- ) -> Result<Vec<ParentLink>, AppError> {
101- let mut result = db
102- .query("SELECT * FROM parent_link WHERE parent = $parent ORDER BY id DESC")
103- .bind(("parent", parent.record()))
104- .await?
105- .check()?;
106- Ok(result.take::<Vec<ParentLink>>(0)?)
107- }
108-
109- pub async fn remove(
110- parent: &UserId,
111- student: &UserId,
112- db: &Database,
113- ) -> Result<Option<ParentLink>, AppError> {
114- let mut result = db
115- .query("DELETE parent_link WHERE parent = $parent AND student = $student RETURN BEFORE")
116- .bind(("parent", parent.record()))
117- .bind(("student", student.record()))
118- .await?
119- .check()?;
120- Ok(result.take::<Vec<ParentLink>>(0)?.into_iter().next())
121- }
122-
123 // Both role-change sweeps (the observed student leaving `student`, the63 // Both role-change sweeps (the observed student leaving `student`, the
124 // observing parent leaving `parent`) live in64 // observing parent leaving `parent`) live in
125 // [`crate::service::user::set_role`]: they commit with the role write65 // [`crate::service::user::set_role`]: they commit with the role write
src/domain/registration.rsmodified+10 -141
@@ -1,12 +1,8 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE};3+use crate::constant::REGISTRATION_TABLE;
4-use crate::database::Database;4+use crate::domain::event::EventId;
5-use crate::db::cap;
6-use crate::domain::event::{Event, EventId};
7-use crate::domain::role::Role;
8 use crate::domain::user::UserId;5 use crate::domain::user::UserId;
9-use crate::error::AppError;
10 6
11 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]7 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
12 pub struct RegistrationId(RecordId);8 pub struct RegistrationId(RecordId);
@@ -41,10 +37,10 @@ impl RegistrationId {
41 /// away from the registration kind hides them without deleting them.37 /// away from the registration kind hides them without deleting them.
42 #[derive(Debug, Clone, SurrealValue)]38 #[derive(Debug, Clone, SurrealValue)]
43 pub struct Registration {39 pub struct Registration {
44- id: RegistrationId,40+ pub(crate) id: RegistrationId,
45- event: EventId,41+ pub(crate) event: EventId,
46- user: UserId,42+ pub(crate) user: UserId,
47- registered_by: UserId,43+ pub(crate) registered_by: UserId,
48 }44 }
49 45
50 impl Registration {46 impl Registration {
@@ -64,139 +60,12 @@ impl Registration {
64 &self.registered_by60 &self.registered_by
65 }61 }
66 62
67- /// Register (idempotently) `user` onto `event`, refusing when a capacity
68- /// cap is set and every seat is taken. Someone already listed gets their
69- /// existing row back untouched — a true no-op that never counts against
70- /// the cap and never rewrites who placed them. The seat is taken by
71- /// [`cap::claim_live_and_create`] on the event row — an atomic single-record
72- /// conditional write that reads `audience.capacity` off that same row as it
73- /// decides, so neither a racing registration nor a concurrent PATCH
74- /// *lowering* the capacity can over-admit. Bound as a number instead, the
75- /// snapshot below would admit every request already in flight when the
76- /// lower cap landed.
77- ///
78- /// The seat is claimed on the event row, so the same statement says nothing
79- /// about the *user* it is for — and a fall to `parent` is the one demotion
80- /// whose sweep ([`crate::service::user::set_role`]) can miss a seat and
81- /// leave it unfreeable: `unregister` refuses a non-student target and a
82- /// parent cannot reach the route at all. So the transaction also claims the
83- /// holder's own record ([`cap::role_claim`]), which is the key that
84- /// demotion writes: either the sweep sees this seat, or this write sees the
85- /// parent and takes it back.
86- pub async fn register(
87- event: &EventId,
88- user: &UserId,
89- registered_by: &UserId,
90- db: &Database,
91- ) -> Result<Registration, AppError> {
92- if let Some(existing) = Self::read_for_user(event, user, db).await? {
93- return Ok(existing);
94- }
95- // Read for its refusals only — the audience kind and the closing time.
96- // The seat count itself is re-read by the claim.
97- Event::read(event, db)
98- .await?
99- .ok_or(AppError::NotFound)?
100- .registration_capacity()?;
101- let registration = Registration {
102- id: RegistrationId::composite(event, user),
103- event: event.clone(),
104- user: user.clone(),
105- registered_by: registered_by.clone(),
106- };
107- match cap::claim_live_and_create(
108- &event.record(),
109- REGISTRATION_COUNT_FIELD,
110- // An uncapped registration list stores no `capacity` key at all
111- // (SurrealDB drops a `NONE`-valued object key), so the coalesce is
112- // what "unlimited" reads as.
113- "audience.capacity ?? $num",
114- cap::UNLIMITED,
115- // Staff hold their own seats, so the bar is not "still a student"
116- // but "still someone who can be taken off the list".
117- Some((&user.record(), &format!("= '{}'", Role::Parent.as_str()))),
118- (&registration.id.record(), &registration),
119- db,
120- )
121- .await?
122- {
123- cap::Claimed::Made(created) => Ok(created),
124- // A concurrent placement of the same pair got there first: hand its
125- // row over, the same no-op the early return above would have made,
126- // and with no seat spent either way.
127- cap::Claimed::Duplicate => Self::read_for_user(event, user, db)
128- .await?
129- .ok_or_else(|| AppError::Internal("failed to register user".into())),
130- // Full, the event was deleted between the read and the claim, or
131- // the holder fell to parent while this ran — the conditional writes
132- // match nothing (or throw) either way, and only this path pays for
133- // the reads that tell them apart.
134- cap::Claimed::Full => match Event::read(event, db).await? {
135- None => Err(AppError::NotFound),
136- Some(_) => match crate::db::user::read(db, user).await? {
137- Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden(
138- "that account was demoted to parent while this request ran — \
139- only students can be registered for",
140- )),
141- _ => Err(AppError::Conflict("the event is full")),
142- },
143- },
144- }
145- }
146-
147- /// Some(_) iff `user` holds a seat on `event` — the audience point check.
148- pub async fn read_for_user(
149- event: &EventId,
150- user: &UserId,
151- db: &Database,
152- ) -> Result<Option<Registration>, AppError> {
153- let mut result = db
154- .query("SELECT * FROM registration WHERE event = $ev AND user = $usr LIMIT 1")
155- .bind(("ev", event.record()))
156- .bind(("usr", user.record()))
157- .await?
158- .check()?;
159- Ok(result.take::<Vec<Registration>>(0)?.into_iter().next())
160- }
161-
162- pub async fn list_for_event(
163- event: &EventId,
164- db: &Database,
165- ) -> Result<Vec<Registration>, AppError> {
166- let mut result = db
167- .query("SELECT * FROM registration WHERE event = $ev ORDER BY id DESC")
168- .bind(("ev", event.record()))
169- .await?
170- .check()?;
171- Ok(result.take::<Vec<Registration>>(0)?)
172- }
173-
174- pub async fn remove(
175- event: &EventId,
176- user: &UserId,
177- db: &Database,
178- ) -> Result<Option<Registration>, AppError> {
179- // The seat comes back in the same transaction as the row that held it.
180- let mut result = db
181- .query(
182- "BEGIN TRANSACTION;
183- LET $gone = (DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE);
184- UPDATE $ev SET registration_count = math::max([(registration_count ?? 0) - array::len($gone), 0]);
185- RETURN $gone;
186- COMMIT TRANSACTION;",
187- )
188- .bind(("ev", event.record()))
189- .bind(("usr", user.record()))
190- .await?
191- .check()?;
192- Ok(result.take::<Vec<Registration>>(3)?.into_iter().next())
193- }
194-
195 // The demotion sweep — freeing every seat a fall to `parent` would strand,63 // The demotion sweep — freeing every seat a fall to `parent` would strand,
196 // and leaving a list that has already frozen exactly as it stands — is an64 // and leaving a list that has already frozen exactly as it stands — is an
197 // arm of [`crate::service::user::set_role`], so the seat comes back in65 // arm of [`crate::service::user::set_role`], so the seat comes back in
198 // the same transaction as the role that invalidated it. The freeze it obeys66 // the same transaction as the role that invalidated it. The freeze it obeys
199- // is [`Event::registration_capacity`]'s `Conflict` arm, re-spelled for67+ // is [`crate::domain::event::Event::registration_capacity`]'s `Conflict`
200- // SurrealQL as [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it68+ // arm, re-spelled for SurrealQL as
201- // by `event::tests::the_sql_freeze_guard_matches_the_rust_one`.69+ // [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it by
70+ // `event::tests::the_sql_freeze_guard_matches_the_rust_one`.
202 }71 }
src/service/message.rsadded+69 -0
@@ -0,0 +1,69 @@
1+//! Message workflows. Every persistence step here is a single atomic
2+//! record write ([`crate::db::message`]) whose rule rides in its own
3+//! `WHERE` clause, so there is no multi-call lock to hold and no policy of
4+//! its own — the handler validates the DTO, gates on the row it just read,
5+//! and sequences these calls. They live in the service so the web layer
6+//! never names the db layer.
7+
8+use crate::database::Database;
9+use crate::db::message;
10+use crate::domain::message::{
11+ Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject,
12+};
13+use crate::domain::user::UserId;
14+use crate::error::AppError;
15+
16+pub async fn send(
17+ db: &Database,
18+ sender: &UserId,
19+ recipient: &UserId,
20+ subject: MessageSubject,
21+ body: MessageBody,
22+ label: Option<MessageLabel>,
23+) -> Result<Message, AppError> {
24+ message::send(db, sender, recipient, subject, body, label).await
25+}
26+
27+pub async fn list_folder(
28+ db: &Database,
29+ user: &UserId,
30+ folder: Folder,
31+ read: Option<bool>,
32+ limit: Option<i64>,
33+ offset: i64,
34+) -> Result<(Vec<Message>, i64), AppError> {
35+ message::list_folder(db, user, folder, read, limit, offset).await
36+}
37+
38+pub async fn read_for(
39+ db: &Database,
40+ id: &MessageId,
41+ user: &UserId,
42+) -> Result<Option<Message>, AppError> {
43+ message::read_for(db, id, user).await
44+}
45+
46+pub async fn set_read(
47+ db: &Database,
48+ message_row: Message,
49+ read: bool,
50+) -> Result<Message, AppError> {
51+ message::set_read(db, message_row, read).await
52+}
53+
54+pub async fn move_to(
55+ db: &Database,
56+ message_row: Message,
57+ user: &UserId,
58+ folder: Folder,
59+) -> Result<Message, AppError> {
60+ message::move_to(db, message_row, user, folder).await
61+}
62+
63+pub async fn delete_for(
64+ db: &Database,
65+ message_row: Message,
66+ user: &UserId,
67+) -> Result<(), AppError> {
68+ message::delete_for(db, message_row, user).await
69+}
src/service/mod.rsmodified+3 -0
@@ -11,8 +11,11 @@ pub mod exam;
11 pub mod exam_attempt;11 pub mod exam_attempt;
12 pub mod exam_question;12 pub mod exam_question;
13 pub mod meal_booking;13 pub mod meal_booking;
14+pub mod message;
14 pub mod note;15 pub mod note;
16+pub mod parent_link;
15 pub mod payment_ledger;17 pub mod payment_ledger;
18+pub mod registration;
16 pub mod session;19 pub mod session;
17 pub mod settings;20 pub mod settings;
18 pub mod user;21 pub mod user;
src/service/parent_link.rsadded+107 -0
@@ -0,0 +1,107 @@
1+//! Parent-link decisions: who may be tied to whom (the admin's `link`),
2+//! and what a link grants. A link row alone is never the grant — every
3+//! parent-side permission re-derives it against the student's *live* role
4+//! through [`links_live`], because the demotion sweeps in
5+//! [`crate::service::user::set_role`] run once over the rows that exist at
6+//! that moment and a sweep can lose a race with `link`. The row-storage
7+//! itself is [`crate::db::parent_link`].
8+
9+use crate::database::Database;
10+use crate::db::parent_link;
11+use crate::domain::parent_link::ParentLink;
12+use crate::domain::role::Role;
13+use crate::domain::user::{User, UserId};
14+use crate::error::{AppError, ValidationError};
15+
16+/// Tie (idempotently) `student` to `parent`. The gate is the school-office
17+/// rule: `{id}` must hold the `parent` role and `user_id` the `student`
18+/// role. A stale-link race cannot start here — a target demoted between
19+/// this check and the upsert fails the role gate again on the next call,
20+/// and the sweeps treat the fresh row like any other.
21+///
22+/// Returns the tie plus the two accounts it was judged on, so the caller
23+/// can render the response without re-reading either.
24+pub async fn link(
25+ db: &Database,
26+ parent: &UserId,
27+ student: &UserId,
28+ linked_by: &UserId,
29+) -> Result<(ParentLink, User, User), AppError> {
30+ let parent = crate::service::user::read(db, parent)
31+ .await?
32+ .ok_or(AppError::NotFound)?;
33+ if parent.get_role() != Role::Parent {
34+ return Err(AppError::Validation(ValidationError::Invalid {
35+ field: "id",
36+ reason: "students can only be tied to a parent account",
37+ }));
38+ }
39+ let Some(student) = crate::service::user::read(db, student).await? else {
40+ return Err(AppError::Validation(ValidationError::Invalid {
41+ field: "user_id",
42+ reason: "target user does not exist",
43+ }));
44+ };
45+ if student.get_role() != Role::Student {
46+ return Err(AppError::Validation(ValidationError::Invalid {
47+ field: "user_id",
48+ reason: "only students can be tied to a parent",
49+ }));
50+ }
51+ let link = parent_link::link(db, parent.get_id(), student.get_id(), linked_by).await?;
52+ Ok((link, parent, student))
53+}
54+
55+/// True iff `parent` holds a *live* link to `student`: the row exists AND
56+/// the student side still holds the student role. The link row alone is
57+/// not the grant — like a stale enrollment, a link whose student side
58+/// changed role must be inert, so the target's live role is re-read here.
59+/// A missing or non-student target reads as `false`, so a parent never
60+/// gets an existence oracle.
61+pub async fn links_live(
62+ db: &Database,
63+ parent: &UserId,
64+ student: &UserId,
65+) -> Result<bool, AppError> {
66+ Ok(parent_link::exists(db, parent, student).await?
67+ && crate::service::user::read(db, student)
68+ .await?
69+ .is_some_and(|student| student.get_role() == Role::Student))
70+}
71+
72+/// May `caller` read `target`'s per-student reports (marks, attendance,
73+/// pomodoro)? Teacher+ always may (per-endpoint narrowing is the caller's
74+/// business); a parent may exactly when a `parent_link` row ties them to the
75+/// target *and* the target still holds the student role. Everyone else —
76+/// students included — gets a 403 (self-reads go through the `/me` endpoints).
77+pub async fn ensure_can_observe(
78+ caller: &User,
79+ target: &UserId,
80+ db: &Database,
81+) -> Result<(), AppError> {
82+ if caller.get_role().at_least(Role::Teacher) {
83+ return Ok(());
84+ }
85+ if caller.get_role() == Role::Parent && links_live(db, caller.get_id(), target).await? {
86+ return Ok(());
87+ }
88+ Err(AppError::Forbidden(
89+ "requires teacher role or higher, or a parent link to this student",
90+ ))
91+}
92+
93+/// Every student `parent` observes, newest link first. Rows, not a live
94+/// filter — callers re-derive each student's live role themselves when the
95+/// grant matters (the inert-row filter lives with each reader).
96+pub async fn list_for_parent(db: &Database, parent: &UserId) -> Result<Vec<ParentLink>, AppError> {
97+ parent_link::list_for_parent(db, parent).await
98+}
99+
100+/// Untie a student from a parent — `Some` iff a tie existed.
101+pub async fn remove(
102+ db: &Database,
103+ parent: &UserId,
104+ student: &UserId,
105+) -> Result<Option<ParentLink>, AppError> {
106+ parent_link::remove(db, parent, student).await
107+}
src/service/registration.rsadded+103 -0
@@ -0,0 +1,103 @@
1+//! The registration workflow: taking a seat on a registration-audience
2+//! event. The reads and the seat-returning delete are
3+//! [`crate::db::registration`]; the seat itself is [`cap`]'s
4+//! claim-on-the-event-row.
5+
6+use crate::constant::REGISTRATION_COUNT_FIELD;
7+use crate::database::Database;
8+use crate::db::cap;
9+use crate::db::registration;
10+use crate::domain::event::{Event, EventId};
11+use crate::domain::registration::{Registration, RegistrationId};
12+use crate::domain::role::Role;
13+use crate::domain::user::UserId;
14+use crate::error::AppError;
15+
16+/// Register (idempotently) `user` onto `event`, refusing when a capacity
17+/// cap is set and every seat is taken. Someone already listed gets their
18+/// existing row back untouched — a true no-op that never counts against
19+/// the cap and never rewrites who placed them. The seat is taken by
20+/// [`cap::claim_live_and_create`] on the event row — an atomic single-record
21+/// conditional write that reads `audience.capacity` off that same row as it
22+/// decides, so neither a racing registration nor a concurrent PATCH
23+/// *lowering* the capacity can over-admit. Bound as a number instead, the
24+/// snapshot below would admit every request already in flight when the
25+/// lower cap landed.
26+///
27+/// The seat is claimed on the event row, so the same statement says nothing
28+/// about the *user* it is for — and a fall to `parent` is the one demotion
29+/// whose sweep ([`crate::service::user::set_role`]) can miss a seat and
30+/// leave it unfreeable: `unregister` refuses a non-student target and a
31+/// parent cannot reach the route at all. So the transaction also claims the
32+/// holder's own record ([`cap::role_claim`]), which is the key that
33+/// demotion writes: either the sweep sees this seat, or this write sees the
34+/// parent and takes it back.
35+pub async fn register(
36+ db: &Database,
37+ event: &EventId,
38+ user: &UserId,
39+ registered_by: &UserId,
40+) -> Result<Registration, AppError> {
41+ if let Some(existing) = registration::read_for_user(db, event, user).await? {
42+ return Ok(existing);
43+ }
44+ // Read for its refusals only — the audience kind and the closing time.
45+ // The seat count itself is re-read by the claim.
46+ Event::read(event, db)
47+ .await?
48+ .ok_or(AppError::NotFound)?
49+ .registration_capacity()?;
50+ let registration_row = Registration {
51+ id: RegistrationId::composite(event, user),
52+ event: event.clone(),
53+ user: user.clone(),
54+ registered_by: registered_by.clone(),
55+ };
56+ match cap::claim_live_and_create(
57+ &event.record(),
58+ REGISTRATION_COUNT_FIELD,
59+ // An uncapped registration list stores no `capacity` key at all
60+ // (SurrealDB drops a `NONE`-valued object key), so the coalesce is
61+ // what "unlimited" reads as.
62+ "audience.capacity ?? $num",
63+ cap::UNLIMITED,
64+ // Staff hold their own seats, so the bar is not "still a student"
65+ // but "still someone who can be taken off the list".
66+ Some((&user.record(), &format!("= '{}'", Role::Parent.as_str()))),
67+ (&registration_row.id.record(), &registration_row),
68+ db,
69+ )
70+ .await?
71+ {
72+ cap::Claimed::Made(created) => Ok(created),
73+ // A concurrent placement of the same pair got there first: hand its
74+ // row over, the same no-op the early return above would have made,
75+ // and with no seat spent either way.
76+ cap::Claimed::Duplicate => registration::read_for_user(db, event, user)
77+ .await?
78+ .ok_or_else(|| AppError::Internal("failed to register user".into())),
79+ // Full, the event was deleted between the read and the claim, or
80+ // the holder fell to parent while this ran — the conditional writes
81+ // match nothing (or throw) either way, and only this path pays for
82+ // the reads that tell them apart.
83+ cap::Claimed::Full => match Event::read(event, db).await? {
84+ None => Err(AppError::NotFound),
85+ Some(_) => match crate::db::user::read(db, user).await? {
86+ Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden(
87+ "that account was demoted to parent while this request ran — \
88+ only students can be registered for",
89+ )),
90+ _ => Err(AppError::Conflict("the event is full")),
91+ },
92+ },
93+ }
94+}
95+
96+/// Take a user off the list; `Some` iff they held a seat.
97+pub async fn remove(
98+ db: &Database,
99+ event: &EventId,
100+ user: &UserId,
101+) -> Result<Option<Registration>, AppError> {
102+ registration::remove(db, event, user).await
103+}
src/web/attendance.rsmodified+2 -1
@@ -15,10 +15,11 @@ use crate::domain::role::Role;
15 use crate::domain::session_attendance::SessionAttendance;15 use crate::domain::session_attendance::SessionAttendance;
16 use crate::domain::user::{User, UserId};16 use crate::domain::user::{User, UserId};
17 use crate::error::{AppError, ErrorResponse};17 use crate::error::{AppError, ErrorResponse};
18+use crate::service::parent_link::ensure_can_observe;
18 use crate::state::AppState;19 use crate::state::AppState;
19 20
20 use super::courses::can_manage_course;21 use super::courses::can_manage_course;
21-use super::{CourseResponse, CurrentUser, course_people, ensure_can_observe, person_map};22+use super::{CourseResponse, CurrentUser, course_people, person_map};
22 23
23 pub fn routes() -> OpenApiRouter<AppState> {24 pub fn routes() -> OpenApiRouter<AppState> {
24 OpenApiRouter::new()25 OpenApiRouter::new()
src/web/classes.rsmodified+3 -2
@@ -26,13 +26,14 @@ use crate::domain::role::Role;
26 use crate::domain::user::{User, UserId};26 use crate::domain::user::{User, UserId};
27 use crate::error::{AppError, ErrorResponse, ValidationError};27 use crate::error::{AppError, ErrorResponse, ValidationError};
28 use crate::service::class_blueprint;28 use crate::service::class_blueprint;
29+use crate::service::parent_link::ensure_can_observe;
29 use crate::state::AppState;30 use crate::state::AppState;
30 31
31 use super::courses::can_manage_course;32 use super::courses::can_manage_course;
32 use super::terms::resolve_term;33 use super::terms::resolve_term;
33 use super::{34 use super::{
34- CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, ensure_can_observe,35+ CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map,
35- person_map, set_or_clear, undo_if_demoted,36+ set_or_clear, undo_if_demoted,
36 };37 };
37 38
38 pub fn routes() -> OpenApiRouter<AppState> {39 pub fn routes() -> OpenApiRouter<AppState> {
src/web/events.rsmodified+9 -6
@@ -14,7 +14,6 @@ use crate::domain::attendance::{Attendance, AttendanceStatus};
14 use crate::domain::class_group::{ClassGroup, ClassGroupId};14 use crate::domain::class_group::{ClassGroup, ClassGroupId};
15 use crate::domain::course::CourseId;15 use crate::domain::course::CourseId;
16 use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};16 use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};
17-use crate::domain::registration::Registration;
18 use crate::domain::role::Role;17 use crate::domain::role::Role;
19 use crate::domain::timestamp::Timestamp;18 use crate::domain::timestamp::Timestamp;
20 use crate::domain::user::{User, UserId};19 use crate::domain::user::{User, UserId};
@@ -752,7 +751,7 @@ async fn register(
752 .await?751 .await?
753 .ok_or(AppError::NotFound)?;752 .ok_or(AppError::NotFound)?;
754 // Fast-fail gate; the authoritative re-check runs inside753 // Fast-fail gate; the authoritative re-check runs inside
755- // `Registration::register` under its lock.754+ // `service::registration::register` under its lock.
756 event.registration_capacity()?;755 event.registration_capacity()?;
757 756
758 let target = match req.user_id {757 let target = match req.user_id {
@@ -772,7 +771,8 @@ async fn register(
772 ));771 ));
773 }772 }
774 773
775- let registration = Registration::register(&event_id, &target, user.get_id(), &st.db).await?;774+ let registration =
775+ crate::service::registration::register(&st.db, &event_id, &target, user.get_id()).await?;
776 // Resolve from the row, not the request: a re-register returns the776 // Resolve from the row, not the request: a re-register returns the
777 // existing seat, whose registered_by is the *original* placer — someone777 // existing seat, whose registered_by is the *original* placer — someone
778 // the {target, caller} pair may not contain.778 // the {target, caller} pair may not contain.
@@ -832,7 +832,7 @@ async fn unregister(
832 // staff member's seat is theirs alone. The bar is *staff*, not "a student":832 // staff member's seat is theirs alone. The bar is *staff*, not "a student":
833 // a parent holds no seat any route can reach — they cannot get past833 // a parent holds no seat any route can reach — they cannot get past
834 // `RequireTeacher` to free their own — so a seat under that role is834 // `RequireTeacher` to free their own — so a seat under that role is
835- // stranded, and a volume written before `Registration::register` claimed835+ // stranded, and a volume written before `service::registration::register` claimed
836 // the holder's row already carries some.836 // the holder's row already carries some.
837 if &target != user.get_id()837 if &target != user.get_id()
838 && let Some(target_user) = crate::service::user::read(&st.db, &target).await?838 && let Some(target_user) = crate::service::user::read(&st.db, &target).await?
@@ -843,7 +843,7 @@ async fn unregister(
843 ));843 ));
844 }844 }
845 845
846- if Registration::remove(&event_id, &target, &st.db)846+ if crate::service::registration::remove(&st.db, &event_id, &target)
847 .await?847 .await?
848 .is_none()848 .is_none()
849 {849 {
@@ -868,7 +868,10 @@ mod tests {
868 let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash)868 let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash)
869 .await869 .await
870 .unwrap();870 .unwrap();
871- crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0871+ crate::service::user::set_role(db, user.get_id(), role)
872+ .await
873+ .unwrap()
874+ .0
872 }875 }
873 876
874 /// `can_manage` is only reached behind `RequireTeacher` today, so this is877 /// `can_manage` is only reached behind `RequireTeacher` today, so this is
src/web/homework.rsmodified+2 -1
@@ -34,6 +34,7 @@ use crate::domain::timestamp::Timestamp;
34 use crate::domain::user::{User, UserId};34 use crate::domain::user::{User, UserId};
35 use crate::error::{AppError, ErrorResponse, ValidationError};35 use crate::error::{AppError, ErrorResponse, ValidationError};
36 use crate::service;36 use crate::service;
37+use crate::service::parent_link::ensure_can_observe;
37 use crate::state::AppState;38 use crate::state::AppState;
38 39
39 use super::courses::{can_manage_course, can_view_course, visible_courses};40 use super::courses::{can_manage_course, can_view_course, visible_courses};
@@ -41,7 +42,7 @@ use super::notes::content_disposition;
41 use super::subjects::subject_in_course;42 use super::subjects::subject_in_course;
42 use super::{43 use super::{
43 CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path,44 CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path,
44- check_not_past, ensure_can_observe, paginate, read_upload, remove_blob, set_or_clear,45+ check_not_past, paginate, read_upload, remove_blob, set_or_clear,
45 };46 };
46 47
47 /// Serializes the homework subsystem's cross-record check-then-writes, which48 /// Serializes the homework subsystem's cross-record check-then-writes, which
src/web/marks.rsmodified+2 -1
@@ -16,10 +16,11 @@ use crate::domain::role::Role;
16 use crate::domain::user::{User, UserId};16 use crate::domain::user::{User, UserId};
17 use crate::error::{AppError, ErrorResponse};17 use crate::error::{AppError, ErrorResponse};
18 use crate::service;18 use crate::service;
19+use crate::service::parent_link::ensure_can_observe;
19 use crate::state::AppState;20 use crate::state::AppState;
20 21
21 use super::courses::can_manage_course;22 use super::courses::can_manage_course;
22-use super::{CourseResponse, CurrentUser, course_people, ensure_can_observe, person_map};23+use super::{CourseResponse, CurrentUser, course_people, person_map};
23 24
24 pub fn routes() -> OpenApiRouter<AppState> {25 pub fn routes() -> OpenApiRouter<AppState> {
25 OpenApiRouter::new()26 OpenApiRouter::new()
src/web/meals.rsmodified+10 -14
@@ -28,7 +28,6 @@ use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot, validate_
28 use crate::domain::menu_dish::{28 use crate::domain::menu_dish::{
29 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,29 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,
30 };30 };
31-use crate::domain::parent_link::ParentLink;
32 // The same idempotence key `/payments/credits` takes — one grammar, one type.31 // The same idempotence key `/payments/credits` takes — one grammar, one type.
33 use crate::domain::payment_ledger::PaymentRequestKey;32 use crate::domain::payment_ledger::PaymentRequestKey;
34 use crate::domain::role::Role;33 use crate::domain::role::Role;
@@ -802,11 +801,7 @@ async fn booking_target(
802 reason: "a parent must name the student the seat is for",801 reason: "a parent must name the student the seat is for",
803 },802 },
804 ))?);803 ))?);
805- if ParentLink::exists(caller.get_id(), &target, db).await?804+ if crate::service::parent_link::links_live(db, caller.get_id(), &target).await? {
806- && crate::service::user::read(db, &target)
807- .await?
808- .is_some_and(|target| target.get_role() == Role::Student)
809- {
810 return Ok(target);805 return Ok(target);
811 }806 }
812 Err(AppError::Forbidden(807 Err(AppError::Forbidden(
@@ -903,7 +898,7 @@ async fn my_bookings(
903 let mut students = vec![user.get_id().clone()];898 let mut students = vec![user.get_id().clone()];
904 if user.get_role() == Role::Parent {899 if user.get_role() == Role::Parent {
905 students.extend(900 students.extend(
906- ParentLink::list_for_parent(user.get_id(), &st.db)901+ crate::service::parent_link::list_for_parent(&st.db, user.get_id())
907 .await?902 .await?
908 .iter()903 .iter()
909 .map(|link| link.get_student().clone()),904 .map(|link| link.get_student().clone()),
@@ -1146,7 +1141,10 @@ async fn mark_attendance(
1146 let student = UserId::from_key(&req.student_id);1141 let student = UserId::from_key(&req.student_id);
1147 // The target must exist; no booking is required, since a walk-in was still1142 // The target must exist; no booking is required, since a walk-in was still
1148 // served and the record is operationally true.1143 // served and the record is operationally true.
1149- if crate::service::user::read(&st.db, &student).await?.is_none() {1144+ if crate::service::user::read(&st.db, &student)
1145+ .await?
1146+ .is_none()
1147+ {
1150 return Err(AppError::Validation(ValidationError::Invalid {1148 return Err(AppError::Validation(ValidationError::Invalid {
1151 field: "student_id",1149 field: "student_id",
1152 reason: "target user does not exist",1150 reason: "target user does not exist",
@@ -1318,7 +1316,8 @@ async fn balance_response(
1318 /// Reading someone else's meal record — money, attendance, dietary profile:1316 /// Reading someone else's meal record — money, attendance, dietary profile:
1319 /// teacher+, or a parent linked to the student. Reading your *own* is always1317 /// teacher+, or a parent linked to the student. Reading your *own* is always
1320 /// allowed, since every `{user}` route here accepts the caller's own id; that1318 /// allowed, since every `{user}` route here accepts the caller's own id; that
1321-/// is the one way this gate differs from [`super::ensure_can_observe`], which1319+/// is the one way this gate differs from
1320+/// [`crate::service::parent_link::ensure_can_observe`], which
1322 /// 403s a self-read because its subjects have their own `/me` routes.1321 /// 403s a self-read because its subjects have their own `/me` routes.
1323 async fn ensure_can_read_student(1322 async fn ensure_can_read_student(
1324 caller: &User,1323 caller: &User,
@@ -1328,7 +1327,7 @@ async fn ensure_can_read_student(
1328 if caller.get_id() == target {1327 if caller.get_id() == target {
1329 return Ok(());1328 return Ok(());
1330 }1329 }
1331- super::ensure_can_observe(caller, target, db).await1330+ crate::service::parent_link::ensure_can_observe(caller, target, db).await
1332 }1331 }
1333 1332
1334 /// May `caller` read `target`'s meal *money* — balance and ledger? Own always;1333 /// May `caller` read `target`'s meal *money* — balance and ledger? Own always;
@@ -1351,10 +1350,7 @@ async fn ensure_can_read_money(
1351 // role must be inert, so the target's live role is re-read. A missing or1350 // role must be inert, so the target's live role is re-read. A missing or
1352 // non-student target falls through to the same 403 — a parent never gets an1351 // non-student target falls through to the same 403 — a parent never gets an
1353 if caller.get_role() == Role::Parent1352 if caller.get_role() == Role::Parent
1354- && ParentLink::exists(caller.get_id(), target, db).await?1353+ && crate::service::parent_link::links_live(db, caller.get_id(), target).await?
1355- && crate::service::user::read(db, target)
1356- .await?
1357- .is_some_and(|target| target.get_role() == Role::Student)
1358 {1354 {
1359 return Ok(());1355 return Ok(());
1360 }1356 }
src/web/messages.rsmodified+9 -8
@@ -15,6 +15,7 @@ use crate::domain::message::{
15 };15 };
16 use crate::domain::user::{User, UserId};16 use crate::domain::user::{User, UserId};
17 use crate::error::{AppError, ErrorResponse, ValidationError};17 use crate::error::{AppError, ErrorResponse, ValidationError};
18+use crate::service::message;
18 use crate::state::AppState;19 use crate::state::AppState;
19 20
20 use super::dto::Role;21 use super::dto::Role;
@@ -206,13 +207,13 @@ async fn send_message(
206 ));207 ));
207 }208 }
208 209
209- let message = Message::send(210+ let message = message::send(
211+ &st.db,
210 user.get_id(),212 user.get_id(),
211 recipient.get_id(),213 recipient.get_id(),
212 subject,214 subject,
213 body,215 body,
214 label,216 label,
215- &st.db,
216 )217 )
217 .await?;218 .await?;
218 let people = people_of([&user, &recipient]);219 let people = people_of([&user, &recipient]);
@@ -250,7 +251,7 @@ async fn list(
250 };251 };
251 252
252 let (messages, total) =253 let (messages, total) =
253- Message::list_folder(user.get_id(), folder, filter.read, limit, offset, &st.db).await?;254+ message::list_folder(&st.db, user.get_id(), folder, filter.read, limit, offset).await?;
254 let people = load_people(&messages, &st.db).await?;255 let people = load_people(&messages, &st.db).await?;
255 let items = messages256 let items = messages
256 .iter()257 .iter()
@@ -288,7 +289,7 @@ async fn update_message(
288 Path(id): Path<String>,289 Path(id): Path<String>,
289 Json(req): Json<UpdateMessage>,290 Json(req): Json<UpdateMessage>,
290 ) -> Result<Json<MessageResponse>, AppError> {291 ) -> Result<Json<MessageResponse>, AppError> {
291- let mut message = Message::read_for(&MessageId::from_key(&id), user.get_id(), &st.db)292+ let mut message = message::read_for(&st.db, &MessageId::from_key(&id), user.get_id())
292 .await?293 .await?
293 .ok_or(AppError::NotFound)?;294 .ok_or(AppError::NotFound)?;
294 295
@@ -313,10 +314,10 @@ async fn update_message(
313 None => None,314 None => None,
314 };315 };
315 if let Some(read) = req.read {316 if let Some(read) = req.read {
316- message = message.set_read(read, &st.db).await?;317+ message = message::set_read(&st.db, message, read).await?;
317 }318 }
318 if let Some(folder) = folder {319 if let Some(folder) = folder {
319- message = message.move_to(user.get_id(), folder, &st.db).await?;320+ message = message::move_to(&st.db, message, user.get_id(), folder).await?;
320 }321 }
321 322
322 let people = load_people(std::slice::from_ref(&message), &st.db).await?;323 let people = load_people(std::slice::from_ref(&message), &st.db).await?;
@@ -344,9 +345,9 @@ async fn delete_message(
344 CurrentUser(user): CurrentUser,345 CurrentUser(user): CurrentUser,
345 Path(id): Path<String>,346 Path(id): Path<String>,
346 ) -> Result<StatusCode, AppError> {347 ) -> Result<StatusCode, AppError> {
347- let message = Message::read_for(&MessageId::from_key(&id), user.get_id(), &st.db)348+ let message = message::read_for(&st.db, &MessageId::from_key(&id), user.get_id())
348 .await?349 .await?
349 .ok_or(AppError::NotFound)?;350 .ok_or(AppError::NotFound)?;
350- message.delete_for(user.get_id(), &st.db).await?;351+ message::delete_for(&st.db, message, user.get_id()).await?;
351 Ok(StatusCode::NO_CONTENT)352 Ok(StatusCode::NO_CONTENT)
352 }353 }
src/web/mod.rsmodified+1 -33
@@ -72,43 +72,11 @@ use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS};
72 use crate::database::Database;72 use crate::database::Database;
73 use crate::domain::exam_question::{Choice, ChoiceInput};73 use crate::domain::exam_question::{Choice, ChoiceInput};
74 use crate::domain::note_file::FileContentType;74 use crate::domain::note_file::FileContentType;
75-use crate::domain::parent_link::ParentLink;
76 use crate::domain::role::Role;75 use crate::domain::role::Role;
77 use crate::domain::timestamp::Timestamp;76 use crate::domain::timestamp::Timestamp;
78-use crate::domain::user::{User, UserId};77+use crate::domain::user::UserId;
79 use crate::error::{AppError, ValidationError};78 use crate::error::{AppError, ValidationError};
80 79
81-/// May `caller` read `target`'s per-student reports (marks, attendance,
82-/// pomodoro)? Teacher+ always may (per-endpoint narrowing is the caller's
83-/// business); a parent may exactly when a `parent_link` row ties them to the
84-/// target *and* the target still holds the student role. Everyone else —
85-/// students included — gets a 403 (self-reads go through the `/me` endpoints).
86-pub(crate) async fn ensure_can_observe(
87- caller: &User,
88- target: &UserId,
89- db: &Database,
90-) -> Result<(), AppError> {
91- if caller.get_role().at_least(Role::Teacher) {
92- return Ok(());
93- }
94- // The link row alone is not the grant: like stale enrollments, a link
95- // whose student side changed role (a sweep lost a race with link_student)
96- // must be inert, so the target's live role is re-read here. Missing or
97- // non-student targets fall through to the same 403 — a parent never gets
98- // an existence oracle.
99- if caller.get_role() == Role::Parent
100- && ParentLink::exists(caller.get_id(), target, db).await?
101- && crate::service::user::read(db, target)
102- .await?
103- .is_some_and(|target| target.get_role() == Role::Student)
104- {
105- return Ok(());
106- }
107- Err(AppError::Forbidden(
108- "requires teacher role or higher, or a parent link to this student",
109- ))
110-}
111-
112 /// Close the window between "this account is teacher+" and the write that80 /// Close the window between "this account is teacher+" and the write that
113 /// records a teacher-only assignment (a class's homeroom teacher, a course's81 /// records a teacher-only assignment (a class's homeroom teacher, a course's
114 /// teacher list). Call it *after* the write, with the account it named.82 /// teacher list). Call it *after* the write, with the account it named.
src/web/payments.rsmodified+5 -7
@@ -3,7 +3,8 @@
3 //!3 //!
4 //! Every write here is manager+ — money is school administration, and a teacher4 //! Every write here is manager+ — money is school administration, and a teacher
5 //! has no business in it. The read gate is deliberately *narrower* than the5 //! has no business in it. The read gate is deliberately *narrower* than the
6-//! per-student reports elsewhere ([`super::ensure_can_observe`]): a student sees6+//! per-student reports elsewhere
7+//! ([`crate::service::parent_link::ensure_can_observe`]): a student sees
7 //! their own record, a parent a linked student's, manager+ everyone's, and a8 //! their own record, a parent a linked student's, manager+ everyone's, and a
8 //! teacher nothing at all.9 //! teacher nothing at all.
9 //!10 //!
@@ -26,7 +27,6 @@ use crate::constant::{MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES};
26 use crate::database::Database;27 use crate::database::Database;
27 use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment};28 use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment};
28 use crate::domain::fee_plan_assignment::FeePlanAssignment;29 use crate::domain::fee_plan_assignment::FeePlanAssignment;
29-use crate::domain::parent_link::ParentLink;
30 use crate::domain::payment_ledger::{30 use crate::domain::payment_ledger::{
31 LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind,31 LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind,
32 PaymentRequestKey,32 PaymentRequestKey,
@@ -775,7 +775,8 @@ async fn record_reversal(
775 /// May `caller` read `target`'s payment record? Own always; a parent only for a775 /// May `caller` read `target`'s payment record? Own always; a parent only for a
776 /// student they hold a live link to; manager+ for anyone.776 /// student they hold a live link to; manager+ for anyone.
777 ///777 ///
778-/// Deliberately narrower than [`super::ensure_can_observe`]: **a teacher sees no778+/// Deliberately narrower than
779+/// [`crate::service::parent_link::ensure_can_observe`]: **a teacher sees no
779 /// money**. What a family owes the school is not classroom information.780 /// money**. What a family owes the school is not classroom information.
780 async fn ensure_can_read_payments(781 async fn ensure_can_read_payments(
781 caller: &User,782 caller: &User,
@@ -790,10 +791,7 @@ async fn ensure_can_read_payments(
790 // non-student target falls through to the same 403 — a parent never gets an791 // non-student target falls through to the same 403 — a parent never gets an
791 // existence oracle.792 // existence oracle.
792 if caller.get_role() == Role::Parent793 if caller.get_role() == Role::Parent
793- && ParentLink::exists(caller.get_id(), target, db).await?794+ && crate::service::parent_link::links_live(db, caller.get_id(), target).await?
794- && crate::service::user::read(db, target)
795- .await?
796- .is_some_and(|target| target.get_role() == Role::Student)
797 {795 {
798 return Ok(());796 return Ok(());
799 }797 }
src/web/pomodoro.rsmodified+2 -1
@@ -11,9 +11,10 @@ use crate::domain::pomodoro::PomodoroSession;
11 use crate::domain::role::Role;11 use crate::domain::role::Role;
12 use crate::domain::user::{User, UserId};12 use crate::domain::user::{User, UserId};
13 use crate::error::{AppError, ErrorResponse};13 use crate::error::{AppError, ErrorResponse};
14+use crate::service::parent_link::ensure_can_observe;
14 use crate::state::AppState;15 use crate::state::AppState;
15 16
16-use super::{CurrentUser, PageParams, ensure_can_observe, paginate};17+use super::{CurrentUser, PageParams, paginate};
17 18
18 pub fn routes() -> OpenApiRouter<AppState> {19 pub fn routes() -> OpenApiRouter<AppState> {
19 OpenApiRouter::new()20 OpenApiRouter::new()
src/web/users.rsmodified+33 -41
@@ -17,20 +17,20 @@ use crate::domain::badge::{self, BadgeAward};
17 use crate::domain::class_group::{ClassGroup, ClassGroupId};17 use crate::domain::class_group::{ClassGroup, ClassGroupId};
18 use crate::domain::class_member::ClassMember;18 use crate::domain::class_member::ClassMember;
19 19
20-use crate::domain::parent_link::ParentLink;
21 use crate::domain::preferences::{Language, PaletteColor, Theme};20 use crate::domain::preferences::{Language, PaletteColor, Theme};
22 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats};21 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats};
23 use crate::domain::role::Role;22 use crate::domain::role::Role;
24 use crate::domain::user::{User, UserId};23 use crate::domain::user::{User, UserId};
25 use crate::error::{AppError, ErrorResponse, ValidationError};24 use crate::error::{AppError, ErrorResponse, ValidationError};
25+use crate::service::parent_link::ensure_can_observe;
26 use crate::state::AppState;26 use crate::state::AppState;
27 27
28 use super::courses::visible_courses;28 use super::courses::visible_courses;
29 use super::dto::AssignableRole;29 use super::dto::AssignableRole;
30 use super::dto::Role as RoleSchema;30 use super::dto::Role as RoleSchema;
31 use super::{31 use super::{
32- CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse,32+ CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse, paginate,
33- ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob, store_blob,33+ read_image_upload, remove_blob, serve_inline_blob, store_blob,
34 };34 };
35 35
36 pub fn routes() -> OpenApiRouter<AppState> {36 pub fn routes() -> OpenApiRouter<AppState> {
@@ -174,14 +174,9 @@ async fn apply_preferences(
174 let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?;174 let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?;
175 let language = merge_field(req.language.as_deref(), Language::try_from_str)?;175 let language = merge_field(req.language.as_deref(), Language::try_from_str)?;
176 let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?;176 let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?;
177- let updated = crate::service::user::set_preferences(177+ let updated =
178- db,178+ crate::service::user::set_preferences(db, user.get_id(), theme, language, palette_color)
179- user.get_id(),179+ .await?;
180- theme,
181- language,
182- palette_color,
183- )
184- .await?;
185 Ok(UserResponse::new(&updated))180 Ok(UserResponse::new(&updated))
186 }181 }
187 182
@@ -541,7 +536,7 @@ async fn students_page(
541 db: &Database,536 db: &Database,
542 ) -> Result<Page<PersonRef>, AppError> {537 ) -> Result<Page<PersonRef>, AppError> {
543 let (limit, offset) = page.resolve()?;538 let (limit, offset) = page.resolve()?;
544- let links = ParentLink::list_for_parent(parent, db).await?;539+ let links = crate::service::parent_link::list_for_parent(db, parent).await?;
545 let ids: Vec<UserId> = links540 let ids: Vec<UserId> = links
546 .iter()541 .iter()
547 .map(|link| link.get_student().clone())542 .map(|link| link.get_student().clone())
@@ -593,30 +588,13 @@ async fn link_student(
593 Path(id): Path<String>,588 Path(id): Path<String>,
594 Json(req): Json<LinkStudent>,589 Json(req): Json<LinkStudent>,
595 ) -> Result<Json<ParentLinkResponse>, AppError> {590 ) -> Result<Json<ParentLinkResponse>, AppError> {
596- let parent = crate::service::user::read(&st.db, &UserId::from_key(&id))591+ let (link, parent, student) = crate::service::parent_link::link(
597- .await?592+ &st.db,
598- .ok_or(AppError::NotFound)?;593+ &UserId::from_key(&id),
599- if parent.get_role() != Role::Parent {594+ &UserId::from_key(&req.user_id),
600- return Err(AppError::Validation(ValidationError::Invalid {595+ admin.get_id(),
601- field: "id",596+ )
602- reason: "students can only be tied to a parent account",597+ .await?;
603- }));
604- }
605- let Some(student) =
606- crate::service::user::read(&st.db, &UserId::from_key(&req.user_id)).await?
607- else {
608- return Err(AppError::Validation(ValidationError::Invalid {
609- field: "user_id",
610- reason: "target user does not exist",
611- }));
612- };
613- if student.get_role() != Role::Student {
614- return Err(AppError::Validation(ValidationError::Invalid {
615- field: "user_id",
616- reason: "only students can be tied to a parent",
617- }));
618- }
619- let link = ParentLink::link(parent.get_id(), student.get_id(), admin.get_id(), &st.db).await?;
620 let people = PersonRef::map_of(&[&parent, &student, &admin]);598 let people = PersonRef::map_of(&[&parent, &student, &admin]);
621 Ok(Json(ParentLinkResponse {599 Ok(Json(ParentLinkResponse {
622 parent: PersonRef::resolve(&people, link.get_parent()),600 parent: PersonRef::resolve(&people, link.get_parent()),
@@ -678,9 +656,13 @@ async fn unlink_student(
678 _admin: RequireAdmin,656 _admin: RequireAdmin,
679 Path((id, student)): Path<(String, String)>,657 Path((id, student)): Path<(String, String)>,
680 ) -> Result<StatusCode, AppError> {658 ) -> Result<StatusCode, AppError> {
681- if ParentLink::remove(&UserId::from_key(&id), &UserId::from_key(&student), &st.db)659+ if crate::service::parent_link::remove(
682- .await?660+ &st.db,
683- .is_none()661+ &UserId::from_key(&id),
662+ &UserId::from_key(&student),
663+ )
664+ .await?
665+ .is_none()
684 {666 {
685 return Err(AppError::NotFound);667 return Err(AppError::NotFound);
686 }668 }
@@ -1070,7 +1052,9 @@ async fn ensure_may_read_profile(
1070 async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> {1052 async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> {
1071 let target = UserId::from_key(id);1053 let target = UserId::from_key(id);
1072 ensure_may_read_profile(caller, &target, &st.db).await?;1054 ensure_may_read_profile(caller, &target, &st.db).await?;
1073- crate::service::user::read(&st.db, &target).await?.ok_or(AppError::NotFound)1055+ crate::service::user::read(&st.db, &target)
1056+ .await?
1057+ .ok_or(AppError::NotFound)
1074 }1058 }
1075 1059
1076 /// The caller's own public profile — what everyone else sees of them.1060 /// The caller's own public profile — what everyone else sees of them.
@@ -1165,7 +1149,15 @@ async fn upload_my_avatar(
1165 1149
1166 let file = ulid::Ulid::new().to_string();1150 let file = ulid::Ulid::new().to_string();
1167 store_blob(&st, &file, &upload.data, || async {1151 store_blob(&st, &file, &upload.data, || async {
1168- match crate::service::user::set_avatar(&st.db, user.get_id(), &file, &upload.content_type, size).await? {1152+ match crate::service::user::set_avatar(
1153+ &st.db,
1154+ user.get_id(),
1155+ &file,
1156+ &upload.content_type,
1157+ size,
1158+ )
1159+ .await?
1160+ {
1169 // Row written; the picture this one replaced comes off disk.1161 // Row written; the picture this one replaced comes off disk.
1170 Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))),1162 Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))),
1171 // The account went away mid-upload — the fresh blob is an orphan.1163 // The account went away mid-upload — the fresh blob is an orphan.
tests/regress_role_sweep.rsmodified+5 -5
@@ -26,10 +26,10 @@ use hezarfen_backend::domain::class_group::{ClassGroup, ClassGroupId, ClassName}
26 use hezarfen_backend::domain::class_member::ClassMember;26 use hezarfen_backend::domain::class_member::ClassMember;
27 use hezarfen_backend::domain::course::CourseId;27 use hezarfen_backend::domain::course::CourseId;
28 use hezarfen_backend::domain::event::EventId;28 use hezarfen_backend::domain::event::EventId;
29-use hezarfen_backend::domain::registration::Registration;
30 use hezarfen_backend::domain::role::Role;29 use hezarfen_backend::domain::role::Role;
31 use hezarfen_backend::domain::timestamp::Timestamp;30 use hezarfen_backend::domain::timestamp::Timestamp;
32 use hezarfen_backend::domain::user::UserId;31 use hezarfen_backend::domain::user::UserId;
32+use hezarfen_backend::service::registration;
33 use serde_json::json;33 use serde_json::json;
34 34
35 /// How many rows `sql` selects ids for.35 /// How many rows `sql` selects ids for.
@@ -165,7 +165,7 @@ async fn a_seat_is_refused_once_the_holder_is_a_parent() {
165 let event = a_registration_event(&app, &teacher, 1).await;165 let event = a_registration_event(&app, &teacher, 1).await;
166 demote(&student, Role::Parent, &db).await;166 demote(&student, Role::Parent, &db).await;
167 167
168- let refused = Registration::register(&event, &student, &UserId::from_key("staff"), &db).await;168+ let refused = registration::register(&db, &event, &student, &UserId::from_key("staff")).await;
169 assert!(169 assert!(
170 refused.is_err(),170 refused.is_err(),
171 "a parent may not be given a seat: {refused:?}"171 "a parent may not be given a seat: {refused:?}"
@@ -190,7 +190,7 @@ async fn a_seat_never_survives_the_demotion_it_raced() {
190 let event = a_registration_event(&app, &teacher, 1).await;190 let event = a_registration_event(&app, &teacher, 1).await;
191 // The bait: a seat the sweep will delete, which is what holds it open.191 // The bait: a seat the sweep will delete, which is what holds it open.
192 let earlier = a_registration_event(&app, &teacher, 1).await;192 let earlier = a_registration_event(&app, &teacher, 1).await;
193- Registration::register(&earlier, &student, &UserId::from_key("staff"), &db)193+ registration::register(&db, &earlier, &student, &UserId::from_key("staff"))
194 .await194 .await
195 .unwrap();195 .unwrap();
196 hold_the_sweep("registration", &db).await;196 hold_the_sweep("registration", &db).await;
@@ -198,7 +198,7 @@ async fn a_seat_never_survives_the_demotion_it_raced() {
198 // The seat is written inside the held window: past the sweep's snapshot,198 // The seat is written inside the held window: past the sweep's snapshot,
199 // before the commit.199 // before the commit.
200 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;200 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;
201- let seat = Registration::register(&event, &student, &UserId::from_key("staff"), &db).await;201+ let seat = registration::register(&db, &event, &student, &UserId::from_key("staff")).await;
202 still_running(&demoting);202 still_running(&demoting);
203 demoting.await.unwrap();203 demoting.await.unwrap();
204 204
@@ -226,7 +226,7 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() {
226 let (app, db) = app_and_db().await;226 let (app, db) = app_and_db().await;
227 let (teacher, student) = a_school(&app, &db).await;227 let (teacher, student) = a_school(&app, &db).await;
228 let event = a_registration_event(&app, &teacher, 1).await;228 let event = a_registration_event(&app, &teacher, 1).await;
229- Registration::register(&event, &student, &UserId::from_key("staff"), &db)229+ registration::register(&db, &event, &student, &UserId::from_key("staff"))
230 .await230 .await
231 .unwrap();231 .unwrap();
232 // The state the old race left: the seat stands, the account is a parent,232 // The state the old race left: the seat stands, the account is a parent,