From 6b0ddff523ccf307205e59e47a35e14672b152e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 29 Aug 2026 23:47:32 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(web):=20the=20admin=20can=20wr?= =?UTF-8?q?ite=20to=20the=20workspace,=20and=20it=20rides=20the=20queue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0020_a_notice_owes_no_rule_either.sql | 38 ++++ crates/izlek-core/src/detail.rs | 5 + crates/izlek-core/src/mail.rs | 1 + crates/izlek-core/src/store/mod.rs | 15 ++ crates/izlek-core/src/store/turso_store.rs | 31 ++++ crates/izlek-core/tests/store.rs | 35 +++- crates/izlek-web/src/i18n.rs | 21 +++ crates/izlek-web/src/logs.rs | 2 + crates/izlek-web/src/server.rs | 13 ++ crates/izlek-web/src/settings.rs | 95 +++++++++- crates/izlek-web/tests/http.rs | 172 ++++++++++++++++++ 11 files changed, 424 insertions(+), 4 deletions(-) create mode 100644 crates/izlek-core/migrations/0020_a_notice_owes_no_rule_either.sql diff --git a/crates/izlek-core/migrations/0020_a_notice_owes_no_rule_either.sql b/crates/izlek-core/migrations/0020_a_notice_owes_no_rule_either.sql new file mode 100644 index 0000000..7502abc --- /dev/null +++ b/crates/izlek-core/migrations/0020_a_notice_owes_no_rule_either.sql @@ -0,0 +1,38 @@ +-- A notice is an admin's own mail to a member — same shape as an invite: +-- no rule, no event, no task, just a subject and a body. 0012's CHECK only +-- named 'invite' alongside 'rule', so a 'notice' row would fail it. SQLite +-- cannot widen a CHECK in place, so the table is rebuilt again, same shape +-- of migration as 0012/0013. +CREATE TABLE mail_send_next ( + id TEXT PRIMARY KEY, + rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE, + event_id TEXT, + task_id TEXT REFERENCES task(id), + recipient TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')), + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + claimed_at TEXT NOT NULL, + next_attempt_at TEXT, + sent_at TEXT, + kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite', 'notice')), + subject TEXT, + body TEXT, + CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)), + CHECK ((kind IN ('invite', 'notice')) = (subject IS NOT NULL AND body IS NOT NULL)) +); + +INSERT INTO mail_send_next +SELECT id, rule_id, event_id, task_id, recipient, state, attempts, last_error, + claimed_at, next_attempt_at, sent_at, kind, subject, body +FROM mail_send; + +DROP INDEX IF EXISTS mail_send_once; +DROP INDEX IF EXISTS mail_send_owed; +DROP INDEX IF EXISTS mail_send_by_rule; +DROP TABLE mail_send; +ALTER TABLE mail_send_next RENAME TO mail_send; + +CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient); +CREATE INDEX mail_send_owed ON mail_send(next_attempt_at); +CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at); diff --git a/crates/izlek-core/src/detail.rs b/crates/izlek-core/src/detail.rs index c7ebed8..e2cad83 100644 --- a/crates/izlek-core/src/detail.rs +++ b/crates/izlek-core/src/detail.rs @@ -158,6 +158,8 @@ pub enum ActivityKind { RuleDeleted, FileAdded, FileRemoved, + /// An admin's own mail to one or more members, outside any rule. + MessageSent, /// A kind written by a newer version than the one reading it. The stored /// detail is shown as-is rather than dropping the row. Other(String), @@ -186,6 +188,7 @@ impl ActivityKind { ActivityKind::RuleDeleted => "rule_deleted", ActivityKind::FileAdded => "file_added", ActivityKind::FileRemoved => "file_removed", + ActivityKind::MessageSent => "message_sent", ActivityKind::Created => "created", ActivityKind::Retitled => "retitled", ActivityKind::Described => "described", @@ -236,6 +239,7 @@ impl ActivityKind { "rule_deleted" => ActivityKind::RuleDeleted, "file_added" => ActivityKind::FileAdded, "file_removed" => ActivityKind::FileRemoved, + "message_sent" => ActivityKind::MessageSent, other => ActivityKind::Other(other.to_string()), } } @@ -294,6 +298,7 @@ impl ActivityEntry { | ActivityKind::RuleEdited | ActivityKind::RuleToggled | ActivityKind::RuleDeleted + | ActivityKind::MessageSent | ActivityKind::Other(_) => detail.to_string(), } } diff --git a/crates/izlek-core/src/mail.rs b/crates/izlek-core/src/mail.rs index f52c059..f8d4a27 100644 --- a/crates/izlek-core/src/mail.rs +++ b/crates/izlek-core/src/mail.rs @@ -696,6 +696,7 @@ impl Engine { | ActivityKind::RuleDeleted | ActivityKind::FileAdded | ActivityKind::FileRemoved + | ActivityKind::MessageSent | ActivityKind::Other(_) => format!("{} touched it.", actor), }, }; diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index a564d88..2cd625c 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -303,6 +303,9 @@ pub enum SendState { pub enum SendKind { Rule, Invite, + /// An admin's own mail to one or more members — no rule, no event, no + /// task, same as an invite. + Notice, } impl SendKind { @@ -310,6 +313,7 @@ impl SendKind { match self { SendKind::Rule => "rule", SendKind::Invite => "invite", + SendKind::Notice => "notice", } } @@ -317,6 +321,7 @@ impl SendKind { match raw { "rule" => Some(SendKind::Rule), "invite" => Some(SendKind::Invite), + "notice" => Some(SendKind::Notice), _ => None, } } @@ -949,6 +954,16 @@ pub trait Store: BoardReads + DetailReads + 'static { at: OffsetDateTime, ) -> Result; + /// Holds an admin's mail to one member: pending, no rule, no event, no + /// task, same shape as [`Store::queue_invite`]. + async fn queue_notice( + &self, + recipient: &str, + subject: &str, + body: &str, + at: OffsetDateTime, + ) -> Result; + /// The server took it. async fn record_send_accepted(&self, send_id: &str, at: OffsetDateTime) -> Result<()>; diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index c8a6ebe..f8532e8 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -72,6 +72,10 @@ const MIGRATIONS: &[(i64, &str)] = &[ (17, include_str!("../../migrations/0017_ui_preference.sql")), (18, include_str!("../../migrations/0018_photo_in_the_user.sql")), (19, include_str!("../../migrations/0019_events_without_a_task.sql")), + ( + 20, + include_str!("../../migrations/0020_a_notice_owes_no_rule_either.sql"), + ), ]; /// The board a fresh workspace gets, and its columns. `Done` is the column @@ -2580,6 +2584,33 @@ impl Store for TursoStore { } } + async fn queue_notice( + &self, + recipient: &str, + subject: &str, + body: &str, + at: OffsetDateTime, + ) -> Result { + let id = Ulid::new().to_string(); + self.conn + .lock() + .await + .execute( + "INSERT INTO mail_send \ + (id, recipient, state, attempts, claimed_at, next_attempt_at, kind, subject, \ + body) \ + VALUES (?1, ?2, 'pending', 0, ?3, ?3, 'notice', ?4, ?5)", + params![id.clone(), recipient, stamp(at)?, subject, body], + ) + .await + .map_err(backend)?; + let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); + match self.one_row(&sql, params![id]).await? { + Some(row) => send_from(&row), + None => Err(StoreError::NotFound), + } + } + async fn record_send_accepted(&self, send_id: &str, at: OffsetDateTime) -> Result<()> { let conn = self.conn.lock().await; let n = conn diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index 5511105..f9b6277 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -236,14 +236,14 @@ async fn migrations_apply_once_and_survive_reopen() { let path = dir.join("izlek.db").to_string_lossy().into_owned(); let first = TursoStore::open(&path).await.unwrap(); - assert_eq!(first.schema_version().await.unwrap(), 19); + assert_eq!(first.schema_version().await.unwrap(), 20); claim(&first).await; drop(first); // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and // must not lose what the first open wrote. let second = TursoStore::open(&path).await.unwrap(); - assert_eq!(second.schema_version().await.unwrap(), 19); + assert_eq!(second.schema_version().await.unwrap(), 20); assert_eq!(second.workspace().await.unwrap().unwrap().name, "Izlek"); drop(second); let _ = std::fs::remove_dir_all(&dir); @@ -260,7 +260,7 @@ async fn migration_0013_rebuilds_mail_rule_without_losing_its_ledger() { a_pre_0013_store_with_a_rule_send_and_decision().await; let store = TursoStore::open(path.to_str().unwrap()).await.unwrap(); - assert_eq!(store.schema_version().await.unwrap(), 19); + assert_eq!(store.schema_version().await.unwrap(), 20); assert_eq!(store.board(&workspace).await.unwrap().unwrap().id, board); let rules = store.mail_rules(&board).await.unwrap(); @@ -5186,3 +5186,32 @@ async fn requeuing_a_send_puts_it_back_in_play_but_leaves_a_sent_one_alone() { let owed = store.sends_owed(now, 10).await.unwrap(); assert!(owed.iter().any(|s| s.id == failed.id), "the requeued send is now due"); } + +#[tokio::test] +async fn a_queued_notice_is_pending_and_due_and_on_the_queue() { + let scratch = Scratch::open().await; + let now = OffsetDateTime::now_utc(); + let queued = scratch + .store + .queue_notice("grace@izlek.sh", "Heads up", "Body text", now) + .await + .unwrap(); + assert_eq!(queued.kind, SendKind::Notice); + assert_eq!(queued.state, SendState::Pending); + assert_eq!(queued.recipient, "grace@izlek.sh"); + assert_eq!(queued.subject.as_deref(), Some("Heads up")); + assert_eq!(queued.body.as_deref(), Some("Body text")); + + let owed = scratch.store.sends_owed(now, 10).await.unwrap(); + assert!(owed.iter().any(|s| s.id == queued.id), "not due: {owed:?}"); + + let mail_queue = scratch + .store + .mail_queue(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); + assert!( + mail_queue.iter().any(|s| s.id == queued.id), + "not in mail_queue: {mail_queue:?}" + ); +} diff --git a/crates/izlek-web/src/i18n.rs b/crates/izlek-web/src/i18n.rs index 3b37e0a..8e38ccb 100644 --- a/crates/izlek-web/src/i18n.rs +++ b/crates/izlek-web/src/i18n.rs @@ -132,6 +132,12 @@ pub enum Key { PhotoLimitLabel, AllowedFileTypesLabel, Members, + Message, + Everyone, + Recipient, + Subject, + Body, + Send, NameCol, AddressCol, RoleCol, @@ -262,6 +268,7 @@ pub enum Key { ActSenderSaved, ActLimitsSaved, ActTestMailSent, + ActMessageSent, UnblockedWord, AColumn, AudienceEmpty, @@ -515,6 +522,18 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (AllowedFileTypesLabel, Tr) => "İZİN VERİLEN DOSYA TÜRLERİ", (Members, En) => "Members", (Members, Tr) => "Üyeler", + (Message, En) => "Message", + (Message, Tr) => "Mesaj", + (Everyone, En) => "Everyone", + (Everyone, Tr) => "Herkes", + (Recipient, En) => "RECIPIENT", + (Recipient, Tr) => "ALICI", + (Subject, En) => "SUBJECT", + (Subject, Tr) => "KONU", + (Body, En) => "BODY", + (Body, Tr) => "İÇERİK", + (Send, En) => "Send", + (Send, Tr) => "Gönder", (NameCol, En) => "NAME", (NameCol, Tr) => "AD", (AddressCol, En) => "ADDRESS", @@ -770,6 +789,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ActLimitsSaved, Tr) => "sınırları kaydetti", (ActTestMailSent, En) => "sent a test mail", (ActTestMailSent, Tr) => "test postası gönderdi", + (ActMessageSent, En) => "sent a message", + (ActMessageSent, Tr) => "mesaj gönderdi", (UnblockedWord, En) => "unblocked", (UnblockedWord, Tr) => "engeli kaldırıldı", (AColumn, En) => "a column", diff --git a/crates/izlek-web/src/logs.rs b/crates/izlek-web/src/logs.rs index d14507d..01b236b 100644 --- a/crates/izlek-web/src/logs.rs +++ b/crates/izlek-web/src/logs.rs @@ -116,6 +116,7 @@ const ACTIVITY_KINDS: &[&str] = &[ "sender_saved", "limits_saved", "test_mail_sent", + "message_sent", "rule_created", "rule_edited", "rule_toggled", @@ -172,6 +173,7 @@ fn activity_sentence(kind: &izlek_core::detail::ActivityKind, detail: &str, lang ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).to_string(), ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).to_string(), ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).to_string(), + ActivityKind::MessageSent => t(lang, Key::ActMessageSent).to_string(), ActivityKind::RoleChanged => crate::i18n::role_changed_label(lang, detail), ActivityKind::RuleCreated => crate::i18n::rule_created_label(lang, detail), ActivityKind::RuleEdited => crate::i18n::rule_edited_label(lang, detail), diff --git a/crates/izlek-web/src/server.rs b/crates/izlek-web/src/server.rs index fd6c56e..e85b513 100644 --- a/crates/izlek-web/src/server.rs +++ b/crates/izlek-web/src/server.rs @@ -351,6 +351,8 @@ pub enum Refusal { NotAnImage, /// A rule with no subject line: the mail it sends would arrive blank. EmptySubject, + /// A message with no body: there is nothing for the recipient to read. + EmptyBody, /// The date field did not hold a date. BadDeadline, /// The link asked for would put a task behind itself. @@ -361,6 +363,8 @@ pub enum Refusal { /// No such task — or none this account may see. Deliberately one answer for /// both. NotFound, + /// A recipient id that names nobody in this workspace. + NoSuchMember, Unavailable, } @@ -401,10 +405,12 @@ impl Refusal { } Refusal::NotAnImage => "That is not an image.".to_string(), Refusal::EmptySubject => "Give the rule a subject line.".to_string(), + Refusal::EmptyBody => "Write something first.".to_string(), Refusal::BadDeadline => "That is not a date.".to_string(), Refusal::Cycle => "That link would put this task behind itself.".to_string(), Refusal::MovedAlready => "Somebody moved this card first.".to_string(), Refusal::NotFound => "No such task.".to_string(), + Refusal::NoSuchMember => "No such member.".to_string(), Refusal::Unavailable => "Something went wrong.".to_string(), } } @@ -433,6 +439,7 @@ impl Refusal { Refusal::Cycle => "Bu bağlantı görevi kendi arkasına koyar.".to_string(), Refusal::MovedAlready => "Bu kartı başka biri zaten taşıdı.".to_string(), Refusal::NotFound => "Böyle bir görev yok.".to_string(), + Refusal::NoSuchMember => "Böyle bir üye yok.".to_string(), Refusal::Unavailable => "Bir şeyler ters gitti.".to_string(), Refusal::BadLimit => { "Limit en az 1 MB, dosya başına en çok 500 MB, fotoğraf başına en çok 20 MB olabilir." @@ -452,6 +459,7 @@ impl Refusal { // language off of, so it falls back to English like the rest. Refusal::BadSender(_) => self.message(), Refusal::EmptySubject => "Kurala bir konu ver.".to_string(), + Refusal::EmptyBody => "Önce bir şey yaz.".to_string(), Refusal::Rejected => "Bu işe yaramadı.".to_string(), Refusal::RateLimited => { "Çok fazla deneme — birkaç dakika bekleyip tekrar dene.".to_string() @@ -500,10 +508,12 @@ impl Refusal { "file-type" => Refusal::FileTypeNotAllowed, "not-an-image" => Refusal::NotAnImage, "empty-subject" => Refusal::EmptySubject, + "empty-body" => Refusal::EmptyBody, "bad-deadline" => Refusal::BadDeadline, "cycle" => Refusal::Cycle, "moved-already" => Refusal::MovedAlready, "not-found" => Refusal::NotFound, + "no-such-member" => Refusal::NoSuchMember, "unavailable" => Refusal::Unavailable, _ => return None, }) @@ -551,10 +561,12 @@ impl Refusal { Refusal::FileTypeNotAllowed => "file-type", Refusal::NotAnImage => "not-an-image", Refusal::EmptySubject => "empty-subject", + Refusal::EmptyBody => "empty-body", Refusal::BadDeadline => "bad-deadline", Refusal::Cycle => "cycle", Refusal::MovedAlready => "moved-already", Refusal::NotFound => "not-found", + Refusal::NoSuchMember => "no-such-member", Refusal::Unavailable => "unavailable", } } @@ -831,6 +843,7 @@ mod refusal_message_tests { Refusal::Cycle, Refusal::MovedAlready, Refusal::NotFound, + Refusal::NoSuchMember, Refusal::Unavailable, ]; for refusal in all { diff --git a/crates/izlek-web/src/settings.rs b/crates/izlek-web/src/settings.rs index d31ff7d..d629fe3 100644 --- a/crates/izlek-web/src/settings.rs +++ b/crates/izlek-web/src/settings.rs @@ -190,6 +190,7 @@ fn section_of_call(call: &str) -> &'static str { "save_sender" | "send_test_mail" => "outgoing", "save_limits" => "limits", "invite_member" | "set_role" | "resend_link" => "members", + "send_message" => "message", _ => "profile", } } @@ -724,6 +725,57 @@ async fn set_role( } } +#[derive(serde::Deserialize)] +struct SendMessageForm { + to: String, + subject: String, + body: String, +} + +#[route(POST "/api/send_message")] +async fn send_message( + cx: &Cx, + Form(input): Form, +) -> Result<(StatusCode, HeaderMap, Vec)> { + let admin = match require_admin(cx).await { + Ok(admin) => admin, + Err(refusal) => return Ok(saved_or_refused("send_message", Some(refusal))), + }; + let subject = input.subject.trim(); + if subject.is_empty() { + return Ok(saved_or_refused("send_message", Some(Refusal::EmptySubject))); + } + let body = input.body.trim(); + if body.is_empty() { + return Ok(saved_or_refused("send_message", Some(Refusal::EmptyBody))); + } + let store = accounts(cx).store().clone(); + let members = store.users(&admin.workspace_id).await?; + let recipients: Vec = if input.to == "everyone" { + members + .into_iter() + .filter(|member| member.id != admin.id) + .map(|member| member.email) + .collect() + } else { + match members.into_iter().find(|member| member.id == input.to) { + Some(member) => vec![member.email], + None => return Ok(saved_or_refused("send_message", Some(Refusal::NoSuchMember))), + } + }; + let now = time::OffsetDateTime::now_utc(); + for recipient in &recipients { + if let Err(problem) = store.queue_notice(recipient, subject, body, now).await { + eprintln!("store error: {problem}"); + return Ok(saved_or_refused("send_message", Some(Refusal::Unavailable))); + } + } + let _ = store + .record_event(Some(&admin.id), &ActivityKind::MessageSent, subject, now) + .await; + Ok(saved_or_refused("send_message", None)) +} + // --------------------------------------------------------------------------- // Page // --------------------------------------------------------------------------- @@ -896,6 +948,7 @@ enum Section { Outgoing, Limits, Members, + Message, } /// The class a rail link wears: `active` on the section it points to when @@ -931,6 +984,7 @@ async fn settings_page(cx: &Cx) -> Result { Some("outgoing") if administers => Section::Outgoing, Some("limits") if administers => Section::Limits, Some("members") if administers => Section::Members, + Some("message") if administers => Section::Message, _ => Section::Profile, }; @@ -964,6 +1018,7 @@ async fn settings_page(cx: &Cx) -> Result { let (role_refusal, _) = call_state(query, "set_role"); let member_refusal = resend_refusal.or(invite_refusal).or(role_refusal); let (password_refusal, _) = call_state(query, "change_password"); + let (message_refusal, message_saved) = call_state(query, "send_message"); let mailed = query_value(query, "mailed").map(decode_q); view! { @@ -985,6 +1040,7 @@ async fn settings_page(cx: &Cx) -> Result { (t(lang, Key::OutgoingMail)) (t(lang, Key::WorkspaceLimits)) (t(lang, Key::Members)) + (t(lang, Key::Message)) }
@@ -1257,7 +1313,7 @@ async fn settings_page(cx: &Cx) -> Result { } - if section == Section::Members && let Some(members) = members { + if section == Section::Members && let Some(members) = &members {

(t(lang, Key::Members))

@@ -1360,6 +1416,43 @@ async fn settings_page(cx: &Cx) -> Result {
} + + if section == Section::Message && let Some(members) = &members { +
+
+

(t(lang, Key::Message))

+ (t(lang, Key::AdminOnly)) +
+
+ + + +
+ if let Some(refusal) = &message_refusal { + (refusal.message_in(lang)) + } + if message_saved { + (t(lang, Key::Saved)) + } + +
+
+
+ }
(crate::dropdown::dropdown_script(cx).await?) diff --git a/crates/izlek-web/tests/http.rs b/crates/izlek-web/tests/http.rs index 8ae467a..f10a9a3 100644 --- a/crates/izlek-web/tests/http.rs +++ b/crates/izlek-web/tests/http.rs @@ -5392,3 +5392,175 @@ async fn retrying_an_already_sent_send_changes_nothing() { let reread = sends.iter().find(|s| s.id == send_id).unwrap(); assert_eq!(reread.state, SendState::Sent, "a sent send was touched by a retry"); } + +// --------------------------------------------------------------------------- +// Send message +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn an_admin_sends_a_message_to_one_member() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let _ = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await; + let mert_id = app.store.user_by_email(&app.workspace_id().await, "emre@izlek.sh").await.unwrap().unwrap().id; + + let answer = app + .post( + "/api/send_message", + Some(&admin_cookie), + &[("to", &mert_id), ("subject", "Heads up"), ("body", "Standup moved to 10.")], + ) + .await; + assert!( + answer.location.as_deref().unwrap_or_default().contains("saved=send_message"), + "{:?}", + answer.location + ); + + let sends = app.store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let notices: Vec<_> = sends.iter().filter(|send| send.kind == SendKind::Notice).collect(); + assert_eq!(notices.len(), 1, "{sends:?}"); + let notice = notices[0]; + assert_eq!(notice.recipient, "emre@izlek.sh"); + assert_eq!(notice.subject.as_deref(), Some("Heads up")); + assert_eq!(notice.body.as_deref(), Some("Standup moved to 10.")); + + let queue = app.get("/logs?section=queue", Some(&admin_cookie)).await; + let html = String::from_utf8_lossy(&queue.bytes); + assert!(html.contains("Heads up"), "{html}"); +} + +#[tokio::test] +async fn an_admin_sends_a_message_to_everyone_and_not_to_themself() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let _ = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await; + let _ = invited(&app, &admin_cookie, "quiet@izlek.sh", "Quiet", Role::Viewer).await; + + let answer = app + .post( + "/api/send_message", + Some(&admin_cookie), + &[("to", "everyone"), ("subject", "All hands"), ("body", "Board meeting Friday.")], + ) + .await; + assert!( + answer.location.as_deref().unwrap_or_default().contains("saved=send_message"), + "{:?}", + answer.location + ); + + let sends = app.store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let notices: Vec<_> = sends.iter().filter(|send| send.kind == SendKind::Notice).collect(); + assert_eq!(notices.len(), 2, "{sends:?}"); + assert!(notices.iter().all(|send| send.recipient != "ada@izlek.sh"), "{sends:?}"); +} + +#[tokio::test] +async fn a_blank_subject_or_body_refuses_and_queues_nothing() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let _ = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await; + + let answer = app + .post( + "/api/send_message", + Some(&admin_cookie), + &[("to", "everyone"), ("subject", " "), ("body", "Something")], + ) + .await; + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal=empty-subject&on=send_message"), + "{:?}", + answer.location + ); + + let answer = app + .post( + "/api/send_message", + Some(&admin_cookie), + &[("to", "everyone"), ("subject", "Subject"), ("body", " ")], + ) + .await; + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal=empty-body&on=send_message"), + "{:?}", + answer.location + ); + + let sends = app.store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + assert!(sends.iter().all(|send| send.kind != SendKind::Notice), "{sends:?}"); + + let location = answer.location.expect("no redirect"); + let page = app.get(&location, Some(&admin_cookie)).await; + let html = String::from_utf8_lossy(&page.bytes); + assert!(html.contains("field-error"), "{html}"); +} + +#[tokio::test] +async fn a_member_may_not_send_a_message_and_never_sees_the_panel() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let member = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await; + + let answer = app + .post( + "/api/send_message", + Some(&member), + &[("to", "everyone"), ("subject", "Sneaky"), ("body", "Should not send")], + ) + .await; + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal=forbidden&on=send_message"), + "{:?}", + answer.location + ); + + let sends = app.store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + assert!(sends.iter().all(|send| send.kind != SendKind::Notice), "{sends:?}"); + + let page = app.get("/settings", Some(&member)).await; + let html = String::from_utf8_lossy(&page.bytes); + assert!(!html.contains("section=message"), "{html}"); + assert!(!html.contains("id=\"message\""), "{html}"); +} + +#[tokio::test] +async fn an_unknown_recipient_refuses_and_never_broadcasts() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let _ = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await; + + let answer = app + .post( + "/api/send_message", + Some(&admin_cookie), + &[("to", "not-a-real-id"), ("subject", "Subject"), ("body", "Body")], + ) + .await; + assert_ne!(answer.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", answer.body); + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal=no-such-member&on=send_message"), + "{:?}", + answer.location + ); + + let sends = app.store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + assert!(sends.iter().all(|send| send.kind != SendKind::Notice), "{sends:?}"); +}