forge
Explore
Log in

Don't you dare go Hollow

The admin can write to the workspace, and it rides the queue

Browse files at this commit

6b0ddff523ccf307205e59e47a35e14672b152e1Ahmet Kaan GümüşParent: 751237d
  • feat
    • the admin can write to the workspace, and it rides the queue
Show full message
✨ feat(web): the admin can write to the workspace, and it rides the queue
crates/izlek-core/migrations/0020_a_notice_owes_no_rule_either.sqladded+38 -0
@@ -0,0 +1,38 @@
1+-- A notice is an admin's own mail to a member — same shape as an invite:
2+-- no rule, no event, no task, just a subject and a body. 0012's CHECK only
3+-- named 'invite' alongside 'rule', so a 'notice' row would fail it. SQLite
4+-- cannot widen a CHECK in place, so the table is rebuilt again, same shape
5+-- of migration as 0012/0013.
6+CREATE TABLE mail_send_next (
7+ id TEXT PRIMARY KEY,
8+ rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE,
9+ event_id TEXT,
10+ task_id TEXT REFERENCES task(id),
11+ recipient TEXT NOT NULL,
12+ state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')),
13+ attempts INTEGER NOT NULL DEFAULT 0,
14+ last_error TEXT,
15+ claimed_at TEXT NOT NULL,
16+ next_attempt_at TEXT,
17+ sent_at TEXT,
18+ kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite', 'notice')),
19+ subject TEXT,
20+ body TEXT,
21+ CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)),
22+ CHECK ((kind IN ('invite', 'notice')) = (subject IS NOT NULL AND body IS NOT NULL))
23+);
24+
25+INSERT INTO mail_send_next
26+SELECT id, rule_id, event_id, task_id, recipient, state, attempts, last_error,
27+ claimed_at, next_attempt_at, sent_at, kind, subject, body
28+FROM mail_send;
29+
30+DROP INDEX IF EXISTS mail_send_once;
31+DROP INDEX IF EXISTS mail_send_owed;
32+DROP INDEX IF EXISTS mail_send_by_rule;
33+DROP TABLE mail_send;
34+ALTER TABLE mail_send_next RENAME TO mail_send;
35+
36+CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient);
37+CREATE INDEX mail_send_owed ON mail_send(next_attempt_at);
38+CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at);
crates/izlek-core/src/detail.rsmodified+5 -0
@@ -158,6 +158,8 @@ pub enum ActivityKind {
158 RuleDeleted,158 RuleDeleted,
159 FileAdded,159 FileAdded,
160 FileRemoved,160 FileRemoved,
161+ /// An admin's own mail to one or more members, outside any rule.
162+ MessageSent,
161 /// A kind written by a newer version than the one reading it. The stored163 /// A kind written by a newer version than the one reading it. The stored
162 /// detail is shown as-is rather than dropping the row.164 /// detail is shown as-is rather than dropping the row.
163 Other(String),165 Other(String),
@@ -186,6 +188,7 @@ impl ActivityKind {
186 ActivityKind::RuleDeleted => "rule_deleted",188 ActivityKind::RuleDeleted => "rule_deleted",
187 ActivityKind::FileAdded => "file_added",189 ActivityKind::FileAdded => "file_added",
188 ActivityKind::FileRemoved => "file_removed",190 ActivityKind::FileRemoved => "file_removed",
191+ ActivityKind::MessageSent => "message_sent",
189 ActivityKind::Created => "created",192 ActivityKind::Created => "created",
190 ActivityKind::Retitled => "retitled",193 ActivityKind::Retitled => "retitled",
191 ActivityKind::Described => "described",194 ActivityKind::Described => "described",
@@ -236,6 +239,7 @@ impl ActivityKind {
236 "rule_deleted" => ActivityKind::RuleDeleted,239 "rule_deleted" => ActivityKind::RuleDeleted,
237 "file_added" => ActivityKind::FileAdded,240 "file_added" => ActivityKind::FileAdded,
238 "file_removed" => ActivityKind::FileRemoved,241 "file_removed" => ActivityKind::FileRemoved,
242+ "message_sent" => ActivityKind::MessageSent,
239 other => ActivityKind::Other(other.to_string()),243 other => ActivityKind::Other(other.to_string()),
240 }244 }
241 }245 }
@@ -294,6 +298,7 @@ impl ActivityEntry {
294 | ActivityKind::RuleEdited298 | ActivityKind::RuleEdited
295 | ActivityKind::RuleToggled299 | ActivityKind::RuleToggled
296 | ActivityKind::RuleDeleted300 | ActivityKind::RuleDeleted
301+ | ActivityKind::MessageSent
297 | ActivityKind::Other(_) => detail.to_string(),302 | ActivityKind::Other(_) => detail.to_string(),
298 }303 }
299 }304 }
crates/izlek-core/src/mail.rsmodified+1 -0
@@ -696,6 +696,7 @@ impl Engine {
696 | ActivityKind::RuleDeleted696 | ActivityKind::RuleDeleted
697 | ActivityKind::FileAdded697 | ActivityKind::FileAdded
698 | ActivityKind::FileRemoved698 | ActivityKind::FileRemoved
699+ | ActivityKind::MessageSent
699 | ActivityKind::Other(_) => format!("{} touched it.", actor),700 | ActivityKind::Other(_) => format!("{} touched it.", actor),
700 },701 },
701 };702 };
crates/izlek-core/src/store/mod.rsmodified+15 -0
@@ -303,6 +303,9 @@ pub enum SendState {
303 pub enum SendKind {303 pub enum SendKind {
304 Rule,304 Rule,
305 Invite,305 Invite,
306+ /// An admin's own mail to one or more members — no rule, no event, no
307+ /// task, same as an invite.
308+ Notice,
306 }309 }
307 310
308 impl SendKind {311 impl SendKind {
@@ -310,6 +313,7 @@ impl SendKind {
310 match self {313 match self {
311 SendKind::Rule => "rule",314 SendKind::Rule => "rule",
312 SendKind::Invite => "invite",315 SendKind::Invite => "invite",
316+ SendKind::Notice => "notice",
313 }317 }
314 }318 }
315 319
@@ -317,6 +321,7 @@ impl SendKind {
317 match raw {321 match raw {
318 "rule" => Some(SendKind::Rule),322 "rule" => Some(SendKind::Rule),
319 "invite" => Some(SendKind::Invite),323 "invite" => Some(SendKind::Invite),
324+ "notice" => Some(SendKind::Notice),
320 _ => None,325 _ => None,
321 }326 }
322 }327 }
@@ -949,6 +954,16 @@ pub trait Store: BoardReads + DetailReads + 'static {
949 at: OffsetDateTime,954 at: OffsetDateTime,
950 ) -> Result<MailSend>;955 ) -> Result<MailSend>;
951 956
957+ /// Holds an admin's mail to one member: pending, no rule, no event, no
958+ /// task, same shape as [`Store::queue_invite`].
959+ async fn queue_notice(
960+ &self,
961+ recipient: &str,
962+ subject: &str,
963+ body: &str,
964+ at: OffsetDateTime,
965+ ) -> Result<MailSend>;
966+
952 /// The server took it.967 /// The server took it.
953 async fn record_send_accepted(&self, send_id: &str, at: OffsetDateTime) -> Result<()>;968 async fn record_send_accepted(&self, send_id: &str, at: OffsetDateTime) -> Result<()>;
954 969
crates/izlek-core/src/store/turso_store.rsmodified+31 -0
@@ -72,6 +72,10 @@ const MIGRATIONS: &[(i64, &str)] = &[
72 (17, include_str!("../../migrations/0017_ui_preference.sql")),72 (17, include_str!("../../migrations/0017_ui_preference.sql")),
73 (18, include_str!("../../migrations/0018_photo_in_the_user.sql")),73 (18, include_str!("../../migrations/0018_photo_in_the_user.sql")),
74 (19, include_str!("../../migrations/0019_events_without_a_task.sql")),74 (19, include_str!("../../migrations/0019_events_without_a_task.sql")),
75+ (
76+ 20,
77+ include_str!("../../migrations/0020_a_notice_owes_no_rule_either.sql"),
78+ ),
75 ];79 ];
76 80
77 /// The board a fresh workspace gets, and its columns. `Done` is the column81 /// The board a fresh workspace gets, and its columns. `Done` is the column
@@ -2580,6 +2584,33 @@ impl Store for TursoStore {
2580 }2584 }
2581 }2585 }
2582 2586
2587+ async fn queue_notice(
2588+ &self,
2589+ recipient: &str,
2590+ subject: &str,
2591+ body: &str,
2592+ at: OffsetDateTime,
2593+ ) -> Result<MailSend> {
2594+ let id = Ulid::new().to_string();
2595+ self.conn
2596+ .lock()
2597+ .await
2598+ .execute(
2599+ "INSERT INTO mail_send \
2600+ (id, recipient, state, attempts, claimed_at, next_attempt_at, kind, subject, \
2601+ body) \
2602+ VALUES (?1, ?2, 'pending', 0, ?3, ?3, 'notice', ?4, ?5)",
2603+ params![id.clone(), recipient, stamp(at)?, subject, body],
2604+ )
2605+ .await
2606+ .map_err(backend)?;
2607+ let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");
2608+ match self.one_row(&sql, params![id]).await? {
2609+ Some(row) => send_from(&row),
2610+ None => Err(StoreError::NotFound),
2611+ }
2612+ }
2613+
2583 async fn record_send_accepted(&self, send_id: &str, at: OffsetDateTime) -> Result<()> {2614 async fn record_send_accepted(&self, send_id: &str, at: OffsetDateTime) -> Result<()> {
2584 let conn = self.conn.lock().await;2615 let conn = self.conn.lock().await;
2585 let n = conn2616 let n = conn
crates/izlek-core/tests/store.rsmodified+32 -3
@@ -236,14 +236,14 @@ async fn migrations_apply_once_and_survive_reopen() {
236 let path = dir.join("izlek.db").to_string_lossy().into_owned();236 let path = dir.join("izlek.db").to_string_lossy().into_owned();
237 237
238 let first = TursoStore::open(&path).await.unwrap();238 let first = TursoStore::open(&path).await.unwrap();
239- assert_eq!(first.schema_version().await.unwrap(), 19);239+ assert_eq!(first.schema_version().await.unwrap(), 20);
240 claim(&first).await;240 claim(&first).await;
241 drop(first);241 drop(first);
242 242
243 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and243 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and
244 // must not lose what the first open wrote.244 // must not lose what the first open wrote.
245 let second = TursoStore::open(&path).await.unwrap();245 let second = TursoStore::open(&path).await.unwrap();
246- assert_eq!(second.schema_version().await.unwrap(), 19);246+ assert_eq!(second.schema_version().await.unwrap(), 20);
247 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Izlek");247 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Izlek");
248 drop(second);248 drop(second);
249 let _ = std::fs::remove_dir_all(&dir);249 let _ = std::fs::remove_dir_all(&dir);
@@ -260,7 +260,7 @@ async fn migration_0013_rebuilds_mail_rule_without_losing_its_ledger() {
260 a_pre_0013_store_with_a_rule_send_and_decision().await;260 a_pre_0013_store_with_a_rule_send_and_decision().await;
261 261
262 let store = TursoStore::open(path.to_str().unwrap()).await.unwrap();262 let store = TursoStore::open(path.to_str().unwrap()).await.unwrap();
263- assert_eq!(store.schema_version().await.unwrap(), 19);263+ assert_eq!(store.schema_version().await.unwrap(), 20);
264 assert_eq!(store.board(&workspace).await.unwrap().unwrap().id, board);264 assert_eq!(store.board(&workspace).await.unwrap().unwrap().id, board);
265 265
266 let rules = store.mail_rules(&board).await.unwrap();266 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() {
5186 let owed = store.sends_owed(now, 10).await.unwrap();5186 let owed = store.sends_owed(now, 10).await.unwrap();
5187 assert!(owed.iter().any(|s| s.id == failed.id), "the requeued send is now due");5187 assert!(owed.iter().any(|s| s.id == failed.id), "the requeued send is now due");
5188 }5188 }
5189+
5190+#[tokio::test]
5191+async fn a_queued_notice_is_pending_and_due_and_on_the_queue() {
5192+ let scratch = Scratch::open().await;
5193+ let now = OffsetDateTime::now_utc();
5194+ let queued = scratch
5195+ .store
5196+ .queue_notice("grace@izlek.sh", "Heads up", "Body text", now)
5197+ .await
5198+ .unwrap();
5199+ assert_eq!(queued.kind, SendKind::Notice);
5200+ assert_eq!(queued.state, SendState::Pending);
5201+ assert_eq!(queued.recipient, "grace@izlek.sh");
5202+ assert_eq!(queued.subject.as_deref(), Some("Heads up"));
5203+ assert_eq!(queued.body.as_deref(), Some("Body text"));
5204+
5205+ let owed = scratch.store.sends_owed(now, 10).await.unwrap();
5206+ assert!(owed.iter().any(|s| s.id == queued.id), "not due: {owed:?}");
5207+
5208+ let mail_queue = scratch
5209+ .store
5210+ .mail_queue(10, izlek_core::store::FeedPage::Newest)
5211+ .await
5212+ .unwrap();
5213+ assert!(
5214+ mail_queue.iter().any(|s| s.id == queued.id),
5215+ "not in mail_queue: {mail_queue:?}"
5216+ );
5217+}
crates/izlek-web/src/i18n.rsmodified+21 -0
@@ -132,6 +132,12 @@ pub enum Key {
132 PhotoLimitLabel,132 PhotoLimitLabel,
133 AllowedFileTypesLabel,133 AllowedFileTypesLabel,
134 Members,134 Members,
135+ Message,
136+ Everyone,
137+ Recipient,
138+ Subject,
139+ Body,
140+ Send,
135 NameCol,141 NameCol,
136 AddressCol,142 AddressCol,
137 RoleCol,143 RoleCol,
@@ -262,6 +268,7 @@ pub enum Key {
262 ActSenderSaved,268 ActSenderSaved,
263 ActLimitsSaved,269 ActLimitsSaved,
264 ActTestMailSent,270 ActTestMailSent,
271+ ActMessageSent,
265 UnblockedWord,272 UnblockedWord,
266 AColumn,273 AColumn,
267 AudienceEmpty,274 AudienceEmpty,
@@ -515,6 +522,18 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
515 (AllowedFileTypesLabel, Tr) => "İZİN VERİLEN DOSYA TÜRLERİ",522 (AllowedFileTypesLabel, Tr) => "İZİN VERİLEN DOSYA TÜRLERİ",
516 (Members, En) => "Members",523 (Members, En) => "Members",
517 (Members, Tr) => "Üyeler",524 (Members, Tr) => "Üyeler",
525+ (Message, En) => "Message",
526+ (Message, Tr) => "Mesaj",
527+ (Everyone, En) => "Everyone",
528+ (Everyone, Tr) => "Herkes",
529+ (Recipient, En) => "RECIPIENT",
530+ (Recipient, Tr) => "ALICI",
531+ (Subject, En) => "SUBJECT",
532+ (Subject, Tr) => "KONU",
533+ (Body, En) => "BODY",
534+ (Body, Tr) => "İÇERİK",
535+ (Send, En) => "Send",
536+ (Send, Tr) => "Gönder",
518 (NameCol, En) => "NAME",537 (NameCol, En) => "NAME",
519 (NameCol, Tr) => "AD",538 (NameCol, Tr) => "AD",
520 (AddressCol, En) => "ADDRESS",539 (AddressCol, En) => "ADDRESS",
@@ -770,6 +789,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
770 (ActLimitsSaved, Tr) => "sınırları kaydetti",789 (ActLimitsSaved, Tr) => "sınırları kaydetti",
771 (ActTestMailSent, En) => "sent a test mail",790 (ActTestMailSent, En) => "sent a test mail",
772 (ActTestMailSent, Tr) => "test postası gönderdi",791 (ActTestMailSent, Tr) => "test postası gönderdi",
792+ (ActMessageSent, En) => "sent a message",
793+ (ActMessageSent, Tr) => "mesaj gönderdi",
773 (UnblockedWord, En) => "unblocked",794 (UnblockedWord, En) => "unblocked",
774 (UnblockedWord, Tr) => "engeli kaldırıldı",795 (UnblockedWord, Tr) => "engeli kaldırıldı",
775 (AColumn, En) => "a column",796 (AColumn, En) => "a column",
crates/izlek-web/src/logs.rsmodified+2 -0
@@ -116,6 +116,7 @@ const ACTIVITY_KINDS: &[&str] = &[
116 "sender_saved",116 "sender_saved",
117 "limits_saved",117 "limits_saved",
118 "test_mail_sent",118 "test_mail_sent",
119+ "message_sent",
119 "rule_created",120 "rule_created",
120 "rule_edited",121 "rule_edited",
121 "rule_toggled",122 "rule_toggled",
@@ -172,6 +173,7 @@ fn activity_sentence(kind: &izlek_core::detail::ActivityKind, detail: &str, lang
172 ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).to_string(),173 ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).to_string(),
173 ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).to_string(),174 ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).to_string(),
174 ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).to_string(),175 ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).to_string(),
176+ ActivityKind::MessageSent => t(lang, Key::ActMessageSent).to_string(),
175 ActivityKind::RoleChanged => crate::i18n::role_changed_label(lang, detail),177 ActivityKind::RoleChanged => crate::i18n::role_changed_label(lang, detail),
176 ActivityKind::RuleCreated => crate::i18n::rule_created_label(lang, detail),178 ActivityKind::RuleCreated => crate::i18n::rule_created_label(lang, detail),
177 ActivityKind::RuleEdited => crate::i18n::rule_edited_label(lang, detail),179 ActivityKind::RuleEdited => crate::i18n::rule_edited_label(lang, detail),
crates/izlek-web/src/server.rsmodified+13 -0
@@ -351,6 +351,8 @@ pub enum Refusal {
351 NotAnImage,351 NotAnImage,
352 /// A rule with no subject line: the mail it sends would arrive blank.352 /// A rule with no subject line: the mail it sends would arrive blank.
353 EmptySubject,353 EmptySubject,
354+ /// A message with no body: there is nothing for the recipient to read.
355+ EmptyBody,
354 /// The date field did not hold a date.356 /// The date field did not hold a date.
355 BadDeadline,357 BadDeadline,
356 /// The link asked for would put a task behind itself.358 /// The link asked for would put a task behind itself.
@@ -361,6 +363,8 @@ pub enum Refusal {
361 /// No such task — or none this account may see. Deliberately one answer for363 /// No such task — or none this account may see. Deliberately one answer for
362 /// both.364 /// both.
363 NotFound,365 NotFound,
366+ /// A recipient id that names nobody in this workspace.
367+ NoSuchMember,
364 Unavailable,368 Unavailable,
365 }369 }
366 370
@@ -401,10 +405,12 @@ impl Refusal {
401 }405 }
402 Refusal::NotAnImage => "That is not an image.".to_string(),406 Refusal::NotAnImage => "That is not an image.".to_string(),
403 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),407 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),
408+ Refusal::EmptyBody => "Write something first.".to_string(),
404 Refusal::BadDeadline => "That is not a date.".to_string(),409 Refusal::BadDeadline => "That is not a date.".to_string(),
405 Refusal::Cycle => "That link would put this task behind itself.".to_string(),410 Refusal::Cycle => "That link would put this task behind itself.".to_string(),
406 Refusal::MovedAlready => "Somebody moved this card first.".to_string(),411 Refusal::MovedAlready => "Somebody moved this card first.".to_string(),
407 Refusal::NotFound => "No such task.".to_string(),412 Refusal::NotFound => "No such task.".to_string(),
413+ Refusal::NoSuchMember => "No such member.".to_string(),
408 Refusal::Unavailable => "Something went wrong.".to_string(),414 Refusal::Unavailable => "Something went wrong.".to_string(),
409 }415 }
410 }416 }
@@ -433,6 +439,7 @@ impl Refusal {
433 Refusal::Cycle => "Bu bağlantı görevi kendi arkasına koyar.".to_string(),439 Refusal::Cycle => "Bu bağlantı görevi kendi arkasına koyar.".to_string(),
434 Refusal::MovedAlready => "Bu kartı başka biri zaten taşıdı.".to_string(),440 Refusal::MovedAlready => "Bu kartı başka biri zaten taşıdı.".to_string(),
435 Refusal::NotFound => "Böyle bir görev yok.".to_string(),441 Refusal::NotFound => "Böyle bir görev yok.".to_string(),
442+ Refusal::NoSuchMember => "Böyle bir üye yok.".to_string(),
436 Refusal::Unavailable => "Bir şeyler ters gitti.".to_string(),443 Refusal::Unavailable => "Bir şeyler ters gitti.".to_string(),
437 Refusal::BadLimit => {444 Refusal::BadLimit => {
438 "Limit en az 1 MB, dosya başına en çok 500 MB, fotoğraf başına en çok 20 MB olabilir."445 "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 {
452 // language off of, so it falls back to English like the rest.459 // language off of, so it falls back to English like the rest.
453 Refusal::BadSender(_) => self.message(),460 Refusal::BadSender(_) => self.message(),
454 Refusal::EmptySubject => "Kurala bir konu ver.".to_string(),461 Refusal::EmptySubject => "Kurala bir konu ver.".to_string(),
462+ Refusal::EmptyBody => "Önce bir şey yaz.".to_string(),
455 Refusal::Rejected => "Bu işe yaramadı.".to_string(),463 Refusal::Rejected => "Bu işe yaramadı.".to_string(),
456 Refusal::RateLimited => {464 Refusal::RateLimited => {
457 "Çok fazla deneme — birkaç dakika bekleyip tekrar dene.".to_string()465 "Çok fazla deneme — birkaç dakika bekleyip tekrar dene.".to_string()
@@ -500,10 +508,12 @@ impl Refusal {
500 "file-type" => Refusal::FileTypeNotAllowed,508 "file-type" => Refusal::FileTypeNotAllowed,
501 "not-an-image" => Refusal::NotAnImage,509 "not-an-image" => Refusal::NotAnImage,
502 "empty-subject" => Refusal::EmptySubject,510 "empty-subject" => Refusal::EmptySubject,
511+ "empty-body" => Refusal::EmptyBody,
503 "bad-deadline" => Refusal::BadDeadline,512 "bad-deadline" => Refusal::BadDeadline,
504 "cycle" => Refusal::Cycle,513 "cycle" => Refusal::Cycle,
505 "moved-already" => Refusal::MovedAlready,514 "moved-already" => Refusal::MovedAlready,
506 "not-found" => Refusal::NotFound,515 "not-found" => Refusal::NotFound,
516+ "no-such-member" => Refusal::NoSuchMember,
507 "unavailable" => Refusal::Unavailable,517 "unavailable" => Refusal::Unavailable,
508 _ => return None,518 _ => return None,
509 })519 })
@@ -551,10 +561,12 @@ impl Refusal {
551 Refusal::FileTypeNotAllowed => "file-type",561 Refusal::FileTypeNotAllowed => "file-type",
552 Refusal::NotAnImage => "not-an-image",562 Refusal::NotAnImage => "not-an-image",
553 Refusal::EmptySubject => "empty-subject",563 Refusal::EmptySubject => "empty-subject",
564+ Refusal::EmptyBody => "empty-body",
554 Refusal::BadDeadline => "bad-deadline",565 Refusal::BadDeadline => "bad-deadline",
555 Refusal::Cycle => "cycle",566 Refusal::Cycle => "cycle",
556 Refusal::MovedAlready => "moved-already",567 Refusal::MovedAlready => "moved-already",
557 Refusal::NotFound => "not-found",568 Refusal::NotFound => "not-found",
569+ Refusal::NoSuchMember => "no-such-member",
558 Refusal::Unavailable => "unavailable",570 Refusal::Unavailable => "unavailable",
559 }571 }
560 }572 }
@@ -831,6 +843,7 @@ mod refusal_message_tests {
831 Refusal::Cycle,843 Refusal::Cycle,
832 Refusal::MovedAlready,844 Refusal::MovedAlready,
833 Refusal::NotFound,845 Refusal::NotFound,
846+ Refusal::NoSuchMember,
834 Refusal::Unavailable,847 Refusal::Unavailable,
835 ];848 ];
836 for refusal in all {849 for refusal in all {
crates/izlek-web/src/settings.rsmodified+94 -1
@@ -190,6 +190,7 @@ fn section_of_call(call: &str) -> &'static str {
190 "save_sender" | "send_test_mail" => "outgoing",190 "save_sender" | "send_test_mail" => "outgoing",
191 "save_limits" => "limits",191 "save_limits" => "limits",
192 "invite_member" | "set_role" | "resend_link" => "members",192 "invite_member" | "set_role" | "resend_link" => "members",
193+ "send_message" => "message",
193 _ => "profile",194 _ => "profile",
194 }195 }
195 }196 }
@@ -724,6 +725,57 @@ async fn set_role(
724 }725 }
725 }726 }
726 727
728+#[derive(serde::Deserialize)]
729+struct SendMessageForm {
730+ to: String,
731+ subject: String,
732+ body: String,
733+}
734+
735+#[route(POST "/api/send_message")]
736+async fn send_message(
737+ cx: &Cx,
738+ Form(input): Form<SendMessageForm>,
739+) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
740+ let admin = match require_admin(cx).await {
741+ Ok(admin) => admin,
742+ Err(refusal) => return Ok(saved_or_refused("send_message", Some(refusal))),
743+ };
744+ let subject = input.subject.trim();
745+ if subject.is_empty() {
746+ return Ok(saved_or_refused("send_message", Some(Refusal::EmptySubject)));
747+ }
748+ let body = input.body.trim();
749+ if body.is_empty() {
750+ return Ok(saved_or_refused("send_message", Some(Refusal::EmptyBody)));
751+ }
752+ let store = accounts(cx).store().clone();
753+ let members = store.users(&admin.workspace_id).await?;
754+ let recipients: Vec<String> = if input.to == "everyone" {
755+ members
756+ .into_iter()
757+ .filter(|member| member.id != admin.id)
758+ .map(|member| member.email)
759+ .collect()
760+ } else {
761+ match members.into_iter().find(|member| member.id == input.to) {
762+ Some(member) => vec![member.email],
763+ None => return Ok(saved_or_refused("send_message", Some(Refusal::NoSuchMember))),
764+ }
765+ };
766+ let now = time::OffsetDateTime::now_utc();
767+ for recipient in &recipients {
768+ if let Err(problem) = store.queue_notice(recipient, subject, body, now).await {
769+ eprintln!("store error: {problem}");
770+ return Ok(saved_or_refused("send_message", Some(Refusal::Unavailable)));
771+ }
772+ }
773+ let _ = store
774+ .record_event(Some(&admin.id), &ActivityKind::MessageSent, subject, now)
775+ .await;
776+ Ok(saved_or_refused("send_message", None))
777+}
778+
727 // ---------------------------------------------------------------------------779 // ---------------------------------------------------------------------------
728 // Page780 // Page
729 // ---------------------------------------------------------------------------781 // ---------------------------------------------------------------------------
@@ -896,6 +948,7 @@ enum Section {
896 Outgoing,948 Outgoing,
897 Limits,949 Limits,
898 Members,950 Members,
951+ Message,
899 }952 }
900 953
901 /// The class a rail link wears: `active` on the section it points to when954 /// 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 {
931 Some("outgoing") if administers => Section::Outgoing,984 Some("outgoing") if administers => Section::Outgoing,
932 Some("limits") if administers => Section::Limits,985 Some("limits") if administers => Section::Limits,
933 Some("members") if administers => Section::Members,986 Some("members") if administers => Section::Members,
987+ Some("message") if administers => Section::Message,
934 _ => Section::Profile,988 _ => Section::Profile,
935 };989 };
936 990
@@ -964,6 +1018,7 @@ async fn settings_page(cx: &Cx) -> Result {
964 let (role_refusal, _) = call_state(query, "set_role");1018 let (role_refusal, _) = call_state(query, "set_role");
965 let member_refusal = resend_refusal.or(invite_refusal).or(role_refusal);1019 let member_refusal = resend_refusal.or(invite_refusal).or(role_refusal);
966 let (password_refusal, _) = call_state(query, "change_password");1020 let (password_refusal, _) = call_state(query, "change_password");
1021+ let (message_refusal, message_saved) = call_state(query, "send_message");
967 let mailed = query_value(query, "mailed").map(decode_q);1022 let mailed = query_value(query, "mailed").map(decode_q);
968 1023
969 view! {1024 view! {
@@ -985,6 +1040,7 @@ async fn settings_page(cx: &Cx) -> Result {
985 <a class=(rail_class(section, Section::Outgoing)) href="/settings?section=outgoing">(t(lang, Key::OutgoingMail))</a>1040 <a class=(rail_class(section, Section::Outgoing)) href="/settings?section=outgoing">(t(lang, Key::OutgoingMail))</a>
986 <a class=(rail_class(section, Section::Limits)) href="/settings?section=limits">(t(lang, Key::WorkspaceLimits))</a>1041 <a class=(rail_class(section, Section::Limits)) href="/settings?section=limits">(t(lang, Key::WorkspaceLimits))</a>
987 <a class=(rail_class(section, Section::Members)) href="/settings?section=members">(t(lang, Key::Members))</a>1042 <a class=(rail_class(section, Section::Members)) href="/settings?section=members">(t(lang, Key::Members))</a>
1043+ <a class=(rail_class(section, Section::Message)) href="/settings?section=message">(t(lang, Key::Message))</a>
988 }1044 }
989 </nav>1045 </nav>
990 <main class="settings-stage">1046 <main class="settings-stage">
@@ -1257,7 +1313,7 @@ async fn settings_page(cx: &Cx) -> Result {
1257 </section>1313 </section>
1258 }1314 }
1259 1315
1260- if section == Section::Members && let Some(members) = members {1316+ if section == Section::Members && let Some(members) = &members {
1261 <section class="panel" id="members">1317 <section class="panel" id="members">
1262 <div class="panel-head">1318 <div class="panel-head">
1263 <h2 class="panel-title">(t(lang, Key::Members))</h2>1319 <h2 class="panel-title">(t(lang, Key::Members))</h2>
@@ -1360,6 +1416,43 @@ async fn settings_page(cx: &Cx) -> Result {
1360 </div>1416 </div>
1361 </section>1417 </section>
1362 }1418 }
1419+
1420+ if section == Section::Message && let Some(members) = &members {
1421+ <section class="panel" id="message">
1422+ <div class="panel-head">
1423+ <h2 class="panel-title">(t(lang, Key::Message))</h2>
1424+ <span class="chip chip-admin">(t(lang, Key::AdminOnly))</span>
1425+ </div>
1426+ <form method="post" action="/api/send_message" class="panel-body">
1427+ <label class="field">
1428+ <span class="field-label">(t(lang, Key::Recipient))</span>
1429+ <select class="field-input" name="to" data-search="">
1430+ <option value="everyone">(t(lang, Key::Everyone))</option>
1431+ for member in members {
1432+ <option value=(member.id.clone())>(member.display_name.clone())</option>
1433+ }
1434+ </select>
1435+ </label>
1436+ <label class="field">
1437+ <span class="field-label">(t(lang, Key::Subject))</span>
1438+ <input class="field-input" type="text" name="subject" maxlength="200">
1439+ </label>
1440+ <label class="field">
1441+ <span class="field-label">(t(lang, Key::Body))</span>
1442+ <textarea class="detail-textarea" name="body" rows="6"></textarea>
1443+ </label>
1444+ <div class="panel-foot">
1445+ if let Some(refusal) = &message_refusal {
1446+ <span class="field-error">(refusal.message_in(lang))</span>
1447+ }
1448+ if message_saved {
1449+ <span class="field-note">(t(lang, Key::Saved))</span>
1450+ }
1451+ <button class="primary" type="submit">(t(lang, Key::Send))</button>
1452+ </div>
1453+ </form>
1454+ </section>
1455+ }
1363 </main>1456 </main>
1364 </div>1457 </div>
1365 (crate::dropdown::dropdown_script(cx).await?)1458 (crate::dropdown::dropdown_script(cx).await?)
crates/izlek-web/tests/http.rsmodified+172 -0
@@ -5392,3 +5392,175 @@ async fn retrying_an_already_sent_send_changes_nothing() {
5392 let reread = sends.iter().find(|s| s.id == send_id).unwrap();5392 let reread = sends.iter().find(|s| s.id == send_id).unwrap();
5393 assert_eq!(reread.state, SendState::Sent, "a sent send was touched by a retry");5393 assert_eq!(reread.state, SendState::Sent, "a sent send was touched by a retry");
5394 }5394 }
5395+
5396+// ---------------------------------------------------------------------------
5397+// Send message
5398+// ---------------------------------------------------------------------------
5399+
5400+#[tokio::test]
5401+async fn an_admin_sends_a_message_to_one_member() {
5402+ let app = App::open().await;
5403+ let admin_cookie = admin(&app).await;
5404+ let _ = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
5405+ let mert_id = app.store.user_by_email(&app.workspace_id().await, "emre@izlek.sh").await.unwrap().unwrap().id;
5406+
5407+ let answer = app
5408+ .post(
5409+ "/api/send_message",
5410+ Some(&admin_cookie),
5411+ &[("to", &mert_id), ("subject", "Heads up"), ("body", "Standup moved to 10.")],
5412+ )
5413+ .await;
5414+ assert!(
5415+ answer.location.as_deref().unwrap_or_default().contains("saved=send_message"),
5416+ "{:?}",
5417+ answer.location
5418+ );
5419+
5420+ let sends = app.store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5421+ let notices: Vec<_> = sends.iter().filter(|send| send.kind == SendKind::Notice).collect();
5422+ assert_eq!(notices.len(), 1, "{sends:?}");
5423+ let notice = notices[0];
5424+ assert_eq!(notice.recipient, "emre@izlek.sh");
5425+ assert_eq!(notice.subject.as_deref(), Some("Heads up"));
5426+ assert_eq!(notice.body.as_deref(), Some("Standup moved to 10."));
5427+
5428+ let queue = app.get("/logs?section=queue", Some(&admin_cookie)).await;
5429+ let html = String::from_utf8_lossy(&queue.bytes);
5430+ assert!(html.contains("Heads up"), "{html}");
5431+}
5432+
5433+#[tokio::test]
5434+async fn an_admin_sends_a_message_to_everyone_and_not_to_themself() {
5435+ let app = App::open().await;
5436+ let admin_cookie = admin(&app).await;
5437+ let _ = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
5438+ let _ = invited(&app, &admin_cookie, "quiet@izlek.sh", "Quiet", Role::Viewer).await;
5439+
5440+ let answer = app
5441+ .post(
5442+ "/api/send_message",
5443+ Some(&admin_cookie),
5444+ &[("to", "everyone"), ("subject", "All hands"), ("body", "Board meeting Friday.")],
5445+ )
5446+ .await;
5447+ assert!(
5448+ answer.location.as_deref().unwrap_or_default().contains("saved=send_message"),
5449+ "{:?}",
5450+ answer.location
5451+ );
5452+
5453+ let sends = app.store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5454+ let notices: Vec<_> = sends.iter().filter(|send| send.kind == SendKind::Notice).collect();
5455+ assert_eq!(notices.len(), 2, "{sends:?}");
5456+ assert!(notices.iter().all(|send| send.recipient != "ada@izlek.sh"), "{sends:?}");
5457+}
5458+
5459+#[tokio::test]
5460+async fn a_blank_subject_or_body_refuses_and_queues_nothing() {
5461+ let app = App::open().await;
5462+ let admin_cookie = admin(&app).await;
5463+ let _ = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
5464+
5465+ let answer = app
5466+ .post(
5467+ "/api/send_message",
5468+ Some(&admin_cookie),
5469+ &[("to", "everyone"), ("subject", " "), ("body", "Something")],
5470+ )
5471+ .await;
5472+ assert!(
5473+ answer
5474+ .location
5475+ .as_deref()
5476+ .unwrap_or_default()
5477+ .contains("refusal=empty-subject&on=send_message"),
5478+ "{:?}",
5479+ answer.location
5480+ );
5481+
5482+ let answer = app
5483+ .post(
5484+ "/api/send_message",
5485+ Some(&admin_cookie),
5486+ &[("to", "everyone"), ("subject", "Subject"), ("body", " ")],
5487+ )
5488+ .await;
5489+ assert!(
5490+ answer
5491+ .location
5492+ .as_deref()
5493+ .unwrap_or_default()
5494+ .contains("refusal=empty-body&on=send_message"),
5495+ "{:?}",
5496+ answer.location
5497+ );
5498+
5499+ let sends = app.store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5500+ assert!(sends.iter().all(|send| send.kind != SendKind::Notice), "{sends:?}");
5501+
5502+ let location = answer.location.expect("no redirect");
5503+ let page = app.get(&location, Some(&admin_cookie)).await;
5504+ let html = String::from_utf8_lossy(&page.bytes);
5505+ assert!(html.contains("field-error"), "{html}");
5506+}
5507+
5508+#[tokio::test]
5509+async fn a_member_may_not_send_a_message_and_never_sees_the_panel() {
5510+ let app = App::open().await;
5511+ let admin_cookie = admin(&app).await;
5512+ let member = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
5513+
5514+ let answer = app
5515+ .post(
5516+ "/api/send_message",
5517+ Some(&member),
5518+ &[("to", "everyone"), ("subject", "Sneaky"), ("body", "Should not send")],
5519+ )
5520+ .await;
5521+ assert!(
5522+ answer
5523+ .location
5524+ .as_deref()
5525+ .unwrap_or_default()
5526+ .contains("refusal=forbidden&on=send_message"),
5527+ "{:?}",
5528+ answer.location
5529+ );
5530+
5531+ let sends = app.store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5532+ assert!(sends.iter().all(|send| send.kind != SendKind::Notice), "{sends:?}");
5533+
5534+ let page = app.get("/settings", Some(&member)).await;
5535+ let html = String::from_utf8_lossy(&page.bytes);
5536+ assert!(!html.contains("section=message"), "{html}");
5537+ assert!(!html.contains("id=\"message\""), "{html}");
5538+}
5539+
5540+#[tokio::test]
5541+async fn an_unknown_recipient_refuses_and_never_broadcasts() {
5542+ let app = App::open().await;
5543+ let admin_cookie = admin(&app).await;
5544+ let _ = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
5545+
5546+ let answer = app
5547+ .post(
5548+ "/api/send_message",
5549+ Some(&admin_cookie),
5550+ &[("to", "not-a-real-id"), ("subject", "Subject"), ("body", "Body")],
5551+ )
5552+ .await;
5553+ assert_ne!(answer.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", answer.body);
5554+ assert!(
5555+ answer
5556+ .location
5557+ .as_deref()
5558+ .unwrap_or_default()
5559+ .contains("refusal=no-such-member&on=send_message"),
5560+ "{:?}",
5561+ answer.location
5562+ );
5563+
5564+ let sends = app.store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5565+ assert!(sends.iter().all(|send| send.kind != SendKind::Notice), "{sends:?}");
5566+}