Skip to main content

rustango_cms/
workflow_mail.rs

1//! Workflow notification helpers.
2//!
3//! Sends email on every workflow state change so reviewers know
4//! when something is waiting on them and submitters know how their
5//! submission was handled. Built on top of the framework's
6//! [`rustango::email::Mailer`] trait — the host wires a backend
7//! (`ConsoleMailer`, an SMTP one, an SES one); when no mailer is
8//! attached, this module is a no-op.
9//!
10//! ## Notifications
11//!
12//! Sent automatically from the page-editor workflow handlers:
13//!   * **submit**  — notify members of the FIRST task's role
14//!   * **approve** to next step — notify members of the NEW current task's role
15//!   * **approve** to finish — notify the submitter
16//!   * **reject**  — notify the submitter
17//!   * **cancel**  — notify the submitter (idempotent — they may
18//!                   have triggered the cancel themselves)
19//!
20//! Failures during send are logged + swallowed; the workflow
21//! transition completes regardless. Notifications are
22//! "best-effort delivery" — production deployments should layer
23//! their own retry/queue between this module and the network.
24
25use rustango::email::{Email, Mailer};
26
27/// Convenience: send to a list of recipients with a shared subject
28/// + plain-text body. Each `recipients` entry is `(username,
29/// email_address)`. Empty list is a no-op. Per-recipient errors
30/// are logged but don't abort the loop.
31pub async fn notify_many(
32    mailer: &dyn Mailer,
33    from: &str,
34    recipients: &[(String, String)],
35    subject: &str,
36    body: &str,
37) {
38    for (username, addr) in recipients {
39        if addr.trim().is_empty() {
40            continue;
41        }
42        let email = Email::new()
43            .from(from.to_owned())
44            .to(addr.to_owned())
45            .subject(subject.to_owned())
46            .body(body.to_owned())
47            .header(
48                "X-Rustango-Cms-Notification".to_owned(),
49                "workflow".to_owned(),
50            );
51        if let Err(e) = mailer.send(&email).await {
52            tracing::warn!(
53                target: "rustango_cms::workflow_mail",
54                error = %e,
55                recipient_username = %username,
56                recipient_email = %addr,
57                "notification send failed (continuing)"
58            );
59        } else {
60            tracing::debug!(
61                target: "rustango_cms::workflow_mail",
62                recipient_username = %username,
63                recipient_email = %addr,
64                "workflow notification sent"
65            );
66        }
67    }
68}
69
70/// User ids of every active member of a role. The notification
71/// preference filter operates on user_ids before email
72/// resolution so we don't synthesise fallback addresses for users
73/// who have muted the event anyway.
74///
75/// # Errors
76/// Driver / query failures.
77pub async fn role_member_user_ids(
78    pool: &rustango::sql::Pool,
79    role_id: i64,
80) -> Result<Vec<i64>, rustango::sql::ExecError> {
81    use rustango::core::Column as _;
82    use rustango::sql::FetcherPool as _;
83    let memberships: Vec<rustango::tenancy::permissions::UserRole> =
84        rustango::tenancy::permissions::UserRole::objects()
85            .where_(rustango::tenancy::permissions::UserRole::role_id.eq(role_id))
86            .fetch(pool)
87            .await?;
88    let user_ids: Vec<i64> = memberships.iter().map(|m| m.user_id).collect();
89    if user_ids.is_empty() {
90        return Ok(Vec::new());
91    }
92    let users: Vec<rustango::tenancy::auth::User> = rustango::tenancy::auth::User::objects()
93        .where_(rustango::tenancy::auth::User::id.is_in(user_ids))
94        .where_(rustango::tenancy::auth::User::active.eq(true))
95        .fetch(pool)
96        .await?;
97    Ok(users
98        .into_iter()
99        .filter_map(|u| u.id.get().copied())
100        .collect())
101}
102
103/// Resolve `(username, email)` pairs for every member of a role.
104/// Used for "notify members of the current task's role" — the
105/// reviewer routing.
106///
107/// ## Email source
108///
109/// The framework's `rustango_users` table (today) doesn't carry an
110/// `email` column. As a transitional measure, we look for a
111/// per-user `data.email` JSON entry (set by the host app when
112/// provisioning users); when absent, falls back to
113/// `<username>@<tenant_slug>.invalid` so logs surface who *would*
114/// have been notified. Once the framework adds a first-class email
115/// column, swap the lookup to the column and delete this fallback.
116///
117/// # Errors
118/// Driver / query failures.
119pub async fn role_member_emails(
120    pool: &rustango::sql::Pool,
121    role_id: i64,
122    tenant_slug: &str,
123) -> Result<Vec<(String, String)>, rustango::sql::ExecError> {
124    use rustango::core::Column as _;
125    use rustango::sql::FetcherPool as _;
126    let memberships: Vec<rustango::tenancy::permissions::UserRole> =
127        rustango::tenancy::permissions::UserRole::objects()
128            .where_(rustango::tenancy::permissions::UserRole::role_id.eq(role_id))
129            .fetch(pool)
130            .await?;
131    let user_ids: Vec<i64> = memberships.iter().map(|m| m.user_id).collect();
132    if user_ids.is_empty() {
133        return Ok(Vec::new());
134    }
135    let users: Vec<rustango::tenancy::auth::User> = rustango::tenancy::auth::User::objects()
136        .where_(rustango::tenancy::auth::User::id.is_in(user_ids))
137        .where_(rustango::tenancy::auth::User::active.eq(true))
138        .fetch(pool)
139        .await?;
140    Ok(users
141        .into_iter()
142        .map(|u| (u.username.clone(), email_for(&u, tenant_slug)))
143        .collect())
144}
145
146/// Resolve the `(username, email)` pair for a single user.
147///
148/// # Errors
149/// Driver / query failures.
150pub async fn user_email(
151    pool: &rustango::sql::Pool,
152    user_id: i64,
153    tenant_slug: &str,
154) -> Result<Option<(String, String)>, rustango::sql::ExecError> {
155    use rustango::core::Column as _;
156    use rustango::sql::FetcherPool as _;
157    let rows: Vec<rustango::tenancy::auth::User> = rustango::tenancy::auth::User::objects()
158        .where_(rustango::tenancy::auth::User::id.eq(user_id))
159        .fetch(pool)
160        .await?;
161    Ok(rows
162        .into_iter()
163        .next()
164        .map(|u| (u.username.clone(), email_for(&u, tenant_slug))))
165}
166
167/// Look up an email for a user: first the `data.email` JSON field
168/// (per-user prefs), then a synthetic
169/// `<username>@<tenant_slug>.invalid` fallback that surfaces in
170/// the mailer's logs but isn't a real address.
171fn email_for(user: &rustango::tenancy::auth::User, tenant_slug: &str) -> String {
172    if let Some(email) = user.data.get("email").and_then(|v| v.as_str()) {
173        if !email.trim().is_empty() {
174            return email.to_owned();
175        }
176    }
177    format!("{}@{}.invalid", user.username, tenant_slug)
178}
179
180/// Compose the standard subject + body for a workflow event.
181/// Format kept deliberately plain — production deployments can
182/// override by replacing the call site with a Tera-rendered body.
183#[must_use]
184pub fn render_notification(
185    event: &str,
186    workflow_name: &str,
187    page_title: &str,
188    page_id: i64,
189    task_name: Option<&str>,
190    actor_username: Option<&str>,
191    comment: Option<&str>,
192) -> (String, String) {
193    let subject = match event {
194        "submit" => format!("[{workflow_name}] Review requested: {page_title}"),
195        "approve_advance" => format!(
196            "[{workflow_name}] Approved on “{task}” — moves to you for next step: {page_title}",
197            task = task_name.unwrap_or("step")
198        ),
199        "approve_finish" => format!("[{workflow_name}] Approved — {page_title} is now published"),
200        "reject" => format!("[{workflow_name}] Changes requested on {page_title}"),
201        "cancel" => format!("[{workflow_name}] Review cancelled: {page_title}"),
202        _ => format!("[{workflow_name}] {event}: {page_title}"),
203    };
204
205    let mut body = String::with_capacity(256);
206    body.push_str(&format!("Page: {page_title}\n"));
207    body.push_str(&format!("Workflow: {workflow_name}\n"));
208    if let Some(t) = task_name {
209        body.push_str(&format!("Task: {t}\n"));
210    }
211    if let Some(actor) = actor_username {
212        body.push_str(&format!("Actor: {actor}\n"));
213    }
214    body.push('\n');
215    let summary = match event {
216        "submit" => "A page has been submitted for your review. Open the editor to approve or request changes.",
217        "approve_advance" => "The current step has been approved. The page is now waiting on your review.",
218        "approve_finish" => "The page has been approved by every reviewer and is now published.",
219        "reject" => "A reviewer has requested changes. Edit the page and resubmit when ready.",
220        "cancel" => "The review has been cancelled. The page returns to its current status.",
221        other => other,
222    };
223    body.push_str(summary);
224    body.push_str("\n\n");
225    if let Some(c) = comment {
226        if !c.trim().is_empty() {
227            body.push_str("Reviewer comment:\n");
228            body.push_str(c);
229            body.push_str("\n\n");
230        }
231    }
232    body.push_str(&format!("Edit: /cms-admin/pages/{page_id}/edit\n"));
233    (subject, body)
234}