forge
Explore
Log in

Don't you dare go Hollow

The admin's mail rules screen

Browse files at this commit

bcc7fa7ca14ace8a329847f079377a75dde97a25Ahmet Kaan GümüşParent: 08366ca
  • feat
    • the admin's mail rules screen
Show full message
✨ feat(rules): the admin's mail rules screen

One sentence per rule, from the MailRules artboard: a switch, "When status
becomes <column> send <subject> to <audience>", the last-sent stamp and a
delete. Writing rules is the admin's alone and the guard sits in each
handler, not in the sidebar: a rule sends mail from the one workspace
sender on everyone's behalf, so a Member reaching the endpoint directly is
refused there. A rule id arriving from the browser is checked against this
workspace's own board, and "not a rule" and "not your rule" answer the same
way, so the endpoint never confirms that someone else's rule exists.

The composer is a <details> whose open state and subject field the component
owns, so a rule that has just been written leaves a closed, empty composer
behind instead of the sentence you already sent.

Nine endpoint tests cover the pair of guards, the refusals (empty subject, a
column off another board, an audience the screen never offers, a foreign
rule id) and the round trip through create, switch off, and delete.

EVIDENCE: nine browser screenshots from the verify harness run |
release server on 127.0.0.1:3111, machine-driven clicks: opened the composer,
typed a subject, pressed Add rule, toggled the switch off and on, pressed
Delete, reopened the composer | the row rendered the sentence with "never
sent", greyed when off, came back when on, vanished on delete leaving the
empty-state line, and the reopened composer was empty
crates/dizey-web/src/app.rsmodified+2 -0
@@ -4,6 +4,7 @@ use leptos_router::components::{Route, Router, Routes};
44 use leptos_router::{SsrMode, path};
55
66 use crate::pages::{Join, Landing};
7+use crate::rules::RulesPage;
78 use crate::settings::SettingsPage;
89
910 /// The HTML document the server streams. `cargo-leptos` writes the bundle to
@@ -48,6 +49,7 @@ pub fn App() -> impl IntoView {
4849 <Routes fallback=NotFound>
4950 <Route path=path!("/") view=Landing ssr=SsrMode::InOrder/>
5051 <Route path=path!("/join/:token") view=Join ssr=SsrMode::InOrder/>
52+ <Route path=path!("/rules") view=RulesPage ssr=SsrMode::InOrder/>
5153 <Route path=path!("/settings") view=SettingsPage ssr=SsrMode::InOrder/>
5254 </Routes>
5355 </Router>
crates/dizey-web/src/auth.rsmodified+5 -0
@@ -46,6 +46,8 @@ pub enum Refusal {
4646 BadSender(String),
4747 /// A comment with nothing in it.
4848 EmptyComment,
49+ /// A rule with no subject line: the mail it sends would arrive blank.
50+ EmptySubject,
4951 /// The date field did not hold a date.
5052 BadDeadline,
5153 /// The link asked for would put a task behind itself.
@@ -85,6 +87,7 @@ impl Refusal {
8587 }
8688 Refusal::BadSender(problem) => problem.clone(),
8789 Refusal::EmptyComment => "Write something first.".to_string(),
90+ Refusal::EmptySubject => "Give the rule a subject line.".to_string(),
8891 Refusal::BadDeadline => "That is not a date.".to_string(),
8992 Refusal::Cycle => "That link would put this task behind itself.".to_string(),
9093 Refusal::MovedAlready => {
@@ -127,6 +130,7 @@ impl Refusal {
127130 Refusal::BadFileType => "bad-file-type",
128131 Refusal::BadSender(_) => "bad-sender",
129132 Refusal::EmptyComment => "empty-comment",
133+ Refusal::EmptySubject => "empty-subject",
130134 Refusal::BadDeadline => "bad-deadline",
131135 Refusal::Cycle => "cycle",
132136 Refusal::MovedAlready => "moved-already",
@@ -151,6 +155,7 @@ impl Refusal {
151155 "link-not-usable" => Refusal::LinkNotUsable,
152156 "empty-title" => Refusal::EmptyTitle,
153157 "empty-comment" => Refusal::EmptyComment,
158+ "empty-subject" => Refusal::EmptySubject,
154159 "bad-deadline" => Refusal::BadDeadline,
155160 "cycle" => Refusal::Cycle,
156161 "moved-already" => Refusal::MovedAlready,
crates/dizey-web/src/lib.rsmodified+1 -0
@@ -7,6 +7,7 @@ pub mod auth;
77 pub mod board;
88 pub mod detail;
99 pub mod pages;
10+pub mod rules;
1011 pub mod settings;
1112 #[cfg(feature = "ssr")]
1213 pub mod server;
crates/dizey-web/src/rules.rsadded+532 -0
@@ -0,0 +1,532 @@
1+//! Mail rules, from the MailRules artboard.
2+//!
3+//! The screen is the admin's, and so is every call behind it: a rule sends mail
4+//! on everyone's behalf, from the one workspace sender, so writing one is not
5+//! something a Member may do even if they reach the endpoint directly. The
6+//! chip in the artboard says "Admin only"; the guard is in the handlers.
7+
8+use leptos::prelude::*;
9+use serde::{Deserialize, Serialize};
10+
11+use crate::auth::{Me, Refusal};
12+
13+/// One rule as the screen reads it: a sentence, a switch and a stamp.
14+///
15+/// The trigger arrives already split into the words the artboard prints —
16+/// "When status becomes" / "Done" — because the two halves are chosen from
17+/// different vocabularies and only the server knows the column names.
18+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
19+pub struct RuleLine {
20+ pub id: String,
21+ /// "When status becomes", or "When a task stops being".
22+ pub when: String,
23+ /// "Done", or "blocked".
24+ pub what: String,
25+ pub subject: String,
26+ /// "assignees", or "everyone on board".
27+ pub audience: String,
28+ pub enabled: bool,
29+ /// `Aug 24 14:02`, or nothing when no mail from this rule has ever been
30+ /// accepted by the mail server.
31+ pub last_sent: Option<String>,
32+}
33+
34+/// A column, for the composer's status list.
35+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
36+pub struct ColumnChoice {
37+ pub id: String,
38+ pub name: String,
39+}
40+
41+/// The screen in one answer.
42+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
43+pub struct RulesSnapshot {
44+ pub me: Me,
45+ pub rules: Vec<RuleLine>,
46+ pub columns: Vec<ColumnChoice>,
47+ /// Whether a sender is connected. Rules that fire with no sender queue
48+ /// rather than fail, and the screen says so instead of leaving somebody to
49+ /// wonder why nothing arrived.
50+ pub sender_connected: bool,
51+}
52+
53+/// The word for an audience, as the artboard writes it.
54+#[cfg(feature = "ssr")]
55+fn audience_word(audience: dizey_core::store::Audience) -> &'static str {
56+ use dizey_core::store::Audience;
57+ match audience {
58+ Audience::Assignees => "assignees",
59+ Audience::Board => "everyone on board",
60+ }
61+}
62+
63+/// Every rule on the board, switched-off ones included, with the columns a new
64+/// rule may name.
65+#[server]
66+pub async fn current_rules() -> Result<Result<RulesSnapshot, Refusal>, ServerFnError> {
67+ use crate::server::{accounts, require_admin};
68+ use dizey_core::store::Trigger;
69+
70+ let user = match require_admin().await {
71+ Ok(user) => user,
72+ Err(refusal) => return Ok(Err(refusal)),
73+ };
74+ let store = accounts().store().clone();
75+ let fail = |e: dizey_core::store::StoreError| ServerFnError::new(e.to_string());
76+ let Some(board) = store.board(&user.workspace_id).await.map_err(fail)? else {
77+ return Ok(Err(Refusal::Unavailable));
78+ };
79+ let columns = store.columns(&board.id).await.map_err(fail)?;
80+ let rules = store.mail_rules(&board.id).await.map_err(fail)?;
81+ let last_sent = store.mail_rule_last_sent(&board.id).await.map_err(fail)?;
82+ let sender_connected = store
83+ .workspace()
84+ .await
85+ .map_err(fail)?
86+ .as_ref()
87+ .map(crate::settings::Sender::of)
88+ .is_some_and(|sender| sender.is_connected());
89+
90+ let lines = rules
91+ .into_iter()
92+ .map(|rule| {
93+ let (when, what) = match &rule.trigger {
94+ Trigger::StatusBecomes(column_id) => (
95+ "When status becomes".to_string(),
96+ columns
97+ .iter()
98+ .find(|column| &column.id == column_id)
99+ .map(|column| column.name.clone())
100+ // A rule can outlive the column it names. Saying so is
101+ // better than printing an id nobody can read.
102+ .unwrap_or_else(|| "a column that is gone".to_string()),
103+ ),
104+ Trigger::Unblocked => (
105+ "When a task stops being".to_string(),
106+ "blocked".to_string(),
107+ ),
108+ };
109+ RuleLine {
110+ when,
111+ what,
112+ subject: rule.subject.clone(),
113+ audience: audience_word(rule.audience).to_string(),
114+ enabled: rule.enabled,
115+ last_sent: last_sent
116+ .iter()
117+ .find(|(id, _)| id == &rule.id)
118+ .map(|(_, at)| dizey_core::detail::moment_label(*at)),
119+ id: rule.id,
120+ }
121+ })
122+ .collect();
123+
124+ Ok(Ok(RulesSnapshot {
125+ me: Me {
126+ id: user.id,
127+ display_name: user.display_name,
128+ email: user.email,
129+ role: user.role,
130+ },
131+ rules: lines,
132+ columns: columns
133+ .into_iter()
134+ .map(|column| ColumnChoice { id: column.id, name: column.name })
135+ .collect(),
136+ sender_connected,
137+ }))
138+}
139+
140+/// Writes one rule.
141+///
142+/// `trigger` is "status" or "unblocked"; `column_id` is only read for the
143+/// first, and is checked against this workspace's own board rather than
144+/// trusted — a column id from somewhere else would otherwise be a way to hang
145+/// a rule off another workspace's board.
146+#[server]
147+pub async fn create_rule(
148+ trigger: String,
149+ column_id: String,
150+ subject: String,
151+ audience: String,
152+) -> Result<Option<Refusal>, ServerFnError> {
153+ use crate::server::{accounts, require_admin};
154+ use dizey_core::store::{Audience, Trigger};
155+
156+ let user = match require_admin().await {
157+ Ok(user) => user,
158+ Err(refusal) => return Ok(Some(refusal)),
159+ };
160+ let subject = subject.trim().to_string();
161+ if subject.is_empty() {
162+ return Ok(Some(Refusal::EmptySubject));
163+ }
164+ let audience = match audience.as_str() {
165+ "assignees" => Audience::Assignees,
166+ "board" => Audience::Board,
167+ _ => return Ok(Some(Refusal::Forbidden)),
168+ };
169+
170+ let store = accounts().store().clone();
171+ let fail = |e: dizey_core::store::StoreError| ServerFnError::new(e.to_string());
172+ let Some(board) = store.board(&user.workspace_id).await.map_err(fail)? else {
173+ return Ok(Some(Refusal::Unavailable));
174+ };
175+ let trigger = match trigger.as_str() {
176+ "unblocked" => Trigger::Unblocked,
177+ "status" => {
178+ let columns = store.columns(&board.id).await.map_err(fail)?;
179+ if !columns.iter().any(|column| column.id == column_id) {
180+ return Ok(Some(Refusal::Forbidden));
181+ }
182+ Trigger::StatusBecomes(column_id)
183+ }
184+ _ => return Ok(Some(Refusal::Forbidden)),
185+ };
186+
187+ store
188+ .create_mail_rule(
189+ &board.id,
190+ &trigger,
191+ &subject,
192+ audience,
193+ time::OffsetDateTime::now_utc(),
194+ )
195+ .await
196+ .map_err(fail)?;
197+ Ok(None)
198+}
199+
200+/// Turns one rule on or off. Switching off stops it firing from here on; mail
201+/// it already owes has been written to the ledger and is still owed.
202+#[server]
203+pub async fn set_rule_enabled(
204+ rule_id: String,
205+ enabled: String,
206+) -> Result<Option<Refusal>, ServerFnError> {
207+ let store = match rule_of_this_workspace(&rule_id).await {
208+ Ok(store) => store,
209+ Err(refusal) => return Ok(Some(refusal)),
210+ };
211+ store
212+ .set_mail_rule_enabled(&rule_id, enabled == "true")
213+ .await
214+ .map_err(|e| ServerFnError::new(e.to_string()))?;
215+ Ok(None)
216+}
217+
218+/// Removes a rule. What it has already sent stays in the ledger: the rule is
219+/// gone, the record of what went out is not.
220+#[server]
221+pub async fn delete_rule(rule_id: String) -> Result<Option<Refusal>, ServerFnError> {
222+ let store = match rule_of_this_workspace(&rule_id).await {
223+ Ok(store) => store,
224+ Err(refusal) => return Ok(Some(refusal)),
225+ };
226+ store
227+ .delete_mail_rule(&rule_id)
228+ .await
229+ .map_err(|e| ServerFnError::new(e.to_string()))?;
230+ Ok(None)
231+}
232+
233+/// The admin's store, once the rule id has been shown to name a rule on this
234+/// workspace's own board.
235+///
236+/// A rule id is opaque and arrives from the browser, so "not yours" and "not a
237+/// rule" are the same answer: neither tells the caller whether the id exists
238+/// somewhere else.
239+#[cfg(feature = "ssr")]
240+async fn rule_of_this_workspace(
241+ rule_id: &str,
242+) -> Result<std::sync::Arc<dyn dizey_core::store::Store>, Refusal> {
243+ use crate::server::{accounts, require_admin};
244+
245+ let user = require_admin().await?;
246+ let store = accounts().store().clone();
247+ let board = store
248+ .board(&user.workspace_id)
249+ .await
250+ .map_err(|_| Refusal::Unavailable)?
251+ .ok_or(Refusal::Unavailable)?;
252+ let rule = store
253+ .mail_rule(rule_id)
254+ .await
255+ .map_err(|_| Refusal::Unavailable)?
256+ .ok_or(Refusal::NotFound)?;
257+ if rule.board_id != board.id {
258+ return Err(Refusal::NotFound);
259+ }
260+ Ok(store)
261+}
262+
263+#[component]
264+pub fn RulesPage() -> impl IntoView {
265+ let rules = Resource::new(|| (), |_| async move { current_rules().await });
266+
267+ view! {
268+ <Suspense fallback=|| view! { <main class="settings-stage"></main> }>
269+ {move || Suspend::new(async move {
270+ match rules.await {
271+ Ok(Ok(snapshot)) => {
272+ view! {
273+ <RulesScreen
274+ snapshot=snapshot
275+ on_change=Callback::new(move |()| rules.refetch())
276+ />
277+ }
278+ .into_any()
279+ }
280+ Ok(Err(refusal)) => {
281+ view! {
282+ <main class="scaffold-note">
283+ <p>{refusal.message()}</p>
284+ <p>
285+ <a href="/">"Back to the board"</a>
286+ </p>
287+ </main>
288+ }
289+ .into_any()
290+ }
291+ Err(_) => {
292+ view! {
293+ <main class="scaffold-note">
294+ <p>"Something went wrong. Reload the page."</p>
295+ </main>
296+ }
297+ .into_any()
298+ }
299+ }
300+ })}
301+ </Suspense>
302+ }
303+}
304+
305+#[component]
306+fn RulesScreen(snapshot: RulesSnapshot, on_change: Callback<()>) -> impl IntoView {
307+ let me = snapshot.me.clone();
308+ let sender_connected = snapshot.sender_connected;
309+ let empty = snapshot.rules.is_empty();
310+ let rows = snapshot
311+ .rules
312+ .into_iter()
313+ .map(|rule| view! { <RuleRow rule=rule on_change=on_change/> })
314+ .collect_view();
315+
316+ view! {
317+ <header class="topbar">
318+ <div class="wordmark">
319+ <span class="wordmark-text">"dizey"</span>
320+ <span class="wordmark-dot"></span>
321+ </div>
322+ <div class="topbar-divider"></div>
323+ <span class="board-name">"Mail rules"</span>
324+ <div class="spacer"></div>
325+ <span class="topbar-who" title=me.email.clone()>
326+ {me.display_name.clone()}
327+ </span>
328+ </header>
329+
330+ <div class="settings-shell">
331+ <nav class="sidenav">
332+ <a class="sidenav-item" href="/">
333+ "Board"
334+ </a>
335+ <a class="sidenav-item sidenav-item-on" href="/rules">
336+ "Mail rules"
337+ </a>
338+ <a class="sidenav-item" href="/settings">
339+ "Settings"
340+ </a>
341+ </nav>
342+
343+ <main class="settings-stage">
344+ <div class="settings-head">
345+ <h1 class="settings-title">"Mail rules"</h1>
346+ <span class="chip chip-admin">"Admin only"</span>
347+ <span class="settings-note">
348+ "One sentence per rule. A rule fires when a task on this board matches it. Only the admin writes them — a rule sends mail on everyone's behalf, from the one workspace sender."
349+ </span>
350+ </div>
351+
352+ {(!sender_connected)
353+ .then(|| {
354+ view! {
355+ <p class="rules-quiet">
356+ "No sender is connected yet, so nothing leaves the machine. Rules still fire and the mail they owe waits in the queue until you connect one in "
357+ <a href="/settings">"Settings"</a>
358+ "."
359+ </p>
360+ }
361+ })}
362+
363+ <Composer columns=snapshot.columns on_change=on_change/>
364+
365+ <div class="rule-list">
366+ {rows}
367+ {empty
368+ .then(|| {
369+ view! {
370+ <p class="rules-quiet">
371+ "No rules yet. Nothing on this board sends mail until you write one."
372+ </p>
373+ }
374+ })}
375+ </div>
376+ </main>
377+ </div>
378+ }
379+}
380+
381+/// The "New rule" control and the sentence it builds.
382+///
383+/// It is a `<details>` rather than a signal-driven panel so that a browser with
384+/// no script can still open it and post the form.
385+#[component]
386+fn Composer(columns: Vec<ColumnChoice>, on_change: Callback<()>) -> impl IntoView {
387+ let action = ServerAction::<CreateRule>::new();
388+ let value = action.value();
389+ // The composer owns its own open state rather than letting `<details>`
390+ // keep it: a rule that has just been written should leave a closed, empty
391+ // composer behind, not the sentence you already sent sitting in the field.
392+ let open = RwSignal::new(false);
393+ let subject = RwSignal::new(String::new());
394+ Effect::new(move |_| {
395+ if matches!(value.get(), Some(Ok(None))) {
396+ subject.set(String::new());
397+ open.set(false);
398+ on_change.run(());
399+ }
400+ });
401+ let refusal = move || match value.get() {
402+ Some(Ok(Some(refusal))) => Some(refusal.message()),
403+ Some(Err(_)) => Some(Refusal::Unavailable.message()),
404+ _ => None,
405+ };
406+ let options = columns
407+ .into_iter()
408+ .map(|column| view! { <option value=column.id>{column.name}</option> })
409+ .collect_view();
410+
411+ view! {
412+ <details class="rule-new" open=move || open.get()>
413+ <summary
414+ class="rule-new-open"
415+ on:click=move |ev| {
416+ ev.prevent_default();
417+ open.update(|o| *o = !*o);
418+ }
419+ >
420+ "New rule"
421+ </summary>
422+ <ActionForm action=action attr:class="rule-new-body">
423+ <label class="rule-field">
424+ <span class="field-label">"WHEN"</span>
425+ <select class="field-input" name="trigger">
426+ <option value="status">"status becomes"</option>
427+ <option value="unblocked">"a task stops being blocked"</option>
428+ </select>
429+ </label>
430+ <label class="rule-field">
431+ <span class="field-label">"COLUMN — FOR A STATUS RULE"</span>
432+ <select class="field-input" name="column_id">
433+ {options}
434+ </select>
435+ </label>
436+ <label class="rule-field">
437+ <span class="field-label">"SEND"</span>
438+ <input
439+ class="field-input"
440+ type="text"
441+ name="subject"
442+ placeholder="Task completed"
443+ maxlength="120"
444+ required
445+ prop:value=move || subject.get()
446+ on:input=move |ev| subject.set(event_target_value(&ev))
447+ />
448+ </label>
449+ <label class="rule-field">
450+ <span class="field-label">"TO"</span>
451+ <select class="field-input" name="audience">
452+ <option value="assignees">"assignees"</option>
453+ <option value="board">"everyone on board"</option>
454+ </select>
455+ </label>
456+ <div class="panel-foot">
457+ {move || {
458+ refusal()
459+ .map(|message| view! { <span class="field-error">{message}</span> })
460+ }}
461+ <button class="primary" type="submit">
462+ "Add rule"
463+ </button>
464+ </div>
465+ <span class="field-note">
466+ "A Viewer is never mailed by a rule, on any audience, and neither is whoever caused the event."
467+ </span>
468+ </ActionForm>
469+ </details>
470+ }
471+}
472+
473+#[component]
474+fn RuleRow(rule: RuleLine, on_change: Callback<()>) -> impl IntoView {
475+ let toggle = ServerAction::<SetRuleEnabled>::new();
476+ let remove = ServerAction::<DeleteRule>::new();
477+ let toggled = toggle.value();
478+ Effect::new(move |_| {
479+ if matches!(toggled.get(), Some(Ok(None))) {
480+ on_change.run(());
481+ }
482+ });
483+ let removed = remove.value();
484+ Effect::new(move |_| {
485+ if matches!(removed.get(), Some(Ok(None))) {
486+ on_change.run(());
487+ }
488+ });
489+
490+ let RuleLine { id, when, what, subject, audience, enabled, last_sent } = rule;
491+ let stamp = last_sent
492+ .map(|moment| format!("last sent {moment}"))
493+ .unwrap_or_else(|| "never sent".to_string());
494+ let row_class = if enabled { "rule-row" } else { "rule-row rule-row-off" };
495+ let switch_class = if enabled { "rule-switch rule-switch-on" } else { "rule-switch" };
496+ let switch_label = if enabled { "Switch this rule off" } else { "Switch this rule on" };
497+ // Each form carries the id in its own hidden field, and each of those
498+ // fields owns its copy: the two live in separate closures.
499+ let toggle_id = id.clone();
500+ let delete_id = id;
501+
502+ view! {
503+ <div class=row_class>
504+ <ActionForm action=toggle attr:class="rule-switch-form">
505+ <input type="hidden" name="rule_id" value=toggle_id/>
506+ <input type="hidden" name="enabled" value=(!enabled).to_string()/>
507+ <button class=switch_class type="submit" title=switch_label>
508+ <span class="rule-switch-knob"></span>
509+ <span class="visually-hidden">{switch_label}</span>
510+ </button>
511+ </ActionForm>
512+
513+ <div class="rule-sentence">
514+ <span>{when}</span>
515+ <span class="rule-term">{what}</span>
516+ <span>"send"</span>
517+ <span class="rule-term">{subject}</span>
518+ <span>"to"</span>
519+ <span class="rule-term">{audience}</span>
520+ </div>
521+
522+ <span class="rule-stamp">{stamp}</span>
523+
524+ <ActionForm action=remove>
525+ <input type="hidden" name="rule_id" value=delete_id/>
526+ <button class="rule-delete" type="submit" title="Delete this rule">
527+ "Delete"
528+ </button>
529+ </ActionForm>
530+ </div>
531+ }
532+}
crates/dizey-web/src/settings.rsmodified+3 -0
@@ -597,6 +597,9 @@ fn SettingsScreen(
597597 <a class="sidenav-item" href="/">
598598 "Board"
599599 </a>
600+ <a class="sidenav-item" href="/rules">
601+ "Mail rules"
602+ </a>
600603 <a class="sidenav-item sidenav-item-on" href="/settings">
601604 "Settings"
602605 </a>
crates/dizey-web/tests/http.rsmodified+324 -0
@@ -1643,3 +1643,327 @@ async fn testing_a_sender_that_was_never_filled_in_says_so_rather_than_sending()
16431643 .await;
16441644 assert!(!seen.body.contains("\"test\":{"), "{}", seen.body);
16451645 }
1646+
1647+/// Writes one rule as the admin, and reports whether the server took it.
1648+async fn rule_written(app: &App, admin: &str, column_id: &str, subject: &str) -> bool {
1649+ let answer = app
1650+ .post(
1651+ path::<dizey_web::rules::CreateRule>(),
1652+ Some(admin),
1653+ &[
1654+ ("trigger", "status"),
1655+ ("column_id", column_id),
1656+ ("subject", subject),
1657+ ("audience", "assignees"),
1658+ ],
1659+ )
1660+ .await;
1661+ answer.status == StatusCode::OK && answer.body == "null"
1662+}
1663+
1664+/// The id of the one rule the workspace has.
1665+async fn only_rule(app: &App, admin: &str) -> String {
1666+ let answer = app
1667+ .post(path::<dizey_web::rules::CurrentRules>(), Some(admin), &[])
1668+ .await;
1669+ answer
1670+ .body
1671+ .split("\"rules\":[")
1672+ .nth(1)
1673+ .and_then(|rest| rest.split("\"id\":\"").nth(1))
1674+ .and_then(|rest| rest.split('"').next())
1675+ .unwrap_or_else(|| panic!("no rule id in {}", answer.body))
1676+ .to_string()
1677+}
1678+
1679+#[tokio::test]
1680+async fn an_admin_writes_a_rule_and_reads_it_back_as_a_sentence() {
1681+ let app = App::open().await;
1682+ let admin_cookie = admin(&app).await;
1683+ let column = first_column(&app, &admin_cookie).await;
1684+
1685+ assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
1686+
1687+ let answer = app
1688+ .post(
1689+ path::<dizey_web::rules::CurrentRules>(),
1690+ Some(&admin_cookie),
1691+ &[],
1692+ )
1693+ .await;
1694+ assert!(
1695+ answer.body.contains("\"when\":\"When status becomes\""),
1696+ "{}",
1697+ answer.body
1698+ );
1699+ assert!(
1700+ answer.body.contains("\"subject\":\"Task completed\""),
1701+ "{}",
1702+ answer.body
1703+ );
1704+ assert!(
1705+ answer.body.contains("\"audience\":\"assignees\""),
1706+ "{}",
1707+ answer.body
1708+ );
1709+ // Nothing has been sent, and the row says so rather than nothing at all.
1710+ assert!(answer.body.contains("\"last_sent\":null"), "{}", answer.body);
1711+}
1712+
1713+#[tokio::test]
1714+async fn a_rule_with_no_subject_is_refused_and_says_why() {
1715+ let app = App::open().await;
1716+ let admin_cookie = admin(&app).await;
1717+ let column = first_column(&app, &admin_cookie).await;
1718+
1719+ let answer = app
1720+ .post(
1721+ path::<dizey_web::rules::CreateRule>(),
1722+ Some(&admin_cookie),
1723+ &[
1724+ ("trigger", "status"),
1725+ ("column_id", &column),
1726+ ("subject", " "),
1727+ ("audience", "assignees"),
1728+ ],
1729+ )
1730+ .await;
1731+ assert!(answer.body.contains("EmptySubject"), "{}", answer.body);
1732+}
1733+
1734+#[tokio::test]
1735+async fn a_rule_may_not_be_hung_off_a_column_that_is_not_on_this_board() {
1736+ let app = App::open().await;
1737+ let admin_cookie = admin(&app).await;
1738+
1739+ let answer = app
1740+ .post(
1741+ path::<dizey_web::rules::CreateRule>(),
1742+ Some(&admin_cookie),
1743+ &[
1744+ ("trigger", "status"),
1745+ ("column_id", &Uuid::new_v4().to_string()),
1746+ ("subject", "Task completed"),
1747+ ("audience", "assignees"),
1748+ ],
1749+ )
1750+ .await;
1751+ assert!(answer.body.contains("Forbidden"), "{}", answer.body);
1752+
1753+ let seen = app
1754+ .post(
1755+ path::<dizey_web::rules::CurrentRules>(),
1756+ Some(&admin_cookie),
1757+ &[],
1758+ )
1759+ .await;
1760+ assert!(seen.body.contains("\"rules\":[]"), "{}", seen.body);
1761+}
1762+
1763+#[tokio::test]
1764+async fn an_audience_the_screen_never_offers_is_refused() {
1765+ let app = App::open().await;
1766+ let admin_cookie = admin(&app).await;
1767+ let column = first_column(&app, &admin_cookie).await;
1768+
1769+ let answer = app
1770+ .post(
1771+ path::<dizey_web::rules::CreateRule>(),
1772+ Some(&admin_cookie),
1773+ &[
1774+ ("trigger", "status"),
1775+ ("column_id", &column),
1776+ ("subject", "Task completed"),
1777+ ("audience", "everyone-everywhere"),
1778+ ],
1779+ )
1780+ .await;
1781+ assert!(answer.body.contains("Forbidden"), "{}", answer.body);
1782+}
1783+
1784+#[tokio::test]
1785+async fn switching_a_rule_off_leaves_it_listed_and_switched_off() {
1786+ let app = App::open().await;
1787+ let admin_cookie = admin(&app).await;
1788+ let column = first_column(&app, &admin_cookie).await;
1789+ assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
1790+ let rule = only_rule(&app, &admin_cookie).await;
1791+
1792+ let answer = app
1793+ .post(
1794+ path::<dizey_web::rules::SetRuleEnabled>(),
1795+ Some(&admin_cookie),
1796+ &[("rule_id", &rule), ("enabled", "false")],
1797+ )
1798+ .await;
1799+ assert_eq!(answer.body, "null", "{}", answer.body);
1800+
1801+ // The screen lists what exists, not what is live.
1802+ let seen = app
1803+ .post(
1804+ path::<dizey_web::rules::CurrentRules>(),
1805+ Some(&admin_cookie),
1806+ &[],
1807+ )
1808+ .await;
1809+ assert!(seen.body.contains("\"enabled\":false"), "{}", seen.body);
1810+ assert!(
1811+ seen.body.contains("\"subject\":\"Task completed\""),
1812+ "{}",
1813+ seen.body
1814+ );
1815+}
1816+
1817+#[tokio::test]
1818+async fn a_rule_id_this_workspace_does_not_own_is_refused() {
1819+ let app = App::open().await;
1820+ let admin_cookie = admin(&app).await;
1821+ let stranger = Uuid::new_v4().to_string();
1822+
1823+ for path in [
1824+ path::<dizey_web::rules::SetRuleEnabled>(),
1825+ path::<dizey_web::rules::DeleteRule>(),
1826+ ] {
1827+ let answer = app
1828+ .post(
1829+ path,
1830+ Some(&admin_cookie),
1831+ &[("rule_id", &stranger), ("enabled", "false")],
1832+ )
1833+ .await;
1834+ assert!(answer.body.contains("NotFound"), "{path}: {}", answer.body);
1835+ }
1836+}
1837+
1838+#[tokio::test]
1839+async fn deleting_a_rule_takes_it_off_the_screen() {
1840+ let app = App::open().await;
1841+ let admin_cookie = admin(&app).await;
1842+ let column = first_column(&app, &admin_cookie).await;
1843+ assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
1844+ let rule = only_rule(&app, &admin_cookie).await;
1845+
1846+ let answer = app
1847+ .post(
1848+ path::<dizey_web::rules::DeleteRule>(),
1849+ Some(&admin_cookie),
1850+ &[("rule_id", &rule)],
1851+ )
1852+ .await;
1853+ assert_eq!(answer.body, "null", "{}", answer.body);
1854+
1855+ let seen = app
1856+ .post(
1857+ path::<dizey_web::rules::CurrentRules>(),
1858+ Some(&admin_cookie),
1859+ &[],
1860+ )
1861+ .await;
1862+ assert!(seen.body.contains("\"rules\":[]"), "{}", seen.body);
1863+}
1864+
1865+#[tokio::test]
1866+async fn only_an_admin_may_read_or_write_the_rules() {
1867+ let app = App::open().await;
1868+ let admin_cookie = admin(&app).await;
1869+ let column = first_column(&app, &admin_cookie).await;
1870+ assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
1871+ let rule = only_rule(&app, &admin_cookie).await;
1872+
1873+ let member = invited(&app, &admin_cookie, "emre@dizey.sh", "Emre", Role::Member).await;
1874+ let viewer = invited(&app, &admin_cookie, "pinar@dizey.sh", "Pinar", Role::Viewer).await;
1875+
1876+ for who in [&member, &viewer] {
1877+ let read = app
1878+ .post(path::<dizey_web::rules::CurrentRules>(), Some(who), &[])
1879+ .await;
1880+ assert!(read.body.contains("Forbidden"), "{}", read.body);
1881+
1882+ let written = app
1883+ .post(
1884+ path::<dizey_web::rules::CreateRule>(),
1885+ Some(who),
1886+ &[
1887+ ("trigger", "status"),
1888+ ("column_id", &column),
1889+ ("subject", "Mail everyone about me"),
1890+ ("audience", "board"),
1891+ ],
1892+ )
1893+ .await;
1894+ assert!(written.body.contains("Forbidden"), "{}", written.body);
1895+
1896+ let switched = app
1897+ .post(
1898+ path::<dizey_web::rules::SetRuleEnabled>(),
1899+ Some(who),
1900+ &[("rule_id", &rule), ("enabled", "false")],
1901+ )
1902+ .await;
1903+ assert!(switched.body.contains("Forbidden"), "{}", switched.body);
1904+
1905+ let deleted = app
1906+ .post(
1907+ path::<dizey_web::rules::DeleteRule>(),
1908+ Some(who),
1909+ &[("rule_id", &rule)],
1910+ )
1911+ .await;
1912+ assert!(deleted.body.contains("Forbidden"), "{}", deleted.body);
1913+ }
1914+
1915+ // And the rule is untouched: still there, still on.
1916+ let seen = app
1917+ .post(
1918+ path::<dizey_web::rules::CurrentRules>(),
1919+ Some(&admin_cookie),
1920+ &[],
1921+ )
1922+ .await;
1923+ assert!(seen.body.contains("\"enabled\":true"), "{}", seen.body);
1924+ assert!(
1925+ !seen.body.contains("Mail everyone about me"),
1926+ "{}",
1927+ seen.body
1928+ );
1929+}
1930+
1931+#[tokio::test]
1932+async fn a_signed_out_browser_may_not_touch_the_rules() {
1933+ let app = App::open().await;
1934+ let admin_cookie = admin(&app).await;
1935+ let column = first_column(&app, &admin_cookie).await;
1936+ assert!(rule_written(&app, &admin_cookie, &column, "Task completed").await);
1937+ let rule = only_rule(&app, &admin_cookie).await;
1938+
1939+ for (path, form) in [
1940+ (
1941+ path::<dizey_web::rules::CurrentRules>(),
1942+ vec![] as Vec<(&str, &str)>,
1943+ ),
1944+ (
1945+ path::<dizey_web::rules::CreateRule>(),
1946+ vec![
1947+ ("trigger", "status"),
1948+ ("column_id", column.as_str()),
1949+ ("subject", "Task completed"),
1950+ ("audience", "assignees"),
1951+ ],
1952+ ),
1953+ (
1954+ path::<dizey_web::rules::SetRuleEnabled>(),
1955+ vec![("rule_id", rule.as_str()), ("enabled", "false")],
1956+ ),
1957+ (
1958+ path::<dizey_web::rules::DeleteRule>(),
1959+ vec![("rule_id", rule.as_str())],
1960+ ),
1961+ ] {
1962+ let answer = app.post(path, None, &form).await;
1963+ assert!(
1964+ answer.body.contains("SignInFirst"),
1965+ "{path}: {}",
1966+ answer.body
1967+ );
1968+ }
1969+}
style/main.scssmodified+158 -0
@@ -1803,3 +1803,161 @@ a {
18031803
18041804 &:hover { color: var(--accent-ink); }
18051805 }
1806+
1807+// --- Mail rules (MailRules artboard) ---------------------------------------
1808+
1809+// Text only a screen reader needs: the switch says what it does in a word the
1810+// eye reads from its position, and the ear cannot.
1811+.visually-hidden {
1812+ position: absolute;
1813+ width: 1px;
1814+ height: 1px;
1815+ margin: -1px;
1816+ padding: 0;
1817+ overflow: hidden;
1818+ clip-path: inset(50%);
1819+ white-space: nowrap;
1820+}
1821+
1822+.rules-quiet {
1823+ margin: 0;
1824+ font-size: 13px;
1825+ color: var(--muted);
1826+}
1827+
1828+.rule-list {
1829+ display: flex;
1830+ flex-direction: column;
1831+ gap: 10px;
1832+}
1833+
1834+.rule-row {
1835+ display: flex;
1836+ align-items: center;
1837+ gap: 14px;
1838+ padding: 16px;
1839+ background: var(--surface);
1840+ border: 1px solid var(--border);
1841+ border-radius: 8px;
1842+
1843+ // A rule that is switched off is still listed — the screen shows what
1844+ // exists, not what is live — and reads as the quieter of the two.
1845+ &-off {
1846+ background: #faf9f4;
1847+ opacity: 0.75;
1848+ }
1849+}
1850+
1851+.rule-switch-form { display: flex; flex-shrink: 0; }
1852+
1853+.rule-switch {
1854+ width: 36px;
1855+ height: 20px;
1856+ padding: 0;
1857+ border: none;
1858+ border-radius: 10px;
1859+ background: #d5d1c7;
1860+ position: relative;
1861+ cursor: pointer;
1862+
1863+ &-knob {
1864+ position: absolute;
1865+ top: 2px;
1866+ left: 2px;
1867+ width: 16px;
1868+ height: 16px;
1869+ border-radius: 50%;
1870+ background: var(--surface);
1871+ }
1872+
1873+ &-on {
1874+ background: var(--accent);
1875+ .rule-switch-knob { left: auto; right: 2px; }
1876+ }
1877+}
1878+
1879+.rule-sentence {
1880+ display: flex;
1881+ align-items: center;
1882+ flex-wrap: wrap;
1883+ gap: 8px;
1884+ flex-grow: 1;
1885+ min-width: 0;
1886+ font-size: 13px;
1887+ color: #3d3a34;
1888+}
1889+
1890+// One chosen word inside the sentence: a column, a subject, an audience.
1891+.rule-term {
1892+ display: inline-flex;
1893+ align-items: center;
1894+ padding: 3px 8px;
1895+ background: var(--accent-tint);
1896+ border: 1px solid #d8dce6;
1897+ border-radius: 5px;
1898+ font-weight: 500;
1899+}
1900+
1901+.rule-row-off .rule-term {
1902+ background: #f1efe8;
1903+ border-color: var(--border-strong);
1904+}
1905+
1906+.rule-stamp {
1907+ flex-shrink: 0;
1908+ font-family: var(--font-mono);
1909+ font-size: 11px;
1910+ color: var(--muted-soft);
1911+}
1912+
1913+.rule-delete {
1914+ flex-shrink: 0;
1915+ height: 32px;
1916+ padding: 0 12px;
1917+ background: transparent;
1918+ border: 1px solid var(--border-strong);
1919+ border-radius: var(--radius);
1920+ color: var(--muted);
1921+ font-family: var(--font-sans);
1922+ font-size: 12px;
1923+ font-weight: 600;
1924+ cursor: pointer;
1925+
1926+ &:hover { background: #f1efe8; color: #a04a24; }
1927+}
1928+
1929+.rule-new {
1930+ background: var(--surface);
1931+ border: 1px solid var(--border);
1932+ border-radius: 10px;
1933+}
1934+
1935+.rule-new-open {
1936+ display: flex;
1937+ align-items: center;
1938+ height: 44px;
1939+ padding: 0 16px;
1940+ font-size: 13px;
1941+ font-weight: 600;
1942+ color: var(--accent-ink);
1943+ cursor: pointer;
1944+ list-style: none;
1945+
1946+ &::marker, &::-webkit-details-marker { display: none; }
1947+ &::before { content: '+'; margin-right: 8px; font-size: 15px; }
1948+}
1949+
1950+.rule-new-body {
1951+ display: flex;
1952+ flex-direction: column;
1953+ gap: 14px;
1954+ padding: 0 16px 16px;
1955+ border-top: 1px solid var(--border);
1956+ padding-top: 16px;
1957+}
1958+
1959+.rule-field {
1960+ display: flex;
1961+ flex-direction: column;
1962+ gap: 6px;
1963+}