forge
Explore
Log in

Don't you dare go Hollow

Mail: SMTP sender settings, outbox worker, rules engine with transactional events, reminders, rules and logs pages, message to members

Browse files at this commit

de8406267a4c2b3a822ac8c032d2504e2edd285fAhmet Kaan GümüşParent: b08e0c0
  • feat
    • mail: SMTP sender settings, outbox worker, rules engine with transactional events, reminders, rules and logs pages, message to members
Show full message
✨ feat: mail: SMTP sender settings, outbox worker, rules engine with transactional events, reminders, rules and logs pages, message to members
Cargo.lockmodified+22 -0
@@ -1905,6 +1905,7 @@ dependencies = [
1905 "iz-core",1905 "iz-core",
1906 "jiff",1906 "jiff",
1907 "jsonwebtoken",1907 "jsonwebtoken",
1908+ "lettre",
1908 "rand 0.10.3",1909 "rand 0.10.3",
1909 "reqwest",1910 "reqwest",
1910 "serde",1911 "serde",
@@ -2076,15 +2077,26 @@ version = "0.11.23"
2076 source = "registry+https://github.com/rust-lang/crates.io-index"2077 source = "registry+https://github.com/rust-lang/crates.io-index"
2077 checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae"2078 checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae"
2078 dependencies = [2079 dependencies = [
2080+ "async-trait",
2081+ "base64 0.23.1",
2079 "email-encoding",2082 "email-encoding",
2080 "email_address",2083 "email_address",
2081 "fastrand",2084 "fastrand",
2085+ "futures-io",
2086+ "futures-util",
2082 "hostname",2087 "hostname",
2083 "httpdate",2088 "httpdate",
2084 "idna",2089 "idna",
2085 "mime",2090 "mime",
2086 "nom 8.0.0",2091 "nom 8.0.0",
2092+ "percent-encoding",
2087 "quoted_printable",2093 "quoted_printable",
2094+ "rustls",
2095+ "socket2",
2096+ "tokio",
2097+ "tokio-rustls",
2098+ "url",
2099+ "webpki-roots",
2088 ]2100 ]
2089 2101
2090 [[package]]2102 [[package]]
@@ -3126,6 +3138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
3126 checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"3138 checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
3127 dependencies = [3139 dependencies = [
3128 "aws-lc-rs",3140 "aws-lc-rs",
3141+ "log",
3129 "once_cell",3142 "once_cell",
3130 "rustls-pki-types",3143 "rustls-pki-types",
3131 "rustls-webpki",3144 "rustls-webpki",
@@ -4939,6 +4952,15 @@ dependencies = [
4939 "rustls-pki-types",4952 "rustls-pki-types",
4940 ]4953 ]
4941 4954
4955+[[package]]
4956+name = "webpki-roots"
4957+version = "1.0.11"
4958+source = "registry+https://github.com/rust-lang/crates.io-index"
4959+checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
4960+dependencies = [
4961+ "rustls-pki-types",
4962+]
4963+
4942 [[package]]4964 [[package]]
4943 name = "which"4965 name = "which"
4944 version = "4.4.2"4966 version = "4.4.2"
Cargo.tomlmodified+1 -0
@@ -25,6 +25,7 @@ http-body-util = "0.1.5"
25 chacha20poly1305 = "0.11.0"25 chacha20poly1305 = "0.11.0"
26 hex = "0.4.3"26 hex = "0.4.3"
27 ipnet = "2.12.2"27 ipnet = "2.12.2"
28+lettre = { version = "0.11.23", default-features = false, features = ["builder", "hostname", "smtp-transport", "tokio1", "tokio1-rustls", "aws-lc-rs", "webpki-roots"] }
28 jsonwebtoken = { version = "11.1.0", default-features = false, features = ["aws_lc_rs"] }29 jsonwebtoken = { version = "11.1.0", default-features = false, features = ["aws_lc_rs"] }
29 jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] }30 jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] }
30 rand = "0.10.3"31 rand = "0.10.3"
crates/iz-core/migrations/0004_mail_events.sqladded+22 -0
@@ -0,0 +1,22 @@
1+-- 0004: the event queue of the mail rules engine. A task or comment write inserts one row per event in
2+-- the same transaction as the change (store/events.rs), so a crash can neither lose nor duplicate an
3+-- event. The rules engine (store/rules_engine.rs) reads unprocessed rows in order and writes the
4+-- decisions and outbox rows of each one. The mail system never inserts here, so mail cannot trigger rules.
5+
6+CREATE TABLE mail_events (
7+ id TEXT PRIMARY KEY,
8+ board_id TEXT NOT NULL REFERENCES boards(id) ON DELETE CASCADE,
9+ -- No foreign key: the ledger of an event outlives its task (a deleted task is still named in mail).
10+ task_id TEXT,
11+ kind TEXT NOT NULL CHECK (kind IN (
12+ 'status', 'unblocked', 'created', 'assigned', 'unassigned', 'commented',
13+ 'deadline_set', 'deadline_cleared', 'retitled', 'linked', 'unlinked', 'deleted'
14+ )),
15+ column_id TEXT,
16+ actor TEXT,
17+ subject TEXT,
18+ detail TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(detail)),
19+ at TEXT NOT NULL,
20+ processed_at TEXT
21+);
22+CREATE INDEX mail_events_pending ON mail_events(at, id) WHERE processed_at IS NULL;
crates/iz-core/src/clock.rsmodified+6 -6
@@ -15,8 +15,7 @@ use crate::error::{Error, Result};
15 use crate::time::format_stamp;15 use crate::time::format_stamp;
16 use crate::zones::{local_to_utc, utc_to_local};16 use crate::zones::{local_to_utc, utc_to_local};
17 17
18-/// How long before a meeting its reminder is due, in minutes. A default; the `reminder_minutes`18+/// How long before a meeting its reminder is due, in minutes, when the setting was never saved.
19-/// setting replaces it once the setting exists.
20 pub const REMINDER_LEAD_MINUTES: i64 = 15;19 pub const REMINDER_LEAD_MINUTES: i64 = 15;
21 20
22 /// What the user typed for a deadline and meeting time. Every part is optional.21 /// What the user typed for a deadline and meeting time. Every part is optional.
@@ -68,10 +67,11 @@ pub fn timestamp_of(stamp: &str) -> Result<Timestamp> {
68 .map_err(|e| Error::Database(format!("stored meeting time is not a stamp: {e}")))67 .map_err(|e| Error::Database(format!("stored meeting time is not a stamp: {e}")))
69 }68 }
70 69
71-/// The moment a reminder for a meeting at `meeting` is due: `REMINDER_LEAD_MINUTES` before it.70+/// The moment a reminder for a meeting at `meeting` is due: `lead_minutes` before it. The lead comes from
72-pub fn reminder_due(meeting: Timestamp) -> Result<String> {71+/// the `reminder_minutes` setting (0 turns reminders off, so the caller never asks for a due time then).
72+pub fn reminder_due(meeting: Timestamp, lead_minutes: i64) -> Result<String> {
73 let due = meeting73 let due = meeting
74- .checked_sub(SignedDuration::from_mins(REMINDER_LEAD_MINUTES))74+ .checked_sub(SignedDuration::from_mins(lead_minutes))
75 .map_err(|e| Error::Invalid(format!("reminder time out of range: {e}")))?;75 .map_err(|e| Error::Invalid(format!("reminder time out of range: {e}")))?;
76 stamp_of(due)76 stamp_of(due)
77 }77 }
@@ -153,7 +153,7 @@ mod tests {
153 fn reminder_is_lead_time_before_meeting() {153 fn reminder_is_lead_time_before_meeting() {
154 let meeting: Timestamp = "2026-01-15T08:30:00Z".parse().unwrap();154 let meeting: Timestamp = "2026-01-15T08:30:00Z".parse().unwrap();
155 assert_eq!(155 assert_eq!(
156- reminder_due(meeting).unwrap(),156+ reminder_due(meeting, REMINDER_LEAD_MINUTES).unwrap(),
157 "2026-01-15T08:15:00.000000000Z"157 "2026-01-15T08:15:00.000000000Z"
158 );158 );
159 }159 }
crates/iz-core/src/lib.rsmodified+3 -0
@@ -10,8 +10,11 @@ pub mod clock;
10 pub mod config;10 pub mod config;
11 pub mod error;11 pub mod error;
12 pub mod limits;12 pub mod limits;
13+pub mod mail_text;
13 pub mod preview;14 pub mod preview;
15+pub mod rules;
14 pub mod secret;16 pub mod secret;
17+pub mod sender;
15 pub mod sheet;18 pub mod sheet;
16 pub mod slides;19 pub mod slides;
17 pub mod sniff;20 pub mod sniff;
crates/iz-core/src/limits.rsmodified+13 -0
@@ -63,3 +63,16 @@ pub const SLIDES_MAX: usize = 200;
63 pub const SLIDE_TEXT_MAX: usize = 4000;63 pub const SLIDE_TEXT_MAX: usize = 4000;
64 /// Largest XML part of a deck that is read, in bytes. Reason: a single slide is far below this.64 /// Largest XML part of a deck that is read, in bytes. Reason: a single slide is far below this.
65 pub const DECK_PART_MAX_BYTES: u64 = 4 * 1024 * 1024;65 pub const DECK_PART_MAX_BYTES: u64 = 4 * 1024 * 1024;
66+
67+/// Longest mail subject after rendering, in characters. Reason: header lines stay short and readable.
68+pub const MAIL_SUBJECT_MAX: usize = 200;
69+/// Longest sender display name, in characters. Reason: a mail client shows only the start of it.
70+pub const SENDER_NAME_MAX: usize = 100;
71+/// Longest host name of the mail server, in characters (DNS limit).
72+pub const SENDER_HOST_MAX: usize = 253;
73+/// Longest SMTP user name, in characters. Reason: long enough for an address, short enough to store.
74+pub const SMTP_USERNAME_MAX: usize = 254;
75+/// Longest SMTP password, in characters. Reason: a generous bound for a stored secret.
76+pub const SMTP_PASSWORD_MAX: usize = 512;
77+/// Highest reminder cap a member can be given, in mails per hour. Reason: above this the cap is no guard.
78+pub const REMINDER_CAP_MAX: u32 = 500;
crates/iz-core/src/mail_text.rsadded+312 -0
@@ -0,0 +1,312 @@
1+//! The words of every mail iz sends: rule mails, reminders, admin notices and the test mail, in English
2+//! and Turkish. Pure text: no I/O, no HTML (the web layer escapes the plain text when it builds the HTML part).
3+//!
4+//! The strings are keyed by [`K`] and matched exhaustively on `(key, language)`, so a missing translation
5+//! does not compile. Values (names, titles, times) are cleaned with [`clean_text`] before they are placed,
6+//! so no value can add a line to a subject. The brand in every text is the single word `iz`.
7+
8+use jiff::Timestamp;
9+
10+use crate::rules::clean_text;
11+use crate::zones::{parse_zone, utc_to_local};
12+
13+/// The language a mail is written in: the recipient's own choice, else the directory's, else English.
14+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15+pub enum MailLang {
16+ /// English.
17+ En,
18+ /// Turkish.
19+ Tr,
20+}
21+
22+impl MailLang {
23+ /// The language for a member: `locale_override` first, then the directory `locale`, else English.
24+ pub fn of(locale_override: Option<&str>, locale: Option<&str>) -> MailLang {
25+ match locale_override.or(locale) {
26+ Some("tr") => MailLang::Tr,
27+ _ => MailLang::En,
28+ }
29+ }
30+}
31+
32+/// A subject and a plain-text body, ready to be stored in the outbox.
33+#[derive(Debug, Clone, PartialEq, Eq)]
34+pub struct Mail {
35+ /// The subject, plain text, already cleaned and short.
36+ pub subject: String,
37+ /// The body, plain text with `\n` line breaks.
38+ pub body: String,
39+}
40+
41+/// Every fixed string of a mail. Matched exhaustively in [`text`].
42+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43+pub enum K {
44+ /// Heading label of the key and title line.
45+ Key,
46+ /// Label of the column.
47+ Column,
48+ /// Label of the deadline day.
49+ Deadline,
50+ /// Label of the assignees.
51+ Assignees,
52+ /// Label of the meeting time.
53+ When,
54+ /// Label of the link back to the board.
55+ Link,
56+ /// Sentence: the task moved to a column.
57+ SentStatus,
58+ /// Sentence: the task was created.
59+ SentCreated,
60+ /// Sentence: someone was assigned.
61+ SentAssigned,
62+ /// Sentence: someone was removed from the assignees.
63+ SentUnassigned,
64+ /// Sentence: a comment was posted.
65+ SentCommented,
66+ /// Sentence: a deadline or meeting time was set.
67+ SentDeadlineSet,
68+ /// Sentence: a deadline or meeting time was cleared.
69+ SentDeadlineCleared,
70+ /// Sentence: the title changed.
71+ SentRetitled,
72+ /// Sentence: a dependency was added.
73+ SentLinked,
74+ /// Sentence: a dependency was removed.
75+ SentUnlinked,
76+ /// Sentence: the task was deleted.
77+ SentDeleted,
78+ /// Sentence: the task stopped being blocked.
79+ SentUnblocked,
80+ /// Subject prefix of a reminder, before the title.
81+ ReminderSubject,
82+ /// The reminder body's first line, before the meeting time.
83+ ReminderLead,
84+ /// Subject of the test mail.
85+ TestSubject,
86+ /// Body of the test mail.
87+ TestBody,
88+}
89+
90+/// The text of `key` in `lang`. Exhaustive over both languages.
91+pub fn text(lang: MailLang, key: K) -> &'static str {
92+ use MailLang::{En, Tr};
93+ match (key, lang) {
94+ (K::Key, En) => "Task",
95+ (K::Key, Tr) => "Kart",
96+ (K::Column, En) => "Column",
97+ (K::Column, Tr) => "Sütun",
98+ (K::Deadline, En) => "Deadline",
99+ (K::Deadline, Tr) => "Son tarih",
100+ (K::Assignees, En) => "Assignees",
101+ (K::Assignees, Tr) => "Atananlar",
102+ (K::When, En) => "Meeting time",
103+ (K::When, Tr) => "Toplantı saati",
104+ (K::Link, En) => "Open the task",
105+ (K::Link, Tr) => "Kartı aç",
106+ (K::SentStatus, En) => "moved the task to the column",
107+ (K::SentStatus, Tr) => "kartı sütuna taşıdı",
108+ (K::SentCreated, En) => "created the task",
109+ (K::SentCreated, Tr) => "kartı oluşturdu",
110+ (K::SentAssigned, En) => "assigned",
111+ (K::SentAssigned, Tr) => "kişisini atadı",
112+ (K::SentUnassigned, En) => "removed the assignment of",
113+ (K::SentUnassigned, Tr) => "kişisinin atamasını kaldırdı",
114+ (K::SentCommented, En) => "commented on the task",
115+ (K::SentCommented, Tr) => "karta yorum yaptı",
116+ (K::SentDeadlineSet, En) => "set the deadline or meeting time",
117+ (K::SentDeadlineSet, Tr) => "son tarihi veya toplantı saatini belirledi",
118+ (K::SentDeadlineCleared, En) => "cleared the deadline or meeting time",
119+ (K::SentDeadlineCleared, Tr) => "son tarihi veya toplantı saatini kaldırdı",
120+ (K::SentRetitled, En) => "changed the title",
121+ (K::SentRetitled, Tr) => "kartın başlığını değiştirdi",
122+ (K::SentLinked, En) => "added a dependency",
123+ (K::SentLinked, Tr) => "bir bağımlılık ekledi",
124+ (K::SentUnlinked, En) => "removed a dependency",
125+ (K::SentUnlinked, Tr) => "bir bağımlılığı kaldırdı",
126+ (K::SentDeleted, En) => "deleted the task",
127+ (K::SentDeleted, Tr) => "kartı sildi",
128+ (K::SentUnblocked, En) => "The task is no longer blocked.",
129+ (K::SentUnblocked, Tr) => "Kart artık engelli değil.",
130+ (K::ReminderSubject, En) => "Reminder:",
131+ (K::ReminderSubject, Tr) => "Hatırlatma:",
132+ (K::ReminderLead, En) => "A meeting for this task is coming up.",
133+ (K::ReminderLead, Tr) => "Bu kart için bir toplantı yaklaşıyor.",
134+ (K::TestSubject, En) => "iz test mail",
135+ (K::TestSubject, Tr) => "iz deneme e-postası",
136+ (K::TestBody, En) => "This is a test mail from iz. No other action follows from it.",
137+ (K::TestBody, Tr) => {
138+ "Bu, iz uygulamasından bir deneme e-postasıdır. Başka bir işlem yapmaz."
139+ }
140+ }
141+}
142+
143+/// The meeting time as text in a member's zone: `2026-10-28 14:30 Europe/Istanbul`. Unknown zones are
144+/// shown in UTC with the zone name `UTC`, so the text is never empty for a stored instant.
145+pub fn when_text(stamp: &str, zoneinfo: &str) -> Option<String> {
146+ let at: Timestamp = stamp.parse().ok()?;
147+ let zone = parse_zone(zoneinfo).ok();
148+ let name = zone
149+ .as_ref()
150+ .and_then(|z| z.iana_name().map(str::to_owned))
151+ .unwrap_or_else(|| "UTC".to_owned());
152+ let zone = zone.unwrap_or(jiff::tz::TimeZone::UTC);
153+ let local = utc_to_local(&zone, at);
154+ Some(format!("{} {}", local.strftime("%Y-%m-%d %H:%M"), name))
155+}
156+
157+/// Everything a rule mail says about one task and one event.
158+pub struct RuleMail<'a> {
159+ /// The recipient's language.
160+ pub lang: MailLang,
161+ /// The trigger word of the event.
162+ pub kind: &'a str,
163+ /// Who did it, by name.
164+ pub actor: &'a str,
165+ /// The person the event names, by name (assigned and unassigned events).
166+ pub subject_name: &'a str,
167+ /// The task key, for example `IZ-42`.
168+ pub key: &'a str,
169+ /// The task title.
170+ pub title: &'a str,
171+ /// The column name.
172+ pub column: &'a str,
173+ /// The deadline day, if any.
174+ pub deadline: Option<&'a str>,
175+ /// The assignee names, sorted as the store lists them.
176+ pub assignees: &'a [String],
177+ /// The meeting time in the recipient's zone, if any.
178+ pub when: Option<&'a str>,
179+ /// The link back to the task.
180+ pub link: &'a str,
181+ /// Whether the details block is included (the rule's `include_details`).
182+ pub details: bool,
183+ /// The subject, already rendered from the rule's template.
184+ pub subject: &'a str,
185+}
186+
187+/// The body of a rule mail: the event sentence, then the details the rule opts into, then the link.
188+pub fn rule_body(m: &RuleMail<'_>) -> String {
189+ let lang = m.lang;
190+ let actor = clean_text(m.actor);
191+ let subject_name = clean_text(m.subject_name);
192+ let sentence = match m.kind {
193+ "status" => format!(
194+ "{actor} {} {}.",
195+ text(lang, K::SentStatus),
196+ clean_text(m.column)
197+ ),
198+ "created" => format!("{actor} {}.", text(lang, K::SentCreated)),
199+ "assigned" => format!("{actor} {} {subject_name}.", text(lang, K::SentAssigned)),
200+ "unassigned" => format!("{actor} {} {subject_name}.", text(lang, K::SentUnassigned)),
201+ "commented" => format!("{actor} {}.", text(lang, K::SentCommented)),
202+ "deadline_set" => format!("{actor} {}.", text(lang, K::SentDeadlineSet)),
203+ "deadline_cleared" => format!("{actor} {}.", text(lang, K::SentDeadlineCleared)),
204+ "retitled" => format!("{actor} {}.", text(lang, K::SentRetitled)),
205+ "linked" => format!("{actor} {}.", text(lang, K::SentLinked)),
206+ "unlinked" => format!("{actor} {}.", text(lang, K::SentUnlinked)),
207+ "deleted" => format!("{actor} {}.", text(lang, K::SentDeleted)),
208+ _ => text(lang, K::SentUnblocked).to_owned(),
209+ };
210+ let mut lines = vec![
211+ format!(
212+ "{}: {} — {}",
213+ text(lang, K::Key),
214+ clean_text(m.key),
215+ clean_text(m.title)
216+ ),
217+ sentence,
218+ ];
219+ if m.details {
220+ lines.push(format!(
221+ "{}: {}",
222+ text(lang, K::Column),
223+ clean_text(m.column)
224+ ));
225+ if let Some(day) = m.deadline {
226+ lines.push(format!("{}: {}", text(lang, K::Deadline), clean_text(day)));
227+ }
228+ let names: Vec<String> = m.assignees.iter().map(|n| clean_text(n)).collect();
229+ if !names.is_empty() {
230+ lines.push(format!(
231+ "{}: {}",
232+ text(lang, K::Assignees),
233+ names.join(", ")
234+ ));
235+ }
236+ if let Some(when) = m.when {
237+ lines.push(format!("{}: {}", text(lang, K::When), clean_text(when)));
238+ }
239+ }
240+ lines.push(format!("{}: {}", text(lang, K::Link), clean_text(m.link)));
241+ lines.join("\n")
242+}
243+
244+/// A reminder for a meeting: subject with the title and key, body with the meeting time in the
245+/// recipient's zone and the link.
246+pub fn reminder(lang: MailLang, key: &str, title: &str, when: &str, link: &str) -> Mail {
247+ Mail {
248+ subject: clean_text(&format!(
249+ "{} {} ({})",
250+ text(lang, K::ReminderSubject),
251+ title,
252+ key
253+ ))
254+ .chars()
255+ .take(crate::limits::MAIL_SUBJECT_MAX)
256+ .collect(),
257+ body: [
258+ text(lang, K::ReminderLead).to_owned(),
259+ format!(
260+ "{}: {} — {}",
261+ text(lang, K::Key),
262+ clean_text(key),
263+ clean_text(title)
264+ ),
265+ format!("{}: {}", text(lang, K::When), clean_text(when)),
266+ format!("{}: {}", text(lang, K::Link), clean_text(link)),
267+ ]
268+ .join("\n"),
269+ }
270+}
271+
272+/// The test mail sent to the admin who asks for one.
273+pub fn test_mail(lang: MailLang) -> Mail {
274+ Mail {
275+ subject: text(lang, K::TestSubject).to_owned(),
276+ body: text(lang, K::TestBody).to_owned(),
277+ }
278+}
279+
280+#[cfg(test)]
281+mod tests {
282+ use super::*;
283+
284+ #[test]
285+ fn every_key_has_text_in_both_languages() {
286+ for key in [
287+ K::Key,
288+ K::Column,
289+ K::Deadline,
290+ K::Assignees,
291+ K::When,
292+ K::Link,
293+ K::TestSubject,
294+ ] {
295+ assert!(!text(MailLang::En, key).is_empty());
296+ assert!(!text(MailLang::Tr, key).is_empty());
297+ }
298+ }
299+
300+ #[test]
301+ fn the_locale_override_wins_over_the_directory() {
302+ assert_eq!(MailLang::of(Some("en"), Some("tr")), MailLang::En);
303+ assert_eq!(MailLang::of(None, Some("tr")), MailLang::Tr);
304+ assert_eq!(MailLang::of(None, None), MailLang::En);
305+ }
306+
307+ #[test]
308+ fn meeting_time_is_shown_in_the_members_zone() {
309+ let text = when_text("2026-10-28T12:00:00.000000000Z", "Europe/Istanbul").unwrap();
310+ assert_eq!(text, "2026-10-28 15:00 Europe/Istanbul");
311+ }
312+}
crates/iz-core/src/rules.rsadded+375 -0
@@ -0,0 +1,375 @@
1+//! Mail rules, pure part: the closed set of triggers and audiences, the verdict of one rule on one
2+//! event, and the rendering of a rule's subject. No I/O. The store (`store/rules_engine.rs`) loads the
3+//! facts (task, members, eligible recipients) and writes the decisions and outbox rows this module decides.
4+//!
5+//! Invariants kept here: the actor of an event is never a recipient of it; a recipient is always one of
6+//! the eligible members handed in (enabled, role admin or member), so a viewer, a role `none` member and a
7+//! disabled member can never be owed mail; a subject is plain text with no control characters, at most
8+//! `MAIL_SUBJECT_MAX` characters, whatever the template or the values were.
9+
10+use crate::limits::MAIL_SUBJECT_MAX;
11+
12+/// Every trigger a rule can name. The schema CHECK lists the same twelve words.
13+pub const TRIGGERS: [&str; 12] = [
14+ "status",
15+ "unblocked",
16+ "created",
17+ "assigned",
18+ "unassigned",
19+ "commented",
20+ "deadline_set",
21+ "deadline_cleared",
22+ "retitled",
23+ "linked",
24+ "unlinked",
25+ "deleted",
26+];
27+
28+/// Who a rule mails. The schema CHECK lists the same four words.
29+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30+pub enum Audience {
31+ /// The task's assignees. For `assigned` and `unassigned`, only the person named by the event.
32+ Assignees,
33+ /// Every eligible member of the board.
34+ Board,
35+ /// The member who created the task.
36+ Creator,
37+ /// The members who opted in to watch this task.
38+ Watchers,
39+}
40+
41+impl Audience {
42+ /// The stored spelling.
43+ pub fn as_str(self) -> &'static str {
44+ match self {
45+ Audience::Assignees => "assignees",
46+ Audience::Board => "board",
47+ Audience::Creator => "creator",
48+ Audience::Watchers => "watchers",
49+ }
50+ }
51+
52+ /// Parses the stored spelling. Unknown text is `None`.
53+ pub fn parse(text: &str) -> Option<Audience> {
54+ match text {
55+ "assignees" => Some(Audience::Assignees),
56+ "board" => Some(Audience::Board),
57+ "creator" => Some(Audience::Creator),
58+ "watchers" => Some(Audience::Watchers),
59+ _ => None,
60+ }
61+ }
62+}
63+
64+/// Whether `text` is one of the triggers.
65+pub fn is_trigger(text: &str) -> bool {
66+ TRIGGERS.contains(&text)
67+}
68+
69+/// The rule fields a verdict depends on.
70+#[derive(Debug, Clone, PartialEq, Eq)]
71+pub struct RuleFacts {
72+ /// Whether the rule is switched on.
73+ pub enabled: bool,
74+ /// Only for `status`: the column that must be entered. `None` means any column.
75+ pub column_id: Option<String>,
76+ /// The project the task must wear. `None` means any project.
77+ pub tag_id: Option<String>,
78+ /// Who is mailed.
79+ pub audience: Audience,
80+}
81+
82+/// The event fields a verdict depends on.
83+#[derive(Debug, Clone, PartialEq, Eq)]
84+pub struct EventFacts {
85+ /// The trigger word of the event.
86+ pub kind: String,
87+ /// The member the event names (the person assigned or removed), if any.
88+ pub subject: Option<String>,
89+ /// The column the task entered, for `status` events.
90+ pub column_id: Option<String>,
91+ /// Who did it. Never mailed about their own action.
92+ pub actor: Option<String>,
93+}
94+
95+/// The task fields a verdict depends on, as they are now.
96+#[derive(Debug, Clone, PartialEq, Eq)]
97+pub struct TaskFacts {
98+ /// The project the task wears.
99+ pub tag_id: String,
100+ /// Whether the task is soft-deleted.
101+ pub deleted: bool,
102+ /// Who created it.
103+ pub creator: String,
104+ /// Current assignees, sorted.
105+ pub assignees: Vec<String>,
106+ /// Members who watch the task, sorted.
107+ pub watchers: Vec<String>,
108+}
109+
110+/// Why a rule does not apply to an event whose task is in the wrong state or place.
111+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112+pub enum Mismatch {
113+ /// A status rule names another column.
114+ Column,
115+ /// The rule is limited to another project.
116+ Project,
117+}
118+
119+impl Mismatch {
120+ /// The text stored in the decision ledger.
121+ pub fn as_str(self) -> &'static str {
122+ match self {
123+ Mismatch::Column => "column",
124+ Mismatch::Project => "project",
125+ }
126+ }
127+}
128+
129+/// The outcome of one rule on one event, before any row is written.
130+#[derive(Debug, Clone, PartialEq, Eq)]
131+pub enum Verdict {
132+ /// The rule is off.
133+ Disabled,
134+ /// The task is gone (deleted before the event was handled), so the mail would be about nothing.
135+ TaskGone,
136+ /// The event does not match the rule's column or project.
137+ NotMatched(Mismatch),
138+ /// The rule applies, but nobody eligible is in the audience (after removing the actor).
139+ NoRecipients,
140+ /// These members are owed the mail, sorted.
141+ Owed(Vec<String>),
142+}
143+
144+/// Decides one rule on one event. `task` is `None` when the task row does not exist. `eligible` is every
145+/// member who may receive mail (enabled, role admin or member), sorted.
146+pub fn evaluate(
147+ rule: &RuleFacts,
148+ event: &EventFacts,
149+ task: Option<&TaskFacts>,
150+ eligible: &[String],
151+) -> Verdict {
152+ if !rule.enabled {
153+ return Verdict::Disabled;
154+ }
155+ let Some(task) = task else {
156+ return Verdict::TaskGone;
157+ };
158+ // A deleted task still announces its own deletion; any other event about it is gone.
159+ if task.deleted && event.kind != "deleted" {
160+ return Verdict::TaskGone;
161+ }
162+ if let Some(column) = &rule.column_id
163+ && event.column_id.as_deref() != Some(column.as_str())
164+ {
165+ return Verdict::NotMatched(Mismatch::Column);
166+ }
167+ if let Some(tag) = &rule.tag_id
168+ && *tag != task.tag_id
169+ {
170+ return Verdict::NotMatched(Mismatch::Project);
171+ }
172+ let owed = audience(rule.audience, event, task, eligible);
173+ if owed.is_empty() {
174+ Verdict::NoRecipients
175+ } else {
176+ Verdict::Owed(owed)
177+ }
178+}
179+
180+/// The recipients of an audience: the candidates, restricted to the eligible members and without the actor.
181+/// Sorted and without duplicates. `eligible` may be in any order.
182+pub fn audience(
183+ audience: Audience,
184+ event: &EventFacts,
185+ task: &TaskFacts,
186+ eligible: &[String],
187+) -> Vec<String> {
188+ let candidates: Vec<&String> = match audience {
189+ Audience::Assignees if matches!(event.kind.as_str(), "assigned" | "unassigned") => {
190+ event.subject.iter().collect()
191+ }
192+ Audience::Assignees => task.assignees.iter().collect(),
193+ Audience::Board => eligible.iter().collect(),
194+ Audience::Creator => vec![&task.creator],
195+ Audience::Watchers => task.watchers.iter().collect(),
196+ };
197+ let mut out: Vec<String> = candidates
198+ .into_iter()
199+ .filter(|sub| eligible.contains(sub))
200+ .filter(|sub| event.actor.as_deref() != Some(sub.as_str()))
201+ .cloned()
202+ .collect();
203+ out.sort();
204+ out.dedup();
205+ out
206+}
207+
208+/// Removes every control character (CR, LF, tab, NUL and the rest of the C0 and C1 sets) and the Unicode
209+/// direction and zero-width format marks that let text pass for something else. Values that go into a
210+/// mail header or a subject are cleaned with this first.
211+pub fn clean_text(text: &str) -> String {
212+ text.chars().filter(|c| !is_unsafe_char(*c)).collect()
213+}
214+
215+/// Whether a character must never reach a mail header or a subject.
216+fn is_unsafe_char(c: char) -> bool {
217+ c.is_control()
218+ || matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}')
219+}
220+
221+/// Renders a subject from its template: `{name}` is replaced by the value of `name` in `vars`. A name
222+/// that is not in `vars` stays as written, so a typo shows in the mail instead of vanishing. The values
223+/// are inserted as they are and are never scanned again. The result is cleaned with [`clean_text`] and
224+/// cut to [`MAIL_SUBJECT_MAX`] characters.
225+pub fn render_subject(template: &str, vars: &[(&str, &str)]) -> String {
226+ let mut out = String::with_capacity(template.len());
227+ let mut rest = template;
228+ while let Some(open) = rest.find('{') {
229+ out.push_str(&rest[..open]);
230+ let after = &rest[open + 1..];
231+ let Some(close) = after.find('}') else {
232+ out.push_str(&rest[open..]);
233+ rest = "";
234+ break;
235+ };
236+ let name = &after[..close];
237+ match vars.iter().find(|(key, _)| *key == name) {
238+ Some((_, value)) => out.push_str(value),
239+ None => {
240+ out.push('{');
241+ out.push_str(name);
242+ out.push('}');
243+ }
244+ }
245+ rest = &after[close + 1..];
246+ }
247+ out.push_str(rest);
248+ clean_text(&out)
249+ .trim()
250+ .chars()
251+ .take(MAIL_SUBJECT_MAX)
252+ .collect()
253+}
254+
255+#[cfg(test)]
256+mod tests {
257+ use super::*;
258+
259+ fn facts(assignees: &[&str], watchers: &[&str]) -> TaskFacts {
260+ TaskFacts {
261+ tag_id: "t1".into(),
262+ deleted: false,
263+ creator: "ada".into(),
264+ assignees: assignees.iter().map(|s| s.to_string()).collect(),
265+ watchers: watchers.iter().map(|s| s.to_string()).collect(),
266+ }
267+ }
268+
269+ fn event(kind: &str, subject: Option<&str>) -> EventFacts {
270+ EventFacts {
271+ kind: kind.into(),
272+ subject: subject.map(str::to_owned),
273+ column_id: None,
274+ actor: Some("ada".into()),
275+ }
276+ }
277+
278+ fn rule(audience: Audience) -> RuleFacts {
279+ RuleFacts {
280+ enabled: true,
281+ column_id: None,
282+ tag_id: None,
283+ audience,
284+ }
285+ }
286+
287+ #[test]
288+ fn the_actor_is_never_owed_and_ineligible_members_never_are() {
289+ let eligible = vec!["bo".to_owned(), "ada".to_owned()];
290+ // "cy" is assigned but not eligible (a viewer, a disabled or a role-none member).
291+ let task = facts(&["ada", "bo", "cy"], &[]);
292+ let verdict = evaluate(
293+ &rule(Audience::Assignees),
294+ &event("commented", None),
295+ Some(&task),
296+ &eligible,
297+ );
298+ assert_eq!(verdict, Verdict::Owed(vec!["bo".to_owned()]));
299+ }
300+
301+ #[test]
302+ fn assignment_events_name_only_the_person_just_assigned() {
303+ let eligible = vec!["bo".to_owned(), "cy".to_owned()];
304+ let task = facts(&["bo", "cy"], &[]);
305+ let verdict = evaluate(
306+ &rule(Audience::Assignees),
307+ &event("assigned", Some("cy")),
308+ Some(&task),
309+ &eligible,
310+ );
311+ assert_eq!(verdict, Verdict::Owed(vec!["cy".to_owned()]));
312+ }
313+
314+ #[test]
315+ fn disabled_gone_and_mismatched_rules_owe_nothing() {
316+ let eligible = vec!["bo".to_owned()];
317+ let task = facts(&["bo"], &[]);
318+ let mut off = rule(Audience::Board);
319+ off.enabled = false;
320+ assert_eq!(
321+ evaluate(&off, &event("created", None), Some(&task), &eligible),
322+ Verdict::Disabled
323+ );
324+ assert_eq!(
325+ evaluate(
326+ &rule(Audience::Board),
327+ &event("created", None),
328+ None,
329+ &eligible
330+ ),
331+ Verdict::TaskGone
332+ );
333+ let mut deleted = facts(&["bo"], &[]);
334+ deleted.deleted = true;
335+ assert_eq!(
336+ evaluate(
337+ &rule(Audience::Board),
338+ &event("commented", None),
339+ Some(&deleted),
340+ &eligible
341+ ),
342+ Verdict::TaskGone
343+ );
344+ let mut status = rule(Audience::Board);
345+ status.column_id = Some("done".into());
346+ let mut moved = event("status", None);
347+ moved.column_id = Some("todo".into());
348+ assert_eq!(
349+ evaluate(&status, &moved, Some(&task), &eligible),
350+ Verdict::NotMatched(Mismatch::Column)
351+ );
352+ }
353+
354+ #[test]
355+ fn subject_is_plain_text_without_line_breaks_and_capped() {
356+ let title = "x\r\nBcc: evil@example.com";
357+ let subject = render_subject(
358+ "New: {title}\r\nBcc: {key}",
359+ &[("title", title), ("key", "IZ-7")],
360+ );
361+ assert!(!subject.contains('\r') && !subject.contains('\n'));
362+ assert!(subject.starts_with("New: xBcc: evil@example.com"));
363+ let long = "a".repeat(500);
364+ assert_eq!(
365+ render_subject("{title}", &[("title", &long)])
366+ .chars()
367+ .count(),
368+ MAIL_SUBJECT_MAX
369+ );
370+ assert_eq!(
371+ render_subject("{nope} {key}", &[("key", "IZ-1")]),
372+ "{nope} IZ-1"
373+ );
374+ }
375+}
crates/iz-core/src/sender.rsadded+260 -0
@@ -0,0 +1,260 @@
1+//! The outgoing mail sender, pure part: what an admin may enter for the SMTP server and the From line,
2+//! and how each field is checked. The password is not handled here; the web layer seals it.
3+//!
4+//! Invariants: no control characters or line breaks in any field that becomes a header or a log line; the
5+//! TLS mode is implicit or STARTTLS, and plaintext only when the host is the loopback name `localhost`,
6+//! `127.0.0.1` or `::1`.
7+
8+use crate::error::{Error, Result};
9+use crate::limits::{SENDER_HOST_MAX, SENDER_NAME_MAX, SMTP_PASSWORD_MAX, SMTP_USERNAME_MAX};
10+
11+/// The name shown in From when the admin leaves it empty.
12+pub const DEFAULT_FROM_NAME: &str = "iz";
13+/// The SMTP port when the admin leaves it empty (submission with STARTTLS).
14+pub const DEFAULT_PORT: u16 = 587;
15+/// Reminders per member per hour when the setting was never saved. Reason: a guard against a burst.
16+pub const DEFAULT_REMINDER_CAP: u32 = 20;
17+
18+/// How the connection to the mail server is protected.
19+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20+pub enum TlsMode {
21+ /// TLS from the first byte (usually port 465).
22+ Implicit,
23+ /// Plain connection upgraded with STARTTLS (usually port 587).
24+ StartTls,
25+ /// No encryption. Allowed only for a loopback host.
26+ Plain,
27+}
28+
29+impl TlsMode {
30+ /// The stored spelling.
31+ pub fn as_str(self) -> &'static str {
32+ match self {
33+ TlsMode::Implicit => "implicit",
34+ TlsMode::StartTls => "starttls",
35+ TlsMode::Plain => "plain",
36+ }
37+ }
38+
39+ /// Parses the stored or submitted spelling.
40+ pub fn parse(text: &str) -> Option<TlsMode> {
41+ match text {
42+ "implicit" => Some(TlsMode::Implicit),
43+ "starttls" => Some(TlsMode::StartTls),
44+ "plain" => Some(TlsMode::Plain),
45+ _ => None,
46+ }
47+ }
48+}
49+
50+/// A checked sender configuration (everything but the password).
51+#[derive(Debug, Clone, PartialEq, Eq)]
52+pub struct Sender {
53+ /// Host name of the mail server.
54+ pub host: String,
55+ /// TCP port of the mail server.
56+ pub port: u16,
57+ /// Connection protection.
58+ pub tls: TlsMode,
59+ /// SMTP user name.
60+ pub username: String,
61+ /// The address mail is sent from.
62+ pub from_address: String,
63+ /// The name shown with the address; never empty (defaults to `iz`).
64+ pub from_name: String,
65+}
66+
67+/// Whether `host` names this machine. Only then may a connection be unencrypted.
68+pub fn is_loopback(host: &str) -> bool {
69+ matches!(host, "localhost" | "127.0.0.1" | "::1")
70+}
71+
72+/// Checks the host name: ASCII letters, digits, dots, hyphens, at most `SENDER_HOST_MAX` characters.
73+fn valid_host(host: &str) -> bool {
74+ let labels_ok = host.split('.').all(|label| {
75+ !label.is_empty()
76+ && label.len() <= 63
77+ && !label.starts_with('-')
78+ && !label.ends_with('-')
79+ && label
80+ .bytes()
81+ .all(|b| b.is_ascii_alphanumeric() || b == b'-')
82+ });
83+ labels_ok && host.len() <= SENDER_HOST_MAX
84+}
85+
86+/// Checks an e-mail address: one `@`, a local part and a domain of ASCII labels, no spaces, no control
87+/// characters, at most 254 characters. Strict on purpose: the address becomes a header.
88+pub fn valid_address(address: &str) -> bool {
89+ if address.len() > 254 || address.bytes().any(|b| b <= b' ' || b == 0x7f) {
90+ return false;
91+ }
92+ let mut parts = address.split('@');
93+ let (Some(local), Some(domain), None) = (parts.next(), parts.next(), parts.next()) else {
94+ return false;
95+ };
96+ let local_ok = !local.is_empty()
97+ && local.len() <= 64
98+ && !local.starts_with('.')
99+ && !local.ends_with('.')
100+ && local
101+ .bytes()
102+ .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~.".contains(&b));
103+ let domain_ok = domain.contains('.')
104+ && domain.split('.').all(|label| {
105+ !label.is_empty()
106+ && label.len() <= 63
107+ && !label.starts_with('-')
108+ && !label.ends_with('-')
109+ && label
110+ .bytes()
111+ .all(|b| b.is_ascii_alphanumeric() || b == b'-')
112+ });
113+ local_ok && domain_ok
114+}
115+
116+/// A display name with no control characters (and no Unicode direction or zero-width marks), at most
117+/// `max` characters. Trimmed. Empty is allowed and returned as empty.
118+pub fn checked_name(text: &str, max: usize) -> Result<String> {
119+ let trimmed = text.trim();
120+ if trimmed.chars().any(|c| c.is_control() || is_format_mark(c)) {
121+ return Err(Error::Invalid(
122+ "the name contains a control character or a line break".into(),
123+ ));
124+ }
125+ if trimmed.chars().count() > max {
126+ return Err(Error::Invalid(format!(
127+ "the name is longer than {max} characters"
128+ )));
129+ }
130+ Ok(trimmed.to_owned())
131+}
132+
133+/// Unicode marks that change how text is read (direction and zero width). Refused in names.
134+fn is_format_mark(c: char) -> bool {
135+ matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}')
136+}
137+
138+/// The raw values of the sender form, as typed.
139+#[derive(Debug, Clone, Default)]
140+pub struct SenderInput {
141+ /// Host name.
142+ pub host: String,
143+ /// Port, as typed.
144+ pub port: String,
145+ /// `implicit`, `starttls` or `plain`.
146+ pub tls: String,
147+ /// SMTP user name.
148+ pub username: String,
149+ /// From address.
150+ pub from_address: String,
151+ /// From name, may be empty.
152+ pub from_name: String,
153+}
154+
155+/// Checks a sender form and returns the checked configuration. Every error is safe to show to the admin.
156+pub fn validate_sender(input: &SenderInput) -> Result<Sender> {
157+ let host = input.host.trim().to_ascii_lowercase();
158+ if host.is_empty() || !valid_host(&host) {
159+ return Err(Error::Invalid(
160+ "the mail server name is not a valid host name".into(),
161+ ));
162+ }
163+ let port_text = input.port.trim();
164+ let port = if port_text.is_empty() {
165+ DEFAULT_PORT
166+ } else {
167+ port_text
168+ .parse::<u16>()
169+ .ok()
170+ .filter(|p| *p >= 1)
171+ .ok_or_else(|| Error::Invalid("the port must be a number from 1 to 65535".into()))?
172+ };
173+ let tls = TlsMode::parse(input.tls.trim())
174+ .ok_or_else(|| Error::Invalid("choose implicit TLS or STARTTLS".into()))?;
175+ if tls == TlsMode::Plain && !is_loopback(&host) {
176+ return Err(Error::Invalid(
177+ "an unencrypted connection is allowed only to localhost".into(),
178+ ));
179+ }
180+ let username = input.username.trim().to_owned();
181+ if username.is_empty()
182+ || username.chars().count() > SMTP_USERNAME_MAX
183+ || username.chars().any(char::is_control)
184+ {
185+ return Err(Error::Invalid(
186+ "the user name is required and must be printable".into(),
187+ ));
188+ }
189+ let from_address = input.from_address.trim().to_owned();
190+ if !valid_address(&from_address) {
191+ return Err(Error::Invalid(
192+ "the from address is not a valid e-mail address".into(),
193+ ));
194+ }
195+ let from_name = checked_name(&input.from_name, SENDER_NAME_MAX)?;
196+ let from_name = if from_name.is_empty() {
197+ DEFAULT_FROM_NAME.to_owned()
198+ } else {
199+ from_name
200+ };
201+ Ok(Sender {
202+ host,
203+ port,
204+ tls,
205+ username,
206+ from_address,
207+ from_name,
208+ })
209+}
210+
211+/// Checks a password: required, at most `SMTP_PASSWORD_MAX` characters, no control characters.
212+pub fn validate_password(password: &str) -> Result<()> {
213+ if password.is_empty()
214+ || password.chars().count() > SMTP_PASSWORD_MAX
215+ || password.chars().any(char::is_control)
216+ {
217+ return Err(Error::Invalid(
218+ "the password is required and must be printable".into(),
219+ ));
220+ }
221+ Ok(())
222+}
223+
224+#[cfg(test)]
225+mod tests {
226+ use super::*;
227+
228+ fn input() -> SenderInput {
229+ SenderInput {
230+ host: "smtp.example.com".into(),
231+ port: "587".into(),
232+ tls: "starttls".into(),
233+ username: "iz".into(),
234+ from_address: "iz@example.com".into(),
235+ from_name: String::new(),
236+ }
237+ }
238+
239+ #[test]
240+ fn a_valid_sender_gets_the_default_name() {
241+ let sender = validate_sender(&input()).unwrap();
242+ assert_eq!(sender.from_name, "iz");
243+ assert_eq!(sender.tls, TlsMode::StartTls);
244+ }
245+
246+ #[test]
247+ fn plaintext_only_to_loopback_and_no_line_breaks_in_names() {
248+ let mut plain = input();
249+ plain.tls = "plain".into();
250+ assert!(validate_sender(&plain).is_err());
251+ plain.host = "localhost".into();
252+ assert!(validate_sender(&plain).is_ok());
253+ let mut breaking = input();
254+ breaking.from_name = "x\r\nBcc: evil@example.com".into();
255+ assert!(validate_sender(&breaking).is_err());
256+ breaking.from_name = "Aile".into();
257+ breaking.from_address = "a b@example.com".into();
258+ assert!(validate_sender(&breaking).is_err());
259+ }
260+}
crates/iz-core/src/store/comments.rsmodified+14 -0
@@ -6,6 +6,7 @@
6 use turso::Connection;6 use turso::Connection;
7 7
8 use super::activity::{self, NewActivity};8 use super::activity::{self, NewActivity};
9+use super::events::{EventDraft, emit};
9 use super::{col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};10 use super::{col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
10 use crate::authz::{Action, Actor, authorize};11 use crate::authz::{Action, Actor, authorize};
11 use crate::error::{Error, Result};12 use crate::error::{Error, Result};
@@ -109,6 +110,19 @@ impl Store {
109 )110 )
110 .await111 .await
111 .map_err(db_err)?;112 .map_err(db_err)?;
113+ emit(
114+ &tx,
115+ EventDraft {
116+ board_id,
117+ task_id: Some(task_id),
118+ kind: "commented",
119+ column_id: None,
120+ actor: Some(author),
121+ subject: None,
122+ detail: serde_json::json!({ "comment": id }),
123+ },
124+ )
125+ .await?;
112 activity::record(126 activity::record(
113 &tx,127 &tx,
114 NewActivity {128 NewActivity {
crates/iz-core/src/store/events.rsadded+54 -0
@@ -0,0 +1,54 @@
1+//! The mail event queue, write side. A task or comment write calls [`emit`] inside its own transaction,
2+//! so the event row exists if and only if the change committed: a crash cannot lose an event or make
3+//! two of them. The rules engine (`rules_engine.rs`) reads the rows later and marks them processed.
4+//!
5+//! Only the write paths of this crate call `emit`. The mail system never does, which is what keeps a
6+//! rule from ever firing on a mail.
7+
8+use turso::transaction::Transaction;
9+
10+use super::{db_err, new_id};
11+use crate::error::Result;
12+use crate::time::now_stamp;
13+
14+/// One event to queue. `kind` is one of the twelve triggers; the schema refuses any other word.
15+pub struct EventDraft<'a> {
16+ /// The board the task belongs to.
17+ pub board_id: &'a str,
18+ /// The task the event is about.
19+ pub task_id: Option<&'a str>,
20+ /// The trigger word.
21+ pub kind: &'static str,
22+ /// The column the task entered, for `status` events.
23+ pub column_id: Option<&'a str>,
24+ /// Who did it.
25+ pub actor: Option<&'a str>,
26+ /// The member the event names, if any.
27+ pub subject: Option<&'a str>,
28+ /// Details for the ledger. Never secrets, never mail text.
29+ pub detail: serde_json::Value,
30+}
31+
32+/// Writes one event row inside `tx`. The caller commits or rolls back with the change it describes.
33+pub async fn emit(tx: &Transaction<'_>, draft: EventDraft<'_>) -> Result<()> {
34+ let detail = serde_json::to_string(&draft.detail)
35+ .map_err(|e| crate::error::Error::Database(format!("event detail is not JSON: {e}")))?;
36+ tx.execute(
37+ "INSERT INTO mail_events (id, board_id, task_id, kind, column_id, actor, subject, detail, at) \
38+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
39+ (
40+ new_id(),
41+ draft.board_id.to_owned(),
42+ draft.task_id.map(str::to_owned),
43+ draft.kind,
44+ draft.column_id.map(str::to_owned),
45+ draft.actor.map(str::to_owned),
46+ draft.subject.map(str::to_owned),
47+ detail,
48+ now_stamp(),
49+ ),
50+ )
51+ .await
52+ .map_err(db_err)?;
53+ Ok(())
54+}
crates/iz-core/src/store/migrate.rsmodified+1 -0
@@ -15,6 +15,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
15 include_str!("../../migrations/0002_session_id_token.sql"),15 include_str!("../../migrations/0002_session_id_token.sql"),
16 ),16 ),
17 (3, include_str!("../../migrations/0003_blob_deletions.sql")),17 (3, include_str!("../../migrations/0003_blob_deletions.sql")),
18+ (4, include_str!("../../migrations/0004_mail_events.sql")),
18 ];19 ];
19 20
20 fn migration_err(e: turso::Error) -> Error {21 fn migration_err(e: turso::Error) -> Error {
crates/iz-core/src/store/mod.rsmodified+7 -1
@@ -11,8 +11,14 @@ pub mod activity;
11 pub mod attachments;11 pub mod attachments;
12 pub mod board;12 pub mod board;
13 pub mod comments;13 pub mod comments;
14+pub mod events;
14 pub mod members;15 pub mod members;
15 pub mod migrate;16 pub mod migrate;
17+pub mod outbox;
18+pub mod reminders;
19+pub mod rules;
20+pub mod rules_engine;
21+pub mod sender;
16 pub mod sessions;22 pub mod sessions;
17 pub mod snapshot;23 pub mod snapshot;
18 pub mod tasks;24 pub mod tasks;
@@ -380,7 +386,7 @@ mod tests {
380 })386 })
381 .await387 .await
382 .unwrap();388 .unwrap();
383- assert_eq!(versions, vec![1, 2, 3]);389+ assert_eq!(versions, vec![1, 2, 3, 4]);
384 }390 }
385 391
386 #[tokio::test]392 #[tokio::test]
crates/iz-core/src/store/outbox.rsadded+514 -0
@@ -0,0 +1,514 @@
1+//! The outbox: every mail iz sends is a row here first, written in the transaction that decided it. The
2+//! worker in `iz-web` claims due rows under a lease, sends them and records the result. Nothing else sends.
3+//!
4+//! Retries: a failed attempt waits `BACKOFF_MINUTES` (1, 5, 15, then 60) before the next one; the fifth
5+//! failure, or a permanent refusal by the server, abandons the row. A row that cannot be sent for lack of a
6+//! sender is held for `HOLD_MINUTES` and spends no attempt. A claim is a lease of `LEASE_MINUTES`: a worker
7+//! that dies lets the row go again after that. Rows of a member who is no longer eligible are abandoned at
8+//! claim time, so a member demoted after the mail was queued never receives it.
9+
10+use jiff::{SignedDuration, Timestamp};
11+use turso::Connection;
12+use turso::transaction::Transaction;
13+
14+use super::{col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
15+use crate::clock::stamp_of;
16+use crate::error::{Error, Result};
17+use crate::limits::{MESSAGE_BODY_MAX, MESSAGE_SUBJECT_MAX};
18+use crate::rules::clean_text;
19+use crate::store::Store;
20+use crate::time::now_stamp;
21+
22+/// Failed attempts before a row is abandoned.
23+pub const MAX_ATTEMPTS: i64 = 5;
24+/// The wait after the first, second, third and fourth failure, in minutes. The fifth failure abandons.
25+pub const BACKOFF_MINUTES: [i64; 4] = [1, 5, 15, 60];
26+/// The wait before trying again when no sender is configured. It spends no attempt.
27+pub const HOLD_MINUTES: i64 = 1;
28+/// How long a claim holds a row before another worker may take it, in minutes.
29+pub const LEASE_MINUTES: i64 = 5;
30+/// The minimum time between two messages to members from the same instance, in minutes.
31+pub const MESSAGE_INTERVAL_MINUTES: i64 = 10;
32+/// Rows of the logs page per page when the page asks for a size the code does not know.
33+pub const PAGE_DEFAULT: usize = 50;
34+/// Largest page of the logs lists. Reason: bounds one response.
35+pub const PAGE_MAX: usize = 200;
36+
37+/// The wait after the `attempts`-th failed attempt, or `None` when the row is abandoned.
38+pub fn backoff_after(attempts: i64) -> Option<SignedDuration> {
39+ if !(1..MAX_ATTEMPTS).contains(&attempts) {
40+ return None;
41+ }
42+ let index = usize::try_from(attempts - 1).ok()?;
43+ BACKOFF_MINUTES
44+ .get(index)
45+ .map(|m| SignedDuration::from_mins(*m))
46+}
47+
48+/// One outbox row with its recipient, as the worker and the logs page read it.
49+#[derive(Debug, Clone, PartialEq, Eq)]
50+pub struct OutboxRow {
51+ /// Row id (ULID).
52+ pub id: String,
53+ /// The rule that owes it, if a rule did.
54+ pub rule_id: Option<String>,
55+ /// The task the mail is about, if any.
56+ pub task_id: Option<String>,
57+ /// `rule`, `notice` or `reminder`.
58+ pub kind: String,
59+ /// The recipient's member id.
60+ pub recipient: String,
61+ /// The recipient's name, for the logs.
62+ pub recipient_name: String,
63+ /// The recipient's address.
64+ pub recipient_email: String,
65+ /// The subject, plain text.
66+ pub subject: String,
67+ /// The body, plain text.
68+ pub body: String,
69+ /// `pending`, `sent`, `failed` or `abandoned`.
70+ pub state: String,
71+ /// Attempts made so far.
72+ pub attempts: i64,
73+ /// The last error the server or the worker reported, if any.
74+ pub last_error: Option<String>,
75+ /// When the row is due next.
76+ pub next_attempt_at: String,
77+ /// When it was sent, if it was.
78+ pub sent_at: Option<String>,
79+ /// When it was queued.
80+ pub created_at: String,
81+}
82+
83+/// A row to queue. `rule_id` is `None` for notices and reminders.
84+pub struct OutboxDraft<'a> {
85+ /// The rule that owes the mail.
86+ pub rule_id: Option<&'a str>,
87+ /// The event (or reminder or message) the mail belongs to.
88+ pub event_id: &'a str,
89+ /// The task the mail is about.
90+ pub task_id: Option<&'a str>,
91+ /// The recipient's member id.
92+ pub recipient: &'a str,
93+ /// `rule`, `notice` or `reminder`.
94+ pub kind: &'a str,
95+ /// The subject, already cleaned.
96+ pub subject: &'a str,
97+ /// The body, already cleaned.
98+ pub body: &'a str,
99+ /// When the row is due first.
100+ pub next_attempt_at: &'a str,
101+}
102+
103+/// Queues one row inside `tx`. Returns `false` when the unique key (rule, event, task, recipient) already
104+/// holds a row, which is how a repeated pass avoids a second mail.
105+pub async fn insert_outbox(tx: &Transaction<'_>, draft: &OutboxDraft<'_>) -> Result<bool> {
106+ let changed = tx
107+ .execute(
108+ "INSERT INTO mail_outbox (id, rule_id, event_id, task_id, recipient, kind, subject, body, state, \
109+ attempts, next_attempt_at, created_at) \
110+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'pending', 0, ?9, ?10) \
111+ ON CONFLICT(rule_id, event_id, task_id, recipient) DO NOTHING",
112+ (
113+ new_id(),
114+ draft.rule_id.map(str::to_owned),
115+ draft.event_id.to_owned(),
116+ draft.task_id.map(str::to_owned),
117+ draft.recipient.to_owned(),
118+ draft.kind.to_owned(),
119+ draft.subject.to_owned(),
120+ draft.body.to_owned(),
121+ draft.next_attempt_at.to_owned(),
122+ now_stamp(),
123+ ),
124+ )
125+ .await
126+ .map_err(db_err)?;
127+ Ok(changed > 0)
128+}
129+
130+/// The columns of an outbox row joined with its recipient. The recipient join is inner: a row whose
131+/// recipient is gone cannot be sent and is never selected.
132+const OUTBOX_COLS: &str = "o.id, o.rule_id, o.task_id, o.kind, o.recipient, m.name, m.email, o.subject, o.body, \
133+ o.state, o.attempts, o.last_error, o.next_attempt_at, o.sent_at, o.created_at";
134+
135+fn map_outbox(row: &turso::Row) -> Result<OutboxRow> {
136+ Ok(OutboxRow {
137+ id: col_text(row, 0)?,
138+ rule_id: col_opt_text(row, 1)?,
139+ task_id: col_opt_text(row, 2)?,
140+ kind: col_text(row, 3)?,
141+ recipient: col_text(row, 4)?,
142+ recipient_name: col_text(row, 5)?,
143+ recipient_email: col_text(row, 6)?,
144+ subject: col_text(row, 7)?,
145+ body: col_text(row, 8)?,
146+ state: col_text(row, 9)?,
147+ attempts: col_int(row, 10)?,
148+ last_error: col_opt_text(row, 11)?,
149+ next_attempt_at: col_text(row, 12)?,
150+ sent_at: col_opt_text(row, 13)?,
151+ created_at: col_text(row, 14)?,
152+ })
153+}
154+
155+/// One page of the outbox, newest first, with the cursor of the next page.
156+#[derive(Debug, Clone, PartialEq, Eq)]
157+pub struct OutboxPage {
158+ /// The rows, newest first.
159+ pub items: Vec<OutboxRow>,
160+ /// Pass back as the cursor of the next (older) page. `None` when this is the last page.
161+ pub next_cursor: Option<String>,
162+}
163+
164+/// Splits a `<stamp>~<id>` cursor. A missing or malformed cursor is `None` (the first page).
165+pub fn parse_cursor(cursor: Option<&str>) -> Result<Option<(String, String)>> {
166+ match cursor.filter(|c| !c.is_empty()) {
167+ None => Ok(None),
168+ Some(text) => text
169+ .split_once('~')
170+ .map(|(at, id)| Some((at.to_owned(), id.to_owned())))
171+ .ok_or_else(|| Error::Invalid("malformed cursor".into())),
172+ }
173+}
174+
175+/// The page size, clamped to `1..=PAGE_MAX`.
176+pub fn clamp_page(limit: usize) -> usize {
177+ limit.clamp(1, PAGE_MAX)
178+}
179+
180+/// Decides whether a claimed recipient may still receive mail: enabled, role admin or member.
181+fn eligible_role(role: &str) -> bool {
182+ matches!(role, "admin" | "member")
183+}
184+
185+impl Store {
186+ /// Claims up to `batch` due rows for sending under a lease of `LEASE_MINUTES`. Rows of recipients who
187+ /// are no longer eligible are abandoned here and not returned. The rows are due when `next_attempt_at`
188+ /// has passed and no live lease holds them.
189+ pub async fn claim_due(&self, now: Timestamp, batch: usize) -> Result<Vec<OutboxRow>> {
190+ let conn = self.inner.conn.lock().await;
191+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
192+ let outcome: Result<Vec<OutboxRow>> = async {
193+ let stamp = stamp_of(now)?;
194+ let lease_cutoff = stamp_of(now - SignedDuration::from_mins(LEASE_MINUTES))?;
195+ let candidates = fetch_all(
196+ &tx,
197+ &format!(
198+ "SELECT {OUTBOX_COLS}, m.role FROM mail_outbox o JOIN members m ON m.sub = o.recipient \
199+ WHERE o.state IN ('pending', 'failed') AND o.next_attempt_at <= ?1 \
200+ AND (o.claimed_at IS NULL OR o.claimed_at <= ?2) \
201+ ORDER BY o.next_attempt_at, o.id LIMIT ?3"
202+ ),
203+ (stamp.clone(), lease_cutoff, i64::try_from(batch).unwrap_or(i64::MAX)),
204+ |row| Ok((map_outbox(row)?, col_text(row, 15)?)),
205+ )
206+ .await?;
207+ let mut claimed = Vec::new();
208+ for (row, role) in candidates {
209+ let member_ok = eligible_role(&role) && member_enabled(&tx, &row.recipient).await?;
210+ if member_ok {
211+ tx.execute(
212+ "UPDATE mail_outbox SET claimed_at = ?2 WHERE id = ?1",
213+ (row.id.clone(), stamp.clone()),
214+ )
215+ .await
216+ .map_err(db_err)?;
217+ claimed.push(row);
218+ } else {
219+ tx.execute(
220+ "UPDATE mail_outbox SET state = 'abandoned', claimed_at = NULL, last_error = ?2 WHERE id = ?1",
221+ (row.id.clone(), "the recipient is no longer eligible for mail".to_owned()),
222+ )
223+ .await
224+ .map_err(db_err)?;
225+ }
226+ }
227+ Ok(claimed)
228+ }
229+ .await;
230+ finish(tx, outcome).await
231+ }
232+
233+ /// Records a successful send: the row is `sent` and counts the attempt.
234+ pub async fn mark_sent(&self, row_id: &str, now: Timestamp) -> Result<()> {
235+ let conn = self.inner.conn.lock().await;
236+ conn.execute(
237+ "UPDATE mail_outbox SET state = 'sent', attempts = attempts + 1, sent_at = ?2, claimed_at = NULL, \
238+ last_error = NULL WHERE id = ?1",
239+ (row_id.to_owned(), stamp_of(now)?),
240+ )
241+ .await
242+ .map_err(db_err)?;
243+ Ok(())
244+ }
245+
246+ /// Records a failed attempt. A permanent refusal, or the last allowed attempt, abandons the row; any
247+ /// other failure schedules the next attempt after the backoff.
248+ pub async fn mark_failed(
249+ &self,
250+ row_id: &str,
251+ now: Timestamp,
252+ error: &str,
253+ permanent: bool,
254+ ) -> Result<String> {
255+ let conn = self.inner.conn.lock().await;
256+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
257+ let outcome: Result<String> = async {
258+ let attempts = fetch_opt(
259+ &tx,
260+ "SELECT attempts FROM mail_outbox WHERE id = ?1",
261+ (row_id.to_owned(),),
262+ |row| col_int(row, 0),
263+ )
264+ .await?
265+ .ok_or(Error::NotFound)?
266+ + 1;
267+ let error = clean_text(error).chars().take(300).collect::<String>();
268+ let next = match backoff_after(attempts) {
269+ Some(wait) if !permanent => {
270+ let at = now + wait;
271+ tx.execute(
272+ "UPDATE mail_outbox SET state = 'failed', attempts = ?2, last_error = ?3, \
273+ next_attempt_at = ?4, claimed_at = NULL WHERE id = ?1",
274+ (row_id.to_owned(), attempts, error, stamp_of(at)?),
275+ )
276+ .await
277+ .map_err(db_err)?;
278+ "failed"
279+ }
280+ _ => {
281+ tx.execute(
282+ "UPDATE mail_outbox SET state = 'abandoned', attempts = ?2, last_error = ?3, claimed_at = NULL \
283+ WHERE id = ?1",
284+ (row_id.to_owned(), attempts, error),
285+ )
286+ .await
287+ .map_err(db_err)?;
288+ "abandoned"
289+ }
290+ };
291+ Ok(next.to_owned())
292+ }
293+ .await;
294+ finish(tx, outcome).await
295+ }
296+
297+ /// Puts a row back for a later attempt without spending one (no sender configured, for example).
298+ pub async fn defer(&self, row_id: &str, until: Timestamp, reason: &str) -> Result<()> {
299+ let conn = self.inner.conn.lock().await;
300+ conn.execute(
301+ "UPDATE mail_outbox SET next_attempt_at = ?2, last_error = ?3, claimed_at = NULL WHERE id = ?1",
302+ (row_id.to_owned(), stamp_of(until)?, reason.to_owned()),
303+ )
304+ .await
305+ .map_err(db_err)?;
306+ Ok(())
307+ }
308+
309+ /// Requeues a failed or abandoned row now, with a fresh attempt count. `NotFound` for any other row.
310+ pub async fn retry_row(&self, row_id: &str, now: Timestamp) -> Result<()> {
311+ let conn = self.inner.conn.lock().await;
312+ let changed = conn
313+ .execute(
314+ "UPDATE mail_outbox SET state = 'pending', attempts = 0, next_attempt_at = ?2, claimed_at = NULL \
315+ WHERE id = ?1 AND state IN ('failed', 'abandoned')",
316+ (row_id.to_owned(), stamp_of(now)?),
317+ )
318+ .await
319+ .map_err(db_err)?;
320+ if changed == 0 {
321+ return Err(Error::NotFound);
322+ }
323+ Ok(())
324+ }
325+
326+ /// One page of the outbox, newest first. `cursor` is the `next_cursor` of the previous page.
327+ pub async fn outbox_page(&self, cursor: Option<&str>, limit: usize) -> Result<OutboxPage> {
328+ let before = parse_cursor(cursor)?;
329+ let limit = clamp_page(limit);
330+ let conn = self.read_conn().await;
331+ let items = fetch_all(
332+ &conn,
333+ &format!(
334+ "SELECT {OUTBOX_COLS} FROM mail_outbox o JOIN members m ON m.sub = o.recipient \
335+ WHERE (?1 IS NULL OR o.created_at < ?1 OR (o.created_at = ?1 AND o.id < ?2)) \
336+ ORDER BY o.created_at DESC, o.id DESC LIMIT ?3"
337+ ),
338+ (
339+ before.as_ref().map(|b| b.0.clone()),
340+ before.as_ref().map(|b| b.1.clone()),
341+ i64::try_from(limit).unwrap_or(i64::MAX),
342+ ),
343+ map_outbox,
344+ )
345+ .await?;
346+ let next_cursor = match items.last() {
347+ Some(last) if items.len() == limit => Some(format!("{}~{}", last.created_at, last.id)),
348+ _ => None,
349+ };
350+ Ok(OutboxPage { items, next_cursor })
351+ }
352+
353+ /// Queues a notice to every eligible member except the sender, then records the time of the message
354+ /// for the rate limit. `Conflict` when the previous message is too recent. Returns the number queued.
355+ pub async fn queue_message(
356+ &self,
357+ actor: &str,
358+ subject: &str,
359+ body: &str,
360+ now: Timestamp,
361+ ) -> Result<usize> {
362+ let subject = clean_text(subject).trim().to_owned();
363+ if subject.is_empty() || subject.chars().count() > MESSAGE_SUBJECT_MAX {
364+ return Err(Error::Invalid(format!(
365+ "the subject must be 1 to {MESSAGE_SUBJECT_MAX} characters"
366+ )));
367+ }
368+ let body = clean_message_body(body)?;
369+ let conn = self.inner.conn.lock().await;
370+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
371+ let outcome: Result<usize> = async {
372+ if let Some(last) = fetch_opt(
373+ &tx,
374+ "SELECT value FROM settings WHERE key = 'message_last_at'",
375+ (),
376+ |row| col_text(row, 0),
377+ )
378+ .await?
379+ {
380+ let last: Timestamp = last.parse().map_err(|_| Error::Database("stored message time".into()))?;
381+ if now < last + SignedDuration::from_mins(MESSAGE_INTERVAL_MINUTES) {
382+ return Err(Error::Conflict(format!(
383+ "a message was sent recently; wait {MESSAGE_INTERVAL_MINUTES} minutes between messages"
384+ )));
385+ }
386+ }
387+ let recipients = fetch_all(
388+ &tx,
389+ "SELECT sub FROM members WHERE disabled = 0 AND role IN ('admin', 'member') AND sub <> ?1 ORDER BY sub",
390+ (actor.to_owned(),),
391+ |row| col_text(row, 0),
392+ )
393+ .await?;
394+ let stamp = stamp_of(now)?;
395+ let event_id = new_id();
396+ let mut queued = 0;
397+ for sub in &recipients {
398+ let draft = OutboxDraft {
399+ rule_id: None,
400+ event_id: &event_id,
401+ task_id: None,
402+ recipient: sub,
403+ kind: "notice",
404+ subject: &subject,
405+ body: &body,
406+ next_attempt_at: &stamp,
407+ };
408+ if insert_outbox(&tx, &draft).await? {
409+ queued += 1;
410+ }
411+ }
412+ tx.execute(
413+ "INSERT INTO settings (key, value, updated_at) VALUES ('message_last_at', ?1, ?1) \
414+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
415+ (stamp,),
416+ )
417+ .await
418+ .map_err(db_err)?;
419+ Ok(queued)
420+ }
421+ .await;
422+ finish(tx, outcome).await
423+ }
424+
425+ /// One page of rule decisions, newest first: the rule's name, the task key, the outcome and its reason.
426+ pub async fn decisions_page(&self, cursor: Option<&str>, limit: usize) -> Result<DecisionPage> {
427+ let before = parse_cursor(cursor)?;
428+ let limit = clamp_page(limit);
429+ let conn = self.read_conn().await;
430+ let items = fetch_all(
431+ &conn,
432+ "SELECT d.id, r.name, t.key, d.outcome, d.detail, d.created_at FROM mail_decisions d \
433+ LEFT JOIN mail_rules r ON r.id = d.rule_id LEFT JOIN tasks t ON t.id = d.task_id \
434+ WHERE (?1 IS NULL OR d.created_at < ?1 OR (d.created_at = ?1 AND d.id < ?2)) \
435+ ORDER BY d.created_at DESC, d.id DESC LIMIT ?3",
436+ (
437+ before.as_ref().map(|b| b.0.clone()),
438+ before.as_ref().map(|b| b.1.clone()),
439+ i64::try_from(limit).unwrap_or(i64::MAX),
440+ ),
441+ |row| {
442+ Ok(Decision {
443+ id: col_text(row, 0)?,
444+ rule_name: col_opt_text(row, 1)?.unwrap_or_default(),
445+ task_key: col_opt_text(row, 2)?,
446+ outcome: col_text(row, 3)?,
447+ detail: col_text(row, 4)?,
448+ at: col_text(row, 5)?,
449+ })
450+ },
451+ )
452+ .await?;
453+ let next_cursor = match items.last() {
454+ Some(last) if items.len() == limit => Some(format!("{}~{}", last.at, last.id)),
455+ _ => None,
456+ };
457+ Ok(DecisionPage { items, next_cursor })
458+ }
459+}
460+
461+/// One rule decision as the logs page shows it.
462+#[derive(Debug, Clone, PartialEq, Eq)]
463+pub struct Decision {
464+ /// Row id.
465+ pub id: String,
466+ /// The rule's name (empty when the rule was deleted).
467+ pub rule_name: String,
468+ /// The task key, if the task still exists.
469+ pub task_key: Option<String>,
470+ /// `owed`, `already_owed`, `no_recipients`, `not_matched`, `disabled` or `task_gone`.
471+ pub outcome: String,
472+ /// The reason, for example the mismatch.
473+ pub detail: String,
474+ /// When it was decided.
475+ pub at: String,
476+}
477+
478+/// One page of decisions, newest first.
479+#[derive(Debug, Clone, PartialEq, Eq)]
480+pub struct DecisionPage {
481+ /// The decisions, newest first.
482+ pub items: Vec<Decision>,
483+ /// Cursor of the next page.
484+ pub next_cursor: Option<String>,
485+}
486+
487+/// Checks a message body: CRLF becomes LF, other control characters go (tab and newline stay), at least one
488+/// visible character, at most `MESSAGE_BODY_MAX` characters.
489+pub fn clean_message_body(body: &str) -> Result<String> {
490+ let normalized = body.replace("\r\n", "\n").replace('\r', "\n");
491+ let cleaned: String = normalized
492+ .chars()
493+ .filter(|c| *c == '\n' || *c == '\t' || !c.is_control())
494+ .collect();
495+ let cleaned = cleaned.trim().to_owned();
496+ if cleaned.is_empty() || cleaned.chars().count() > MESSAGE_BODY_MAX {
497+ return Err(Error::Invalid(format!(
498+ "the message must be 1 to {MESSAGE_BODY_MAX} characters"
499+ )));
500+ }
501+ Ok(cleaned)
502+}
503+
504+/// Whether the member's account is enabled. Read inside the claim transaction.
505+async fn member_enabled(conn: &Connection, sub: &str) -> Result<bool> {
506+ Ok(fetch_opt(
507+ conn,
508+ "SELECT disabled FROM members WHERE sub = ?1",
509+ (sub.to_owned(),),
510+ |row| col_int(row, 0),
511+ )
512+ .await?
513+ .is_some_and(|disabled| disabled == 0))
514+}
crates/iz-core/src/store/reminders.rsadded+180 -0
@@ -0,0 +1,180 @@
1+//! Meeting reminders. One reminder per (task, member, meeting value): it is due `reminder_minutes` before the
2+//! meeting, and a reminder is sent at most once for each due value.
3+//!
4+//! `sync_reminders` runs inside every write that can change a reminder (the meeting time, the assignees, the
5+//! done state, the deletion). It drops the unsent rows and the rows of an old due value, then makes one row
6+//! per eligible assignee for the current one. So a changed meeting time re-arms the reminder, and a change
7+//! that does not move the due value (moving a card to done and back, say) keeps the sent mark. A task that
8+//! is done, deleted, has no meeting or has a past meeting gets no new rows.
9+//!
10+//! `run_reminders` sends the due rows as outbox rows, with a per-recipient cap per hour (the spam guard).
11+//! A reminder over the cap is marked sent without a mail and logged, so it is not retried forever.
12+
13+use jiff::Timestamp;
14+use turso::transaction::Transaction;
15+
16+use super::outbox::{OutboxDraft, insert_outbox};
17+use super::{col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
18+use crate::clock::{reminder_due, stamp_of, timestamp_of};
19+use crate::error::Result;
20+use crate::mail_text::{MailLang, reminder, when_text};
21+use crate::store::Store;
22+use crate::store::rules_engine::task_link;
23+
24+/// The lead time of reminders in minutes, from the setting (0 is off).
25+pub async fn lead_minutes(conn: &turso::Connection) -> Result<i64> {
26+ let value = fetch_opt(
27+ conn,
28+ "SELECT value FROM settings WHERE key = 'reminder_minutes'",
29+ (),
30+ |row| col_text(row, 0),
31+ )
32+ .await?;
33+ Ok(value
34+ .and_then(|v| v.parse::<i64>().ok())
35+ .unwrap_or(crate::clock::REMINDER_LEAD_MINUTES)
36+ .clamp(0, 1440))
37+}
38+
39+/// Rebuilds the reminders of one task inside `tx`. See the module comment for the rule.
40+pub(super) async fn sync_reminders(tx: &Transaction<'_>, task_id: &str) -> Result<()> {
41+ tx.execute(
42+ "DELETE FROM reminders WHERE task_id = ?1 AND sent_at IS NULL",
43+ (task_id.to_owned(),),
44+ )
45+ .await
46+ .map_err(db_err)?;
47+ let lead = lead_minutes(tx).await?;
48+ let state = fetch_opt(
49+ tx,
50+ "SELECT meeting_at, done_at, deleted_at FROM tasks WHERE id = ?1",
51+ (task_id.to_owned(),),
52+ |row| {
53+ Ok((
54+ col_opt_text(row, 0)?,
55+ col_opt_text(row, 1)?,
56+ col_opt_text(row, 2)?,
57+ ))
58+ },
59+ )
60+ .await?;
61+ let due = match state {
62+ Some((Some(meeting), None, None)) if lead > 0 => {
63+ let at = timestamp_of(&meeting)?;
64+ if at <= Timestamp::now() {
65+ None
66+ } else {
67+ Some(reminder_due(at, lead)?)
68+ }
69+ }
70+ _ => None,
71+ };
72+ let Some(due) = due else {
73+ // No active meeting: unsent rows are gone; sent rows stay, so a return to the same value is not re-sent.
74+ return Ok(());
75+ };
76+ tx.execute(
77+ "DELETE FROM reminders WHERE task_id = ?1 AND due_at <> ?2",
78+ (task_id.to_owned(), due.clone()),
79+ )
80+ .await
81+ .map_err(db_err)?;
82+ tx.execute(
83+ "INSERT INTO reminders (task_id, sub, due_at, sent_at) \
84+ SELECT a.task_id, a.sub, ?2, NULL FROM task_assignees a \
85+ WHERE a.task_id = ?1 AND EXISTS ( \
86+ SELECT 1 FROM members m WHERE m.sub = a.sub AND m.disabled = 0 AND m.role IN ('admin', 'member')) \
87+ ON CONFLICT(task_id, sub) DO NOTHING",
88+ (task_id.to_owned(), due),
89+ )
90+ .await
91+ .map_err(db_err)?;
92+ Ok(())
93+}
94+
95+impl Store {
96+ /// Sends the reminders that are due at `now`, at most `batch` of them, as outbox rows. `cap` is the most
97+ /// reminder mails one member may be queued in the hour before `now`. Returns the number queued.
98+ pub async fn run_reminders(
99+ &self,
100+ now: Timestamp,
101+ base_url: &str,
102+ cap: u32,
103+ batch: usize,
104+ ) -> Result<usize> {
105+ let conn = self.inner.conn.lock().await;
106+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
107+ let outcome: Result<usize> = async {
108+ let stamp = stamp_of(now)?;
109+ let window_start = stamp_of(now - jiff::SignedDuration::from_hours(1))?;
110+ let due = fetch_all(
111+ &tx,
112+ "SELECT r.task_id, r.sub, t.key, t.title, t.meeting_at, m.zoneinfo, m.locale, m.locale_override \
113+ FROM reminders r JOIN tasks t ON t.id = r.task_id JOIN members m ON m.sub = r.sub \
114+ WHERE r.sent_at IS NULL AND r.due_at <= ?1 AND t.deleted_at IS NULL \
115+ AND m.disabled = 0 AND m.role IN ('admin', 'member') \
116+ ORDER BY r.due_at, r.task_id, r.sub LIMIT ?2",
117+ (stamp.clone(), i64::try_from(batch).unwrap_or(i64::MAX)),
118+ |row| {
119+ Ok((
120+ col_text(row, 0)?,
121+ col_text(row, 1)?,
122+ col_text(row, 2)?,
123+ col_text(row, 3)?,
124+ col_opt_text(row, 4)?,
125+ col_text(row, 5)?,
126+ col_opt_text(row, 6)?,
127+ col_opt_text(row, 7)?,
128+ ))
129+ },
130+ )
131+ .await?;
132+ let mut queued = 0;
133+ for (task_id, sub, key, title, meeting, zone, locale, locale_override) in due {
134+ let sent_before = fetch_opt(
135+ &tx,
136+ "SELECT COUNT(*) FROM mail_outbox WHERE recipient = ?1 AND kind = 'reminder' AND created_at >= ?2",
137+ (sub.clone(), window_start.clone()),
138+ |row| col_int(row, 0),
139+ )
140+ .await?
141+ .unwrap_or(0);
142+ let over_cap = sent_before >= i64::from(cap);
143+ if !over_cap {
144+ let lang = MailLang::of(locale_override.as_deref(), locale.as_deref());
145+ let when = meeting
146+ .as_deref()
147+ .and_then(|at| when_text(at, &zone))
148+ .unwrap_or_default();
149+ let link = task_link(base_url, &key);
150+ let mail = reminder(lang, &key, &title, &when, &link);
151+ let event_id = new_id();
152+ let draft = OutboxDraft {
153+ rule_id: None,
154+ event_id: &event_id,
155+ task_id: Some(&task_id),
156+ recipient: &sub,
157+ kind: "reminder",
158+ subject: &mail.subject,
159+ body: &mail.body,
160+ next_attempt_at: &stamp,
161+ };
162+ if insert_outbox(&tx, &draft).await? {
163+ queued += 1;
164+ }
165+ } else {
166+ tracing::warn!(recipient = %sub, cap, "reminder suppressed by the hourly cap");
167+ }
168+ tx.execute(
169+ "UPDATE reminders SET sent_at = ?3 WHERE task_id = ?1 AND sub = ?2",
170+ (task_id, sub, stamp.clone()),
171+ )
172+ .await
173+ .map_err(db_err)?;
174+ }
175+ Ok(queued)
176+ }
177+ .await;
178+ finish(tx, outcome).await
179+ }
180+}
crates/iz-core/src/store/rules.rsadded+295 -0
@@ -0,0 +1,295 @@
1+//! Mail rules as stored: the list, the create/edit/delete writes and the enable switch. The rules
2+//! themselves are evaluated in `rules_engine.rs`. Every write is checked here: the trigger and audience
3+//! words, the column only for `status`, and the column and project belonging to the board.
4+
5+use turso::Connection;
6+
7+use super::{col_bool, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
8+use crate::error::{Error, Result};
9+use crate::limits::RULE_SUBJECT_MAX;
10+use crate::rules::{Audience, is_trigger};
11+use crate::store::Store;
12+use crate::time::now_stamp;
13+
14+/// The longest rule name, in characters.
15+pub const RULE_NAME_MAX: usize = 120;
16+
17+/// One rule as stored.
18+#[derive(Debug, Clone, PartialEq, Eq)]
19+pub struct MailRule {
20+ /// Rule id (ULID).
21+ pub id: String,
22+ /// The board it belongs to.
23+ pub board_id: String,
24+ /// The admin's name for it.
25+ pub name: String,
26+ /// The trigger word.
27+ pub trigger: String,
28+ /// Only for `status`: the column that must be entered; `None` is any column.
29+ pub column_id: Option<String>,
30+ /// The project it is limited to; `None` is any project.
31+ pub tag_id: Option<String>,
32+ /// Who is mailed.
33+ pub audience: Audience,
34+ /// Whether the mail carries the details block.
35+ pub include_details: bool,
36+ /// Whether the rule is on.
37+ pub enabled: bool,
38+ /// The subject template, with `{key}`, `{title}`, `{column}`, `{actor}`, `{tag}`, `{deadline}`.
39+ pub subject_template: String,
40+ /// UTC stamp of creation.
41+ pub created_at: String,
42+}
43+
44+/// The fields of a rule as the admin enters them. The store checks them all.
45+#[derive(Debug, Clone, PartialEq, Eq)]
46+pub struct RuleInput {
47+ /// Name, 1 to 120 characters.
48+ pub name: String,
49+ /// The trigger word.
50+ pub trigger: String,
51+ /// Column, only with the `status` trigger.
52+ pub column_id: Option<String>,
53+ /// Project, or `None` for any.
54+ pub tag_id: Option<String>,
55+ /// Audience word.
56+ pub audience: String,
57+ /// Whether to include the details block.
58+ pub include_details: bool,
59+ /// Whether the rule is on.
60+ pub enabled: bool,
61+ /// Subject template, 1 to 120 characters.
62+ pub subject_template: String,
63+}
64+
65+const RULE_COLS: &str = "id, board_id, name, trigger, column_id, tag_id, audience, include_details, enabled, \
66+ subject_template, created_at";
67+
68+fn map_rule(row: &turso::Row) -> Result<MailRule> {
69+ let audience_text = col_text(row, 6)?;
70+ let audience = Audience::parse(&audience_text)
71+ .ok_or_else(|| Error::Database(format!("unknown stored audience: {audience_text}")))?;
72+ Ok(MailRule {
73+ id: col_text(row, 0)?,
74+ board_id: col_text(row, 1)?,
75+ name: col_text(row, 2)?,
76+ trigger: col_text(row, 3)?,
77+ column_id: col_opt_text(row, 4)?,
78+ tag_id: col_opt_text(row, 5)?,
79+ audience,
80+ include_details: col_bool(row, 7)?,
81+ enabled: col_bool(row, 8)?,
82+ subject_template: col_text(row, 9)?,
83+ created_at: col_text(row, 10)?,
84+ })
85+}
86+
87+/// Checks the input and returns the cleaned copy. Every refusal is a message for the admin.
88+async fn checked(conn: &Connection, board_id: &str, input: &RuleInput) -> Result<RuleInput> {
89+ let name = input.name.trim().to_owned();
90+ if name.is_empty() || name.chars().count() > RULE_NAME_MAX {
91+ return Err(Error::Invalid(format!(
92+ "the name must be 1 to {RULE_NAME_MAX} characters"
93+ )));
94+ }
95+ let trigger = input.trigger.trim().to_owned();
96+ if !is_trigger(&trigger) {
97+ return Err(Error::Invalid("that trigger does not exist".into()));
98+ }
99+ let column_id = match input
100+ .column_id
101+ .as_deref()
102+ .map(str::trim)
103+ .filter(|c| !c.is_empty())
104+ {
105+ None => None,
106+ Some(column) if trigger == "status" => {
107+ let live = fetch_opt(
108+ conn,
109+ "SELECT id FROM columns WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL",
110+ (column.to_owned(), board_id.to_owned()),
111+ |row| col_text(row, 0),
112+ )
113+ .await?;
114+ if live.is_none() {
115+ return Err(Error::Invalid("that column does not exist".into()));
116+ }
117+ Some(column.to_owned())
118+ }
119+ Some(_) => {
120+ return Err(Error::Invalid(
121+ "only a status rule can name a column".into(),
122+ ));
123+ }
124+ };
125+ let tag_id = match input
126+ .tag_id
127+ .as_deref()
128+ .map(str::trim)
129+ .filter(|t| !t.is_empty())
130+ {
131+ None => None,
132+ Some(tag) => {
133+ let known = fetch_opt(
134+ conn,
135+ "SELECT id FROM tags WHERE id = ?1 AND board_id = ?2",
136+ (tag.to_owned(), board_id.to_owned()),
137+ |row| col_text(row, 0),
138+ )
139+ .await?;
140+ if known.is_none() {
141+ return Err(Error::Invalid("that project does not exist".into()));
142+ }
143+ Some(tag.to_owned())
144+ }
145+ };
146+ let audience = input.audience.trim().to_owned();
147+ if Audience::parse(&audience).is_none() {
148+ return Err(Error::Invalid("that audience does not exist".into()));
149+ }
150+ let subject_template = input.subject_template.trim().to_owned();
151+ if subject_template.is_empty() || subject_template.chars().count() > RULE_SUBJECT_MAX {
152+ return Err(Error::Invalid(format!(
153+ "the subject must be 1 to {RULE_SUBJECT_MAX} characters"
154+ )));
155+ }
156+ Ok(RuleInput {
157+ name,
158+ trigger,
159+ column_id,
160+ tag_id,
161+ audience,
162+ include_details: input.include_details,
163+ enabled: input.enabled,
164+ subject_template,
165+ })
166+}
167+
168+impl Store {
169+ /// Every rule of the board, oldest first.
170+ pub async fn list_rules(&self, board_id: &str) -> Result<Vec<MailRule>> {
171+ let conn = self.read_conn().await;
172+ fetch_all(
173+ &conn,
174+ &format!(
175+ "SELECT {RULE_COLS} FROM mail_rules WHERE board_id = ?1 ORDER BY created_at, id"
176+ ),
177+ (board_id.to_owned(),),
178+ map_rule,
179+ )
180+ .await
181+ }
182+
183+ /// One rule of the board, or `NotFound`.
184+ pub async fn rule(&self, board_id: &str, rule_id: &str) -> Result<MailRule> {
185+ let conn = self.read_conn().await;
186+ fetch_opt(
187+ &conn,
188+ &format!("SELECT {RULE_COLS} FROM mail_rules WHERE id = ?1 AND board_id = ?2"),
189+ (rule_id.to_owned(), board_id.to_owned()),
190+ map_rule,
191+ )
192+ .await?
193+ .ok_or(Error::NotFound)
194+ }
195+
196+ /// Creates a rule after checking it. Returns the stored rule.
197+ pub async fn create_rule(&self, board_id: &str, input: &RuleInput) -> Result<MailRule> {
198+ let conn = self.inner.conn.lock().await;
199+ let input = checked(&conn, board_id, input).await?;
200+ let id = new_id();
201+ conn.execute(
202+ "INSERT INTO mail_rules (id, board_id, name, trigger, column_id, tag_id, audience, include_details, \
203+ enabled, subject_template, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
204+ (
205+ id.clone(),
206+ board_id.to_owned(),
207+ input.name,
208+ input.trigger,
209+ input.column_id,
210+ input.tag_id,
211+ input.audience,
212+ i64::from(input.include_details),
213+ i64::from(input.enabled),
214+ input.subject_template,
215+ now_stamp(),
216+ ),
217+ )
218+ .await
219+ .map_err(db_err)?;
220+ drop(conn);
221+ self.rule(board_id, &id).await
222+ }
223+
224+ /// Replaces the fields of a rule after checking them. The rule keeps its id and creation time.
225+ pub async fn update_rule(
226+ &self,
227+ board_id: &str,
228+ rule_id: &str,
229+ input: &RuleInput,
230+ ) -> Result<MailRule> {
231+ let conn = self.inner.conn.lock().await;
232+ let input = checked(&conn, board_id, input).await?;
233+ let changed = conn
234+ .execute(
235+ "UPDATE mail_rules SET name = ?3, trigger = ?4, column_id = ?5, tag_id = ?6, audience = ?7, \
236+ include_details = ?8, enabled = ?9, subject_template = ?10 WHERE id = ?1 AND board_id = ?2",
237+ (
238+ rule_id.to_owned(),
239+ board_id.to_owned(),
240+ input.name,
241+ input.trigger,
242+ input.column_id,
243+ input.tag_id,
244+ input.audience,
245+ i64::from(input.include_details),
246+ i64::from(input.enabled),
247+ input.subject_template,
248+ ),
249+ )
250+ .await
251+ .map_err(db_err)?;
252+ drop(conn);
253+ if changed == 0 {
254+ return Err(Error::NotFound);
255+ }
256+ self.rule(board_id, rule_id).await
257+ }
258+
259+ /// Switches a rule on or off.
260+ pub async fn set_rule_enabled(
261+ &self,
262+ board_id: &str,
263+ rule_id: &str,
264+ enabled: bool,
265+ ) -> Result<()> {
266+ let conn = self.inner.conn.lock().await;
267+ let changed = conn
268+ .execute(
269+ "UPDATE mail_rules SET enabled = ?3 WHERE id = ?1 AND board_id = ?2",
270+ (rule_id.to_owned(), board_id.to_owned(), i64::from(enabled)),
271+ )
272+ .await
273+ .map_err(db_err)?;
274+ if changed == 0 {
275+ return Err(Error::NotFound);
276+ }
277+ Ok(())
278+ }
279+
280+ /// Deletes a rule. Its outbox rows stay (the link to the rule is cleared), and its decisions go with it.
281+ pub async fn delete_rule(&self, board_id: &str, rule_id: &str) -> Result<()> {
282+ let conn = self.inner.conn.lock().await;
283+ let changed = conn
284+ .execute(
285+ "DELETE FROM mail_rules WHERE id = ?1 AND board_id = ?2",
286+ (rule_id.to_owned(), board_id.to_owned()),
287+ )
288+ .await
289+ .map_err(db_err)?;
290+ if changed == 0 {
291+ return Err(Error::NotFound);
292+ }
293+ Ok(())
294+ }
295+}
crates/iz-core/src/store/rules_engine.rsadded+559 -0
@@ -0,0 +1,559 @@
1+//! The rules engine: turns queued events into decisions and outbox rows.
2+//!
3+//! One pass reads up to `batch` unprocessed events in order and handles all of them in one transaction:
4+//! for each event, every rule with its trigger gets one decision row (outcome and reason) and, when it
5+//! owes mail, one outbox row per recipient. The unique keys (decision per rule, event and task; outbox per
6+//! rule, event, task and recipient) make a repeated pass a no-op. The pass either commits everything or
7+//! nothing, so a crash between the two leaves the events unprocessed and they are handled again.
8+//!
9+//! Recipients come from the eligible members only (enabled, role admin or member), and the actor is
10+//! removed by `rules::audience`. Mail text is built per recipient in the recipient's language and zone.
11+
12+use jiff::Timestamp;
13+use turso::Connection;
14+use turso::transaction::Transaction;
15+
16+use super::outbox::{OutboxDraft, insert_outbox};
17+use super::{col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
18+use crate::clock::stamp_of;
19+use crate::error::Result;
20+use crate::mail_text::{MailLang, RuleMail, rule_body, when_text};
21+use crate::rules::{Audience, EventFacts, RuleFacts, TaskFacts, Verdict, evaluate, render_subject};
22+use crate::store::Store;
23+use crate::time::now_stamp;
24+
25+/// One unprocessed event as read back.
26+struct QueuedEvent {
27+ id: String,
28+ board_id: String,
29+ task_id: Option<String>,
30+ kind: String,
31+ column_id: Option<String>,
32+ actor: Option<String>,
33+ subject: Option<String>,
34+}
35+
36+/// An eligible member: enabled, role admin or member. The language and zone are the ones mail uses.
37+#[derive(Clone)]
38+struct Eligible {
39+ sub: String,
40+ lang: MailLang,
41+ zone: String,
42+}
43+
44+/// The task row fields a mail body needs.
45+struct TaskRow {
46+ key: String,
47+ title: String,
48+ column_id: String,
49+ tag_id: String,
50+ deadline: Option<String>,
51+ meeting_at: Option<String>,
52+ deleted: bool,
53+ creator: String,
54+}
55+
56+/// What one pass did. Returned for logs and tests.
57+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
58+pub struct PassReport {
59+ /// Events handled in this pass.
60+ pub events: usize,
61+ /// Outbox rows queued in this pass.
62+ pub mails: usize,
63+}
64+
65+/// The eligible members of the instance, sorted by id.
66+async fn eligible_members(tx: &Transaction<'_>) -> Result<Vec<Eligible>> {
67+ fetch_all(
68+ tx,
69+ "SELECT sub, locale, locale_override, zoneinfo FROM members \
70+ WHERE disabled = 0 AND role IN ('admin', 'member') ORDER BY sub",
71+ (),
72+ |row| {
73+ let locale = col_opt_text(row, 1)?;
74+ let locale_override = col_opt_text(row, 2)?;
75+ Ok(Eligible {
76+ sub: col_text(row, 0)?,
77+ lang: MailLang::of(locale_override.as_deref(), locale.as_deref()),
78+ zone: col_text(row, 3)?,
79+ })
80+ },
81+ )
82+ .await
83+}
84+
85+/// The task row of `task_id` on `board_id`, deleted or not.
86+async fn task_row(conn: &Connection, board_id: &str, task_id: &str) -> Result<Option<TaskRow>> {
87+ fetch_opt(
88+ conn,
89+ "SELECT key, title, column_id, tag_id, deadline, meeting_at, deleted_at, created_by FROM tasks \
90+ WHERE id = ?1 AND board_id = ?2",
91+ (task_id.to_owned(), board_id.to_owned()),
92+ |row| {
93+ Ok(TaskRow {
94+ key: col_text(row, 0)?,
95+ title: col_text(row, 1)?,
96+ column_id: col_text(row, 2)?,
97+ tag_id: col_text(row, 3)?,
98+ deadline: col_opt_text(row, 4)?,
99+ meeting_at: col_opt_text(row, 5)?,
100+ deleted: col_opt_text(row, 6)?.is_some(),
101+ creator: col_text(row, 7)?,
102+ })
103+ },
104+ )
105+ .await
106+}
107+
108+/// Sorted ids of the people assigned to `task_id`, and the names in the same order.
109+async fn assignees_of(conn: &Connection, task_id: &str) -> Result<Vec<(String, String)>> {
110+ fetch_all(
111+ conn,
112+ "SELECT a.sub, m.name FROM task_assignees a JOIN members m ON m.sub = a.sub \
113+ WHERE a.task_id = ?1 ORDER BY a.sub",
114+ (task_id.to_owned(),),
115+ |row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
116+ )
117+ .await
118+}
119+
120+/// Sorted ids of the members who watch `task_id`.
121+async fn watchers_of(conn: &Connection, task_id: &str) -> Result<Vec<String>> {
122+ fetch_all(
123+ conn,
124+ "SELECT sub FROM task_watchers WHERE task_id = ?1 ORDER BY sub",
125+ (task_id.to_owned(),),
126+ |row| col_text(row, 0),
127+ )
128+ .await
129+}
130+
131+/// A name by id, or empty when the member is unknown.
132+async fn name_of(conn: &Connection, sub: &str) -> Result<String> {
133+ Ok(fetch_opt(
134+ conn,
135+ "SELECT name FROM members WHERE sub = ?1",
136+ (sub.to_owned(),),
137+ |row| col_text(row, 0),
138+ )
139+ .await?
140+ .unwrap_or_default())
141+}
142+
143+/// A column or project name by id, or empty when it is gone.
144+async fn label_of(conn: &Connection, table: &'static str, id: &str) -> Result<String> {
145+ let sql = match table {
146+ "columns" => "SELECT name FROM columns WHERE id = ?1",
147+ _ => "SELECT name FROM tags WHERE id = ?1",
148+ };
149+ Ok(
150+ fetch_opt(conn, sql, (id.to_owned(),), |row| col_text(row, 0))
151+ .await?
152+ .unwrap_or_default(),
153+ )
154+}
155+
156+/// The link back to a task. The base has no trailing slash (see `config.base_url`).
157+pub fn task_link(base_url: &str, key: &str) -> String {
158+ format!("{}/?task={key}", base_url.trim_end_matches('/'))
159+}
160+
161+/// Handles one event: every rule of its trigger gets a decision, and mail rows for the owed recipients.
162+async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Result<usize> {
163+ let rules = fetch_all(
164+ tx,
165+ "SELECT id, column_id, tag_id, audience, enabled, subject_template, include_details FROM mail_rules \
166+ WHERE board_id = ?1 AND trigger = ?2 ORDER BY created_at, id",
167+ (event.board_id.clone(), event.kind.clone()),
168+ |row| {
169+ let audience_text = col_text(row, 3)?;
170+ let audience = Audience::parse(&audience_text).unwrap_or(Audience::Assignees);
171+ Ok((
172+ col_text(row, 0)?,
173+ RuleFacts {
174+ enabled: col_int(row, 4)? == 1,
175+ column_id: col_opt_text(row, 1)?,
176+ tag_id: col_opt_text(row, 2)?,
177+ audience,
178+ },
179+ col_text(row, 5)?,
180+ col_int(row, 6)? == 1,
181+ ))
182+ },
183+ )
184+ .await?;
185+ if rules.is_empty() {
186+ return Ok(0);
187+ }
188+ let eligible = eligible_members(tx).await?;
189+ let subs: Vec<String> = eligible.iter().map(|m| m.sub.clone()).collect();
190+ let task = match &event.task_id {
191+ Some(task_id) => task_row(tx, &event.board_id, task_id).await?,
192+ None => None,
193+ };
194+ let facts = match (&event.task_id, &task) {
195+ (Some(task_id), Some(row)) => Some(TaskFacts {
196+ tag_id: row.tag_id.clone(),
197+ deleted: row.deleted,
198+ creator: row.creator.clone(),
199+ assignees: assignees_of(tx, task_id)
200+ .await?
201+ .into_iter()
202+ .map(|(sub, _)| sub)
203+ .collect(),
204+ watchers: watchers_of(tx, task_id).await?,
205+ }),
206+ _ => None,
207+ };
208+ let event_facts = EventFacts {
209+ kind: event.kind.clone(),
210+ subject: event.subject.clone(),
211+ column_id: event.column_id.clone(),
212+ actor: event.actor.clone(),
213+ };
214+ let actor_name = match &event.actor {
215+ Some(actor) => name_of(tx, actor).await?,
216+ None => String::new(),
217+ };
218+ let subject_name = match &event.subject {
219+ Some(sub) => name_of(tx, sub).await?,
220+ None => String::new(),
221+ };
222+ let queued_at = now_stamp();
223+ let mut mails = 0;
224+ for (rule_id, rule, template, details) in &rules {
225+ let verdict = evaluate(rule, &event_facts, facts.as_ref(), &subs);
226+ let (outcome, detail, recipients) = match &verdict {
227+ Verdict::Disabled => ("disabled", String::new(), Vec::new()),
228+ Verdict::TaskGone => ("task_gone", String::new(), Vec::new()),
229+ Verdict::NotMatched(reason) => ("not_matched", reason.as_str().to_owned(), Vec::new()),
230+ Verdict::NoRecipients => ("no_recipients", "empty".to_owned(), Vec::new()),
231+ Verdict::Owed(recipients) => ("owed", String::new(), recipients.clone()),
232+ };
233+ let mut queued = 0;
234+ if let (Some(row), Some(task_id)) = (&task, &event.task_id) {
235+ let column_id = event
236+ .column_id
237+ .clone()
238+ .unwrap_or_else(|| row.column_id.clone());
239+ let column = label_of(tx, "columns", &column_id).await?;
240+ let tag = label_of(tx, "tags", &row.tag_id).await?;
241+ let assignees: Vec<String> = assignees_of(tx, task_id)
242+ .await?
243+ .into_iter()
244+ .map(|(_, n)| n)
245+ .collect();
246+ let link = task_link(base_url, &row.key);
247+ for sub in &recipients {
248+ let Some(member) = eligible.iter().find(|m| &m.sub == sub) else {
249+ continue;
250+ };
251+ let when = row
252+ .meeting_at
253+ .as_deref()
254+ .and_then(|at| when_text(at, &member.zone));
255+ let subject = render_subject(
256+ template,
257+ &[
258+ ("key", &row.key),
259+ ("title", &row.title),
260+ ("column", &column),
261+ ("actor", &actor_name),
262+ ("tag", &tag),
263+ ("deadline", row.deadline.as_deref().unwrap_or("")),
264+ ],
265+ );
266+ let body = rule_body(&RuleMail {
267+ lang: member.lang,
268+ kind: &event.kind,
269+ actor: &actor_name,
270+ subject_name: &subject_name,
271+ key: &row.key,
272+ title: &row.title,
273+ column: &column,
274+ deadline: row.deadline.as_deref(),
275+ assignees: &assignees,
276+ when: when.as_deref(),
277+ link: &link,
278+ details: *details,
279+ subject: &subject,
280+ });
281+ let draft = OutboxDraft {
282+ rule_id: Some(rule_id),
283+ event_id: &event.id,
284+ task_id: Some(task_id),
285+ recipient: sub,
286+ kind: "rule",
287+ subject: &subject,
288+ body: &body,
289+ next_attempt_at: &queued_at,
290+ };
291+ if insert_outbox(tx, &draft).await? {
292+ queued += 1;
293+ }
294+ }
295+ }
296+ mails += queued;
297+ let outcome = if outcome == "owed" && queued == 0 {
298+ "already_owed"
299+ } else {
300+ outcome
301+ };
302+ tx.execute(
303+ "INSERT INTO mail_decisions (id, rule_id, event_id, task_id, outcome, detail, created_at) \
304+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT(rule_id, event_id, task_id) DO NOTHING",
305+ (
306+ new_id(),
307+ rule_id.clone(),
308+ event.id.clone(),
309+ event.task_id.clone(),
310+ outcome,
311+ detail,
312+ now_stamp(),
313+ ),
314+ )
315+ .await
316+ .map_err(db_err)?;
317+ }
318+ Ok(mails)
319+}
320+
321+impl Store {
322+ /// One pass of the rules engine over up to `batch` queued events, in one transaction. `now` stamps the
323+ /// outbox rows; `base_url` is the link base of the mails.
324+ pub async fn run_rules(
325+ &self,
326+ now: Timestamp,
327+ base_url: &str,
328+ batch: usize,
329+ ) -> Result<PassReport> {
330+ let conn = self.inner.conn.lock().await;
331+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
332+ let outcome: Result<PassReport> = async {
333+ let events = fetch_all(
334+ &tx,
335+ "SELECT id, board_id, task_id, kind, column_id, actor, subject FROM mail_events \
336+ WHERE processed_at IS NULL ORDER BY at, id LIMIT ?1",
337+ (i64::try_from(batch).unwrap_or(i64::MAX),),
338+ |row| {
339+ Ok(QueuedEvent {
340+ id: col_text(row, 0)?,
341+ board_id: col_text(row, 1)?,
342+ task_id: col_opt_text(row, 2)?,
343+ kind: col_text(row, 3)?,
344+ column_id: col_opt_text(row, 4)?,
345+ actor: col_opt_text(row, 5)?,
346+ subject: col_opt_text(row, 6)?,
347+ })
348+ },
349+ )
350+ .await?;
351+ let mut report = PassReport::default();
352+ let stamp = stamp_of(now)?;
353+ for event in &events {
354+ report.mails += handle(&tx, event, base_url).await?;
355+ tx.execute(
356+ "UPDATE mail_events SET processed_at = ?2 WHERE id = ?1",
357+ (event.id.clone(), stamp.clone()),
358+ )
359+ .await
360+ .map_err(db_err)?;
361+ report.events += 1;
362+ }
363+ Ok(report)
364+ }
365+ .await;
366+ finish(tx, outcome).await
367+ }
368+}
369+
370+#[cfg(test)]
371+mod tests {
372+ use jiff::{SignedDuration, Timestamp};
373+
374+ use super::*;
375+ use crate::clock::stamp_of;
376+ use crate::store::rules::RuleInput;
377+ use crate::store::tasks::{NewTask, TaskEdit};
378+ use crate::store::test_support::seeded;
379+ use crate::time::stamp_after;
380+ use std::time::Duration;
381+
382+ const BASE: &str = "http://127.0.0.1:7654";
383+
384+ fn rule(trigger: &str, audience: &str) -> RuleInput {
385+ RuleInput {
386+ name: "Test rule".into(),
387+ trigger: trigger.into(),
388+ column_id: None,
389+ tag_id: None,
390+ audience: audience.into(),
391+ include_details: true,
392+ enabled: true,
393+ subject_template: "{key} {title}".into(),
394+ }
395+ }
396+
397+ fn new_task(column: &str, tag: &str, assignees: &[&str], meeting: Option<String>) -> NewTask {
398+ NewTask {
399+ title: "Dentist".into(),
400+ description: String::new(),
401+ column_id: column.into(),
402+ tag_id: tag.into(),
403+ deadline: None,
404+ meeting_at: meeting,
405+ assignees: assignees.iter().map(|s| s.to_string()).collect(),
406+ parent_id: None,
407+ link: None,
408+ }
409+ }
410+
411+ /// The first column and the default project of the board.
412+ async fn column_and_tag(store: &Store, board_id: &str) -> (String, String) {
413+ let column = store.columns(board_id).await.unwrap()[0].id.clone();
414+ let tag = store.tags(board_id).await.unwrap()[0].id.clone();
415+ (column, tag)
416+ }
417+
418+ #[tokio::test]
419+ async fn a_mail_event_cannot_trigger_a_rule() {
420+ let (_dir, store, board_id) = seeded().await;
421+ store
422+ .create_rule(&board_id, &rule("commented", "board"))
423+ .await
424+ .unwrap();
425+ // A notice is mail, not a board event: queuing and sending it writes no event.
426+ let queued = store
427+ .queue_message("ada", "Hello", "Bye", Timestamp::now())
428+ .await
429+ .unwrap();
430+ assert_eq!(queued, 1);
431+ let now = Timestamp::now();
432+ for row in store.claim_due(now, 10).await.unwrap() {
433+ store.mark_sent(&row.id, now).await.unwrap();
434+ }
435+ let report = store.run_rules(now, BASE, 100).await.unwrap();
436+ assert_eq!(
437+ report,
438+ PassReport {
439+ events: 0,
440+ mails: 0
441+ }
442+ );
443+ let rule_mail = store
444+ .outbox_page(None, 100)
445+ .await
446+ .unwrap()
447+ .items
448+ .iter()
449+ .filter(|row| row.kind == "rule")
450+ .count();
451+ assert_eq!(rule_mail, 0);
452+ }
453+
454+ #[tokio::test]
455+ async fn a_ghost_member_and_the_actor_receive_nothing() {
456+ let (_dir, store, board_id) = seeded().await;
457+ let (column, tag) = column_and_tag(&store, &board_id).await;
458+ let ghost = crate::store::members::DirectoryMember {
459+ sub: "ghost".into(),
460+ email: "ghost@example.com".into(),
461+ name: "Ghost".into(),
462+ im_admin: false,
463+ disabled: false,
464+ locale: None,
465+ zoneinfo: "UTC".into(),
466+ picture_version: 0,
467+ };
468+ store
469+ .apply_directory_member(&ghost, crate::authz::Role::Member)
470+ .await
471+ .unwrap();
472+ store
473+ .create_rule(&board_id, &rule("created", "board"))
474+ .await
475+ .unwrap();
476+ store
477+ .create_task(
478+ &board_id,
479+ new_task(&column, &tag, &["bo", "ghost"], None),
480+ "ada",
481+ )
482+ .await
483+ .unwrap();
484+ // The member leaves the family after being assigned: the queued mail must not reach them.
485+ let mut gone = ghost.clone();
486+ gone.disabled = true;
487+ store
488+ .apply_directory_member(&gone, crate::authz::Role::Member)
489+ .await
490+ .unwrap();
491+ store.run_rules(Timestamp::now(), BASE, 100).await.unwrap();
492+ let rows = store.outbox_page(None, 100).await.unwrap().items;
493+ let recipients: Vec<&str> = rows.iter().map(|r| r.recipient.as_str()).collect();
494+ assert_eq!(
495+ recipients,
496+ vec!["bo"],
497+ "only the eligible, non-acting member is mailed"
498+ );
499+ // Anybody claiming the queued mail after the change is refused as well.
500+ let claimed = store.claim_due(Timestamp::now(), 10).await.unwrap();
501+ assert!(claimed.iter().all(|r| r.recipient != "ghost"));
502+ }
503+
504+ #[tokio::test]
505+ async fn a_reminder_fires_once_per_meeting_and_re_arms_after_a_change() {
506+ let (_dir, store, board_id) = seeded().await;
507+ let (column, tag) = column_and_tag(&store, &board_id).await;
508+ let now = Timestamp::now();
509+ let meeting = stamp_after(Duration::from_secs(2 * 3600));
510+ let task = store
511+ .create_task(
512+ &board_id,
513+ new_task(&column, &tag, &["bo"], Some(meeting)),
514+ "ada",
515+ )
516+ .await
517+ .unwrap();
518+ let reminders_for_bo = |store: &Store| {
519+ let store = store.clone();
520+ async move {
521+ store
522+ .outbox_page(None, 200)
523+ .await
524+ .unwrap()
525+ .items
526+ .iter()
527+ .filter(|r| r.kind == "reminder" && r.recipient == "bo")
528+ .count()
529+ }
530+ };
531+ // Past the due time (meeting minus 15 minutes) once: one reminder.
532+ let after_due = now + SignedDuration::from_mins(110);
533+ store.run_reminders(after_due, BASE, 20, 100).await.unwrap();
534+ store.run_reminders(after_due, BASE, 20, 100).await.unwrap();
535+ assert_eq!(reminders_for_bo(&store).await, 1);
536+ // Moving the meeting re-arms the reminder for the new due value.
537+ let moved = stamp_of(now + SignedDuration::from_hours(4)).unwrap();
538+ let edit = TaskEdit {
539+ title: task.title.clone(),
540+ description: task.description.clone(),
541+ tag_id: task.tag_id.clone(),
542+ deadline: None,
543+ meeting_at: Some(moved),
544+ };
545+ store
546+ .edit_task(&board_id, &task.id, edit, "ada")
547+ .await
548+ .unwrap();
549+ store
550+ .run_reminders(now + SignedDuration::from_hours(5), BASE, 20, 100)
551+ .await
552+ .unwrap();
553+ store
554+ .run_reminders(now + SignedDuration::from_hours(5), BASE, 20, 100)
555+ .await
556+ .unwrap();
557+ assert_eq!(reminders_for_bo(&store).await, 2);
558+ }
559+}
crates/iz-core/src/store/sender.rsadded+196 -0
@@ -0,0 +1,196 @@
1+//! Stored mail settings: the sender (SMTP host, port, TLS mode, user name, From address and name, and the
2+//! sealed password) and the reminder settings (lead time and hourly cap). They live in the `settings` table
3+//! as plain text, except the password, which the web layer seals before it gets here.
4+//!
5+//! The password is never read back into a page. `load_sender` says only whether it is set.
6+
7+use turso::transaction::Transaction;
8+
9+use super::{col_text, db_err, fetch_opt, finish};
10+use crate::clock::REMINDER_LEAD_MINUTES;
11+use crate::error::{Error, Result};
12+use crate::sender::{DEFAULT_REMINDER_CAP, Sender};
13+use crate::store::Store;
14+use crate::time::now_stamp;
15+
16+/// Settings key of each sender field. The password key holds the sealed value.
17+const KEYS: [&str; 6] = [
18+ "mail_host",
19+ "mail_port",
20+ "mail_tls",
21+ "mail_username",
22+ "mail_from_address",
23+ "mail_from_name",
24+];
25+/// Settings key of the sealed SMTP password.
26+pub const KEY_PASSWORD: &str = "mail_password";
27+/// Settings key of the reminder lead time in minutes.
28+pub const KEY_REMINDER_MINUTES: &str = "reminder_minutes";
29+/// Settings key of the reminder cap per member per hour.
30+pub const KEY_REMINDER_CAP: &str = "reminder_hourly_cap";
31+
32+/// What the store knows about the sender. The password is only represented by its sealed text.
33+#[derive(Debug, Clone, PartialEq, Eq)]
34+pub struct SenderState {
35+ /// The checked configuration, or `None` when a field is missing or was never saved.
36+ pub sender: Option<Sender>,
37+ /// Whether a password is stored.
38+ pub password_set: bool,
39+ /// The sealed password, for the web layer to open when it connects.
40+ pub sealed_password: Option<String>,
41+}
42+
43+/// The settings of reminders: lead minutes (0 is off) and the cap per member per hour.
44+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45+pub struct ReminderSettings {
46+ /// Minutes before a meeting that the reminder is due.
47+ pub lead_minutes: u32,
48+ /// Reminder mails one member may receive in an hour.
49+ pub hourly_cap: u32,
50+}
51+
52+impl Default for ReminderSettings {
53+ fn default() -> Self {
54+ ReminderSettings {
55+ lead_minutes: u32::try_from(REMINDER_LEAD_MINUTES).unwrap_or(15),
56+ hourly_cap: DEFAULT_REMINDER_CAP,
57+ }
58+ }
59+}
60+
61+/// Writes settings in `tx`, one upsert each, with the same stamp.
62+async fn put_all(tx: &Transaction<'_>, pairs: &[(&str, String)]) -> Result<()> {
63+ let stamp = now_stamp();
64+ for (key, value) in pairs {
65+ tx.execute(
66+ "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \
67+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
68+ (key.to_string(), value.clone(), stamp.clone()),
69+ )
70+ .await
71+ .map_err(db_err)?;
72+ }
73+ Ok(())
74+}
75+
76+impl Store {
77+ /// The sender as stored. A configuration with a missing field reads as `sender: None`.
78+ pub async fn load_sender(&self) -> Result<SenderState> {
79+ let conn = self.read_conn().await;
80+ let mut values = Vec::with_capacity(KEYS.len());
81+ for key in KEYS {
82+ let value = fetch_opt(
83+ &conn,
84+ "SELECT value FROM settings WHERE key = ?1",
85+ (key.to_owned(),),
86+ |row| col_text(row, 0),
87+ )
88+ .await?;
89+ values.push(value);
90+ }
91+ let sealed_password = fetch_opt(
92+ &conn,
93+ "SELECT value FROM settings WHERE key = ?1",
94+ (KEY_PASSWORD.to_owned(),),
95+ |row| col_text(row, 0),
96+ )
97+ .await?;
98+ let sender = match values.as_slice() {
99+ [
100+ Some(host),
101+ Some(port),
102+ Some(tls),
103+ Some(username),
104+ Some(address),
105+ Some(name),
106+ ] => {
107+ let input = crate::sender::SenderInput {
108+ host: host.clone(),
109+ port: port.clone(),
110+ tls: tls.clone(),
111+ username: username.clone(),
112+ from_address: address.clone(),
113+ from_name: name.clone(),
114+ };
115+ crate::sender::validate_sender(&input).ok()
116+ }
117+ _ => None,
118+ };
119+ Ok(SenderState {
120+ sender,
121+ password_set: sealed_password.is_some(),
122+ sealed_password,
123+ })
124+ }
125+
126+ /// Saves the sender. `sealed_password` replaces the stored password when it is `Some`; `None` keeps it.
127+ pub async fn save_sender(&self, sender: &Sender, sealed_password: Option<&str>) -> Result<()> {
128+ let conn = self.inner.conn.lock().await;
129+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
130+ let outcome: Result<()> = async {
131+ let mut pairs: Vec<(&str, String)> = vec![
132+ (KEYS[0], sender.host.clone()),
133+ (KEYS[1], sender.port.to_string()),
134+ (KEYS[2], sender.tls.as_str().to_owned()),
135+ (KEYS[3], sender.username.clone()),
136+ (KEYS[4], sender.from_address.clone()),
137+ (KEYS[5], sender.from_name.clone()),
138+ ];
139+ if let Some(sealed) = sealed_password {
140+ pairs.push((KEY_PASSWORD, sealed.to_owned()));
141+ }
142+ put_all(&tx, &pairs).await
143+ }
144+ .await;
145+ finish(tx, outcome).await
146+ }
147+
148+ /// The reminder settings as stored, or the defaults for a value never saved.
149+ pub async fn reminder_settings(&self) -> Result<ReminderSettings> {
150+ let conn = self.read_conn().await;
151+ let lead = super::reminders::lead_minutes(&conn).await?;
152+ let cap = fetch_opt(
153+ &conn,
154+ "SELECT value FROM settings WHERE key = ?1",
155+ (KEY_REMINDER_CAP.to_owned(),),
156+ |row| col_text(row, 0),
157+ )
158+ .await?
159+ .and_then(|v| v.parse::<u32>().ok())
160+ .unwrap_or(DEFAULT_REMINDER_CAP);
161+ Ok(ReminderSettings {
162+ lead_minutes: u32::try_from(lead).unwrap_or(0),
163+ hourly_cap: cap.min(crate::limits::REMINDER_CAP_MAX),
164+ })
165+ }
166+
167+ /// Saves the reminder settings. The lead is `0..=REMINDER_MINUTES_MAX`, the cap `1..=REMINDER_CAP_MAX`.
168+ pub async fn save_reminder_settings(&self, settings: ReminderSettings) -> Result<()> {
169+ if settings.lead_minutes > crate::limits::REMINDER_MINUTES_MAX {
170+ return Err(Error::Invalid(format!(
171+ "the reminder lead must be 0 to {} minutes",
172+ crate::limits::REMINDER_MINUTES_MAX
173+ )));
174+ }
175+ if settings.hourly_cap == 0 || settings.hourly_cap > crate::limits::REMINDER_CAP_MAX {
176+ return Err(Error::Invalid(format!(
177+ "the reminder cap must be 1 to {} mails per hour",
178+ crate::limits::REMINDER_CAP_MAX
179+ )));
180+ }
181+ let conn = self.inner.conn.lock().await;
182+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
183+ let outcome: Result<()> = async {
184+ put_all(
185+ &tx,
186+ &[
187+ (KEY_REMINDER_MINUTES, settings.lead_minutes.to_string()),
188+ (KEY_REMINDER_CAP, settings.hourly_cap.to_string()),
189+ ],
190+ )
191+ .await
192+ }
193+ .await;
194+ finish(tx, outcome).await
195+ }
196+}
crates/iz-core/src/store/tasks.rsmodified+60 -45
@@ -16,11 +16,13 @@ use turso::transaction::Transaction;
16 16
17 use super::activity::{self, NewActivity};17 use super::activity::{self, NewActivity};
18 use super::board::{Column, Tag, column_in, live_columns};18 use super::board::{Column, Tag, column_in, live_columns};
19+use super::events::{EventDraft, emit};
20+use super::reminders::sync_reminders;
19 use super::{21 use super::{
20 col_int, col_opt_text, col_real, col_text, db_err, fetch_all, fetch_opt, finish, new_id,22 col_int, col_opt_text, col_real, col_text, db_err, fetch_all, fetch_opt, finish, new_id,
21 };23 };
22 use crate::board::{fold_for_search, format_key, is_overdue, position_between, would_cycle};24 use crate::board::{fold_for_search, format_key, is_overdue, position_between, would_cycle};
23-use crate::clock::{reminder_due, timestamp_of};25+use crate::clock::timestamp_of;
24 use crate::error::{Error, Result};26 use crate::error::{Error, Result};
25 use crate::limits::{DESCRIPTION_MAX, TITLE_MAX};27 use crate::limits::{DESCRIPTION_MAX, TITLE_MAX};
26 use crate::store::Store;28 use crate::store::Store;
@@ -424,6 +426,31 @@ async fn record_transition(
424 Ok(())426 Ok(())
425 }427 }
426 428
429+/// Queues one mail event for a task write, inside the write's transaction (see `events.rs`).
430+async fn queue_event(
431+ tx: &Transaction<'_>,
432+ board_id: &str,
433+ task_id: &str,
434+ kind: &'static str,
435+ actor: &str,
436+ subject: Option<&str>,
437+ column: Option<&str>,
438+) -> Result<()> {
439+ emit(
440+ tx,
441+ EventDraft {
442+ board_id,
443+ task_id: Some(task_id),
444+ kind,
445+ column_id: column,
446+ actor: Some(actor),
447+ subject,
448+ detail: serde_json::json!({}),
449+ },
450+ )
451+ .await
452+}
453+
427 /// Writes one task-scoped activity row.454 /// Writes one task-scoped activity row.
428 async fn log(455 async fn log(
429 tx: &Transaction<'_>,456 tx: &Transaction<'_>,
@@ -446,50 +473,6 @@ async fn log(
446 .await473 .await
447 }474 }
448 475
449-/// Rebuilds the pending reminders of one task (inventory 2.4): one per assignee, due a fixed lead time
450-/// before the meeting. Sent reminders are kept. None are made when the task is done, deleted, has no
451-/// meeting, or its meeting is in the past.
452-async fn sync_reminders(tx: &Transaction<'_>, task_id: &str) -> Result<()> {
453- tx.execute(
454- "DELETE FROM reminders WHERE task_id = ?1 AND sent_at IS NULL",
455- (task_id.to_owned(),),
456- )
457- .await
458- .map_err(db_err)?;
459- let state = fetch_opt(
460- tx,
461- "SELECT meeting_at, done_at, deleted_at FROM tasks WHERE id = ?1",
462- (task_id.to_owned(),),
463- |row| {
464- Ok((
465- col_opt_text(row, 0)?,
466- col_opt_text(row, 1)?,
467- col_opt_text(row, 2)?,
468- ))
469- },
470- )
471- .await?;
472- let Some((Some(meeting), None, None)) = state else {
473- return Ok(());
474- };
475- let at = timestamp_of(&meeting)?;
476- if at <= Timestamp::now() {
477- return Ok(());
478- }
479- let due = reminder_due(at)?;
480- tx.execute(
481- "INSERT INTO reminders (task_id, sub, due_at, sent_at) \
482- SELECT a.task_id, a.sub, ?2, NULL FROM task_assignees a \
483- WHERE a.task_id = ?1 AND EXISTS ( \
484- SELECT 1 FROM members m WHERE m.sub = a.sub AND m.disabled = 0 AND m.role IN ('admin', 'member')) \
485- ON CONFLICT(task_id, sub) DO NOTHING",
486- (task_id.to_owned(), due),
487- )
488- .await
489- .map_err(db_err)?;
490- Ok(())
491-}
492-
493 impl Store {476 impl Store {
494 /// Creates a task with everything it starts with, in one transaction: the key (from the board's477 /// Creates a task with everything it starts with, in one transaction: the key (from the board's
495 /// counter, never reused), the placement, the assignees, the optional subtask parent and the optional478 /// counter, never reused), the placement, the assignees, the optional subtask parent and the optional
@@ -585,6 +568,7 @@ impl Store {
585 )568 )
586 .await569 .await
587 .map_err(db_err)?;570 .map_err(db_err)?;
571+ queue_event(&tx, board_id, &id, "linked", actor, None, None).await?;
588 let direction_text = match direction {572 let direction_text = match direction {
589 LinkDirection::BlockedBy => "blocked_by",573 LinkDirection::BlockedBy => "blocked_by",
590 LinkDirection::Blocks => "blocks",574 LinkDirection::Blocks => "blocks",
@@ -607,6 +591,7 @@ impl Store {
607 .await591 .await
608 .map_err(db_err)?;592 .map_err(db_err)?;
609 log(&tx, &id, actor, "assigned", Some(sub), serde_json::json!({})).await?;593 log(&tx, &id, actor, "assigned", Some(sub), serde_json::json!({})).await?;
594+ queue_event(&tx, board_id, &id, "assigned", actor, Some(sub.as_str()), None).await?;
610 }595 }
611 log(596 log(
612 &tx,597 &tx,
@@ -618,6 +603,7 @@ impl Store {
618 )603 )
619 .await?;604 .await?;
620 record_transition(&tx, &id, None, &column.id, actor).await?;605 record_transition(&tx, &id, None, &column.id, actor).await?;
606+ queue_event(&tx, board_id, &id, "created", actor, None, None).await?;
621 sync_reminders(&tx, &id).await?;607 sync_reminders(&tx, &id).await?;
622 live_task(&tx, board_id, &id).await608 live_task(&tx, board_id, &id).await
623 }609 }
@@ -693,6 +679,19 @@ impl Store {
693 }679 }
694 sync_reminders(&tx, task_id).await?;680 sync_reminders(&tx, task_id).await?;
695 }681 }
682+ if before.title != title {
683+ queue_event(&tx, board_id, task_id, "retitled", actor, None, None).await?;
684+ }
685+ let deadline_set = edit.deadline.is_some() && before.deadline != edit.deadline
686+ || edit.meeting_at.is_some() && before.meeting_at != edit.meeting_at;
687+ let deadline_cleared = before.deadline.is_some() && edit.deadline.is_none()
688+ || before.meeting_at.is_some() && edit.meeting_at.is_none();
689+ if deadline_set {
690+ queue_event(&tx, board_id, task_id, "deadline_set", actor, None, None).await?;
691+ }
692+ if deadline_cleared {
693+ queue_event(&tx, board_id, task_id, "deadline_cleared", actor, None, None).await?;
694+ }
696 live_task(&tx, board_id, task_id).await695 live_task(&tx, board_id, task_id).await
697 }696 }
698 .await;697 .await;
@@ -774,6 +773,7 @@ impl Store {
774 if task.done_at.is_some() != target.is_done {773 if task.done_at.is_some() != target.is_done {
775 sync_reminders(&tx, task_id).await?;774 sync_reminders(&tx, task_id).await?;
776 }775 }
776+ queue_event(&tx, board_id, task_id, "status", actor, None, Some(target.id.as_str())).await?;
777 Ok(MoveOutcome::Moved)777 Ok(MoveOutcome::Moved)
778 }778 }
779 .await;779 .await;
@@ -813,6 +813,7 @@ impl Store {
813 .map_err(db_err)?;813 .map_err(db_err)?;
814 log(&tx, id, actor, "task_deleted", None, serde_json::json!({})).await?;814 log(&tx, id, actor, "task_deleted", None, serde_json::json!({})).await?;
815 }815 }
816+ queue_event(&tx, board_id, task_id, "deleted", actor, None, None).await?;
816 let doomed_set: HashSet<&str> = doomed.iter().map(String::as_str).collect();817 let doomed_set: HashSet<&str> = doomed.iter().map(String::as_str).collect();
817 let mut edges: Vec<(String, String)> = Vec::new();818 let mut edges: Vec<(String, String)> = Vec::new();
818 for id in &doomed {819 for id in &doomed {
@@ -851,6 +852,7 @@ impl Store {
851 serde_json::json!({ "blocker": blocking }),852 serde_json::json!({ "blocker": blocking }),
852 )853 )
853 .await?;854 .await?;
855+ queue_event(&tx, board_id, &blocked, "unblocked", actor, None, None).await?;
854 freed.push(blocked);856 freed.push(blocked);
855 }857 }
856 }858 }
@@ -893,6 +895,7 @@ impl Store {
893 .map_err(db_err)?;895 .map_err(db_err)?;
894 if added > 0 {896 if added > 0 {
895 log(&tx, task_id, actor, "assigned", Some(sub), serde_json::json!({})).await?;897 log(&tx, task_id, actor, "assigned", Some(sub), serde_json::json!({})).await?;
898+ queue_event(&tx, board_id, task_id, "assigned", actor, Some(sub.as_str()), None).await?;
896 }899 }
897 }900 }
898 sync_reminders(&tx, task_id).await901 sync_reminders(&tx, task_id).await
@@ -923,6 +926,16 @@ impl Store {
923 .await926 .await
924 .map_err(db_err)?;927 .map_err(db_err)?;
925 if removed > 0 {928 if removed > 0 {
929+ queue_event(
930+ &tx,
931+ board_id,
932+ task_id,
933+ "unassigned",
934+ actor,
935+ Some(sub.as_str()),
936+ None,
937+ )
938+ .await?;
926 log(939 log(
927 &tx,940 &tx,
928 task_id,941 task_id,
@@ -1041,6 +1054,7 @@ impl Store {
1041 if would_cycle(&refs, (blocked_id, blocking_id)) {1054 if would_cycle(&refs, (blocked_id, blocking_id)) {
1042 return Err(Error::Conflict("this link would make a dependency cycle".into()));1055 return Err(Error::Conflict("this link would make a dependency cycle".into()));
1043 }1056 }
1057+ queue_event(&tx, board_id, blocked_id, "linked", actor, None, None).await?;
1044 let now = now_stamp();1058 let now = now_stamp();
1045 if existing.is_some() {1059 if existing.is_some() {
1046 tx.execute(1060 tx.execute(
@@ -1095,6 +1109,7 @@ impl Store {
1095 if changed == 0 {1109 if changed == 0 {
1096 return Err(Error::NotFound);1110 return Err(Error::NotFound);
1097 }1111 }
1112+ queue_event(&tx, board_id, blocked_id, "unlinked", actor, None, None).await?;
1098 log(1113 log(
1099 &tx,1114 &tx,
1100 blocked_id,1115 blocked_id,
crates/iz-web/Cargo.tomlmodified+1 -0
@@ -34,6 +34,7 @@ topcoat.workspace = true
34 tracing.workspace = true34 tracing.workspace = true
35 thiserror.workspace = true35 thiserror.workspace = true
36 tracing-subscriber = { workspace = true, features = ["env-filter"] }36 tracing-subscriber = { workspace = true, features = ["env-filter"] }
37+lettre.workspace = true
37 38
38 [dev-dependencies]39 [dev-dependencies]
39 # Makes Ed25519 keys for the token tests. Never used by the server.40 # Makes Ed25519 keys for the token tests. Never used by the server.
crates/iz-web/src/auth.rsmodified+10 -1
@@ -44,6 +44,8 @@ pub enum Need {
44 Viewer,44 Viewer,
45 /// Creating and changing tasks, comments and files.45 /// Creating and changing tasks, comments and files.
46 Member,46 Member,
47+ /// The administrator pages: sender, mail rules, logs and messages to members.
48+ Admin,
47 }49 }
48 50
49 /// A signed-in member and the session that carries them.51 /// A signed-in member and the session that carries them.
@@ -129,10 +131,17 @@ pub async fn require_role(cx: &Cx, need: Need) -> Result<CurrentMember> {
129 let action = match need {131 let action = match need {
130 Need::Viewer => Action::ReadBoard,132 Need::Viewer => Action::ReadBoard,
131 Need::Member => Action::WriteTask,133 Need::Member => Action::WriteTask,
134+ Need::Admin => Action::Administer,
132 };135 };
133 match authorize(&me.actor(), &action) {136 match authorize(&me.actor(), &action) {
134 Ok(()) => Ok(me),137 Ok(()) => Ok(me),
135- Err(Denied::Forbidden) if need == Need::Member => Err(forbidden().into()),138+ // An active member who is refused an admin page is told so (403). A disabled member is not,
139+ // so a disabled administrator sees the same 404 as anyone without access.
140+ Err(Denied::Forbidden)
141+ if need == Need::Member || (need == Need::Admin && !me.member.disabled) =>
142+ {
143+ Err(forbidden().into())
144+ }
136 Err(_) => Err(not_found().into()),145 Err(_) => Err(not_found().into()),
137 }146 }
138 }147 }
crates/iz-web/src/boot.rsmodified+1 -0
@@ -51,6 +51,7 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> {
51 let (stop_tx, stop_rx) = watch::channel(false);51 let (stop_tx, stop_rx) = watch::channel(false);
52 directory::spawn(state.clone(), stop_rx.clone());52 directory::spawn(state.clone(), stop_rx.clone());
53 attachments::spawn(state.clone(), stop_rx.clone());53 attachments::spawn(state.clone(), stop_rx.clone());
54+ crate::mail::spawn(state.clone(), stop_rx.clone());
54 tokio::spawn(async move {55 tokio::spawn(async move {
55 shutdown_signal().await;56 shutdown_signal().await;
56 tracing::info!("shutdown signal received");57 tracing::info!("shutdown signal received");
crates/iz-web/src/i18n/admin.rsadded+399 -0
@@ -0,0 +1,399 @@
1+//! Strings of the admin pages: settings (sender, reminders, message to members), mail rules and logs.
2+//! One variant per phrase; `t` matches `(key, lang)` exhaustively, so a missing Turkish text does not compile.
3+//! Sentences with values use `{}` placeholders filled by `fill`, never by concatenation in views.
4+
5+use super::Lang;
6+
7+/// One phrase of the admin pages.
8+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9+pub enum K {
10+ // Shared
11+ NavSettings,
12+ NavRules,
13+ NavLogs,
14+ Edit,
15+ Delete,
16+ Retry,
17+ Enabled,
18+ Apply,
19+ Older,
20+ NothingYet,
21+ // Sender
22+ SettingsTitle,
23+ SenderHeading,
24+ SenderHelp,
25+ FieldHost,
26+ FieldPort,
27+ FieldTls,
28+ TlsImplicit,
29+ TlsStartTls,
30+ TlsPlain,
31+ FieldUsername,
32+ FieldPassword,
33+ PasswordHint,
34+ PasswordSet,
35+ PasswordNotSet,
36+ FieldFromAddress,
37+ FieldFromName,
38+ FromNameHint,
39+ SaveSender,
40+ CheckConnection,
41+ SendTestMail,
42+ SenderNotConfigured,
43+ // Reminders
44+ RemindersHeading,
45+ ReminderLead,
46+ ReminderCap,
47+ SaveReminders,
48+ // Message to members
49+ MessageHeading,
50+ MessageHelp,
51+ MessageSubject,
52+ MessageBody,
53+ SendMessage,
54+ // Notices
55+ NoticeSenderSaved,
56+ NoticeCheckOk,
57+ NoticeTestSent,
58+ NoticeRemindersSaved,
59+ NoticeMessageQueued,
60+ NoticeRuleSaved,
61+ NoticeRuleDeleted,
62+ NoticeRuleSwitched,
63+ NoticeRetried,
64+ // Rules
65+ RulesTitle,
66+ RulesHelp,
67+ NoRules,
68+ RuleOn,
69+ RuleOff,
70+ NewRule,
71+ EditRule,
72+ FieldName,
73+ FieldTrigger,
74+ FieldColumn,
75+ AnyColumn,
76+ FieldProject,
77+ AnyProject,
78+ FieldAudience,
79+ FieldSubject,
80+ SubjectHint,
81+ IncludeDetails,
82+ SaveRule,
83+ CancelEdit,
84+ RuleSentence,
85+ TrigStatus,
86+ TrigStatusAny,
87+ TrigUnblocked,
88+ TrigCreated,
89+ TrigAssigned,
90+ TrigUnassigned,
91+ TrigCommented,
92+ TrigDeadlineSet,
93+ TrigDeadlineCleared,
94+ TrigRetitled,
95+ TrigLinked,
96+ TrigUnlinked,
97+ TrigDeleted,
98+ AudAssignees,
99+ AudBoard,
100+ AudCreator,
101+ AudWatchers,
102+ ProjectNote,
103+ // Logs
104+ LogsTitle,
105+ SectionOutbox,
106+ SectionDecisions,
107+ SectionActivity,
108+ ColRecipient,
109+ ColSubject,
110+ ColState,
111+ ColAttempts,
112+ ColLastError,
113+ ColWhen,
114+ ColRule,
115+ ColTask,
116+ ColOutcome,
117+ ColDetail,
118+ ColWho,
119+ ColWhat,
120+ StatePending,
121+ StateSent,
122+ StateFailed,
123+ StateAbandoned,
124+ OutOwed,
125+ OutAlreadyOwed,
126+ OutNoRecipients,
127+ OutNotMatched,
128+ OutDisabled,
129+ OutTaskGone,
130+ ReasonColumn,
131+ ReasonProject,
132+ FilterKind,
133+ // Errors
134+}
135+
136+/// The text of `key` in `lang`. Placeholders are `{}` and are filled by [`fill`].
137+pub fn t(lang: Lang, key: K) -> &'static str {
138+ use Lang::{En, Tr};
139+ match (key, lang) {
140+ (K::NavSettings, En) => "Settings",
141+ (K::NavSettings, Tr) => "Ayarlar",
142+ (K::NavRules, En) => "Mail rules",
143+ (K::NavRules, Tr) => "Mail kuralları",
144+ (K::NavLogs, En) => "Logs",
145+ (K::NavLogs, Tr) => "Kayıtlar",
146+ (K::Edit, En) => "Edit",
147+ (K::Edit, Tr) => "Düzenle",
148+ (K::Delete, En) => "Delete",
149+ (K::Delete, Tr) => "Sil",
150+ (K::Retry, En) => "Retry",
151+ (K::Retry, Tr) => "Yeniden dene",
152+ (K::Enabled, En) => "Enabled",
153+ (K::Enabled, Tr) => "Etkin",
154+ (K::Apply, En) => "Apply",
155+ (K::Apply, Tr) => "Uygula",
156+ (K::Older, En) => "Older",
157+ (K::Older, Tr) => "Daha eski",
158+ (K::NothingYet, En) => "Nothing here yet.",
159+ (K::NothingYet, Tr) => "Henüz burada bir şey yok.",
160+ (K::SettingsTitle, En) => "Settings",
161+ (K::SettingsTitle, Tr) => "Ayarlar",
162+ (K::SenderHeading, En) => "Outgoing mail",
163+ (K::SenderHeading, Tr) => "Giden e-posta",
164+ (K::SenderHelp, En) => {
165+ "The server that sends iz mail. The password is stored sealed and is never shown again."
166+ }
167+ (K::SenderHelp, Tr) => {
168+ "iz e-postalarını gönderen sunucu. Parola şifreli saklanır ve bir daha gösterilmez."
169+ }
170+ (K::FieldHost, En) => "Mail server",
171+ (K::FieldHost, Tr) => "Posta sunucusu",
172+ (K::FieldPort, En) => "Port",
173+ (K::FieldPort, Tr) => "Port",
174+ (K::FieldTls, En) => "Encryption",
175+ (K::FieldTls, Tr) => "Şifreleme",
176+ (K::TlsImplicit, En) => "Implicit TLS",
177+ (K::TlsImplicit, Tr) => "Baştan TLS (implicit)",
178+ (K::TlsStartTls, En) => "STARTTLS",
179+ (K::TlsStartTls, Tr) => "STARTTLS",
180+ (K::TlsPlain, En) => "None (localhost only)",
181+ (K::TlsPlain, Tr) => "Yok (yalnızca localhost)",
182+ (K::FieldUsername, En) => "User name",
183+ (K::FieldUsername, Tr) => "Kullanıcı adı",
184+ (K::FieldPassword, En) => "Password",
185+ (K::FieldPassword, Tr) => "Parola",
186+ (K::PasswordHint, En) => "Leave empty to keep the stored password.",
187+ (K::PasswordHint, Tr) => "Kayıtlı parolayı korumak için boş bırakın.",
188+ (K::PasswordSet, En) => "set",
189+ (K::PasswordSet, Tr) => "ayarlı",
190+ (K::PasswordNotSet, En) => "not set",
191+ (K::PasswordNotSet, Tr) => "ayarlı değil",
192+ (K::FieldFromAddress, En) => "From address",
193+ (K::FieldFromAddress, Tr) => "Gönderen adresi",
194+ (K::FieldFromName, En) => "From name",
195+ (K::FieldFromName, Tr) => "Gönderen adı",
196+ (K::FromNameHint, En) => "Empty means iz.",
197+ (K::FromNameHint, Tr) => "Boş bırakılırsa iz kullanılır.",
198+ (K::SaveSender, En) => "Save sender",
199+ (K::SaveSender, Tr) => "Göndereni kaydet",
200+ (K::CheckConnection, En) => "Check connection",
201+ (K::CheckConnection, Tr) => "Bağlantıyı denetle",
202+ (K::SendTestMail, En) => "Send test mail to me",
203+ (K::SendTestMail, Tr) => "Bana deneme e-postası gönder",
204+ (K::SenderNotConfigured, En) => "No sender is set up yet, so mail waits in the outbox.",
205+ (K::SenderNotConfigured, Tr) => {
206+ "Gönderen henüz ayarlanmadı; e-postalar giden kutusunda bekler."
207+ }
208+ (K::RemindersHeading, En) => "Meeting reminders",
209+ (K::RemindersHeading, Tr) => "Toplantı hatırlatmaları",
210+ (K::ReminderLead, En) => "Minutes before the meeting (0 turns reminders off)",
211+ (K::ReminderLead, Tr) => "Toplantıdan kaç dakika önce (0 hatırlatmayı kapatır)",
212+ (K::ReminderCap, En) => "Most reminder mails per member per hour",
213+ (K::ReminderCap, Tr) => "Üye başına saatte en çok hatırlatma e-postası",
214+ (K::SaveReminders, En) => "Save reminders",
215+ (K::SaveReminders, Tr) => "Hatırlatmaları kaydet",
216+ (K::MessageHeading, En) => "Message to members",
217+ (K::MessageHeading, Tr) => "Üyelere ileti",
218+ (K::MessageHelp, En) => {
219+ "Sent as mail to every active member except you. One message every 10 minutes."
220+ }
221+ (K::MessageHelp, Tr) => {
222+ "Siz hariç etkin her üyeye e-posta olarak gönderilir. 10 dakikada bir ileti gönderilebilir."
223+ }
224+ (K::MessageSubject, En) => "Subject",
225+ (K::MessageSubject, Tr) => "Konu",
226+ (K::MessageBody, En) => "Message",
227+ (K::MessageBody, Tr) => "İleti",
228+ (K::SendMessage, En) => "Send message",
229+ (K::SendMessage, Tr) => "İletiyi gönder",
230+ (K::NoticeSenderSaved, En) => "Sender saved.",
231+ (K::NoticeSenderSaved, Tr) => "Gönderen kaydedildi.",
232+ (K::NoticeCheckOk, En) => "The server accepted the connection.",
233+ (K::NoticeCheckOk, Tr) => "Sunucu bağlantıyı kabul etti.",
234+ (K::NoticeTestSent, En) => "Test mail sent to your address.",
235+ (K::NoticeTestSent, Tr) => "Deneme e-postası adresinize gönderildi.",
236+ (K::NoticeRemindersSaved, En) => "Reminder settings saved.",
237+ (K::NoticeRemindersSaved, Tr) => "Hatırlatma ayarları kaydedildi.",
238+ (K::NoticeMessageQueued, En) => "Message queued for {} members.",
239+ (K::NoticeMessageQueued, Tr) => "İleti {} üye için kuyruğa alındı.",
240+ (K::NoticeRuleSaved, En) => "Rule saved.",
241+ (K::NoticeRuleSaved, Tr) => "Kural kaydedildi.",
242+ (K::NoticeRuleDeleted, En) => "Rule deleted.",
243+ (K::NoticeRuleDeleted, Tr) => "Kural silindi.",
244+ (K::NoticeRuleSwitched, En) => "Rule switched.",
245+ (K::NoticeRuleSwitched, Tr) => "Kural değiştirildi.",
246+ (K::NoticeRetried, En) => "Queued again.",
247+ (K::NoticeRetried, Tr) => "Yeniden kuyruğa alındı.",
248+ (K::RulesTitle, En) => "Mail rules",
249+ (K::RulesTitle, Tr) => "Mail kuralları",
250+ (K::RulesHelp, En) => "A rule mails people when something happens on the board.",
251+ (K::RulesHelp, Tr) => "Kural, panoda bir şey olduğunda kişilere e-posta gönderir.",
252+ (K::NoRules, En) => "No rules yet.",
253+ (K::NoRules, Tr) => "Henüz kural yok.",
254+ (K::RuleOn, En) => "On",
255+ (K::RuleOn, Tr) => "Açık",
256+ (K::RuleOff, En) => "Off",
257+ (K::RuleOff, Tr) => "Kapalı",
258+ (K::NewRule, En) => "New rule",
259+ (K::NewRule, Tr) => "Yeni kural",
260+ (K::EditRule, En) => "Edit rule",
261+ (K::EditRule, Tr) => "Kuralı düzenle",
262+ (K::FieldName, En) => "Name",
263+ (K::FieldName, Tr) => "Ad",
264+ (K::FieldTrigger, En) => "When",
265+ (K::FieldTrigger, Tr) => "Ne zaman",
266+ (K::FieldColumn, En) => "Column (for the moves-to trigger)",
267+ (K::FieldColumn, Tr) => "Sütun (taşınma tetikleyicisi için)",
268+ (K::AnyColumn, En) => "Any column",
269+ (K::AnyColumn, Tr) => "Herhangi bir sütun",
270+ (K::FieldProject, En) => "Project",
271+ (K::FieldProject, Tr) => "Proje",
272+ (K::AnyProject, En) => "Any project",
273+ (K::AnyProject, Tr) => "Herhangi bir proje",
274+ (K::FieldAudience, En) => "Who gets the mail",
275+ (K::FieldAudience, Tr) => "E-postayı kim alır",
276+ (K::FieldSubject, En) => "Subject",
277+ (K::FieldSubject, Tr) => "Konu",
278+ (K::SubjectHint, En) => "Placeholders: {key} {title} {column} {actor} {tag} {deadline}",
279+ (K::SubjectHint, Tr) => "Yer tutucular: {key} {title} {column} {actor} {tag} {deadline}",
280+ (K::IncludeDetails, En) => {
281+ "Include the details (column, deadline, assignees, meeting time)"
282+ }
283+ (K::IncludeDetails, Tr) => "Ayrıntıları ekle (sütun, son tarih, atananlar, toplantı saati)",
284+ (K::SaveRule, En) => "Save rule",
285+ (K::SaveRule, Tr) => "Kuralı kaydet",
286+ (K::CancelEdit, En) => "Cancel",
287+ (K::CancelEdit, Tr) => "Vazgeç",
288+ (K::RuleSentence, En) => "When a task {}, mail {}. Subject: “{}”.",
289+ (K::RuleSentence, Tr) => "Bir kart {}, {} e-posta alır. Konu: “{}”.",
290+ (K::TrigStatus, En) => "moves to {}",
291+ (K::TrigStatus, Tr) => "{} sütununa taşınırsa",
292+ (K::TrigStatusAny, En) => "moves to any column",
293+ (K::TrigStatusAny, Tr) => "herhangi bir sütuna taşınırsa",
294+ (K::TrigUnblocked, En) => "stops being blocked",
295+ (K::TrigUnblocked, Tr) => "engelli olmaktan çıkarsa",
296+ (K::TrigCreated, En) => "is created",
297+ (K::TrigCreated, Tr) => "oluşturulursa",
298+ (K::TrigAssigned, En) => "is assigned to someone",
299+ (K::TrigAssigned, Tr) => "birine atanırsa",
300+ (K::TrigUnassigned, En) => "loses an assignee",
301+ (K::TrigUnassigned, Tr) => "bir atanan çıkarılırsa",
302+ (K::TrigCommented, En) => "gets a comment",
303+ (K::TrigCommented, Tr) => "yorum alırsa",
304+ (K::TrigDeadlineSet, En) => "gets a deadline or meeting time",
305+ (K::TrigDeadlineSet, Tr) => "son tarih veya toplantı saati alırsa",
306+ (K::TrigDeadlineCleared, En) => "loses its deadline or meeting time",
307+ (K::TrigDeadlineCleared, Tr) => "son tarihi veya toplantı saati kalkarsa",
308+ (K::TrigRetitled, En) => "is renamed",
309+ (K::TrigRetitled, Tr) => "başlığı değişirse",
310+ (K::TrigLinked, En) => "gets a dependency",
311+ (K::TrigLinked, Tr) => "bir bağımlılık alırsa",
312+ (K::TrigUnlinked, En) => "loses a dependency",
313+ (K::TrigUnlinked, Tr) => "bir bağımlılığı kalkarsa",
314+ (K::TrigDeleted, En) => "is deleted",
315+ (K::TrigDeleted, Tr) => "silinirse",
316+ (K::AudAssignees, En) => "the assignees",
317+ (K::AudAssignees, Tr) => "atanan kişiler",
318+ (K::AudBoard, En) => "every member",
319+ (K::AudBoard, Tr) => "tüm üyeler",
320+ (K::AudCreator, En) => "the creator",
321+ (K::AudCreator, Tr) => "kartı oluşturan",
322+ (K::AudWatchers, En) => "the watchers",
323+ (K::AudWatchers, Tr) => "izleyenler",
324+ (K::ProjectNote, En) => "(project {})",
325+ (K::ProjectNote, Tr) => "({} projesi)",
326+ (K::LogsTitle, En) => "Logs",
327+ (K::LogsTitle, Tr) => "Kayıtlar",
328+ (K::SectionOutbox, En) => "Outbox",
329+ (K::SectionOutbox, Tr) => "Giden kutusu",
330+ (K::SectionDecisions, En) => "Rule decisions",
331+ (K::SectionDecisions, Tr) => "Kural kararları",
332+ (K::SectionActivity, En) => "Activity",
333+ (K::SectionActivity, Tr) => "Etkinlik",
334+ (K::ColRecipient, En) => "Recipient",
335+ (K::ColRecipient, Tr) => "Alıcı",
336+ (K::ColSubject, En) => "Subject",
337+ (K::ColSubject, Tr) => "Konu",
338+ (K::ColState, En) => "State",
339+ (K::ColState, Tr) => "Durum",
340+ (K::ColAttempts, En) => "Attempts",
341+ (K::ColAttempts, Tr) => "Deneme",
342+ (K::ColLastError, En) => "Last error",
343+ (K::ColLastError, Tr) => "Son hata",
344+ (K::ColWhen, En) => "When",
345+ (K::ColWhen, Tr) => "Zaman",
346+ (K::ColRule, En) => "Rule",
347+ (K::ColRule, Tr) => "Kural",
348+ (K::ColTask, En) => "Task",
349+ (K::ColTask, Tr) => "Kart",
350+ (K::ColOutcome, En) => "Outcome",
351+ (K::ColOutcome, Tr) => "Sonuç",
352+ (K::ColDetail, En) => "Detail",
353+ (K::ColDetail, Tr) => "Ayrıntı",
354+ (K::ColWho, En) => "Who",
355+ (K::ColWho, Tr) => "Kim",
356+ (K::ColWhat, En) => "What",
357+ (K::ColWhat, Tr) => "Ne",
358+ (K::StatePending, En) => "pending",
359+ (K::StatePending, Tr) => "bekliyor",
360+ (K::StateSent, En) => "sent",
361+ (K::StateSent, Tr) => "gönderildi",
362+ (K::StateFailed, En) => "failed, will retry",
363+ (K::StateFailed, Tr) => "başarısız, yeniden denenecek",
364+ (K::StateAbandoned, En) => "abandoned",
365+ (K::StateAbandoned, Tr) => "vazgeçildi",
366+ (K::OutOwed, En) => "owed",
367+ (K::OutOwed, Tr) => "gönderilecek",
368+ (K::OutAlreadyOwed, En) => "already owed",
369+ (K::OutAlreadyOwed, Tr) => "zaten kuyrukta",
370+ (K::OutNoRecipients, En) => "no recipients",
371+ (K::OutNoRecipients, Tr) => "alıcı yok",
372+ (K::OutNotMatched, En) => "not matched",
373+ (K::OutNotMatched, Tr) => "eşleşmedi",
374+ (K::OutDisabled, En) => "rule off",
375+ (K::OutDisabled, Tr) => "kural kapalı",
376+ (K::OutTaskGone, En) => "task gone",
377+ (K::OutTaskGone, Tr) => "kart yok",
378+ (K::ReasonColumn, En) => "another column",
379+ (K::ReasonColumn, Tr) => "başka sütun",
380+ (K::ReasonProject, En) => "another project",
381+ (K::ReasonProject, Tr) => "başka proje",
382+ (K::FilterKind, En) => "Kind",
383+ (K::FilterKind, Tr) => "Tür",
384+ }
385+}
386+
387+/// Fills the `{}` placeholders of `template` in order. Extra placeholders stay empty.
388+pub fn fill(template: &str, values: &[&str]) -> String {
389+ let mut out = String::with_capacity(template.len() + 16);
390+ let mut rest = template;
391+ let mut values = values.iter();
392+ while let Some(at) = rest.find("{}") {
393+ out.push_str(&rest[..at]);
394+ out.push_str(values.next().copied().unwrap_or(""));
395+ rest = &rest[at + 2..];
396+ }
397+ out.push_str(rest);
398+ out
399+}
crates/iz-web/src/i18n/mod.rsmodified+1 -0
@@ -7,6 +7,7 @@
7 //! This module decides the language. It does not format sentences with values; those get small7 //! This module decides the language. It does not format sentences with values; those get small
8 //! helper functions next to their keys.8 //! helper functions next to their keys.
9 9
10+pub mod admin;
10 pub mod board;11 pub mod board;
11 pub mod shell;12 pub mod shell;
12 pub mod task;13 pub mod task;
crates/iz-web/src/mail/compose.rsadded+210 -0
@@ -0,0 +1,210 @@
1+//! Builds the message of one outbox row with lettre's typed builders. It is the only place a mail
2+//! header is written, and it never takes a header from text: every name and the subject go through
3+//! `clean_text` first, so a CR or LF in a member's name or an actor's name cannot start a header line.
4+//!
5+//! The body is plain text, and an HTML alternative is made from it here with every character escaped.
6+//! It is not a rendering of a page, so it never contains a link or script the text did not have.
7+
8+use iz_core::rules::clean_text;
9+use iz_core::sender::Sender;
10+use lettre::Address;
11+use lettre::message::{Mailbox, Message, MultiPart};
12+
13+/// Longest subject sent, in characters. Reason: the same cap as the subject field of a rule.
14+pub const SUBJECT_MAX: usize = iz_core::limits::MAIL_SUBJECT_MAX;
15+/// Longest display name of a mailbox, in characters. Reason: a name is a label, not a sentence.
16+const NAME_MAX: usize = 100;
17+/// Message-ID domain used when the base URL has no usable host. Reason: a fixed, valid fallback.
18+const FALLBACK_DOMAIN: &str = "localhost";
19+
20+/// What the builder needs besides the row: the sender's configuration and the recipient.
21+pub struct Outgoing<'a> {
22+ /// The checked sender configuration (host, port, and the From address and name).
23+ pub sender: &'a Sender,
24+ /// The recipient's display name.
25+ pub to_name: &'a str,
26+ /// The recipient's address, as the directory has it.
27+ pub to_address: &'a str,
28+ /// The subject, plain text.
29+ pub subject: &'a str,
30+ /// The body, plain text.
31+ pub body: &'a str,
32+ /// The outbox row id. It makes the Message-ID unique.
33+ pub row_id: &'a str,
34+ /// The domain part of the Message-ID, taken from the base URL.
35+ pub domain: &'a str,
36+}
37+
38+/// Builds the message. `Err` holds the reason as text; the caller stores it as the last error.
39+pub fn build(m: &Outgoing<'_>) -> Result<Message, String> {
40+ let from_name = bounded(&m.sender.from_name, NAME_MAX);
41+ let from_address: Address = m
42+ .sender
43+ .from_address
44+ .parse()
45+ .map_err(|_| "the sender address is not valid".to_owned())?;
46+ let to_address: Address = m
47+ .to_address
48+ .parse()
49+ .map_err(|_| "the recipient address is not valid".to_owned())?;
50+ let from = Mailbox::new(non_empty(from_name), from_address);
51+ let to = Mailbox::new(non_empty(bounded(m.to_name, NAME_MAX)), to_address);
52+ let subject = bounded(m.subject, SUBJECT_MAX);
53+ let body = clean_body(m.body);
54+ let html = html_alternative(&body);
55+ Message::builder()
56+ .from(from)
57+ .to(to)
58+ .subject(subject)
59+ .message_id(Some(format!("<{}@{}>", m.row_id, safe_domain(m.domain))))
60+ .date_now()
61+ .multipart(MultiPart::alternative_plain_html(body, html))
62+ .map_err(|e| format!("cannot build the message: {e}"))
63+}
64+
65+/// The text with control and invisible formatting characters removed, cut to `max` characters.
66+fn bounded(text: &str, max: usize) -> String {
67+ clean_text(text).trim().chars().take(max).collect()
68+}
69+
70+/// `None` for an empty name, so the mailbox has only the address.
71+fn non_empty(name: String) -> Option<String> {
72+ (!name.is_empty()).then_some(name)
73+}
74+
75+/// The body with CRLF and CR turned into LF, and control characters other than tab and LF removed.
76+fn clean_body(body: &str) -> String {
77+ let normalized = body.replace("\r\n", "\n").replace('\r', "\n");
78+ normalized
79+ .chars()
80+ .filter(|c| *c == '\n' || *c == '\t' || !c.is_control())
81+ .collect()
82+}
83+
84+/// The HTML alternative: each line is one paragraph, every character escaped. Nothing else is emitted.
85+fn html_alternative(text: &str) -> String {
86+ let mut out = String::from("<!DOCTYPE html>\n<html><body>\n");
87+ for line in text.split('\n') {
88+ if line.is_empty() {
89+ out.push_str("<br>\n");
90+ } else {
91+ out.push_str("<p>");
92+ out.push_str(&escape(line));
93+ out.push_str("</p>\n");
94+ }
95+ }
96+ out.push_str("</body></html>\n");
97+ out
98+}
99+
100+/// Escapes the five characters that are special in HTML text and attribute values.
101+pub fn escape(text: &str) -> String {
102+ let mut out = String::with_capacity(text.len());
103+ for c in text.chars() {
104+ match c {
105+ '&' => out.push_str("&amp;"),
106+ '<' => out.push_str("&lt;"),
107+ '>' => out.push_str("&gt;"),
108+ '"' => out.push_str("&quot;"),
109+ '\'' => out.push_str("&#39;"),
110+ other => out.push(other),
111+ }
112+ }
113+ out
114+}
115+
116+/// The host of a base URL, reduced to letters, digits, dots and dashes. The fallback when it is empty.
117+pub fn domain_of(base_url: &str) -> String {
118+ let host = reqwest::Url::parse(base_url)
119+ .ok()
120+ .and_then(|url| url.host_str().map(str::to_owned))
121+ .unwrap_or_default();
122+ safe_domain(&host).to_owned()
123+}
124+
125+/// `domain` if it is made of letters, digits, dots and dashes; the fallback otherwise.
126+fn safe_domain(domain: &str) -> &str {
127+ let usable = !domain.is_empty()
128+ && domain.len() <= 253
129+ && domain
130+ .bytes()
131+ .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-');
132+ if usable { domain } else { FALLBACK_DOMAIN }
133+}
134+
135+#[cfg(test)]
136+mod tests {
137+ use super::*;
138+
139+ fn sender(from_name: &str) -> Sender {
140+ Sender {
141+ host: "mail.example.test".into(),
142+ port: 587,
143+ tls: iz_core::sender::TlsMode::StartTls,
144+ username: "u".into(),
145+ from_address: "iz@example.test".into(),
146+ from_name: from_name.into(),
147+ }
148+ }
149+
150+ /// A CRLF in the from name, the actor's name or the subject must not produce a header line.
151+ #[test]
152+ fn crlf_and_bcc_injection_makes_no_extra_header() {
153+ let evil = sender("Board\r\nBcc: spy@evil.test");
154+ let message = build(&Outgoing {
155+ sender: &evil,
156+ to_name: "Ada\r\nBcc: spy@evil.test",
157+ to_address: "ada@example.test",
158+ subject: "Task moved\r\nBcc: spy@evil.test\r\nX-Injected: 1",
159+ body: "Hello",
160+ row_id: "01HZ",
161+ domain: "iz.example.test",
162+ })
163+ .expect("builds");
164+ let text = String::from_utf8_lossy(&message.formatted()).into_owned();
165+ let headers = text.split("\r\n\r\n").next().unwrap_or_default();
166+ assert!(
167+ !headers.lines().any(|line| line.starts_with("Bcc:")),
168+ "{headers}"
169+ );
170+ assert!(
171+ !headers.lines().any(|line| line.starts_with("X-Injected:")),
172+ "{headers}"
173+ );
174+ }
175+
176+ #[test]
177+ fn subject_is_cleaned_and_cut_to_the_limit() {
178+ let long = format!("{}\r\n{}", "a".repeat(300), "b");
179+ let message = build(&Outgoing {
180+ sender: &sender("iz"),
181+ to_name: "",
182+ to_address: "ada@example.test",
183+ subject: &long,
184+ body: "x",
185+ row_id: "01HZ",
186+ domain: "iz.example.test",
187+ })
188+ .expect("builds");
189+ let text = String::from_utf8_lossy(&message.formatted()).into_owned();
190+ let subject_line = text
191+ .lines()
192+ .find(|line| line.starts_with("Subject:"))
193+ .expect("has a subject");
194+ assert!(subject_line.len() <= "Subject: ".len() + SUBJECT_MAX);
195+ }
196+
197+ #[test]
198+ fn html_alternative_escapes_every_value() {
199+ let html = html_alternative("<script>alert(1)</script> & \"q\"");
200+ assert!(!html.contains("<script>"));
201+ assert!(html.contains("&lt;script&gt;alert(1)&lt;/script&gt; &amp; &quot;q&quot;"));
202+ }
203+
204+ #[test]
205+ fn a_bad_domain_falls_back() {
206+ assert_eq!(domain_of("https://iz.example.test/x"), "iz.example.test");
207+ assert_eq!(domain_of("not a url"), FALLBACK_DOMAIN);
208+ assert_eq!(safe_domain("a b>c"), FALLBACK_DOMAIN);
209+ }
210+}
crates/iz-web/src/mail/mod.rsadded+245 -0
@@ -0,0 +1,245 @@
1+//! Outgoing mail: the SMTP transport built from the stored sender, the worker that runs the rules, the
2+//! reminders and the outbox, and the admin's connection check and test mail.
3+//!
4+//! The worker is one loop (`spawn`) that does three things in order on every tick: runs one rules pass
5+//! (events to decisions and outbox rows), queues the due reminders, then sends the claimed outbox rows.
6+//! A failed send is recorded on its row with the attempt count and the backoff; it never stops the loop.
7+//! Every message is built by `compose.rs` with lettre's typed builders. The transport uses a 20 second
8+//! timeout, and plaintext SMTP is allowed only to a loopback host (`iz_core::sender::TlsMode::Plain`).
9+
10+mod compose;
11+
12+use std::time::Duration;
13+
14+use iz_core::mail_text::{self, MailLang};
15+use iz_core::rules::clean_text;
16+use iz_core::secret;
17+use iz_core::sender::{Sender, TlsMode};
18+use iz_core::store::new_id;
19+use iz_core::store::outbox::HOLD_MINUTES;
20+use jiff::{SignedDuration, Timestamp};
21+use lettre::transport::smtp::authentication::Credentials;
22+use lettre::transport::smtp::client::Tls;
23+use lettre::{AsyncSmtpTransport, AsyncTransport, Tokio1Executor};
24+use tokio::sync::watch;
25+
26+use crate::state::AppState;
27+use compose::Outgoing;
28+
29+/// How long one SMTP operation may take. Reason: a stuck server must not hold the worker.
30+pub const SMTP_TIMEOUT: Duration = Duration::from_secs(20);
31+/// Time between two worker passes. Reason: mail is near-live without polling the database hard.
32+const TICK: Duration = Duration::from_secs(5);
33+/// Rules events handled per pass.
34+const RULES_BATCH: usize = 100;
35+/// Reminders queued per pass.
36+const REMINDER_BATCH: usize = 100;
37+/// Outbox rows claimed per pass.
38+const DELIVER_BATCH: usize = 20;
39+/// Longest error text kept on an outbox row, in characters. Reason: keeps the logs page short.
40+const ERROR_MAX: usize = 300;
41+
42+/// A configured sender ready to send: the checked settings and the transport built from them.
43+pub struct Configured {
44+ /// The checked configuration (From address and name are read from here).
45+ pub sender: Sender,
46+ /// The SMTP transport.
47+ pub transport: AsyncSmtpTransport<Tokio1Executor>,
48+}
49+
50+/// Starts the worker. It stops when the shared stop flag is set.
51+pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {
52+ tokio::spawn(async move {
53+ loop {
54+ if let Err(error) = pass(&state).await {
55+ tracing::error!(error = %error, "mail pass failed");
56+ }
57+ tokio::select! {
58+ () = tokio::time::sleep(TICK) => {}
59+ _ = stop.wait_for(|stopped| *stopped) => break,
60+ }
61+ }
62+ tracing::info!("mail worker stopped");
63+ });
64+}
65+
66+/// One pass: rules, reminders, delivery. Each step commits on its own.
67+async fn pass(state: &AppState) -> iz_core::Result<()> {
68+ let now = Timestamp::now();
69+ let base = state.config.base_url.as_str();
70+ let report = state.store.run_rules(now, base, RULES_BATCH).await?;
71+ if report.events > 0 {
72+ tracing::debug!(
73+ events = report.events,
74+ mails = report.mails,
75+ "rules pass done"
76+ );
77+ }
78+ let cap = state.store.reminder_settings().await?.hourly_cap;
79+ state
80+ .store
81+ .run_reminders(now, base, cap, REMINDER_BATCH)
82+ .await?;
83+ deliver(state).await
84+}
85+
86+/// Sends the claimed outbox rows. Without a configured sender the rows wait a minute and are tried again.
87+async fn deliver(state: &AppState) -> iz_core::Result<()> {
88+ let rows = state
89+ .store
90+ .claim_due(Timestamp::now(), DELIVER_BATCH)
91+ .await?;
92+ if rows.is_empty() {
93+ return Ok(());
94+ }
95+ let Some(configured) = configured(state).await? else {
96+ for row in &rows {
97+ let until = after_minutes(Timestamp::now(), HOLD_MINUTES);
98+ state
99+ .store
100+ .defer(&row.id, until, "no sender is set up yet")
101+ .await?;
102+ }
103+ return Ok(());
104+ };
105+ let domain = compose::domain_of(&state.config.base_url);
106+ for row in rows {
107+ let outgoing = Outgoing {
108+ sender: &configured.sender,
109+ to_name: &row.recipient_name,
110+ to_address: &row.recipient_email,
111+ subject: &row.subject,
112+ body: &row.body,
113+ row_id: &row.id,
114+ domain: &domain,
115+ };
116+ let message = match compose::build(&outgoing) {
117+ Ok(message) => message,
118+ Err(reason) => {
119+ // A row that cannot be built will not build later either; it is not retried.
120+ state
121+ .store
122+ .mark_failed(&row.id, Timestamp::now(), &describe(&reason), true)
123+ .await?;
124+ continue;
125+ }
126+ };
127+ match configured.transport.send(message).await {
128+ Ok(_) => state.store.mark_sent(&row.id, Timestamp::now()).await?,
129+ Err(error) => {
130+ let permanent = error.is_permanent();
131+ state
132+ .store
133+ .mark_failed(
134+ &row.id,
135+ Timestamp::now(),
136+ &describe(&error.to_string()),
137+ permanent,
138+ )
139+ .await?;
140+ }
141+ }
142+ }
143+ Ok(())
144+}
145+
146+/// The configured sender with its transport, or `None` when no sender is saved. The password is opened
147+/// here, for the length of one pass, and is not kept.
148+pub async fn configured(state: &AppState) -> iz_core::Result<Option<Configured>> {
149+ let stored = state.store.load_sender().await?;
150+ let Some(sender) = stored.sender else {
151+ return Ok(None);
152+ };
153+ let password = match stored.sealed_password {
154+ Some(sealed) => {
155+ let bytes = secret::open(&state.key, &sealed)?;
156+ String::from_utf8(bytes)
157+ .map_err(|_| iz_core::Error::Crypto("the stored password is not text".into()))?
158+ }
159+ None => String::new(),
160+ };
161+ let transport = transport(&sender, &password).map_err(iz_core::Error::Invalid)?;
162+ Ok(Some(Configured { sender, transport }))
163+}
164+
165+/// Builds the SMTP transport. Implicit TLS and STARTTLS require the certificate chain to verify; plain
166+/// SMTP is used only for a loopback host and never upgrades. Credentials are sent only with a user name.
167+pub fn transport(
168+ sender: &Sender,
169+ password: &str,
170+) -> Result<AsyncSmtpTransport<Tokio1Executor>, String> {
171+ let builder = match sender.tls {
172+ TlsMode::Implicit => AsyncSmtpTransport::<Tokio1Executor>::relay(&sender.host)
173+ .map_err(|e| format!("cannot use the mail server: {e}"))?,
174+ TlsMode::StartTls => AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&sender.host)
175+ .map_err(|e| format!("cannot use the mail server: {e}"))?,
176+ TlsMode::Plain => {
177+ AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&sender.host).tls(Tls::None)
178+ }
179+ };
180+ let mut builder = builder.port(sender.port).timeout(Some(SMTP_TIMEOUT));
181+ if !sender.username.is_empty() {
182+ builder = builder.credentials(Credentials::new(
183+ sender.username.clone(),
184+ password.to_owned(),
185+ ));
186+ }
187+ Ok(builder.build())
188+}
189+
190+/// Asks the configured server to accept a connection (the "check connection" button). Sends nothing.
191+pub async fn check(state: &AppState) -> iz_core::Result<()> {
192+ let Some(configured) = configured(state).await? else {
193+ return Err(iz_core::Error::Invalid("no sender is set up yet".into()));
194+ };
195+ match configured.transport.test_connection().await {
196+ Ok(true) => Ok(()),
197+ Ok(false) => Err(iz_core::Error::Invalid(
198+ "the server did not accept the connection".into(),
199+ )),
200+ Err(error) => Err(iz_core::Error::Invalid(describe(&error.to_string()))),
201+ }
202+}
203+
204+/// Sends the test mail to one address (the "send test mail to me" button), in the sender's language.
205+pub async fn send_test(
206+ state: &AppState,
207+ to_name: &str,
208+ to_address: &str,
209+ lang: MailLang,
210+) -> iz_core::Result<()> {
211+ let Some(configured) = configured(state).await? else {
212+ return Err(iz_core::Error::Invalid("no sender is set up yet".into()));
213+ };
214+ let mail = mail_text::test_mail(lang);
215+ let domain = compose::domain_of(&state.config.base_url);
216+ let row_id = new_id();
217+ let message = compose::build(&Outgoing {
218+ sender: &configured.sender,
219+ to_name,
220+ to_address,
221+ subject: &mail.subject,
222+ body: &mail.body,
223+ row_id: &row_id,
224+ domain: &domain,
225+ })
226+ .map_err(iz_core::Error::Invalid)?;
227+ configured
228+ .transport
229+ .send(message)
230+ .await
231+ .map_err(|error| iz_core::Error::Invalid(describe(&error.to_string())))?;
232+ Ok(())
233+}
234+
235+/// The text of an error, cleaned and shortened for a row or an alert. Server text is shown, never the
236+/// password, which lettre does not echo.
237+fn describe(text: &str) -> String {
238+ clean_text(text).chars().take(ERROR_MAX).collect()
239+}
240+
241+/// `at` moved forward by `minutes`. Saturates at `at` on overflow, so a row is never due in the past.
242+fn after_minutes(at: Timestamp, minutes: i64) -> Timestamp {
243+ at.checked_add(SignedDuration::from_mins(minutes))
244+ .unwrap_or(at)
245+}
crates/iz-web/src/main.rsmodified+1 -0
@@ -15,6 +15,7 @@ mod directory;
15 mod health;15 mod health;
16 mod i18n;16 mod i18n;
17 mod live;17 mod live;
18+mod mail;
18 mod oidc;19 mod oidc;
19 mod pages;20 mod pages;
20 mod security;21 mod security;
crates/iz-web/src/pages/admin.rsadded+69 -0
@@ -0,0 +1,69 @@
1+//! Shared pieces of the administrator pages (`/settings`, `/rules`, `/logs`): the viewer for the topbar,
2+//! the translation of a store refusal into an alert, the notice codes of the redirects, and the
3+//! redirect itself. Each page file does its own gate, load and render.
4+//!
5+//! A refusal the admin can fix (a bad port, a duplicate name, a too-early message) is shown on the page
6+//! with the form's values and status `422`. Anything else goes to the framework's error page.
7+
8+use serde::Deserialize;
9+use topcoat::Result;
10+use topcoat::router::error::see_other;
11+use topcoat::router::response::Response;
12+
13+use crate::auth::CurrentMember;
14+use crate::i18n::Lang;
15+use crate::i18n::admin::{K, fill, t};
16+use crate::pages::task::core_err;
17+use crate::views::ViewerInfo;
18+
19+/// The status of a page re-rendered with a refusal.
20+pub const REFUSED: topcoat::router::StatusCode = topcoat::router::StatusCode::UNPROCESSABLE_ENTITY;
21+
22+/// The topbar's view of the signed-in admin.
23+pub fn viewer_of(me: &CurrentMember) -> ViewerInfo {
24+ ViewerInfo {
25+ name: me.member.name.clone(),
26+ is_admin: true,
27+ csrf: me.session.csrf_token.clone(),
28+ }
29+}
30+
31+/// The text of a refusal the admin can act on: the store's own message for `Invalid` and `Conflict`.
32+/// Anything else is the framework's error page.
33+pub fn user_text(error: iz_core::Error) -> Result<String> {
34+ match error {
35+ iz_core::Error::Invalid(text) | iz_core::Error::Conflict(text) => Ok(text),
36+ other => Err(core_err(other)),
37+ }
38+}
39+
40+/// The translated confirmation for a notice code from a redirect's query. `queued` is the number of
41+/// messages for `message`. Unknown codes give `None`, so a made-up query shows nothing.
42+pub fn notice_text(lang: Lang, code: &str, queued: Option<&str>) -> Option<String> {
43+ let text = match code {
44+ "sender" => t(lang, K::NoticeSenderSaved).to_owned(),
45+ "checked" => t(lang, K::NoticeCheckOk).to_owned(),
46+ "test" => t(lang, K::NoticeTestSent).to_owned(),
47+ "reminders" => t(lang, K::NoticeRemindersSaved).to_owned(),
48+ "message" => fill(t(lang, K::NoticeMessageQueued), &[queued.unwrap_or("0")]),
49+ "rule" => t(lang, K::NoticeRuleSaved).to_owned(),
50+ "rule_deleted" => t(lang, K::NoticeRuleDeleted).to_owned(),
51+ "rule_switched" => t(lang, K::NoticeRuleSwitched).to_owned(),
52+ "retried" => t(lang, K::NoticeRetried).to_owned(),
53+ _ => return None,
54+ };
55+ Some(text)
56+}
57+
58+/// A redirect (Post/Redirect/Get) to `path`. Returned as the handler's error, like the other pages.
59+pub fn back(path: &str) -> Result<Response> {
60+ Err(see_other(path).into())
61+}
62+
63+/// A form that carries only the CSRF token: the enable switch, delete, retry and the check buttons.
64+#[derive(Debug, Default, Deserialize)]
65+#[serde(default)]
66+pub struct CsrfForm {
67+ /// The session's CSRF token.
68+ pub csrf: String,
69+}
crates/iz-web/src/pages/logs.rsadded+169 -0
@@ -0,0 +1,169 @@
1+//! The logs page (`/logs`): the mail outbox with each row's state, attempts and last error, the rule
2+//! decisions, and the board's activity with filters and keyset paging. Administrators only.
3+//!
4+//! The outbox has a retry button for a row that failed or was abandoned. The retry checks the CSRF token
5+//! first and only moves that row back to pending; it does not send anything itself.
6+
7+use std::collections::HashMap;
8+
9+use iz_core::store::activity::ActivityFilter;
10+use iz_core::store::outbox::{PAGE_DEFAULT, parse_cursor};
11+use jiff::Timestamp;
12+use topcoat::Result;
13+use topcoat::context::{Cx, app_context};
14+use topcoat::router::content::Form;
15+use topcoat::router::response::Response;
16+use topcoat::router::{path_param_segment, route};
17+use topcoat::view::view;
18+
19+use crate::auth::{Need, percent_encode, query_param, require_csrf, require_role};
20+use crate::i18n::admin::{K, t};
21+use crate::i18n::{Lang, lang};
22+use crate::pages::admin::{CsrfForm, back, notice_text, viewer_of};
23+use crate::pages::board::the_board;
24+use crate::pages::task::core_err;
25+use crate::state::AppState;
26+use crate::views::admin::{ActivityRow, LogSection, LogsView, logs_content};
27+use crate::views::{ViewerInfo, respond, shell};
28+
29+/// Longest kind filter kept, in characters. Reason: an event kind is a short word.
30+const KIND_MAX: usize = 40;
31+
32+/// The section named by `?section=`. Anything else is the outbox.
33+fn section_of(text: Option<&str>) -> LogSection {
34+ match text {
35+ Some("decisions") => LogSection::Decisions,
36+ Some("activity") => LogSection::Activity,
37+ _ => LogSection::Outbox,
38+ }
39+}
40+
41+/// Renders the logs page for the signed-in admin.
42+async fn render(
43+ cx: &Cx,
44+ viewer: &ViewerInfo,
45+ csrf: &str,
46+ language: Lang,
47+ page: &LogsView,
48+) -> Result<Response> {
49+ let document = view! {
50+ cx =>
51+ shell(title: t(language, K::LogsTitle), lang: language,
52+ viewer: Some(viewer), page_script: None,
53+ logs_content(page: page, csrf: csrf, lang: language)
54+ )
55+ };
56+ respond(cx, document).await
57+}
58+
59+/// `GET /logs?section=outbox|decisions|activity&cursor=&kind=`.
60+#[route(GET "/logs")]
61+async fn logs_page(cx: &Cx) -> Result<Response> {
62+ let state = app_context::<AppState>(cx);
63+ let me = require_role(cx, Need::Admin).await?;
64+ let language = lang(cx, me.member.locale_override.as_deref());
65+ let section = section_of(query_param(cx, "section").as_deref());
66+ let cursor = query_param(cx, "cursor").filter(|c| !c.is_empty());
67+ // A malformed cursor is the first page, not an error: the page never shows another board's rows.
68+ let cursor = cursor.filter(|c| parse_cursor(Some(c.as_str())).is_ok());
69+ let kind: String = query_param(cx, "kind")
70+ .unwrap_or_default()
71+ .trim()
72+ .chars()
73+ .take(KIND_MAX)
74+ .collect();
75+ let notice = query_param(cx, "notice").and_then(|code| notice_text(language, &code, None));
76+ let board = the_board(&state.store).await?;
77+
78+ let mut page = LogsView {
79+ section,
80+ outbox: Vec::new(),
81+ decisions: Vec::new(),
82+ activity: Vec::new(),
83+ kind: kind.clone(),
84+ next: None,
85+ notice,
86+ };
87+ match section {
88+ LogSection::Outbox => {
89+ let rows = state
90+ .store
91+ .outbox_page(cursor.as_deref(), PAGE_DEFAULT)
92+ .await
93+ .map_err(core_err)?;
94+ page.outbox = rows.items;
95+ page.next = rows
96+ .next_cursor
97+ .map(|c| format!("/logs?section=outbox&cursor={}", percent_encode(&c)));
98+ }
99+ LogSection::Decisions => {
100+ let rows = state
101+ .store
102+ .decisions_page(cursor.as_deref(), PAGE_DEFAULT)
103+ .await
104+ .map_err(core_err)?;
105+ page.decisions = rows.items;
106+ page.next = rows
107+ .next_cursor
108+ .map(|c| format!("/logs?section=decisions&cursor={}", percent_encode(&c)));
109+ }
110+ LogSection::Activity => {
111+ let filter = ActivityFilter {
112+ kind: (!kind.is_empty()).then(|| kind.clone()),
113+ actor: None,
114+ };
115+ let rows = state
116+ .store
117+ .list_recent(&board.id, &filter, cursor.as_deref(), PAGE_DEFAULT)
118+ .await
119+ .map_err(core_err)?;
120+ let names: HashMap<String, String> = state
121+ .store
122+ .list_members()
123+ .await?
124+ .into_iter()
125+ .map(|m| (m.sub, m.name))
126+ .collect();
127+ page.activity = rows
128+ .items
129+ .into_iter()
130+ .map(|row| ActivityRow {
131+ at: row.at,
132+ who: row
133+ .actor
134+ .as_deref()
135+ .and_then(|sub| names.get(sub))
136+ .cloned()
137+ .unwrap_or_default(),
138+ kind: row.kind,
139+ detail: row.detail,
140+ })
141+ .collect();
142+ page.next = rows.next_cursor.map(|c| {
143+ format!(
144+ "/logs?section=activity&kind={}&cursor={}",
145+ percent_encode(&kind),
146+ percent_encode(&c)
147+ )
148+ });
149+ }
150+ }
151+ let viewer = viewer_of(&me);
152+ let csrf = me.session.csrf_token.clone();
153+ render(cx, &viewer, &csrf, language, &page).await
154+}
155+
156+/// `POST /logs/outbox/{id}/retry`: moves a failed or abandoned row back to pending.
157+#[route(POST "/logs/outbox/{id}/retry")]
158+async fn retry_row(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> {
159+ let state = app_context::<AppState>(cx);
160+ let form = form.map(|Form(form)| form).unwrap_or_default();
161+ let row_id = path_param_segment(cx, "id").to_owned();
162+ require_csrf(cx, Need::Admin, &form.csrf).await?;
163+ state
164+ .store
165+ .retry_row(&row_id, Timestamp::now())
166+ .await
167+ .map_err(core_err)?;
168+ back("/logs?section=outbox&notice=retried")
169+}
crates/iz-web/src/pages/mod.rsmodified+4 -0
@@ -1,10 +1,14 @@
1 //! The pages and the page-level layers. One file per page.1 //! The pages and the page-level layers. One file per page.
2 2
3+pub mod admin;
3 pub mod backchannel;4 pub mod backchannel;
4 pub mod board;5 pub mod board;
5 pub mod files;6 pub mod files;
7+pub mod logs;
6 pub mod not_found;8 pub mod not_found;
7 pub mod photo;9 pub mod photo;
10+pub mod rules;
11+pub mod settings;
8 pub mod sign_in;12 pub mod sign_in;
9 pub mod task;13 pub mod task;
10 pub mod tasks;14 pub mod tasks;
crates/iz-web/src/pages/rules.rsadded+332 -0
@@ -0,0 +1,332 @@
1+//! The mail rules page (`/rules`): the list with each rule in one sentence, the form to create or edit a
2+//! rule, the enable switch and delete. Administrators only. Every write checks the CSRF token first
3+//! (`auth::require_csrf`). The rule's rules (the trigger words, the column for the status trigger, the
4+//! projects of the board, the subject length) are the store's; a refusal re-renders the form with the
5+//! typed values and status `422`.
6+//!
7+//! A rule's sentence is built from its stored fields and the board's current names, so a renamed column
8+//! reads right without changing the rule.
9+
10+use iz_core::rules::Audience;
11+use iz_core::rules::TRIGGERS;
12+use iz_core::store::board::{Column, Tag};
13+use iz_core::store::rules::{MailRule, RuleInput};
14+use serde::Deserialize;
15+use topcoat::Result;
16+use topcoat::context::{Cx, app_context};
17+use topcoat::router::content::Form;
18+use topcoat::router::response::Response;
19+use topcoat::router::{StatusCode, path_param_segment, route};
20+use topcoat::view::view;
21+
22+use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role};
23+use crate::i18n::admin::{K, fill, t};
24+use crate::i18n::{Lang, lang};
25+use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewer_of};
26+use crate::pages::board::the_board;
27+use crate::pages::task::core_err;
28+use crate::state::AppState;
29+use crate::views::admin::{
30+ RuleFormView, RuleRow, RulesView, audience_label, rules_content, trigger_label,
31+};
32+use crate::views::{ViewerInfo, respond, shell};
33+
34+/// The subject a new rule starts with. Data, not text the reader sees.
35+const DEFAULT_SUBJECT: &str = "{key} {title}";
36+
37+/// The rule form as posted. Checkboxes are sent as `on` or not at all.
38+#[derive(Debug, Default, Deserialize)]
39+#[serde(default)]
40+struct RuleSubmit {
41+ csrf: String,
42+ name: String,
43+ trigger: String,
44+ column: String,
45+ tag: String,
46+ audience: String,
47+ subject: String,
48+ include_details: String,
49+ enabled: String,
50+}
51+
52+/// The enable switch as posted: `1` turns the rule on, anything else turns it off.
53+#[derive(Debug, Default, Deserialize)]
54+#[serde(default)]
55+struct EnabledSubmit {
56+ csrf: String,
57+ enabled: String,
58+}
59+
60+/// An empty optional id, as the store's `None`.
61+fn optional(text: &str) -> Option<String> {
62+ let text = text.trim();
63+ (!text.is_empty()).then(|| text.to_owned())
64+}
65+
66+/// The store's input for a submitted form.
67+fn input_of(form: &RuleSubmit) -> RuleInput {
68+ RuleInput {
69+ name: form.name.clone(),
70+ trigger: form.trigger.clone(),
71+ column_id: optional(&form.column),
72+ tag_id: optional(&form.tag),
73+ audience: form.audience.clone(),
74+ include_details: form.include_details == "on",
75+ enabled: form.enabled == "on",
76+ subject_template: form.subject.clone(),
77+ }
78+}
79+
80+/// The form as the page shows it, from a submitted form.
81+fn form_of(form: &RuleSubmit) -> RuleFormView {
82+ RuleFormView {
83+ name: form.name.clone(),
84+ trigger: form.trigger.clone(),
85+ column: form.column.clone(),
86+ tag: form.tag.clone(),
87+ audience: form.audience.clone(),
88+ subject: form.subject.clone(),
89+ include_details: form.include_details == "on",
90+ enabled: form.enabled == "on",
91+ }
92+}
93+
94+/// The form as the page shows a saved rule.
95+fn form_of_rule(rule: &MailRule) -> RuleFormView {
96+ RuleFormView {
97+ name: rule.name.clone(),
98+ trigger: rule.trigger.clone(),
99+ column: rule.column_id.clone().unwrap_or_default(),
100+ tag: rule.tag_id.clone().unwrap_or_default(),
101+ audience: rule.audience.as_str().to_owned(),
102+ subject: rule.subject_template.clone(),
103+ include_details: rule.include_details,
104+ enabled: rule.enabled,
105+ }
106+}
107+
108+/// The empty form of a new rule.
109+fn new_form() -> RuleFormView {
110+ RuleFormView {
111+ trigger: TRIGGERS[0].to_owned(),
112+ audience: Audience::Assignees.as_str().to_owned(),
113+ subject: DEFAULT_SUBJECT.to_owned(),
114+ enabled: true,
115+ ..RuleFormView::default()
116+ }
117+}
118+
119+/// The rule in one sentence, from its stored fields and the board's current names.
120+fn sentence(lang: Lang, rule: &MailRule, columns: &[Column], tags: &[Tag]) -> String {
121+ let trigger = if rule.trigger == "status" {
122+ match rule
123+ .column_id
124+ .as_deref()
125+ .and_then(|id| columns.iter().find(|c| c.id == id))
126+ {
127+ Some(column) => fill(t(lang, K::TrigStatus), &[column.name.as_str()]),
128+ None => t(lang, K::TrigStatusAny).to_owned(),
129+ }
130+ } else {
131+ trigger_label(lang, &rule.trigger).to_owned()
132+ };
133+ let mut text = fill(
134+ t(lang, K::RuleSentence),
135+ &[
136+ trigger.as_str(),
137+ audience_label(lang, rule.audience.as_str()),
138+ rule.subject_template.as_str(),
139+ ],
140+ );
141+ if let Some(tag) = rule
142+ .tag_id
143+ .as_deref()
144+ .and_then(|id| tags.iter().find(|tag| tag.id == id))
145+ {
146+ text.push(' ');
147+ text.push_str(&fill(t(lang, K::ProjectNote), &[tag.name.as_str()]));
148+ }
149+ text
150+}
151+
152+/// Which form the page shows: its values, the rule being edited (if any), and whether it is shown.
153+struct FormShown {
154+ form: RuleFormView,
155+ editing: Option<String>,
156+ show_form: bool,
157+}
158+
159+/// The page's data: the rules, the choices of the form, and the form itself.
160+async fn rules_view(
161+ state: &AppState,
162+ board_id: &str,
163+ lang: Lang,
164+ shown: FormShown,
165+ notice: Option<String>,
166+ alert: Option<String>,
167+) -> Result<RulesView> {
168+ let rules = state.store.list_rules(board_id).await?;
169+ let columns: Vec<Column> = state
170+ .store
171+ .columns(board_id)
172+ .await?
173+ .into_iter()
174+ .filter(|c| c.deleted_at.is_none())
175+ .collect();
176+ let tags = state.store.tags(board_id).await?;
177+ let rows = rules
178+ .iter()
179+ .map(|rule| RuleRow {
180+ id: rule.id.clone(),
181+ name: rule.name.clone(),
182+ sentence: sentence(lang, rule, &columns, &tags),
183+ enabled: rule.enabled,
184+ })
185+ .collect();
186+ Ok(RulesView {
187+ lang,
188+ rules: rows,
189+ columns: columns
190+ .iter()
191+ .map(|c| (c.id.clone(), c.name.clone()))
192+ .collect(),
193+ tags: tags
194+ .iter()
195+ .map(|t| (t.id.clone(), t.name.clone()))
196+ .collect(),
197+ form: shown.form,
198+ editing: shown.editing,
199+ show_form: shown.show_form,
200+ notice,
201+ alert,
202+ })
203+}
204+
205+/// Renders the page with `status`. The CSRF token of the session goes in every form.
206+async fn render(
207+ cx: &Cx,
208+ me: &CurrentMember,
209+ page: RulesView,
210+ status: StatusCode,
211+) -> Result<Response> {
212+ let lang = page.lang;
213+ let viewer: ViewerInfo = viewer_of(me);
214+ let csrf = me.session.csrf_token.clone();
215+ let document = view! {
216+ cx =>
217+ (status)
218+ shell(title: t(lang, K::RulesTitle), lang: lang,
219+ viewer: Some(&viewer), page_script: None,
220+ rules_content(page: &page, csrf: csrf.as_str())
221+ )
222+ };
223+ respond(cx, document).await
224+}
225+
226+/// Re-renders the page after a refused form, with the typed values and the store's message.
227+async fn refused(
228+ cx: &Cx,
229+ state: &AppState,
230+ me: &CurrentMember,
231+ board_id: &str,
232+ form: &RuleSubmit,
233+ editing: Option<String>,
234+ error: iz_core::Error,
235+) -> Result<Response> {
236+ let language = lang(cx, me.member.locale_override.as_deref());
237+ let message = user_text(error)?;
238+ let shown = FormShown {
239+ form: form_of(form),
240+ editing,
241+ show_form: true,
242+ };
243+ let page = rules_view(state, board_id, language, shown, None, Some(message)).await?;
244+ render(cx, me, page, REFUSED).await
245+}
246+
247+/// `GET /rules`, with `?new=1` for a new rule or `?edit=<id>` for a saved one.
248+#[route(GET "/rules")]
249+async fn rules_page(cx: &Cx) -> Result<Response> {
250+ let state = app_context::<AppState>(cx);
251+ let me = require_role(cx, Need::Admin).await?;
252+ let language = lang(cx, me.member.locale_override.as_deref());
253+ let board = the_board(&state.store).await?;
254+ let notice = query_param(cx, "notice").and_then(|code| notice_text(language, &code, None));
255+ let (form, editing, show_form) = match query_param(cx, "edit").filter(|id| !id.is_empty()) {
256+ Some(id) => {
257+ let rule = state.store.rule(&board.id, &id).await.map_err(core_err)?;
258+ (form_of_rule(&rule), Some(rule.id.clone()), true)
259+ }
260+ None => (new_form(), None, query_param(cx, "new").is_some()),
261+ };
262+ let shown = FormShown {
263+ form,
264+ editing,
265+ show_form,
266+ };
267+ let page = rules_view(state, &board.id, language, shown, notice, None).await?;
268+ render(cx, &me, page, StatusCode::OK).await
269+}
270+
271+/// `POST /rules`: creates a rule.
272+#[route(POST "/rules")]
273+async fn create_rule(cx: &Cx, form: Option<Form<RuleSubmit>>) -> Result<Response> {
274+ let state = app_context::<AppState>(cx);
275+ let form = form.map(|Form(form)| form).unwrap_or_default();
276+ let me = require_csrf(cx, Need::Admin, &form.csrf).await?;
277+ let board = the_board(&state.store).await?;
278+ match state.store.create_rule(&board.id, &input_of(&form)).await {
279+ Ok(_) => back("/rules?notice=rule"),
280+ Err(error) => refused(cx, state, &me, &board.id, &form, None, error).await,
281+ }
282+}
283+
284+/// `POST /rules/{id}/edit`: saves a changed rule.
285+#[route(POST "/rules/{id}/edit")]
286+async fn update_rule(cx: &Cx, form: Option<Form<RuleSubmit>>) -> Result<Response> {
287+ let state = app_context::<AppState>(cx);
288+ let form = form.map(|Form(form)| form).unwrap_or_default();
289+ let rule_id = path_param_segment(cx, "id").to_owned();
290+ let me = require_csrf(cx, Need::Admin, &form.csrf).await?;
291+ let board = the_board(&state.store).await?;
292+ match state
293+ .store
294+ .update_rule(&board.id, &rule_id, &input_of(&form))
295+ .await
296+ {
297+ Ok(_) => back("/rules?notice=rule"),
298+ Err(error) => refused(cx, state, &me, &board.id, &form, Some(rule_id), error).await,
299+ }
300+}
301+
302+/// `POST /rules/{id}/enabled`: turns a rule on or off.
303+#[route(POST "/rules/{id}/enabled")]
304+async fn set_enabled(cx: &Cx, form: Option<Form<EnabledSubmit>>) -> Result<Response> {
305+ let state = app_context::<AppState>(cx);
306+ let form = form.map(|Form(form)| form).unwrap_or_default();
307+ let rule_id = path_param_segment(cx, "id").to_owned();
308+ require_csrf(cx, Need::Admin, &form.csrf).await?;
309+ let board = the_board(&state.store).await?;
310+ state
311+ .store
312+ .set_rule_enabled(&board.id, &rule_id, form.enabled == "1")
313+ .await
314+ .map_err(core_err)?;
315+ back("/rules?notice=rule_switched")
316+}
317+
318+/// `POST /rules/{id}/delete`: deletes a rule. Its past decisions and mail stay in the logs.
319+#[route(POST "/rules/{id}/delete")]
320+async fn delete_rule(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> {
321+ let state = app_context::<AppState>(cx);
322+ let form = form.map(|Form(form)| form).unwrap_or_default();
323+ let rule_id = path_param_segment(cx, "id").to_owned();
324+ require_csrf(cx, Need::Admin, &form.csrf).await?;
325+ let board = the_board(&state.store).await?;
326+ state
327+ .store
328+ .delete_rule(&board.id, &rule_id)
329+ .await
330+ .map_err(core_err)?;
331+ back("/rules?notice=rule_deleted")
332+}
crates/iz-web/src/pages/settings.rsadded+281 -0
@@ -0,0 +1,281 @@
1+//! The administrator settings page (`GET /settings`): the outgoing mail server, the reminder settings and
2+//! the message to members. Every write is an administrator's form with a CSRF token checked before any
3+//! side effect (`auth::require_csrf`). The password is sealed when it is saved and never rendered back.
4+//!
5+//! A refusal the admin can fix re-renders the page with the typed server values (never the password) and
6+//! status `422`. A success redirects with a notice code in the query string.
7+
8+use iz_core::mail_text::MailLang;
9+use iz_core::secret;
10+use iz_core::sender::{
11+ DEFAULT_FROM_NAME, DEFAULT_PORT, SenderInput, TlsMode, validate_password, validate_sender,
12+};
13+use iz_core::store::sender::{ReminderSettings, SenderState};
14+use jiff::Timestamp;
15+use serde::Deserialize;
16+use topcoat::Result;
17+use topcoat::context::{Cx, app_context};
18+use topcoat::router::content::Form;
19+use topcoat::router::response::Response;
20+use topcoat::router::{StatusCode, route};
21+use topcoat::view::view;
22+
23+use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role};
24+use crate::i18n::admin::{K, t};
25+use crate::i18n::{Lang, lang};
26+use crate::mail;
27+use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewer_of};
28+use crate::state::AppState;
29+use crate::views::admin::{SenderForm, SettingsView, settings_content};
30+use crate::views::{ViewerInfo, respond, shell};
31+
32+/// The sender form as posted.
33+#[derive(Debug, Default, Deserialize)]
34+#[serde(default)]
35+struct SenderSubmit {
36+ csrf: String,
37+ host: String,
38+ port: String,
39+ tls: String,
40+ username: String,
41+ password: String,
42+ from_address: String,
43+ from_name: String,
44+}
45+
46+/// The reminder form as posted.
47+#[derive(Debug, Default, Deserialize)]
48+#[serde(default)]
49+struct RemindersSubmit {
50+ csrf: String,
51+ lead: String,
52+ cap: String,
53+}
54+
55+/// The message-to-members form as posted.
56+#[derive(Debug, Default, Deserialize)]
57+#[serde(default)]
58+struct MessageSubmit {
59+ csrf: String,
60+ subject: String,
61+ body: String,
62+}
63+
64+/// The sender form as the store has it. The password is only ever a flag.
65+fn sender_form(stored: &SenderState) -> SenderForm {
66+ match &stored.sender {
67+ Some(sender) => SenderForm {
68+ host: sender.host.clone(),
69+ port: sender.port.to_string(),
70+ tls: sender.tls.as_str().to_owned(),
71+ username: sender.username.clone(),
72+ from_address: sender.from_address.clone(),
73+ from_name: sender.from_name.clone(),
74+ password_set: stored.password_set,
75+ },
76+ None => SenderForm {
77+ port: DEFAULT_PORT.to_string(),
78+ tls: TlsMode::StartTls.as_str().to_owned(),
79+ from_name: DEFAULT_FROM_NAME.to_owned(),
80+ password_set: stored.password_set,
81+ ..SenderForm::default()
82+ },
83+ }
84+}
85+
86+/// The page's data: the stored settings, or the typed `form` when a save was refused.
87+async fn settings_view(
88+ state: &AppState,
89+ lang: Lang,
90+ form: Option<SenderForm>,
91+ notice: Option<String>,
92+ alert: Option<String>,
93+) -> Result<SettingsView> {
94+ let stored = state.store.load_sender().await?;
95+ let reminders: ReminderSettings = state.store.reminder_settings().await?;
96+ let mut sender = form.unwrap_or_else(|| sender_form(&stored));
97+ sender.password_set = stored.password_set;
98+ Ok(SettingsView {
99+ lang,
100+ configured: stored.sender.is_some(),
101+ sender,
102+ reminder_lead: reminders.lead_minutes,
103+ reminder_cap: reminders.hourly_cap,
104+ notice,
105+ alert,
106+ })
107+}
108+
109+/// Renders the settings page with `status`. The CSRF token of the session goes in every form.
110+async fn render(
111+ cx: &Cx,
112+ me: &CurrentMember,
113+ page: SettingsView,
114+ status: StatusCode,
115+) -> Result<Response> {
116+ let lang = page.lang;
117+ let viewer: ViewerInfo = viewer_of(me);
118+ let csrf = me.session.csrf_token.clone();
119+ let document = view! {
120+ cx =>
121+ (status)
122+ shell(title: t(lang, K::SettingsTitle), lang: lang,
123+ viewer: Some(&viewer), page_script: None,
124+ settings_content(page: &page, csrf: csrf.as_str())
125+ )
126+ };
127+ respond(cx, document).await
128+}
129+
130+/// `GET /settings`. Administrators only.
131+#[route(GET "/settings")]
132+async fn settings_page(cx: &Cx) -> Result<Response> {
133+ let state = app_context::<AppState>(cx);
134+ let me = require_role(cx, Need::Admin).await?;
135+ let language = lang(cx, me.member.locale_override.as_deref());
136+ let queued = query_param(cx, "queued");
137+ let notice =
138+ query_param(cx, "notice").and_then(|code| notice_text(language, &code, queued.as_deref()));
139+ let page = settings_view(state, language, None, notice, None).await?;
140+ render(cx, &me, page, StatusCode::OK).await
141+}
142+
143+/// `POST /settings/sender`: saves the server, the sender and (when typed) the password.
144+#[route(POST "/settings/sender")]
145+async fn save_sender(cx: &Cx, form: Option<Form<SenderSubmit>>) -> Result<Response> {
146+ let state = app_context::<AppState>(cx);
147+ let form = form.map(|Form(form)| form).unwrap_or_default();
148+ let me = require_csrf(cx, Need::Admin, &form.csrf).await?;
149+ let language = lang(cx, me.member.locale_override.as_deref());
150+ let typed = SenderForm {
151+ host: form.host.clone(),
152+ port: form.port.clone(),
153+ tls: form.tls.clone(),
154+ username: form.username.clone(),
155+ from_address: form.from_address.clone(),
156+ from_name: form.from_name.clone(),
157+ password_set: false,
158+ };
159+ let outcome: iz_core::Result<()> = async {
160+ let sender = validate_sender(&SenderInput {
161+ host: form.host.clone(),
162+ port: form.port.clone(),
163+ tls: form.tls.clone(),
164+ username: form.username.clone(),
165+ from_address: form.from_address.clone(),
166+ from_name: form.from_name.clone(),
167+ })?;
168+ // An empty password keeps the stored one; a typed one is checked and sealed here, once.
169+ let sealed = if form.password.is_empty() {
170+ None
171+ } else {
172+ validate_password(&form.password)?;
173+ Some(secret::seal(&state.key, form.password.as_bytes())?)
174+ };
175+ state.store.save_sender(&sender, sealed.as_deref()).await
176+ }
177+ .await;
178+ match outcome {
179+ Ok(()) => back("/settings?notice=sender"),
180+ Err(error) => {
181+ let message = user_text(error)?;
182+ let page = settings_view(state, language, Some(typed), None, Some(message)).await?;
183+ render(cx, &me, page, REFUSED).await
184+ }
185+ }
186+}
187+
188+/// `POST /settings/sender/check`: asks the server to accept a connection. Sends no mail.
189+#[route(POST "/settings/sender/check")]
190+async fn check_sender(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> {
191+ let state = app_context::<AppState>(cx);
192+ let form = form.map(|Form(form)| form).unwrap_or_default();
193+ let me = require_csrf(cx, Need::Admin, &form.csrf).await?;
194+ let language = lang(cx, me.member.locale_override.as_deref());
195+ match mail::check(state).await {
196+ Ok(()) => back("/settings?notice=checked"),
197+ Err(error) => {
198+ let message = user_text(error)?;
199+ let page = settings_view(state, language, None, None, Some(message)).await?;
200+ render(cx, &me, page, REFUSED).await
201+ }
202+ }
203+}
204+
205+/// `POST /settings/sender/test`: sends the test mail to the signed-in admin's own address.
206+#[route(POST "/settings/sender/test")]
207+async fn send_test(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> {
208+ let state = app_context::<AppState>(cx);
209+ let form = form.map(|Form(form)| form).unwrap_or_default();
210+ let me = require_csrf(cx, Need::Admin, &form.csrf).await?;
211+ let language = lang(cx, me.member.locale_override.as_deref());
212+ let mail_lang = MailLang::of(
213+ me.member.locale_override.as_deref(),
214+ me.member.locale.as_deref(),
215+ );
216+ match mail::send_test(state, &me.member.name, &me.member.email, mail_lang).await {
217+ Ok(()) => back("/settings?notice=test"),
218+ Err(error) => {
219+ let message = user_text(error)?;
220+ let page = settings_view(state, language, None, None, Some(message)).await?;
221+ render(cx, &me, page, REFUSED).await
222+ }
223+ }
224+}
225+
226+/// `POST /settings/reminders`: the lead time (0 is off) and the cap per member per hour.
227+#[route(POST "/settings/reminders")]
228+async fn save_reminders(cx: &Cx, form: Option<Form<RemindersSubmit>>) -> Result<Response> {
229+ let state = app_context::<AppState>(cx);
230+ let form = form.map(|Form(form)| form).unwrap_or_default();
231+ let me = require_csrf(cx, Need::Admin, &form.csrf).await?;
232+ let language = lang(cx, me.member.locale_override.as_deref());
233+ let outcome: iz_core::Result<()> = async {
234+ let lead_minutes = form.lead.trim().parse::<u32>().map_err(|_| {
235+ iz_core::Error::Invalid("the lead time must be a whole number of minutes".into())
236+ })?;
237+ let hourly_cap = form
238+ .cap
239+ .trim()
240+ .parse::<u32>()
241+ .map_err(|_| iz_core::Error::Invalid("the cap must be a whole number".into()))?;
242+ state
243+ .store
244+ .save_reminder_settings(ReminderSettings {
245+ lead_minutes,
246+ hourly_cap,
247+ })
248+ .await
249+ }
250+ .await;
251+ match outcome {
252+ Ok(()) => back("/settings?notice=reminders"),
253+ Err(error) => {
254+ let message = user_text(error)?;
255+ let page = settings_view(state, language, None, None, Some(message)).await?;
256+ render(cx, &me, page, REFUSED).await
257+ }
258+ }
259+}
260+
261+/// `POST /settings/message`: queues one notice to every active member except the sender. Rate-limited by
262+/// the store (one every ten minutes).
263+#[route(POST "/settings/message")]
264+async fn send_message(cx: &Cx, form: Option<Form<MessageSubmit>>) -> Result<Response> {
265+ let state = app_context::<AppState>(cx);
266+ let form = form.map(|Form(form)| form).unwrap_or_default();
267+ let me = require_csrf(cx, Need::Admin, &form.csrf).await?;
268+ let language = lang(cx, me.member.locale_override.as_deref());
269+ let outcome = state
270+ .store
271+ .queue_message(&me.member.sub, &form.subject, &form.body, Timestamp::now())
272+ .await;
273+ match outcome {
274+ Ok(count) => back(&format!("/settings?notice=message&queued={count}")),
275+ Err(error) => {
276+ let message = user_text(error)?;
277+ let page = settings_view(state, language, None, None, Some(message)).await?;
278+ render(cx, &me, page, REFUSED).await
279+ }
280+ }
281+}
crates/iz-web/src/views/admin.rsadded+601 -0
@@ -0,0 +1,601 @@
1+//! The administrator pages: sender and reminders with the message to members (`/settings`), mail rules
2+//! (`/rules`) and logs (`/logs`). Each page is plain data in, markup out. Handlers build the data in
3+//! `pages/`; nothing here reads the store.
4+//!
5+//! The password of the sender is never a field value: the form shows only whether one is set. Every
6+//! value is escaped by `view!`, and no script or handler is emitted.
7+
8+use topcoat::Result;
9+use topcoat::view::{View, component, view};
10+
11+use crate::i18n::Lang;
12+use crate::i18n::admin::{K, t};
13+use crate::views::board::flag;
14+use crate::views::{alert, notice};
15+
16+/// The sender form as it is shown. The password is never here, only `password_set`.
17+#[derive(Debug, Clone, Default)]
18+pub struct SenderForm {
19+ /// Host name.
20+ pub host: String,
21+ /// Port, as text.
22+ pub port: String,
23+ /// `implicit`, `starttls` or `plain`.
24+ pub tls: String,
25+ /// SMTP user name.
26+ pub username: String,
27+ /// From address.
28+ pub from_address: String,
29+ /// From name.
30+ pub from_name: String,
31+ /// Whether a password is stored.
32+ pub password_set: bool,
33+}
34+
35+/// A row of the rules list: the name, the sentence the rule says, and whether it is on.
36+#[derive(Debug, Clone)]
37+pub struct RuleRow {
38+ /// Rule id.
39+ pub id: String,
40+ /// The admin's name for the rule.
41+ pub name: String,
42+ /// The rule in one sentence.
43+ pub sentence: String,
44+ /// Whether the rule is on.
45+ pub enabled: bool,
46+}
47+
48+/// The rule form as it is shown: the typed values, or the saved rule being edited.
49+#[derive(Debug, Clone, Default)]
50+pub struct RuleFormView {
51+ /// The name.
52+ pub name: String,
53+ /// The trigger word.
54+ pub trigger: String,
55+ /// The column id (only for the status trigger).
56+ pub column: String,
57+ /// The project id, or empty for any.
58+ pub tag: String,
59+ /// The audience word.
60+ pub audience: String,
61+ /// The subject template.
62+ pub subject: String,
63+ /// Whether the mail carries the details block.
64+ pub include_details: bool,
65+ /// Whether the rule is on.
66+ pub enabled: bool,
67+}
68+
69+/// One activity row of the logs.
70+#[derive(Debug, Clone)]
71+pub struct ActivityRow {
72+ /// When it happened, as stored.
73+ pub at: String,
74+ /// Who did it, by name.
75+ pub who: String,
76+ /// The event kind.
77+ pub kind: String,
78+ /// The details, as stored JSON text.
79+ pub detail: String,
80+}
81+
82+/// The sections of the logs page.
83+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84+pub enum LogSection {
85+ /// Mail queued for sending.
86+ Outbox,
87+ /// The rules' decisions.
88+ Decisions,
89+ /// The board's activity.
90+ Activity,
91+}
92+
93+/// The rows of one logs page. Only the section in `section` is filled.
94+#[derive(Debug, Clone)]
95+pub struct LogsView {
96+ /// The section shown.
97+ pub section: LogSection,
98+ /// Outbox rows, newest first.
99+ pub outbox: Vec<iz_core::store::outbox::OutboxRow>,
100+ /// Rule decisions, newest first.
101+ pub decisions: Vec<iz_core::store::outbox::Decision>,
102+ /// Activity rows, newest first.
103+ pub activity: Vec<ActivityRow>,
104+ /// The kind filter text, as typed.
105+ pub kind: String,
106+ /// The link to the older page, when there is one.
107+ pub next: Option<String>,
108+ /// A confirmation, already translated.
109+ pub notice: Option<String>,
110+}
111+
112+/// The settings page: sender, reminders and the message to members.
113+#[derive(Debug, Clone)]
114+pub struct SettingsView {
115+ /// The language.
116+ pub lang: Lang,
117+ /// Whether the sender is complete enough to send.
118+ pub configured: bool,
119+ /// The sender form.
120+ pub sender: SenderForm,
121+ /// Lead time of the reminders, in minutes.
122+ pub reminder_lead: u32,
123+ /// Reminder mails one member may get per hour.
124+ pub reminder_cap: u32,
125+ /// A confirmation to show above the page, already translated.
126+ pub notice: Option<String>,
127+ /// A refusal to show above the page, already translated or a store message.
128+ pub alert: Option<String>,
129+}
130+
131+/// The rules page: the list, the form (new or editing), and the choices of the form.
132+#[derive(Debug, Clone)]
133+pub struct RulesView {
134+ /// The language.
135+ pub lang: Lang,
136+ /// The rules, oldest first.
137+ pub rules: Vec<RuleRow>,
138+ /// The columns the status trigger can name, `(id, name)`.
139+ pub columns: Vec<(String, String)>,
140+ /// The projects the rule can be limited to, `(id, name)`.
141+ pub tags: Vec<(String, String)>,
142+ /// The form to show.
143+ pub form: RuleFormView,
144+ /// The id of the rule being edited, or `None` for a new rule.
145+ pub editing: Option<String>,
146+ /// Whether the form is shown.
147+ pub show_form: bool,
148+ /// A confirmation, already translated.
149+ pub notice: Option<String>,
150+ /// A refusal, already translated or a store message.
151+ pub alert: Option<String>,
152+}
153+
154+/// The tabs of the administrator area. `current` is the page shown.
155+#[component]
156+pub async fn admin_tabs(lang: Lang, current: &str) -> Result<impl View> {
157+ let settings = if current == "settings" {
158+ "tab current"
159+ } else {
160+ "tab"
161+ };
162+ let rules = if current == "rules" {
163+ "tab current"
164+ } else {
165+ "tab"
166+ };
167+ let logs = if current == "logs" {
168+ "tab current"
169+ } else {
170+ "tab"
171+ };
172+ Ok(view! {
173+ <nav class="tabs" aria-label=(t(lang, K::SettingsTitle))>
174+ <a class=(settings) href="/settings">(t(lang, K::NavSettings))</a>
175+ <a class=(rules) href="/rules">(t(lang, K::NavRules))</a>
176+ <a class=(logs) href="/logs">(t(lang, K::NavLogs))</a>
177+ </nav>
178+ })
179+}
180+
181+/// The settings page body.
182+#[component]
183+pub async fn settings_content(page: &SettingsView, csrf: &str) -> Result<impl View> {
184+ let lang = page.lang;
185+ let sender = &page.sender;
186+ let tls_implicit = sender.tls == "implicit";
187+ let tls_starttls = sender.tls == "starttls";
188+ let tls_plain = sender.tls == "plain";
189+ let lead = page.reminder_lead.to_string();
190+ let cap = page.reminder_cap.to_string();
191+ let password_state = if sender.password_set {
192+ t(lang, K::PasswordSet)
193+ } else {
194+ t(lang, K::PasswordNotSet)
195+ };
196+ Ok(view! {
197+ <h1>(t(lang, K::SettingsTitle))</h1>
198+ admin_tabs(lang: lang, current: "settings")
199+ if let Some(message) = &page.alert {
200+ alert(message: message.as_str())
201+ }
202+ if let Some(message) = &page.notice {
203+ notice(message: message.as_str())
204+ }
205+ <section class="card">
206+ <h2>(t(lang, K::SenderHeading))</h2>
207+ <p class="field-hint">(t(lang, K::SenderHelp))</p>
208+ if !page.configured {
209+ <p class="field-hint">(t(lang, K::SenderNotConfigured))</p>
210+ }
211+ <form method="post" action="/settings/sender" class="stack">
212+ <input type="hidden" name="csrf" value=(csrf)>
213+ <div class="field">
214+ <label for="mail-host">(t(lang, K::FieldHost))</label>
215+ <input id="mail-host" name="host" value=(sender.host.as_str()) maxlength="253" autocomplete="off">
216+ </div>
217+ <div class="field">
218+ <label for="mail-port">(t(lang, K::FieldPort))</label>
219+ <input id="mail-port" name="port" inputmode="numeric" value=(sender.port.as_str()) maxlength="5">
220+ </div>
221+ <div class="field">
222+ <label for="mail-tls">(t(lang, K::FieldTls))</label>
223+ <select id="mail-tls" name="tls">
224+ <option value="implicit" selected=(flag(tls_implicit))>(t(lang, K::TlsImplicit))</option>
225+ <option value="starttls" selected=(flag(tls_starttls))>(t(lang, K::TlsStartTls))</option>
226+ <option value="plain" selected=(flag(tls_plain))>(t(lang, K::TlsPlain))</option>
227+ </select>
228+ </div>
229+ <div class="field">
230+ <label for="mail-user">(t(lang, K::FieldUsername))</label>
231+ <input id="mail-user" name="username" value=(sender.username.as_str()) maxlength="254" autocomplete="off">
232+ </div>
233+ <div class="field">
234+ <label for="mail-password">(t(lang, K::FieldPassword))</label>
235+ <input id="mail-password" type="password" name="password" maxlength="512" autocomplete="new-password">
236+ <p class="field-hint">(password_state) " " (t(lang, K::PasswordHint))</p>
237+ </div>
238+ <div class="field">
239+ <label for="mail-from">(t(lang, K::FieldFromAddress))</label>
240+ <input id="mail-from" type="email" name="from_address" value=(sender.from_address.as_str()) maxlength="254">
241+ </div>
242+ <div class="field">
243+ <label for="mail-from-name">(t(lang, K::FieldFromName))</label>
244+ <input id="mail-from-name" name="from_name" value=(sender.from_name.as_str()) maxlength="100">
245+ <p class="field-hint">(t(lang, K::FromNameHint))</p>
246+ </div>
247+ <button class="button primary" type="submit">(t(lang, K::SaveSender))</button>
248+ </form>
249+ <div class="actions">
250+ <form method="post" action="/settings/sender/check">
251+ <input type="hidden" name="csrf" value=(csrf)>
252+ <button class="button" type="submit">(t(lang, K::CheckConnection))</button>
253+ </form>
254+ <form method="post" action="/settings/sender/test">
255+ <input type="hidden" name="csrf" value=(csrf)>
256+ <button class="button" type="submit">(t(lang, K::SendTestMail))</button>
257+ </form>
258+ </div>
259+ </section>
260+ <section class="card">
261+ <h2>(t(lang, K::RemindersHeading))</h2>
262+ <form method="post" action="/settings/reminders" class="stack">
263+ <input type="hidden" name="csrf" value=(csrf)>
264+ <div class="field">
265+ <label for="rem-lead">(t(lang, K::ReminderLead))</label>
266+ <input id="rem-lead" name="lead" inputmode="numeric" value=(lead.as_str()) maxlength="4">
267+ </div>
268+ <div class="field">
269+ <label for="rem-cap">(t(lang, K::ReminderCap))</label>
270+ <input id="rem-cap" name="cap" inputmode="numeric" value=(cap.as_str()) maxlength="4">
271+ </div>
272+ <button class="button" type="submit">(t(lang, K::SaveReminders))</button>
273+ </form>
274+ </section>
275+ <section class="card">
276+ <h2>(t(lang, K::MessageHeading))</h2>
277+ <p class="field-hint">(t(lang, K::MessageHelp))</p>
278+ <form method="post" action="/settings/message" class="stack">
279+ <input type="hidden" name="csrf" value=(csrf)>
280+ <div class="field">
281+ <label for="msg-subject">(t(lang, K::MessageSubject))</label>
282+ <input id="msg-subject" name="subject" maxlength="200" required=(flag(true))>
283+ </div>
284+ <div class="field">
285+ <label for="msg-body">(t(lang, K::MessageBody))</label>
286+ <textarea id="msg-body" name="body" maxlength="20000" required=(flag(true))></textarea>
287+ </div>
288+ <button class="button" type="submit">(t(lang, K::SendMessage))</button>
289+ </form>
290+ </section>
291+ })
292+}
293+
294+/// The rules page body: the list with the sentence of each rule, then the form.
295+#[component]
296+pub async fn rules_content(page: &RulesView, csrf: &str) -> Result<impl View> {
297+ let lang = page.lang;
298+ let form = &page.form;
299+ let heading = if page.editing.is_some() {
300+ t(lang, K::EditRule)
301+ } else {
302+ t(lang, K::NewRule)
303+ };
304+ let audiences = ["assignees", "board", "creator", "watchers"];
305+ let triggers = iz_core::rules::TRIGGERS;
306+ Ok(view! {
307+ <h1>(t(lang, K::RulesTitle))</h1>
308+ <p class="field-hint">(t(lang, K::RulesHelp))</p>
309+ admin_tabs(lang: lang, current: "rules")
310+ if let Some(message) = &page.alert {
311+ alert(message: message.as_str())
312+ }
313+ if let Some(message) = &page.notice {
314+ notice(message: message.as_str())
315+ }
316+ <section class="card">
317+ if page.rules.is_empty() {
318+ <p>(t(lang, K::NoRules))</p>
319+ }
320+ <ul class="rule-list">
321+ for rule in page.rules.iter() {
322+ <li class="rule-row">
323+ <div>
324+ <strong>(rule.name.as_str())</strong>
325+ <p>(rule.sentence.as_str())</p>
326+ </div>
327+ <div class="actions">
328+ <form method="post" action=(format!("/rules/{}/enabled", rule.id)) class="inline">
329+ <input type="hidden" name="csrf" value=(csrf)>
330+ <input type="hidden" name="enabled" value=(if rule.enabled { "" } else { "1" })>
331+ <button class="button" type="submit">(if rule.enabled { t(lang, K::RuleOn) } else { t(lang, K::RuleOff) })</button>
332+ </form>
333+ <a class="button" href=(format!("/rules?edit={}", rule.id))>(t(lang, K::Edit))</a>
334+ <form method="post" action=(format!("/rules/{}/delete", rule.id)) class="inline">
335+ <input type="hidden" name="csrf" value=(csrf)>
336+ <button class="button danger" type="submit">(t(lang, K::Delete))</button>
337+ </form>
338+ </div>
339+ </li>
340+ }
341+ </ul>
342+ <a class="button primary" href="/rules?new=1">(t(lang, K::NewRule))</a>
343+ </section>
344+ if page.show_form {
345+ <section class="card">
346+ <h2>(heading)</h2>
347+ <form method="post" action=(match &page.editing { Some(id) => format!("/rules/{id}/edit"), None => "/rules".to_owned() }) class="stack">
348+ <input type="hidden" name="csrf" value=(csrf)>
349+ <div class="field">
350+ <label for="rule-name">(t(lang, K::FieldName))</label>
351+ <input id="rule-name" name="name" maxlength="120" value=(form.name.as_str()) required=(flag(true))>
352+ </div>
353+ <div class="field">
354+ <label for="rule-trigger">(t(lang, K::FieldTrigger))</label>
355+ <select id="rule-trigger" name="trigger">
356+ for word in triggers.iter() {
357+ <option value=(*word) selected=(flag(form.trigger == *word))>(trigger_label(lang, word))</option>
358+ }
359+ </select>
360+ </div>
361+ <div class="field">
362+ <label for="rule-column">(t(lang, K::FieldColumn))</label>
363+ <select id="rule-column" name="column">
364+ <option value="" selected=(flag(form.column.is_empty()))>(t(lang, K::AnyColumn))</option>
365+ for (id, name) in page.columns.iter() {
366+ <option value=(id.as_str()) selected=(flag(form.column == *id))>(name.as_str())</option>
367+ }
368+ </select>
369+ </div>
370+ <div class="field">
371+ <label for="rule-tag">(t(lang, K::FieldProject))</label>
372+ <select id="rule-tag" name="tag">
373+ <option value="" selected=(flag(form.tag.is_empty()))>(t(lang, K::AnyProject))</option>
374+ for (id, name) in page.tags.iter() {
375+ <option value=(id.as_str()) selected=(flag(form.tag == *id))>(name.as_str())</option>
376+ }
377+ </select>
378+ </div>
379+ <div class="field">
380+ <label for="rule-audience">(t(lang, K::FieldAudience))</label>
381+ <select id="rule-audience" name="audience">
382+ for word in audiences.iter() {
383+ <option value=(*word) selected=(flag(form.audience == *word))>(audience_label(lang, word))</option>
384+ }
385+ </select>
386+ </div>
387+ <div class="field">
388+ <label for="rule-subject">(t(lang, K::FieldSubject))</label>
389+ <input id="rule-subject" name="subject" maxlength="120" value=(form.subject.as_str()) required=(flag(true))>
390+ <p class="field-hint">(t(lang, K::SubjectHint))</p>
391+ </div>
392+ <label class="check">
393+ <input type="checkbox" name="include_details" value="on" checked=(flag(form.include_details))>
394+ (t(lang, K::IncludeDetails))
395+ </label>
396+ <label class="check">
397+ <input type="checkbox" name="enabled" value="on" checked=(flag(form.enabled))>
398+ (t(lang, K::Enabled))
399+ </label>
400+ <div class="actions">
401+ <button class="button primary" type="submit">(t(lang, K::SaveRule))</button>
402+ <a class="button" href="/rules">(t(lang, K::CancelEdit))</a>
403+ </div>
404+ </form>
405+ </section>
406+ }
407+ })
408+}
409+
410+/// The logs page body: the section tabs, the filter for the activity, and the rows of the section.
411+#[component]
412+pub async fn logs_content(page: &LogsView, csrf: &str, lang: Lang) -> Result<impl View> {
413+ let outbox = page.section == LogSection::Outbox;
414+ let decisions = page.section == LogSection::Decisions;
415+ let activity = page.section == LogSection::Activity;
416+ Ok(view! {
417+ <h1>(t(lang, K::LogsTitle))</h1>
418+ if let Some(message) = &page.notice {
419+ notice(message: message.as_str())
420+ }
421+ <nav class="tabs" aria-label=(t(lang, K::LogsTitle))>
422+ <a class=(if outbox { "tab current" } else { "tab" }) href="/logs?section=outbox">(t(lang, K::SectionOutbox))</a>
423+ <a class=(if decisions { "tab current" } else { "tab" }) href="/logs?section=decisions">(t(lang, K::SectionDecisions))</a>
424+ <a class=(if activity { "tab current" } else { "tab" }) href="/logs?section=activity">(t(lang, K::SectionActivity))</a>
425+ </nav>
426+ admin_tabs(lang: lang, current: "logs")
427+ if outbox {
428+ <section class="card">
429+ if page.outbox.is_empty() {
430+ <p>(t(lang, K::NothingYet))</p>
431+ } else {
432+ <table class="log-table">
433+ <thead><tr>
434+ <th>(t(lang, K::ColWhen))</th>
435+ <th>(t(lang, K::ColRecipient))</th>
436+ <th>(t(lang, K::ColSubject))</th>
437+ <th>(t(lang, K::ColState))</th>
438+ <th>(t(lang, K::ColAttempts))</th>
439+ <th>(t(lang, K::ColLastError))</th>
440+ <th></th>
441+ </tr></thead>
442+ <tbody>
443+ for (row, attempts) in page.outbox.iter().map(|r| (r, r.attempts.to_string())) {
444+ <tr>
445+ <td>(row.created_at.as_str())</td>
446+ <td>(row.recipient_name.as_str()) " <" (row.recipient_email.as_str()) ">"</td>
447+ <td>(row.subject.as_str())</td>
448+ <td>(outbox_state(lang, row.state.as_str()))</td>
449+ <td>(attempts.as_str())</td>
450+ <td>(row.last_error.as_deref().unwrap_or(""))</td>
451+ <td>
452+ if row.state == "failed" || row.state == "abandoned" {
453+ <form method="post" action=(format!("/logs/outbox/{}/retry", row.id)) class="inline">
454+ <input type="hidden" name="csrf" value=(csrf)>
455+ <button class="button" type="submit">(t(lang, K::Retry))</button>
456+ </form>
457+ }
458+ </td>
459+ </tr>
460+ }
461+ </tbody>
462+ </table>
463+ }
464+ </section>
465+ }
466+ if decisions {
467+ <section class="card">
468+ if page.decisions.is_empty() {
469+ <p>(t(lang, K::NothingYet))</p>
470+ } else {
471+ <table class="log-table">
472+ <thead><tr>
473+ <th>(t(lang, K::ColWhen))</th>
474+ <th>(t(lang, K::ColRule))</th>
475+ <th>(t(lang, K::ColTask))</th>
476+ <th>(t(lang, K::ColOutcome))</th>
477+ <th>(t(lang, K::ColDetail))</th>
478+ </tr></thead>
479+ <tbody>
480+ for row in page.decisions.iter() {
481+ <tr>
482+ <td>(row.at.as_str())</td>
483+ <td>(row.rule_name.as_str())</td>
484+ <td>(row.task_key.as_deref().unwrap_or(""))</td>
485+ <td>(outcome_label(lang, row.outcome.as_str()))</td>
486+ <td>(reason_label(lang, row.detail.as_str()))</td>
487+ </tr>
488+ }
489+ </tbody>
490+ </table>
491+ }
492+ </section>
493+ }
494+ if activity {
495+ <section class="card">
496+ <form method="get" action="/logs" class="filter-bar">
497+ <input type="hidden" name="section" value="activity">
498+ <label for="log-kind">(t(lang, K::FilterKind))</label>
499+ <input id="log-kind" name="kind" value=(page.kind.as_str()) maxlength="40">
500+ <button class="button" type="submit">(t(lang, K::Apply))</button>
501+ </form>
502+ if page.activity.is_empty() {
503+ <p>(t(lang, K::NothingYet))</p>
504+ } else {
505+ <table class="log-table">
506+ <thead><tr>
507+ <th>(t(lang, K::ColWhen))</th>
508+ <th>(t(lang, K::ColWho))</th>
509+ <th>(t(lang, K::ColWhat))</th>
510+ <th>(t(lang, K::ColDetail))</th>
511+ </tr></thead>
512+ <tbody>
513+ for row in page.activity.iter() {
514+ <tr>
515+ <td>(row.at.as_str())</td>
516+ <td>(row.who.as_str())</td>
517+ <td>(row.kind.as_str())</td>
518+ <td><code>(row.detail.as_str())</code></td>
519+ </tr>
520+ }
521+ </tbody>
522+ </table>
523+ }
524+ </section>
525+ }
526+ if let Some(href) = page.next.as_ref() {
527+ <p><a class="button" href=(href.as_str())>(t(lang, K::Older))</a></p>
528+ }
529+ })
530+}
531+
532+/// The word for a trigger in the rules list and form.
533+pub fn trigger_label(lang: Lang, word: &str) -> &'static str {
534+ t(
535+ lang,
536+ match word {
537+ "status" => K::TrigStatus,
538+ "unblocked" => K::TrigUnblocked,
539+ "created" => K::TrigCreated,
540+ "assigned" => K::TrigAssigned,
541+ "unassigned" => K::TrigUnassigned,
542+ "commented" => K::TrigCommented,
543+ "deadline_set" => K::TrigDeadlineSet,
544+ "deadline_cleared" => K::TrigDeadlineCleared,
545+ "retitled" => K::TrigRetitled,
546+ "linked" => K::TrigLinked,
547+ "unlinked" => K::TrigUnlinked,
548+ _ => K::TrigDeleted,
549+ },
550+ )
551+}
552+
553+/// The phrase of an audience.
554+pub fn audience_label(lang: Lang, word: &str) -> &'static str {
555+ t(
556+ lang,
557+ match word {
558+ "assignees" => K::AudAssignees,
559+ "board" => K::AudBoard,
560+ "creator" => K::AudCreator,
561+ _ => K::AudWatchers,
562+ },
563+ )
564+}
565+
566+/// The label of an outbox state.
567+fn outbox_state(lang: Lang, state: &str) -> &'static str {
568+ t(
569+ lang,
570+ match state {
571+ "sent" => K::StateSent,
572+ "failed" => K::StateFailed,
573+ "abandoned" => K::StateAbandoned,
574+ _ => K::StatePending,
575+ },
576+ )
577+}
578+
579+/// The label of a decision outcome.
580+fn outcome_label(lang: Lang, outcome: &str) -> &'static str {
581+ t(
582+ lang,
583+ match outcome {
584+ "owed" => K::OutOwed,
585+ "already_owed" => K::OutAlreadyOwed,
586+ "no_recipients" => K::OutNoRecipients,
587+ "not_matched" => K::OutNotMatched,
588+ "disabled" => K::OutDisabled,
589+ _ => K::OutTaskGone,
590+ },
591+ )
592+}
593+
594+/// The label of the reason a decision gave, as stored (`column` or `project`).
595+fn reason_label(lang: Lang, detail: &str) -> &'static str {
596+ match detail {
597+ "column" => t(lang, K::ReasonColumn),
598+ "project" => t(lang, K::ReasonProject),
599+ _ => "",
600+ }
601+}
crates/iz-web/src/views/mod.rsmodified+1 -0
@@ -8,6 +8,7 @@ use topcoat::context::Cx;
8 use topcoat::router::response::{IntoResponse, Response};8 use topcoat::router::response::{IntoResponse, Response};
9 use topcoat::view::{Child, View, ViewExt, component, view};9 use topcoat::view::{Child, View, ViewExt, component, view};
10 10
11+pub mod admin;
11 pub mod board;12 pub mod board;
12 pub mod files;13 pub mod files;
13 pub mod task;14 pub mod task;