From 79189b8499bb9246c044e3659f24c998e822abf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 23 Jul 2026 17:46:36 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(messages):=20remember=20where?= =?UTF-8?q?=20a=20filed=20copy=20came=20from?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.md | 13 ++- src/database.rs | 6 ++ src/domain/message.rs | 208 ++++++++++++++++++++++++++++++++++-------- src/lib.rs | 2 +- src/web/messages.rs | 66 +++++++------- tests/integration.rs | 86 +++++++++++++++++ 6 files changed, 308 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index d042d50..76fc67f 100644 --- a/README.md +++ b/README.md @@ -673,13 +673,24 @@ but each **owns their copy independently**: the recipient's moves through as a read receipt); the sender's moves through `sent` → `trash`. Filing or deleting your copy never changes the other side's view. +Every copy remembers where it was filed from, so it can go back there. Moving +into `archive`/`trash` stamps the folder you left onto the copy's +`previous_folder`, and restoring is a `PATCH` of `folder` back to that value: +an inbox message you archive and then trash returns to `archive`, and from +there to `inbox`. Two folders are never stamped — the trash itself (pulling a +copy out of the trash must not leave it pointing back at the discard pile) and +the folder you are already in — and moving back to `inbox`/`sent` clears the +stamp. `previous_folder` is therefore `null` for any copy sitting in its home +folder, and for copies filed before the field existed; both mean "restore to +`inbox`" (`sent` for the sender's copy). + Listing is per folder — `GET /messages?folder=` with `inbox` (default), `sent`, `archive`, or `trash` (trash shows both received and sent copies you trashed) — newest first, paged, with sender/recipient rendered as person refs plus their role. `?read=false` narrows to unread (`true` to read), and since `total` counts the filtered view, `?folder=inbox&read=false&limit=1` is the one-row unread-badge query. `PATCH /messages/{id}` flips `read` (recipient only) or -moves your copy (`folder`), restoring from trash included. `DELETE` is +moves your copy (`folder`), restoring included. `DELETE` is permanent, allowed only while your copy sits in the trash (`409` otherwise), and physically removes the row once both sides have deleted theirs. Replying is just sending a new message back — the frontend prefixes the subject if it diff --git a/src/database.rs b/src/database.rs index 37ac363..455e858 100644 --- a/src/database.rs +++ b/src/database.rs @@ -102,6 +102,12 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false; DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent'; DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox'; + -- Where each side's copy sat before it was filed into archive/trash, so a + -- restore lands where it came from. NONE while the copy is in its home + -- folder — and on rows filed before this field existed (2026-07-23), which + -- restore to the home folder just as they always did. + DEFINE FIELD IF NOT EXISTS sender_origin ON message TYPE option; + DEFINE FIELD IF NOT EXISTS recipient_origin ON message TYPE option; DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender; DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient; diff --git a/src/domain/message.rs b/src/domain/message.rs index dc149b2..2d11be8 100644 --- a/src/domain/message.rs +++ b/src/domain/message.rs @@ -1,8 +1,10 @@ //! One-to-one mail-style messages. A single row serves both ends: the //! recipient's `read` flag plus one folder field per side, so each party //! files (archive/trash) and deletes their copy without touching the -//! other's. A side that permanently deletes goes to the hidden `deleted` -//! folder; once both sides are `deleted` the row itself is removed. +//! other's. Filing also stamps that side's origin folder, so a copy can be +//! put back where it came from. A side that permanently deletes goes to the +//! hidden `deleted` folder; once both sides are `deleted` the row itself is +//! removed. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; @@ -14,13 +16,88 @@ use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; -/// Folders a sender may file their side into (`sent` is the default). -pub const SENDER_FOLDERS: [&str; 2] = ["sent", "trash"]; -/// Folders a recipient may file their side into (`inbox` is the default). -pub const RECIPIENT_FOLDERS: [&str; 3] = ["inbox", "archive", "trash"]; -/// The hidden "my copy is gone" folder; never a valid move target — reached -/// only through [`Message::delete_for`]. -const DELETED_FOLDER: &str = "deleted"; +/// The mailbox folders a copy can sit in — the single source of folder names +/// for the whole stack. Nothing else may spell a folder: the DB columns, the +/// query filter and the restore stamp all pass through this enum, so a typo +/// is a compile error rather than a silently empty folder. +/// +/// `#[surreal(untagged, rename_all = "lowercase")]` stores each variant as a +/// bare lowercase string (`"inbox"`, `"archive"`, …) in the `TYPE string` +/// columns, and round-trips straight back — same trick as `domain::role`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +#[surreal(untagged, rename_all = "lowercase")] +pub enum Folder { + Inbox, + Sent, + Archive, + Trash, + /// The hidden "my copy is gone" folder; never a valid move or list + /// target — reached only through [`Message::delete_for`]. + Deleted, +} + +impl Folder { + /// Folders a sender may file their side into (`Sent` is their home). + pub const SENDER: [Folder; 2] = [Folder::Sent, Folder::Trash]; + /// Folders a recipient may file their side into (`Inbox` is their home). + pub const RECIPIENT: [Folder; 3] = [Folder::Inbox, Folder::Archive, Folder::Trash]; + + /// The storage/wire form. Must stay in lockstep with `rename_all`. + pub fn as_str(self) -> &'static str { + match self { + Folder::Inbox => "inbox", + Folder::Sent => "sent", + Folder::Archive => "archive", + Folder::Trash => "trash", + Folder::Deleted => "deleted", + } + } + + /// Parse a caller-supplied folder name. `deleted` is internal, so it is + /// rejected here like any other unknown word — a caller can never name it. + pub fn try_new(value: &str) -> Result { + match value { + "inbox" => Ok(Folder::Inbox), + "sent" => Ok(Folder::Sent), + "archive" => Ok(Folder::Archive), + "trash" => Ok(Folder::Trash), + _ => Err(ValidationError::Invalid { + field: "folder", + reason: "must be one of: inbox, sent, archive, trash", + }), + } + } + + /// Where a side's copy lives when nothing has been filed away. + pub fn home(is_sender: bool) -> Self { + if is_sender { + Folder::Sent + } else { + Folder::Inbox + } + } + + /// The folders a side may move its copy to. + pub fn allowed_for(is_sender: bool) -> &'static [Folder] { + if is_sender { + &Folder::SENDER + } else { + &Folder::RECIPIENT + } + } + + /// A filed-away copy — one that has somewhere to be restored to. + fn is_filed(self) -> bool { + matches!(self, Folder::Archive | Folder::Trash) + } + + /// Whether this folder is worth remembering as a restore target. The + /// trash is not: pulling a copy out of the trash and into the archive + /// must not leave it pointing back at the trash. + fn is_restore_target(self) -> bool { + matches!(self, Folder::Inbox | Folder::Sent | Folder::Archive) + } +} #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct MessageId(RecordId); @@ -100,8 +177,12 @@ pub struct Message { label: Option, sent_at: Timestamp, read: bool, - sender_folder: String, - recipient_folder: String, + sender_folder: Folder, + recipient_folder: Folder, + /// Where each side's copy sat before it was filed into archive/trash — + /// the restore target. `None` while the copy sits in its home folder. + sender_origin: Option, + recipient_origin: Option, } impl Message { @@ -142,11 +223,22 @@ impl Message { } /// The folder `user`'s side of this message currently sits in. - pub fn folder_of(&self, user: &UserId) -> &str { + pub fn folder_of(&self, user: &UserId) -> Folder { + if self.is_sender(user) { + self.sender_folder + } else { + self.recipient_folder + } + } + + /// Where `user`'s copy came from before it was filed away — `None` when + /// it isn't filed away (or was filed by a binary older than the memory), + /// in which case restoring means [`Folder::home`]. + pub fn origin_of(&self, user: &UserId) -> Option { if self.is_sender(user) { - &self.sender_folder + self.sender_origin } else { - &self.recipient_folder + self.recipient_origin } } @@ -167,8 +259,10 @@ impl Message { label, sent_at: Timestamp::now(), read: false, - sender_folder: "sent".to_string(), - recipient_folder: "inbox".to_string(), + sender_folder: Folder::Sent, + recipient_folder: Folder::Inbox, + sender_origin: None, + recipient_origin: None, }; let created: Option = db.create(message.id.record()).content(message).await?; created.ok_or_else(|| AppError::Internal("failed to create message".into())) @@ -181,13 +275,13 @@ impl Message { /// folder condition is parenthesized because trash's is an OR. pub async fn list_folder( user: &UserId, - folder: &str, + folder: Folder, read: Option, db: &Database, ) -> Result, AppError> { let condition = match folder { - "sent" => "sender = $usr AND sender_folder = 'sent'", - "trash" => { + Folder::Sent => "sender = $usr AND sender_folder = 'sent'", + Folder::Trash => { "(recipient = $usr AND recipient_folder = 'trash') \ OR (sender = $usr AND sender_folder = 'trash')" } @@ -203,7 +297,7 @@ impl Message { "SELECT * FROM message WHERE ({condition}){read_clause} ORDER BY id DESC" )) .bind(("usr", user.record())) - .bind(("folder", folder.to_string())) + .bind(("folder", folder.as_str().to_string())) .bind(("read", read.unwrap_or_default())) .await? .check()?; @@ -220,7 +314,7 @@ impl Message { let message: Option = db.select(id.record()).await?; Ok(message.filter(|message| { (&message.sender == user || &message.recipient == user) - && message.folder_of(user) != DELETED_FOLDER + && message.folder_of(user) != Folder::Deleted })) } @@ -241,23 +335,41 @@ impl Message { } /// File `user`'s side into `folder` (already validated against that - /// side's allowed set). Field-scoped for the same race reason as - /// [`Message::set_read`]. + /// side's allowed set), stamping where the copy came from so it can be + /// restored. Only the caller's two fields are written — field-scoped for + /// the same race reason as [`Message::set_read`]. + /// + /// Filing away remembers the folder being left, so `inbox → archive → + /// trash` restores to `archive` and that back to `inbox`. Two folders are + /// never stamped: the trash (`trash → archive` would leave the copy + /// pointing back at the discard pile — it falls back to the home folder) + /// and the target itself (a no-op move keeps the memory it had). Moving + /// back to a home folder clears it. pub async fn move_to( self, user: &UserId, - folder: &str, + folder: Folder, db: &Database, ) -> Result { - let field = if self.is_sender(user) { - "sender_folder" + let current = self.folder_of(user); + let (field, origin_field) = if self.is_sender(user) { + ("sender_folder", "sender_origin") } else { - "recipient_folder" + ("recipient_folder", "recipient_origin") + }; + let origin = match folder { + _ if !folder.is_filed() => None, + _ if current == folder => self.origin_of(user), + _ if current.is_restore_target() => Some(current), + _ => None, }; let mut result = db - .query(format!("UPDATE $id SET {field} = $folder RETURN AFTER")) + .query(format!( + "UPDATE $id SET {field} = $folder, {origin_field} = $origin RETURN AFTER" + )) .bind(("id", self.id.record())) - .bind(("folder", folder.to_string())) + .bind(("folder", folder.as_str().to_string())) + .bind(("origin", origin.map(|origin| origin.as_str().to_string()))) .await? .check()?; result @@ -274,18 +386,19 @@ impl Message { /// post-write row, so two concurrent deletes can't leak an all-deleted /// row. pub async fn delete_for(self, user: &UserId, db: &Database) -> Result<(), AppError> { - let field = if self.is_sender(user) { - "sender_folder" + let (field, origin_field) = if self.is_sender(user) { + ("sender_folder", "sender_origin") } else { - "recipient_folder" + ("recipient_folder", "recipient_origin") }; let mut result = db .query(format!( - "UPDATE $id SET {field} = $deleted WHERE {field} = $trash RETURN AFTER" + "UPDATE $id SET {field} = $deleted, {origin_field} = NONE \ + WHERE {field} = $trash RETURN AFTER" )) .bind(("id", self.id.record())) - .bind(("deleted", DELETED_FOLDER.to_string())) - .bind(("trash", "trash".to_string())) + .bind(("deleted", Folder::Deleted.as_str().to_string())) + .bind(("trash", Folder::Trash.as_str().to_string())) .await? .check()?; let Some(after) = result.take::>(0)?.into_iter().next() else { @@ -293,7 +406,7 @@ impl Message { "only messages in the trash can be permanently deleted", )); }; - if after.sender_folder == DELETED_FOLDER && after.recipient_folder == DELETED_FOLDER { + if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted { let _: Option = db.delete(after.id.record()).await?; } Ok(()) @@ -324,11 +437,26 @@ mod tests { label: None, sent_at: Timestamp::now(), read: false, - sender_folder: "sent".to_string(), - recipient_folder: "archive".to_string(), + sender_folder: Folder::Sent, + recipient_folder: Folder::Archive, + sender_origin: None, + recipient_origin: Some(Folder::Inbox), }; assert!(message.is_sender(&sender)); - assert_eq!(message.folder_of(&sender), "sent"); - assert_eq!(message.folder_of(&recipient), "archive"); + assert_eq!(message.folder_of(&sender), Folder::Sent); + assert_eq!(message.folder_of(&recipient), Folder::Archive); + assert_eq!(message.origin_of(&sender), None); + assert_eq!(message.origin_of(&recipient), Some(Folder::Inbox)); + } + + #[tokio::test] + async fn folder_names_parse_and_the_hidden_one_does_not() { + assert_eq!(Folder::try_new("archive").unwrap(), Folder::Archive); + assert!(Folder::try_new("deleted").is_err()); + assert!(Folder::try_new("spam").is_err()); + assert_eq!(Folder::home(true), Folder::Sent); + assert_eq!(Folder::home(false), Folder::Inbox); + assert!(!Folder::allowed_for(true).contains(&Folder::Archive)); + assert!(Folder::allowed_for(false).contains(&Folder::Archive)); } } diff --git a/src/lib.rs b/src/lib.rs index 77627dd..fca0a75 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -45,7 +45,7 @@ use crate::state::AppState; (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"), (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"), (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`)"), - (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"), + (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"), (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"), (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"), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), diff --git a/src/web/messages.rs b/src/web/messages.rs index 476d29b..12998f5 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -10,8 +10,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::message::{ - Message, MessageBody, MessageId, MessageLabel, MessageSubject, RECIPIENT_FOLDERS, - SENDER_FOLDERS, + Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject, }; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -26,10 +25,6 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(update_message, delete_message)) } -/// The folders a message list can show. `inbox` and `archive` hold received -/// messages, `sent` holds sent ones, `trash` holds both sides' trashed copies. -const FOLDERS: [&str; 4] = ["inbox", "sent", "archive", "trash"]; - #[derive(Deserialize, ToSchema)] struct SendMessage { /// The receiving user's id (find people via `GET /users/search`). @@ -50,8 +45,8 @@ struct UpdateMessage { /// Mark read (`true`) or unread (`false`). Recipient only. read: Option, /// Move the caller's copy: a recipient may file into `inbox`, `archive`, - /// or `trash`; a sender into `sent` or `trash`. Restoring from the trash - /// is moving back to `inbox`/`sent`. + /// or `trash`; a sender into `sent` or `trash`. Restoring is moving back + /// to the copy's `previous_folder`. #[schema(example = "archive")] folder: Option, } @@ -87,6 +82,12 @@ struct MessageResponse { read: bool, #[schema(example = "inbox")] folder: String, + /// Where the caller's copy sat before it was filed into `archive`/`trash` + /// — `PATCH` `folder` back to this to restore it. `null` whenever the copy + /// is not filed away, and on copies filed before this was recorded; both + /// mean "restore to `inbox`" (`sent` for the sender's copy). + #[schema(example = "inbox")] + previous_folder: Option, } /// `PersonRef` plus role, keyed by user id — messages show *who* wrote and @@ -148,7 +149,10 @@ impl MessageResponse { label: message.get_label().map(|label| label.as_str().to_string()), sent_at: message.get_sent_at().as_millis(), read: message.is_read(), - folder: message.folder_of(caller).to_string(), + folder: message.folder_of(caller).as_str().to_string(), + previous_folder: message + .origin_of(caller) + .map(|folder| folder.as_str().to_string()), } } } @@ -231,15 +235,12 @@ async fn list( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let folder = filter.folder.unwrap_or_else(|| "inbox".to_string()); - if !FOLDERS.contains(&folder.as_str()) { - return Err(AppError::Validation(ValidationError::Invalid { - field: "folder", - reason: "must be one of: inbox, sent, archive, trash", - })); - } + let folder = match filter.folder { + Some(ref folder) => Folder::try_new(folder)?, + None => Folder::Inbox, + }; - let messages = Message::list_folder(user.get_id(), &folder, filter.read, &st.db).await?; + let messages = Message::list_folder(user.get_id(), folder, filter.read, &st.db).await?; let total = messages.len() as i64; let slice = paginate(&messages, limit, offset); let people = load_people(slice, &st.db).await?; @@ -253,7 +254,10 @@ async fn list( /// Update the caller's view of a message: flip the read flag (recipient /// only) and/or move the caller's copy between folders. Each side files /// independently — archiving or trashing never touches the other party's -/// copy. Omitted fields change nothing. +/// copy. Filing into `archive`/`trash` records the folder left behind as the +/// copy's `previous_folder`, so restoring is a move back to that value +/// (`inbox`, or `sent` for the sender's copy, when it is `null`). Omitted +/// fields change nothing. #[utoipa::path( patch, path = "/{id}", @@ -286,23 +290,23 @@ async fn update_message( "only the recipient can change the read flag", )); } - if let Some(ref folder) = req.folder { - let allowed: &[&str] = if message.is_sender(user.get_id()) { - &SENDER_FOLDERS - } else { - &RECIPIENT_FOLDERS - }; - if !allowed.contains(&folder.as_str()) { - return Err(AppError::Validation(ValidationError::Invalid { - field: "folder", - reason: "not a folder this side of the message can move to", - })); + let folder = match req.folder { + Some(ref folder) => { + let folder = Folder::try_new(folder)?; + if !Folder::allowed_for(message.is_sender(user.get_id())).contains(&folder) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "folder", + reason: "not a folder this side of the message can move to", + })); + } + Some(folder) } - } + None => None, + }; if let Some(read) = req.read { message = message.set_read(read, &st.db).await?; } - if let Some(ref folder) = req.folder { + if let Some(folder) = folder { message = message.move_to(user.get_id(), folder, &st.db).await?; } diff --git a/tests/integration.rs b/tests/integration.rs index ad8214b..e7162d6 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -11947,6 +11947,92 @@ async fn messages_flow_through_folders_per_side() { assert!(rows.is_empty(), "both-sides-deleted row is removed"); } +/// A filed copy remembers the folder it left, so restoring lands where it +/// came from instead of always in the inbox. +#[tokio::test] +async fn messages_remember_the_folder_a_filed_copy_came_from() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; // student + let hoca = login_as(&app, &db, "hoca", "teacher").await; + let hoca_id = me_id(&app, &hoca).await; + + let res = send( + &app, + "POST", + "/messages", + Some(&ali), + Some(json!({ "recipient_id": hoca_id, "subject": "etüt" })), + ) + .await; + let msg_id = res.body["id"].as_str().expect("message id").to_string(); + assert!( + res.body["previous_folder"].is_null(), + "a home copy has none" + ); + + let file = |actor: &'static str, folder: &'static str| { + let app = app.clone(); + let (ali, hoca) = (ali.clone(), hoca.clone()); + let msg_id = msg_id.clone(); + async move { + let session = if actor == "ali" { ali } else { hoca }; + let res = send( + &app, + "PATCH", + &format!("/messages/{msg_id}"), + Some(&session), + Some(json!({ "folder": folder })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "move to {folder}"); + res.body["previous_folder"].clone() + } + }; + + // inbox → archive → trash walks the memory one hop at a time. + assert_eq!(file("hoca", "archive").await, json!("inbox")); + assert_eq!(file("hoca", "trash").await, json!("archive")); + // Restoring to the remembered folder puts the copy back there — with no + // memory of its own, since it came out of the trash and the trash is + // never a restore target. It falls back to the home folder. + assert!(file("hoca", "archive").await.is_null()); + let archive = send(&app, "GET", "/messages?folder=archive", Some(&hoca), None).await; + assert_eq!(common::items(&archive.body).len(), 1); + // Back home clears the stamp for good. + assert!(file("hoca", "inbox").await.is_null()); + + // A no-op move keeps the memory it already had. + assert_eq!(file("hoca", "archive").await, json!("inbox")); + assert_eq!(file("hoca", "archive").await, json!("inbox")); + + // The sender's side has only one home, so its trash always points at it. + assert_eq!(file("ali", "trash").await, json!("sent")); + // The two sides' memories are independent. + let trash = send(&app, "GET", "/messages?folder=trash", Some(&ali), None).await; + assert_eq!(common::items(&trash.body)[0]["previous_folder"], "sent"); + let archive = send(&app, "GET", "/messages?folder=archive", Some(&hoca), None).await; + assert_eq!(common::items(&archive.body)[0]["previous_folder"], "inbox"); + + // Deleting drops the stamp with the rest of that side's copy. + let res = send( + &app, + "DELETE", + &format!("/messages/{msg_id}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + let mut result = db + .query("SELECT VALUE sender_origin FROM message") + .await + .expect("read origins") + .check() + .expect("read origins check"); + let origins: Vec> = result.take(0).expect("origin rows"); + assert_eq!(origins, vec![None], "the deleted side keeps no origin"); +} + #[tokio::test] async fn messages_guard_parties_recipients_and_folders() { let (app, db) = app_and_db().await;