forge
Explore
Log in

Don't you dare go Hollow

Remember where a filed copy came from

Browse files at this commit

79189b8499bb9246c044e3659f24c998e822abf7Ahmet Kaan GümüşParent: 266e175
  • feat
    • remember where a filed copy came from
Show full message
✨ feat(messages): remember where a filed copy came from

Archiving or trashing a copy stamps the folder it left onto that side's
origin field, exposed as `previous_folder`, so restoring puts it back
where it came from instead of always in the inbox.

The trash is never stamped — pulling a copy out of it must not leave the
copy pointing back at the discard pile — and a no-op move keeps the stamp
it had. `null` means "restore to the home folder", which is also how rows
filed before the field existed read (option columns, no backfill).

Folder names become a `Folder` enum: the DB columns, the list filter and
the stamp all pass through it, so the stale string arrays are gone and a
typo is a compile error rather than a silently empty folder.
README.mdmodified+12 -1
@@ -673,13 +673,24 @@ but each **owns their copy independently**: the recipient's moves through
673 as a read receipt); the sender's moves through `sent` → `trash`. Filing or673 as a read receipt); the sender's moves through `sent` → `trash`. Filing or
674 deleting your copy never changes the other side's view.674 deleting your copy never changes the other side's view.
675 675
676+Every copy remembers where it was filed from, so it can go back there. Moving
677+into `archive`/`trash` stamps the folder you left onto the copy's
678+`previous_folder`, and restoring is a `PATCH` of `folder` back to that value:
679+an inbox message you archive and then trash returns to `archive`, and from
680+there to `inbox`. Two folders are never stamped — the trash itself (pulling a
681+copy out of the trash must not leave it pointing back at the discard pile) and
682+the folder you are already in — and moving back to `inbox`/`sent` clears the
683+stamp. `previous_folder` is therefore `null` for any copy sitting in its home
684+folder, and for copies filed before the field existed; both mean "restore to
685+`inbox`" (`sent` for the sender's copy).
686+
676 Listing is per folder — `GET /messages?folder=` with `inbox` (default),687 Listing is per folder — `GET /messages?folder=` with `inbox` (default),
677 `sent`, `archive`, or `trash` (trash shows both received and sent copies you688 `sent`, `archive`, or `trash` (trash shows both received and sent copies you
678 trashed) — newest first, paged, with sender/recipient rendered as person refs689 trashed) — newest first, paged, with sender/recipient rendered as person refs
679 plus their role. `?read=false` narrows to unread (`true` to read), and since690 plus their role. `?read=false` narrows to unread (`true` to read), and since
680 `total` counts the filtered view, `?folder=inbox&read=false&limit=1` is the691 `total` counts the filtered view, `?folder=inbox&read=false&limit=1` is the
681 one-row unread-badge query. `PATCH /messages/{id}` flips `read` (recipient only) or692 one-row unread-badge query. `PATCH /messages/{id}` flips `read` (recipient only) or
682-moves your copy (`folder`), restoring from trash included. `DELETE` is693+moves your copy (`folder`), restoring included. `DELETE` is
683 permanent, allowed only while your copy sits in the trash (`409` otherwise),694 permanent, allowed only while your copy sits in the trash (`409` otherwise),
684 and physically removes the row once both sides have deleted theirs. Replying695 and physically removes the row once both sides have deleted theirs. Replying
685 is just sending a new message back — the frontend prefixes the subject if it696 is just sending a new message back — the frontend prefixes the subject if it
src/database.rsmodified+6 -0
@@ -102,6 +102,12 @@ const MIGRATION: &str = "
102 DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false;102 DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false;
103 DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent';103 DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent';
104 DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox';104 DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox';
105+ -- Where each side's copy sat before it was filed into archive/trash, so a
106+ -- restore lands where it came from. NONE while the copy is in its home
107+ -- folder — and on rows filed before this field existed (2026-07-23), which
108+ -- restore to the home folder just as they always did.
109+ DEFINE FIELD IF NOT EXISTS sender_origin ON message TYPE option<string>;
110+ DEFINE FIELD IF NOT EXISTS recipient_origin ON message TYPE option<string>;
105 DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender;111 DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender;
106 DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient;112 DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient;
107 113
src/domain/message.rsmodified+168 -40
@@ -1,8 +1,10 @@
1 //! One-to-one mail-style messages. A single row serves both ends: the1 //! One-to-one mail-style messages. A single row serves both ends: the
2 //! recipient's `read` flag plus one folder field per side, so each party2 //! recipient's `read` flag plus one folder field per side, so each party
3 //! files (archive/trash) and deletes their copy without touching the3 //! files (archive/trash) and deletes their copy without touching the
4-//! other's. A side that permanently deletes goes to the hidden `deleted`4+//! other's. Filing also stamps that side's origin folder, so a copy can be
5-//! folder; once both sides are `deleted` the row itself is removed.5+//! put back where it came from. A side that permanently deletes goes to the
6+//! hidden `deleted` folder; once both sides are `deleted` the row itself is
7+//! removed.
6 8
7 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};9 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
8 use ulid::Ulid;10 use ulid::Ulid;
@@ -14,13 +16,88 @@ use crate::domain::user::UserId;
14 use crate::error::{AppError, ValidationError};16 use crate::error::{AppError, ValidationError};
15 use crate::validate::{validate_optional, validate_required};17 use crate::validate::{validate_optional, validate_required};
16 18
17-/// Folders a sender may file their side into (`sent` is the default).19+/// The mailbox folders a copy can sit in — the single source of folder names
18-pub const SENDER_FOLDERS: [&str; 2] = ["sent", "trash"];20+/// for the whole stack. Nothing else may spell a folder: the DB columns, the
19-/// Folders a recipient may file their side into (`inbox` is the default).21+/// query filter and the restore stamp all pass through this enum, so a typo
20-pub const RECIPIENT_FOLDERS: [&str; 3] = ["inbox", "archive", "trash"];22+/// is a compile error rather than a silently empty folder.
21-/// The hidden "my copy is gone" folder; never a valid move target — reached23+///
22-/// only through [`Message::delete_for`].24+/// `#[surreal(untagged, rename_all = "lowercase")]` stores each variant as a
23-const DELETED_FOLDER: &str = "deleted";25+/// bare lowercase string (`"inbox"`, `"archive"`, …) in the `TYPE string`
26+/// columns, and round-trips straight back — same trick as `domain::role`.
27+#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
28+#[surreal(untagged, rename_all = "lowercase")]
29+pub enum Folder {
30+ Inbox,
31+ Sent,
32+ Archive,
33+ Trash,
34+ /// The hidden "my copy is gone" folder; never a valid move or list
35+ /// target — reached only through [`Message::delete_for`].
36+ Deleted,
37+}
38+
39+impl Folder {
40+ /// Folders a sender may file their side into (`Sent` is their home).
41+ pub const SENDER: [Folder; 2] = [Folder::Sent, Folder::Trash];
42+ /// Folders a recipient may file their side into (`Inbox` is their home).
43+ pub const RECIPIENT: [Folder; 3] = [Folder::Inbox, Folder::Archive, Folder::Trash];
44+
45+ /// The storage/wire form. Must stay in lockstep with `rename_all`.
46+ pub fn as_str(self) -> &'static str {
47+ match self {
48+ Folder::Inbox => "inbox",
49+ Folder::Sent => "sent",
50+ Folder::Archive => "archive",
51+ Folder::Trash => "trash",
52+ Folder::Deleted => "deleted",
53+ }
54+ }
55+
56+ /// Parse a caller-supplied folder name. `deleted` is internal, so it is
57+ /// rejected here like any other unknown word — a caller can never name it.
58+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
59+ match value {
60+ "inbox" => Ok(Folder::Inbox),
61+ "sent" => Ok(Folder::Sent),
62+ "archive" => Ok(Folder::Archive),
63+ "trash" => Ok(Folder::Trash),
64+ _ => Err(ValidationError::Invalid {
65+ field: "folder",
66+ reason: "must be one of: inbox, sent, archive, trash",
67+ }),
68+ }
69+ }
70+
71+ /// Where a side's copy lives when nothing has been filed away.
72+ pub fn home(is_sender: bool) -> Self {
73+ if is_sender {
74+ Folder::Sent
75+ } else {
76+ Folder::Inbox
77+ }
78+ }
79+
80+ /// The folders a side may move its copy to.
81+ pub fn allowed_for(is_sender: bool) -> &'static [Folder] {
82+ if is_sender {
83+ &Folder::SENDER
84+ } else {
85+ &Folder::RECIPIENT
86+ }
87+ }
88+
89+ /// A filed-away copy — one that has somewhere to be restored to.
90+ fn is_filed(self) -> bool {
91+ matches!(self, Folder::Archive | Folder::Trash)
92+ }
93+
94+ /// Whether this folder is worth remembering as a restore target. The
95+ /// trash is not: pulling a copy out of the trash and into the archive
96+ /// must not leave it pointing back at the trash.
97+ fn is_restore_target(self) -> bool {
98+ matches!(self, Folder::Inbox | Folder::Sent | Folder::Archive)
99+ }
100+}
24 101
25 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]102 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
26 pub struct MessageId(RecordId);103 pub struct MessageId(RecordId);
@@ -100,8 +177,12 @@ pub struct Message {
100 label: Option<MessageLabel>,177 label: Option<MessageLabel>,
101 sent_at: Timestamp,178 sent_at: Timestamp,
102 read: bool,179 read: bool,
103- sender_folder: String,180+ sender_folder: Folder,
104- recipient_folder: String,181+ recipient_folder: Folder,
182+ /// Where each side's copy sat before it was filed into archive/trash —
183+ /// the restore target. `None` while the copy sits in its home folder.
184+ sender_origin: Option<Folder>,
185+ recipient_origin: Option<Folder>,
105 }186 }
106 187
107 impl Message {188 impl Message {
@@ -142,11 +223,22 @@ impl Message {
142 }223 }
143 224
144 /// The folder `user`'s side of this message currently sits in.225 /// The folder `user`'s side of this message currently sits in.
145- pub fn folder_of(&self, user: &UserId) -> &str {226+ pub fn folder_of(&self, user: &UserId) -> Folder {
227+ if self.is_sender(user) {
228+ self.sender_folder
229+ } else {
230+ self.recipient_folder
231+ }
232+ }
233+
234+ /// Where `user`'s copy came from before it was filed away — `None` when
235+ /// it isn't filed away (or was filed by a binary older than the memory),
236+ /// in which case restoring means [`Folder::home`].
237+ pub fn origin_of(&self, user: &UserId) -> Option<Folder> {
146 if self.is_sender(user) {238 if self.is_sender(user) {
147- &self.sender_folder239+ self.sender_origin
148 } else {240 } else {
149- &self.recipient_folder241+ self.recipient_origin
150 }242 }
151 }243 }
152 244
@@ -167,8 +259,10 @@ impl Message {
167 label,259 label,
168 sent_at: Timestamp::now(),260 sent_at: Timestamp::now(),
169 read: false,261 read: false,
170- sender_folder: "sent".to_string(),262+ sender_folder: Folder::Sent,
171- recipient_folder: "inbox".to_string(),263+ recipient_folder: Folder::Inbox,
264+ sender_origin: None,
265+ recipient_origin: None,
172 };266 };
173 let created: Option<Message> = db.create(message.id.record()).content(message).await?;267 let created: Option<Message> = db.create(message.id.record()).content(message).await?;
174 created.ok_or_else(|| AppError::Internal("failed to create message".into()))268 created.ok_or_else(|| AppError::Internal("failed to create message".into()))
@@ -181,13 +275,13 @@ impl Message {
181 /// folder condition is parenthesized because trash's is an OR.275 /// folder condition is parenthesized because trash's is an OR.
182 pub async fn list_folder(276 pub async fn list_folder(
183 user: &UserId,277 user: &UserId,
184- folder: &str,278+ folder: Folder,
185 read: Option<bool>,279 read: Option<bool>,
186 db: &Database,280 db: &Database,
187 ) -> Result<Vec<Message>, AppError> {281 ) -> Result<Vec<Message>, AppError> {
188 let condition = match folder {282 let condition = match folder {
189- "sent" => "sender = $usr AND sender_folder = 'sent'",283+ Folder::Sent => "sender = $usr AND sender_folder = 'sent'",
190- "trash" => {284+ Folder::Trash => {
191 "(recipient = $usr AND recipient_folder = 'trash') \285 "(recipient = $usr AND recipient_folder = 'trash') \
192 OR (sender = $usr AND sender_folder = 'trash')"286 OR (sender = $usr AND sender_folder = 'trash')"
193 }287 }
@@ -203,7 +297,7 @@ impl Message {
203 "SELECT * FROM message WHERE ({condition}){read_clause} ORDER BY id DESC"297 "SELECT * FROM message WHERE ({condition}){read_clause} ORDER BY id DESC"
204 ))298 ))
205 .bind(("usr", user.record()))299 .bind(("usr", user.record()))
206- .bind(("folder", folder.to_string()))300+ .bind(("folder", folder.as_str().to_string()))
207 .bind(("read", read.unwrap_or_default()))301 .bind(("read", read.unwrap_or_default()))
208 .await?302 .await?
209 .check()?;303 .check()?;
@@ -220,7 +314,7 @@ impl Message {
220 let message: Option<Message> = db.select(id.record()).await?;314 let message: Option<Message> = db.select(id.record()).await?;
221 Ok(message.filter(|message| {315 Ok(message.filter(|message| {
222 (&message.sender == user || &message.recipient == user)316 (&message.sender == user || &message.recipient == user)
223- && message.folder_of(user) != DELETED_FOLDER317+ && message.folder_of(user) != Folder::Deleted
224 }))318 }))
225 }319 }
226 320
@@ -241,23 +335,41 @@ impl Message {
241 }335 }
242 336
243 /// File `user`'s side into `folder` (already validated against that337 /// File `user`'s side into `folder` (already validated against that
244- /// side's allowed set). Field-scoped for the same race reason as338+ /// side's allowed set), stamping where the copy came from so it can be
245- /// [`Message::set_read`].339+ /// restored. Only the caller's two fields are written — field-scoped for
340+ /// the same race reason as [`Message::set_read`].
341+ ///
342+ /// Filing away remembers the folder being left, so `inbox → archive →
343+ /// trash` restores to `archive` and that back to `inbox`. Two folders are
344+ /// never stamped: the trash (`trash → archive` would leave the copy
345+ /// pointing back at the discard pile — it falls back to the home folder)
346+ /// and the target itself (a no-op move keeps the memory it had). Moving
347+ /// back to a home folder clears it.
246 pub async fn move_to(348 pub async fn move_to(
247 self,349 self,
248 user: &UserId,350 user: &UserId,
249- folder: &str,351+ folder: Folder,
250 db: &Database,352 db: &Database,
251 ) -> Result<Message, AppError> {353 ) -> Result<Message, AppError> {
252- let field = if self.is_sender(user) {354+ let current = self.folder_of(user);
253- "sender_folder"355+ let (field, origin_field) = if self.is_sender(user) {
356+ ("sender_folder", "sender_origin")
254 } else {357 } else {
255- "recipient_folder"358+ ("recipient_folder", "recipient_origin")
359+ };
360+ let origin = match folder {
361+ _ if !folder.is_filed() => None,
362+ _ if current == folder => self.origin_of(user),
363+ _ if current.is_restore_target() => Some(current),
364+ _ => None,
256 };365 };
257 let mut result = db366 let mut result = db
258- .query(format!("UPDATE $id SET {field} = $folder RETURN AFTER"))367+ .query(format!(
368+ "UPDATE $id SET {field} = $folder, {origin_field} = $origin RETURN AFTER"
369+ ))
259 .bind(("id", self.id.record()))370 .bind(("id", self.id.record()))
260- .bind(("folder", folder.to_string()))371+ .bind(("folder", folder.as_str().to_string()))
372+ .bind(("origin", origin.map(|origin| origin.as_str().to_string())))
261 .await?373 .await?
262 .check()?;374 .check()?;
263 result375 result
@@ -274,18 +386,19 @@ impl Message {
274 /// post-write row, so two concurrent deletes can't leak an all-deleted386 /// post-write row, so two concurrent deletes can't leak an all-deleted
275 /// row.387 /// row.
276 pub async fn delete_for(self, user: &UserId, db: &Database) -> Result<(), AppError> {388 pub async fn delete_for(self, user: &UserId, db: &Database) -> Result<(), AppError> {
277- let field = if self.is_sender(user) {389+ let (field, origin_field) = if self.is_sender(user) {
278- "sender_folder"390+ ("sender_folder", "sender_origin")
279 } else {391 } else {
280- "recipient_folder"392+ ("recipient_folder", "recipient_origin")
281 };393 };
282 let mut result = db394 let mut result = db
283 .query(format!(395 .query(format!(
284- "UPDATE $id SET {field} = $deleted WHERE {field} = $trash RETURN AFTER"396+ "UPDATE $id SET {field} = $deleted, {origin_field} = NONE \
397+ WHERE {field} = $trash RETURN AFTER"
285 ))398 ))
286 .bind(("id", self.id.record()))399 .bind(("id", self.id.record()))
287- .bind(("deleted", DELETED_FOLDER.to_string()))400+ .bind(("deleted", Folder::Deleted.as_str().to_string()))
288- .bind(("trash", "trash".to_string()))401+ .bind(("trash", Folder::Trash.as_str().to_string()))
289 .await?402 .await?
290 .check()?;403 .check()?;
291 let Some(after) = result.take::<Vec<Message>>(0)?.into_iter().next() else {404 let Some(after) = result.take::<Vec<Message>>(0)?.into_iter().next() else {
@@ -293,7 +406,7 @@ impl Message {
293 "only messages in the trash can be permanently deleted",406 "only messages in the trash can be permanently deleted",
294 ));407 ));
295 };408 };
296- if after.sender_folder == DELETED_FOLDER && after.recipient_folder == DELETED_FOLDER {409+ if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted {
297 let _: Option<Message> = db.delete(after.id.record()).await?;410 let _: Option<Message> = db.delete(after.id.record()).await?;
298 }411 }
299 Ok(())412 Ok(())
@@ -324,11 +437,26 @@ mod tests {
324 label: None,437 label: None,
325 sent_at: Timestamp::now(),438 sent_at: Timestamp::now(),
326 read: false,439 read: false,
327- sender_folder: "sent".to_string(),440+ sender_folder: Folder::Sent,
328- recipient_folder: "archive".to_string(),441+ recipient_folder: Folder::Archive,
442+ sender_origin: None,
443+ recipient_origin: Some(Folder::Inbox),
329 };444 };
330 assert!(message.is_sender(&sender));445 assert!(message.is_sender(&sender));
331- assert_eq!(message.folder_of(&sender), "sent");446+ assert_eq!(message.folder_of(&sender), Folder::Sent);
332- assert_eq!(message.folder_of(&recipient), "archive");447+ assert_eq!(message.folder_of(&recipient), Folder::Archive);
448+ assert_eq!(message.origin_of(&sender), None);
449+ assert_eq!(message.origin_of(&recipient), Some(Folder::Inbox));
450+ }
451+
452+ #[tokio::test]
453+ async fn folder_names_parse_and_the_hidden_one_does_not() {
454+ assert_eq!(Folder::try_new("archive").unwrap(), Folder::Archive);
455+ assert!(Folder::try_new("deleted").is_err());
456+ assert!(Folder::try_new("spam").is_err());
457+ assert_eq!(Folder::home(true), Folder::Sent);
458+ assert_eq!(Folder::home(false), Folder::Inbox);
459+ assert!(!Folder::allowed_for(true).contains(&Folder::Archive));
460+ assert!(Folder::allowed_for(false).contains(&Folder::Archive));
333 }461 }
334 }462 }
src/lib.rsmodified+1 -1
@@ -45,7 +45,7 @@ use crate::state::AppState;
45 (name = "chat", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chat_conversations` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHAT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chat/conversations/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chat/conversations/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chat_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no AI service connected, sending answers `503` and writes nothing"),45 (name = "chat", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chat_conversations` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHAT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chat/conversations/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chat/conversations/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chat_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no AI service connected, sending answers `503` and writes nothing"),
46 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"),46 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"),
47 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"),47 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"),
48- (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`trash`. `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),48+ (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),
49 (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts"),49 (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts"),
50 (name = "courses", description = "Courses — kind `course` (regular class), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. A course with anyone still enrolled refuses deletion (409) — empty the roster first"),50 (name = "courses", description = "Courses — kind `course` (regular class), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. A course with anyone still enrolled refuses deletion (409) — empty the roster first"),
51 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),51 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
src/web/messages.rsmodified+35 -31
@@ -10,8 +10,7 @@ use utoipa_axum::routes;
10 10
11 use crate::database::Database;11 use crate::database::Database;
12 use crate::domain::message::{12 use crate::domain::message::{
13- Message, MessageBody, MessageId, MessageLabel, MessageSubject, RECIPIENT_FOLDERS,13+ Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject,
14- SENDER_FOLDERS,
15 };14 };
16 use crate::domain::user::{User, UserId};15 use crate::domain::user::{User, UserId};
17 use crate::error::{AppError, ErrorResponse, ValidationError};16 use crate::error::{AppError, ErrorResponse, ValidationError};
@@ -26,10 +25,6 @@ pub fn routes() -> OpenApiRouter<AppState> {
26 .routes(routes!(update_message, delete_message))25 .routes(routes!(update_message, delete_message))
27 }26 }
28 27
29-/// The folders a message list can show. `inbox` and `archive` hold received
30-/// messages, `sent` holds sent ones, `trash` holds both sides' trashed copies.
31-const FOLDERS: [&str; 4] = ["inbox", "sent", "archive", "trash"];
32-
33 #[derive(Deserialize, ToSchema)]28 #[derive(Deserialize, ToSchema)]
34 struct SendMessage {29 struct SendMessage {
35 /// The receiving user's id (find people via `GET /users/search`).30 /// The receiving user's id (find people via `GET /users/search`).
@@ -50,8 +45,8 @@ struct UpdateMessage {
50 /// Mark read (`true`) or unread (`false`). Recipient only.45 /// Mark read (`true`) or unread (`false`). Recipient only.
51 read: Option<bool>,46 read: Option<bool>,
52 /// Move the caller's copy: a recipient may file into `inbox`, `archive`,47 /// Move the caller's copy: a recipient may file into `inbox`, `archive`,
53- /// or `trash`; a sender into `sent` or `trash`. Restoring from the trash48+ /// or `trash`; a sender into `sent` or `trash`. Restoring is moving back
54- /// is moving back to `inbox`/`sent`.49+ /// to the copy's `previous_folder`.
55 #[schema(example = "archive")]50 #[schema(example = "archive")]
56 folder: Option<String>,51 folder: Option<String>,
57 }52 }
@@ -87,6 +82,12 @@ struct MessageResponse {
87 read: bool,82 read: bool,
88 #[schema(example = "inbox")]83 #[schema(example = "inbox")]
89 folder: String,84 folder: String,
85+ /// Where the caller's copy sat before it was filed into `archive`/`trash`
86+ /// — `PATCH` `folder` back to this to restore it. `null` whenever the copy
87+ /// is not filed away, and on copies filed before this was recorded; both
88+ /// mean "restore to `inbox`" (`sent` for the sender's copy).
89+ #[schema(example = "inbox")]
90+ previous_folder: Option<String>,
90 }91 }
91 92
92 /// `PersonRef` plus role, keyed by user id — messages show *who* wrote and93 /// `PersonRef` plus role, keyed by user id — messages show *who* wrote and
@@ -148,7 +149,10 @@ impl MessageResponse {
148 label: message.get_label().map(|label| label.as_str().to_string()),149 label: message.get_label().map(|label| label.as_str().to_string()),
149 sent_at: message.get_sent_at().as_millis(),150 sent_at: message.get_sent_at().as_millis(),
150 read: message.is_read(),151 read: message.is_read(),
151- folder: message.folder_of(caller).to_string(),152+ folder: message.folder_of(caller).as_str().to_string(),
153+ previous_folder: message
154+ .origin_of(caller)
155+ .map(|folder| folder.as_str().to_string()),
152 }156 }
153 }157 }
154 }158 }
@@ -231,15 +235,12 @@ async fn list(
231 Query(page): Query<PageParams>,235 Query(page): Query<PageParams>,
232 ) -> Result<Json<Page<MessageResponse>>, AppError> {236 ) -> Result<Json<Page<MessageResponse>>, AppError> {
233 let (limit, offset) = page.resolve()?;237 let (limit, offset) = page.resolve()?;
234- let folder = filter.folder.unwrap_or_else(|| "inbox".to_string());238+ let folder = match filter.folder {
235- if !FOLDERS.contains(&folder.as_str()) {239+ Some(ref folder) => Folder::try_new(folder)?,
236- return Err(AppError::Validation(ValidationError::Invalid {240+ None => Folder::Inbox,
237- field: "folder",241+ };
238- reason: "must be one of: inbox, sent, archive, trash",
239- }));
240- }
241 242
242- let messages = Message::list_folder(user.get_id(), &folder, filter.read, &st.db).await?;243+ let messages = Message::list_folder(user.get_id(), folder, filter.read, &st.db).await?;
243 let total = messages.len() as i64;244 let total = messages.len() as i64;
244 let slice = paginate(&messages, limit, offset);245 let slice = paginate(&messages, limit, offset);
245 let people = load_people(slice, &st.db).await?;246 let people = load_people(slice, &st.db).await?;
@@ -253,7 +254,10 @@ async fn list(
253 /// Update the caller's view of a message: flip the read flag (recipient254 /// Update the caller's view of a message: flip the read flag (recipient
254 /// only) and/or move the caller's copy between folders. Each side files255 /// only) and/or move the caller's copy between folders. Each side files
255 /// independently — archiving or trashing never touches the other party's256 /// independently — archiving or trashing never touches the other party's
256-/// copy. Omitted fields change nothing.257+/// copy. Filing into `archive`/`trash` records the folder left behind as the
258+/// copy's `previous_folder`, so restoring is a move back to that value
259+/// (`inbox`, or `sent` for the sender's copy, when it is `null`). Omitted
260+/// fields change nothing.
257 #[utoipa::path(261 #[utoipa::path(
258 patch,262 patch,
259 path = "/{id}",263 path = "/{id}",
@@ -286,23 +290,23 @@ async fn update_message(
286 "only the recipient can change the read flag",290 "only the recipient can change the read flag",
287 ));291 ));
288 }292 }
289- if let Some(ref folder) = req.folder {293+ let folder = match req.folder {
290- let allowed: &[&str] = if message.is_sender(user.get_id()) {294+ Some(ref folder) => {
291- &SENDER_FOLDERS295+ let folder = Folder::try_new(folder)?;
292- } else {296+ if !Folder::allowed_for(message.is_sender(user.get_id())).contains(&folder) {
293- &RECIPIENT_FOLDERS297+ return Err(AppError::Validation(ValidationError::Invalid {
294- };298+ field: "folder",
295- if !allowed.contains(&folder.as_str()) {299+ reason: "not a folder this side of the message can move to",
296- return Err(AppError::Validation(ValidationError::Invalid {300+ }));
297- field: "folder",301+ }
298- reason: "not a folder this side of the message can move to",302+ Some(folder)
299- }));
300 }303 }
301- }304+ None => None,
305+ };
302 if let Some(read) = req.read {306 if let Some(read) = req.read {
303 message = message.set_read(read, &st.db).await?;307 message = message.set_read(read, &st.db).await?;
304 }308 }
305- if let Some(ref folder) = req.folder {309+ if let Some(folder) = folder {
306 message = message.move_to(user.get_id(), folder, &st.db).await?;310 message = message.move_to(user.get_id(), folder, &st.db).await?;
307 }311 }
308 312
tests/integration.rsmodified+86 -0
@@ -11947,6 +11947,92 @@ async fn messages_flow_through_folders_per_side() {
11947 assert!(rows.is_empty(), "both-sides-deleted row is removed");11947 assert!(rows.is_empty(), "both-sides-deleted row is removed");
11948 }11948 }
11949 11949
11950+/// A filed copy remembers the folder it left, so restoring lands where it
11951+/// came from instead of always in the inbox.
11952+#[tokio::test]
11953+async fn messages_remember_the_folder_a_filed_copy_came_from() {
11954+ let (app, db) = app_and_db().await;
11955+ let ali = login(&app, "ali").await; // student
11956+ let hoca = login_as(&app, &db, "hoca", "teacher").await;
11957+ let hoca_id = me_id(&app, &hoca).await;
11958+
11959+ let res = send(
11960+ &app,
11961+ "POST",
11962+ "/messages",
11963+ Some(&ali),
11964+ Some(json!({ "recipient_id": hoca_id, "subject": "etüt" })),
11965+ )
11966+ .await;
11967+ let msg_id = res.body["id"].as_str().expect("message id").to_string();
11968+ assert!(
11969+ res.body["previous_folder"].is_null(),
11970+ "a home copy has none"
11971+ );
11972+
11973+ let file = |actor: &'static str, folder: &'static str| {
11974+ let app = app.clone();
11975+ let (ali, hoca) = (ali.clone(), hoca.clone());
11976+ let msg_id = msg_id.clone();
11977+ async move {
11978+ let session = if actor == "ali" { ali } else { hoca };
11979+ let res = send(
11980+ &app,
11981+ "PATCH",
11982+ &format!("/messages/{msg_id}"),
11983+ Some(&session),
11984+ Some(json!({ "folder": folder })),
11985+ )
11986+ .await;
11987+ assert_eq!(res.status, StatusCode::OK, "move to {folder}");
11988+ res.body["previous_folder"].clone()
11989+ }
11990+ };
11991+
11992+ // inbox → archive → trash walks the memory one hop at a time.
11993+ assert_eq!(file("hoca", "archive").await, json!("inbox"));
11994+ assert_eq!(file("hoca", "trash").await, json!("archive"));
11995+ // Restoring to the remembered folder puts the copy back there — with no
11996+ // memory of its own, since it came out of the trash and the trash is
11997+ // never a restore target. It falls back to the home folder.
11998+ assert!(file("hoca", "archive").await.is_null());
11999+ let archive = send(&app, "GET", "/messages?folder=archive", Some(&hoca), None).await;
12000+ assert_eq!(common::items(&archive.body).len(), 1);
12001+ // Back home clears the stamp for good.
12002+ assert!(file("hoca", "inbox").await.is_null());
12003+
12004+ // A no-op move keeps the memory it already had.
12005+ assert_eq!(file("hoca", "archive").await, json!("inbox"));
12006+ assert_eq!(file("hoca", "archive").await, json!("inbox"));
12007+
12008+ // The sender's side has only one home, so its trash always points at it.
12009+ assert_eq!(file("ali", "trash").await, json!("sent"));
12010+ // The two sides' memories are independent.
12011+ let trash = send(&app, "GET", "/messages?folder=trash", Some(&ali), None).await;
12012+ assert_eq!(common::items(&trash.body)[0]["previous_folder"], "sent");
12013+ let archive = send(&app, "GET", "/messages?folder=archive", Some(&hoca), None).await;
12014+ assert_eq!(common::items(&archive.body)[0]["previous_folder"], "inbox");
12015+
12016+ // Deleting drops the stamp with the rest of that side's copy.
12017+ let res = send(
12018+ &app,
12019+ "DELETE",
12020+ &format!("/messages/{msg_id}"),
12021+ Some(&ali),
12022+ None,
12023+ )
12024+ .await;
12025+ assert_eq!(res.status, StatusCode::NO_CONTENT);
12026+ let mut result = db
12027+ .query("SELECT VALUE sender_origin FROM message")
12028+ .await
12029+ .expect("read origins")
12030+ .check()
12031+ .expect("read origins check");
12032+ let origins: Vec<Option<String>> = result.take(0).expect("origin rows");
12033+ assert_eq!(origins, vec![None], "the deleted side keeps no origin");
12034+}
12035+
11950 #[tokio::test]12036 #[tokio::test]
11951 async fn messages_guard_parties_recipients_and_folders() {12037 async fn messages_guard_parties_recipients_and_folders() {
11952 let (app, db) = app_and_db().await;12038 let (app, db) = app_and_db().await;