Skip to main content

rustango_cms/notify/
targets.rs

1//! Keeping a form's `notify_emails` setting and the target table in step.
2
3use rustango::core::Column as _;
4use rustango::sql::{ExecError, FetcherPool as _, Pool};
5
6use super::model::NotificationTarget;
7
8/// Marks a target this code owns, so a sync can rewrite it without
9/// clobbering one an editor made by hand.
10pub const MANAGED_BY_FORM: &str = "form_settings";
11
12/// Mirror a form's `notify_emails` into a real target.
13///
14/// Form settings had their own recipient list and their own send loop. Rather
15/// than keep a second notification path alive beside the new one — with its
16/// own bugs and no retries — the setting becomes an ordinary email target
17/// scoped to that form. It then gains the outbox, the delivery log and the
18/// retry button for free, and shows up in the admin next to Slack and Teams
19/// instead of being invisible unless you open the form.
20///
21/// Idempotent: creates, updates, or removes the managed target to match
22/// `emails`. Hand-made targets for the same form are untouched.
23///
24/// # Errors
25/// Driver / query failures.
26pub async fn sync_form_email(
27    pool: &Pool,
28    form_id: i64,
29    form_title: &str,
30    emails: &str,
31) -> Result<(), ExecError> {
32    let existing: Vec<NotificationTarget> = NotificationTarget::objects()
33        .where_(NotificationTarget::source_id.eq(form_id))
34        .where_(NotificationTarget::kind.eq("email".to_owned()))
35        .fetch(pool)
36        .await?;
37    let mut managed = existing.into_iter().find(|t| {
38        t.config_map().get("managed_by").map(String::as_str) == Some(MANAGED_BY_FORM)
39    });
40
41    let clean: Vec<&str> = emails
42        .split(',')
43        .map(str::trim)
44        .filter(|s| !s.is_empty())
45        .collect();
46
47    if clean.is_empty() {
48        // Cleared in the form editor → the target goes too, otherwise
49        // turning notifications off in one place leaves them on in another.
50        if let Some(t) = managed {
51            t.delete(pool).await?;
52        }
53        return Ok(());
54    }
55
56    // Writing a target encrypts its `secret` column (empty here, but still
57    // encrypted), and the framework's cast panics without the key. Say so
58    // instead: this runs on every boot, so a panic would stop the site from
59    // starting the moment an editor typed a notification address.
60    if std::env::var_os("RUSTANGO_SECRET_KEY").is_none() {
61        return Err(ExecError::Driver(rustango::sql::sqlx::Error::Configuration(
62            "RUSTANGO_SECRET_KEY is not set, so email notifications can't be stored".into(),
63        )));
64    }
65
66    let config = serde_json::json!({
67        "recipients": clean.join(", "),
68        "managed_by": MANAGED_BY_FORM,
69    })
70    .to_string();
71    let label = format!("{form_title} — email");
72
73    match managed.take() {
74        Some(mut t) => {
75            t.label = label;
76            t.config = config;
77            t.events = "form.submitted".to_owned();
78            t.enabled = true;
79            t.save(pool).await?;
80        }
81        None => {
82            let mut row = NotificationTarget {
83                id: rustango::sql::Auto::Unset,
84                label,
85                kind: "email".to_owned(),
86                config,
87                // No secret: the mailer holds the credentials, not the target.
88                secret: rustango::casts::Cast::new(String::new().into()),
89                events: "form.submitted".to_owned(),
90                source_id: form_id,
91                enabled: true,
92                created_at: rustango::sql::Auto::Unset,
93            };
94            row.insert(pool).await?;
95        }
96    }
97    Ok(())
98}