Skip to main content

rustango_cms/
page_subscription.rs

1//! Per-user opt-in subscriptions to page publish events.
2//!
3//! Editors / stakeholders subscribe to pages they care about and
4//! receive an email when the page transitions into Published. Fires
5//! from the same three publish paths the `after_publish_page` hook
6//! does (single page edit, bulk publish, workflow auto-publish).
7//!
8//! Notification delivery is best-effort and depends on the host
9//! having wired a mailer via `router_with_mailer` / `with_mailer_from`.
10//! Hosts that haven't wired one log a debug line and skip — no
11//! invariants broken.
12
13use chrono::{DateTime, Utc};
14use rustango::sql::Auto;
15use rustango::Model;
16use serde::{Deserialize, Serialize};
17
18#[derive(Model, Debug, Clone, Serialize, Deserialize)]
19#[rustango(
20    table = "cms_page_subscription",
21    app = "cms",
22    display = "id",
23    admin(
24        list_display = "page_id, user_id, comment_notifications, created_at",
25        ordering = "page_id, user_id",
26    )
27)]
28pub struct PageSubscription {
29    #[rustango(primary_key)]
30    pub id: Auto<i64>,
31
32    #[rustango(fk = "cms_page", on = "id", index)]
33    pub page_id: i64,
34
35    #[rustango(fk = "rustango_users", on = "id", index)]
36    pub user_id: i64,
37
38    /// Bonus track — when set, also notify on new comments.
39    /// Defaults to false so subscriptions stay scoped to publish
40    /// events; opt-in to broader notifications explicitly.
41    #[rustango(default = "false")]
42    pub comment_notifications: bool,
43
44    #[rustango(auto_now_add)]
45    pub created_at: Auto<DateTime<Utc>>,
46}
47
48/// Whether `user_id` has an active subscription on `page_id`.
49///
50/// # Errors
51/// Driver / query failures.
52pub async fn is_subscribed(
53    pool: &rustango::sql::Pool,
54    page_id: i64,
55    user_id: i64,
56) -> Result<bool, rustango::sql::ExecError> {
57    use rustango::core::Column as _;
58    use rustango::sql::FetcherPool as _;
59    let rows: Vec<PageSubscription> = PageSubscription::objects()
60        .where_(PageSubscription::page_id.eq(page_id))
61        .where_(PageSubscription::user_id.eq(user_id))
62        .fetch(pool)
63        .await?;
64    Ok(!rows.is_empty())
65}
66
67/// Subscribe `user_id` to publish events for `page_id`. Idempotent —
68/// re-subscribing does not insert a duplicate row.
69///
70/// # Errors
71/// Driver / query failures.
72pub async fn subscribe(
73    pool: &rustango::sql::Pool,
74    page_id: i64,
75    user_id: i64,
76) -> Result<PageSubscription, rustango::sql::ExecError> {
77    use rustango::core::Column as _;
78    use rustango::sql::FetcherPool as _;
79    let existing: Vec<PageSubscription> = PageSubscription::objects()
80        .where_(PageSubscription::page_id.eq(page_id))
81        .where_(PageSubscription::user_id.eq(user_id))
82        .fetch(pool)
83        .await?;
84    if let Some(row) = existing.into_iter().next() {
85        return Ok(row);
86    }
87    let mut row = PageSubscription {
88        id: Auto::Unset,
89        page_id,
90        user_id,
91        comment_notifications: false,
92        created_at: Auto::Unset,
93    };
94    row.insert(pool).await?;
95    Ok(row)
96}
97
98/// Remove `user_id`'s subscription on `page_id`. No-op when no row
99/// exists. Returns the number of rows deleted (0 or 1).
100///
101/// # Errors
102/// Driver / query failures.
103pub async fn unsubscribe(
104    pool: &rustango::sql::Pool,
105    page_id: i64,
106    user_id: i64,
107) -> Result<usize, rustango::sql::ExecError> {
108    use rustango::core::Column as _;
109    use rustango::sql::FetcherPool as _;
110    let existing: Vec<PageSubscription> = PageSubscription::objects()
111        .where_(PageSubscription::page_id.eq(page_id))
112        .where_(PageSubscription::user_id.eq(user_id))
113        .fetch(pool)
114        .await?;
115    let mut removed = 0;
116    for row in existing {
117        row.delete(pool).await?;
118        removed += 1;
119    }
120    Ok(removed)
121}
122
123/// Every subscriber of `page_id`. Used by the notification fan-out
124/// when a page publishes.
125///
126/// # Errors
127/// Driver / query failures.
128pub async fn subscribers_for_page(
129    pool: &rustango::sql::Pool,
130    page_id: i64,
131) -> Result<Vec<PageSubscription>, rustango::sql::ExecError> {
132    use rustango::core::Column as _;
133    use rustango::sql::FetcherPool as _;
134    PageSubscription::objects()
135        .where_(PageSubscription::page_id.eq(page_id))
136        .fetch(pool)
137        .await
138}
139
140/// Compose the publish-notification subject + body for one page.
141#[must_use]
142pub fn render_publish_notification(
143    page_title: &str,
144    page_url: &str,
145    actor_username: Option<&str>,
146) -> (String, String) {
147    let subject = format!("Published: {page_title}");
148    let actor_line = actor_username
149        .map(|u| format!("Published by: {u}\n"))
150        .unwrap_or_default();
151    let body = format!(
152        "“{page_title}” just went live.\n\n\
153         {actor_line}\
154         View live: {page_url}\n\n\
155         You're receiving this because you subscribed to publish notifications for this page in the CMS.\n\
156         To stop receiving these, open the page editor and click \"Unsubscribe\" on the Status side panel.\n"
157    );
158    (subject, body)
159}
160
161/// Fan out a publish notification to every subscriber of `page_id`.
162/// Best-effort — if the mailer is missing or any send fails, the
163/// publish itself is unaffected.
164pub async fn notify_publish(
165    mailer: Option<&dyn rustango::email::Mailer>,
166    from: &str,
167    pool: &rustango::sql::Pool,
168    tenant_slug: &str,
169    page_id: i64,
170    page_title: &str,
171    page_url: &str,
172    actor_username: Option<&str>,
173) {
174    let Some(mailer) = mailer else {
175        return;
176    };
177    let subs = match subscribers_for_page(pool, page_id).await {
178        Ok(rows) => rows,
179        Err(e) => {
180            tracing::warn!(
181                target: "rustango_cms::page_subscription",
182                page_id, error = %e,
183                "subscribers lookup failed; skipping notify"
184            );
185            return;
186        }
187    };
188    if subs.is_empty() {
189        return;
190    }
191    // #197 — drop subscribers who have muted the publish category
192    // before resolving emails. Default-enabled, so the first-touch
193    // user still gets a notification.
194    let sub_user_ids: Vec<i64> = subs.iter().map(|s| s.user_id).collect();
195    let allowed: std::collections::HashSet<i64> = crate::notification_pref::filter_enabled(
196        pool,
197        &sub_user_ids,
198        crate::notification_pref::PAGE_PUBLISHED_SUBSCRIBED,
199    )
200    .await
201    .map(|v| v.into_iter().collect())
202    .unwrap_or_else(|_| sub_user_ids.iter().copied().collect());
203    let subs: Vec<_> = subs
204        .into_iter()
205        .filter(|s| allowed.contains(&s.user_id))
206        .collect();
207    if subs.is_empty() {
208        return;
209    }
210    // Skip notifying the actor (they don't need an email about
211    // their own publish). Match by user id; fall back to no-skip
212    // when actor isn't identifiable.
213    let mut pairs: Vec<(String, String)> = Vec::with_capacity(subs.len());
214    for sub in subs {
215        match crate::workflow_mail::user_email(pool, sub.user_id, tenant_slug).await {
216            Ok(Some(pair)) => pairs.push(pair),
217            Ok(None) => {}
218            Err(e) => {
219                tracing::warn!(
220                    target: "rustango_cms::page_subscription",
221                    user_id = sub.user_id, error = %e,
222                    "subscriber email lookup failed; skipping",
223                );
224            }
225        }
226    }
227    if let Some(actor) = actor_username {
228        pairs.retain(|(username, _)| username != actor);
229    }
230    if pairs.is_empty() {
231        return;
232    }
233    let (subject, body) = render_publish_notification(page_title, page_url, actor_username);
234    crate::workflow_mail::notify_many(mailer, from, &pairs, &subject, &body).await;
235}
236
237/// Compose the subject + body for the pre-publish reminder.
238/// Mirrors `render_publish_notification` but flags that the publish
239/// hasn't happened yet so subscribers can intervene.
240#[must_use]
241pub fn render_pre_publish_notification(
242    page_title: &str,
243    page_url: &str,
244    go_live_at: chrono::DateTime<chrono::Utc>,
245) -> (String, String) {
246    let subject = format!("Publishing soon: {page_title}");
247    let body = format!(
248        "Heads up — “{page_title}” is scheduled to publish at {go_live_at}.\n\n         \
249         View live (once published): {page_url}\n\n         \
250         You're receiving this because you subscribed to publish notifications for this page in the CMS.\n         \
251         To stop receiving these, open the page editor and click \"Unsubscribe\" on the Status side panel.\n",
252        page_title = page_title,
253        go_live_at = go_live_at.to_rfc3339(),
254        page_url = page_url,
255    );
256    (subject, body)
257}
258
259/// Fan out a pre-publish reminder. Called from the schedule
260/// sweep when a page's `go_live_at` is within the next hour. Same
261/// muting + actor-skip semantics as [`notify_publish`].
262pub async fn notify_pre_publish(
263    mailer: Option<&dyn rustango::email::Mailer>,
264    from: &str,
265    pool: &rustango::sql::Pool,
266    tenant_slug: &str,
267    page_id: i64,
268    page_title: &str,
269    page_url: &str,
270    go_live_at: chrono::DateTime<chrono::Utc>,
271) {
272    let Some(mailer) = mailer else {
273        return;
274    };
275    let subs = match subscribers_for_page(pool, page_id).await {
276        Ok(rows) => rows,
277        Err(e) => {
278            tracing::warn!(
279                target: "rustango_cms::page_subscription",
280                page_id, error = %e,
281                "subscribers lookup failed; skipping pre-publish notify"
282            );
283            return;
284        }
285    };
286    if subs.is_empty() {
287        return;
288    }
289    let sub_user_ids: Vec<i64> = subs.iter().map(|s| s.user_id).collect();
290    let allowed: std::collections::HashSet<i64> = crate::notification_pref::filter_enabled(
291        pool,
292        &sub_user_ids,
293        crate::notification_pref::PAGE_PUBLISHED_SUBSCRIBED,
294    )
295    .await
296    .map(|v| v.into_iter().collect())
297    .unwrap_or_else(|_| sub_user_ids.iter().copied().collect());
298    let subs: Vec<_> = subs
299        .into_iter()
300        .filter(|s| allowed.contains(&s.user_id))
301        .collect();
302    if subs.is_empty() {
303        return;
304    }
305    let mut pairs: Vec<(String, String)> = Vec::with_capacity(subs.len());
306    for sub in subs {
307        match crate::workflow_mail::user_email(pool, sub.user_id, tenant_slug).await {
308            Ok(Some(pair)) => pairs.push(pair),
309            Ok(None) => {}
310            Err(e) => {
311                tracing::warn!(
312                    target: "rustango_cms::page_subscription",
313                    user_id = sub.user_id, error = %e,
314                    "subscriber email lookup failed; skipping",
315                );
316            }
317        }
318    }
319    if pairs.is_empty() {
320        return;
321    }
322    let (subject, body) = render_pre_publish_notification(page_title, page_url, go_live_at);
323    crate::workflow_mail::notify_many(mailer, from, &pairs, &subject, &body).await;
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    #[test]
331    fn subject_includes_page_title() {
332        let (subject, _) = render_publish_notification("Spring sale", "https://x/", None);
333        assert!(subject.contains("Spring sale"));
334        assert!(subject.starts_with("Published:"));
335    }
336
337    #[test]
338    fn body_mentions_actor_when_present() {
339        let (_, body) = render_publish_notification("X", "https://y/", Some("alice"));
340        assert!(body.contains("Published by: alice"));
341    }
342
343    #[test]
344    fn body_skips_actor_line_when_absent() {
345        let (_, body) = render_publish_notification("X", "https://y/", None);
346        assert!(!body.contains("Published by:"));
347    }
348
349    #[test]
350    fn body_includes_unsubscribe_hint() {
351        let (_, body) = render_publish_notification("X", "https://y/", None);
352        assert!(body.contains("Unsubscribe"));
353    }
354}