Skip to main content

rustango_cms/
notification_pref.rs

1//! Per-user notification preferences.
2//!
3//! Editors opt out of categories of notifications they don't want
4//! to receive. Every fire-site (`workflow_mail`, `page_subscription`,
5//! comment replies) checks [`is_enabled`] before delivering so the
6//! mailer doesn't burn cycles building emails for unsubscribed users.
7//!
8//! Missing rows are treated as **enabled** — first-touch users get
9//! every notification until they explicitly disable a category. This
10//! matches the principle of least surprise: a new editor hears about
11//! everything, then trims.
12
13use rustango::sql::Auto;
14use rustango::Model;
15use serde::{Deserialize, Serialize};
16
17/// Every category an editor can mute. String keys (not an enum)
18/// because the set is editor-facing and host plugins may
19/// register their own kinds via the same table.
20pub const WORKFLOW_SUBMITTED: &str = "workflow_submitted";
21pub const WORKFLOW_APPROVED: &str = "workflow_approved";
22pub const WORKFLOW_REJECTED: &str = "workflow_rejected";
23pub const COMMENT_REPLIED: &str = "comment_replied";
24pub const COMMENT_RESOLVED: &str = "comment_resolved";
25pub const PAGE_PUBLISHED_SUBSCRIBED: &str = "page_published_subscribed";
26
27/// The full canonical list — rendered in order on the preferences
28/// page. (label, kind, hint) for each row.
29pub const ALL_KINDS: &[(&str, &str, &str)] = &[
30    (
31        "Workflow: review requested",
32        WORKFLOW_SUBMITTED,
33        "A page enters a workflow step that you can approve / reject.",
34    ),
35    (
36        "Workflow: approved",
37        WORKFLOW_APPROVED,
38        "A page you submitted has been approved and published.",
39    ),
40    (
41        "Workflow: rejected / cancelled",
42        WORKFLOW_REJECTED,
43        "A reviewer requested changes or the workflow was cancelled.",
44    ),
45    (
46        "Comments: replies",
47        COMMENT_REPLIED,
48        "Someone replied to a comment thread you participate in.",
49    ),
50    (
51        "Comments: resolved",
52        COMMENT_RESOLVED,
53        "A comment thread you participate in was marked resolved.",
54    ),
55    (
56        "Page subscriptions",
57        PAGE_PUBLISHED_SUBSCRIBED,
58        "A page you subscribed to via the page editor is published.",
59    ),
60];
61
62#[derive(Model, Debug, Clone, Serialize, Deserialize)]
63#[rustango(
64    table = "cms_notification_pref",
65    app = "cms",
66    display = "kind",
67    admin(list_display = "user_id, kind, enabled", ordering = "user_id, kind",)
68)]
69pub struct NotificationPref {
70    #[rustango(primary_key)]
71    pub id: Auto<i64>,
72
73    #[rustango(fk = "rustango_users", on = "id", index)]
74    pub user_id: i64,
75
76    #[rustango(max_length = 64, index)]
77    pub kind: String,
78
79    pub enabled: bool,
80}
81
82/// Whether `user_id` wants to receive notifications of `kind`. A
83/// missing row is treated as `true` — opt-out semantics.
84///
85/// # Errors
86/// Driver / query failures.
87pub async fn is_enabled(
88    pool: &rustango::sql::Pool,
89    user_id: i64,
90    kind: &str,
91) -> Result<bool, rustango::sql::ExecError> {
92    use rustango::core::Column as _;
93    use rustango::sql::FetcherPool as _;
94    let rows: Vec<NotificationPref> = NotificationPref::objects()
95        .where_(NotificationPref::user_id.eq(user_id))
96        .where_(NotificationPref::kind.eq(kind.to_owned()))
97        .fetch(pool)
98        .await?;
99    Ok(rows.into_iter().next().is_none_or(|r| r.enabled))
100}
101
102/// Upsert the toggle for `(user_id, kind)`.
103///
104/// # Errors
105/// Driver / query failures.
106pub async fn set_enabled(
107    pool: &rustango::sql::Pool,
108    user_id: i64,
109    kind: &str,
110    enabled: bool,
111) -> Result<(), rustango::sql::ExecError> {
112    use rustango::core::Column as _;
113    use rustango::sql::FetcherPool as _;
114    let rows: Vec<NotificationPref> = NotificationPref::objects()
115        .where_(NotificationPref::user_id.eq(user_id))
116        .where_(NotificationPref::kind.eq(kind.to_owned()))
117        .fetch(pool)
118        .await?;
119    if let Some(mut row) = rows.into_iter().next() {
120        row.enabled = enabled;
121        row.save_pool(pool).await?;
122    } else {
123        let mut row = NotificationPref {
124            id: Auto::Unset,
125            user_id,
126            kind: kind.to_owned(),
127            enabled,
128        };
129        row.insert_pool(pool).await?;
130    }
131    Ok(())
132}
133
134/// Every preference row for a user, keyed by kind.
135///
136/// # Errors
137/// Driver / query failures.
138pub async fn map_for_user(
139    pool: &rustango::sql::Pool,
140    user_id: i64,
141) -> Result<std::collections::HashMap<String, bool>, rustango::sql::ExecError> {
142    use rustango::core::Column as _;
143    use rustango::sql::FetcherPool as _;
144    let rows: Vec<NotificationPref> = NotificationPref::objects()
145        .where_(NotificationPref::user_id.eq(user_id))
146        .fetch(pool)
147        .await?;
148    Ok(rows.into_iter().map(|r| (r.kind, r.enabled)).collect())
149}
150
151/// Filter `user_ids` to those who haven't opted out of `kind`.
152/// Missing rows are kept (default = enabled). Used at fan-out sites
153/// to skip email composition for muted users.
154///
155/// # Errors
156/// Driver / query failures.
157pub async fn filter_enabled(
158    pool: &rustango::sql::Pool,
159    user_ids: &[i64],
160    kind: &str,
161) -> Result<Vec<i64>, rustango::sql::ExecError> {
162    use rustango::core::Column as _;
163    use rustango::sql::FetcherPool as _;
164    if user_ids.is_empty() {
165        return Ok(Vec::new());
166    }
167    let rows: Vec<NotificationPref> = NotificationPref::objects()
168        .where_(NotificationPref::user_id.is_in(user_ids.to_vec()))
169        .where_(NotificationPref::kind.eq(kind.to_owned()))
170        .fetch(pool)
171        .await?;
172    let disabled: std::collections::HashSet<i64> = rows
173        .into_iter()
174        .filter(|r| !r.enabled)
175        .map(|r| r.user_id)
176        .collect();
177    Ok(user_ids
178        .iter()
179        .copied()
180        .filter(|id| !disabled.contains(id))
181        .collect())
182}
183
184/// Map a workflow event name to the preference kind a recipient
185/// uses to mute it. Centralised so the routing stays consistent
186/// across every workflow notification call site.
187#[must_use]
188pub fn pref_kind_for_workflow_event(event: &str) -> &'static str {
189    match event {
190        "submit" | "approve_advance" => WORKFLOW_SUBMITTED,
191        "approve_finish" => WORKFLOW_APPROVED,
192        "reject" | "cancel" => WORKFLOW_REJECTED,
193        _ => WORKFLOW_SUBMITTED,
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn pref_kind_routes_workflow_events() {
203        assert_eq!(pref_kind_for_workflow_event("submit"), WORKFLOW_SUBMITTED);
204        assert_eq!(
205            pref_kind_for_workflow_event("approve_advance"),
206            WORKFLOW_SUBMITTED
207        );
208        assert_eq!(
209            pref_kind_for_workflow_event("approve_finish"),
210            WORKFLOW_APPROVED
211        );
212        assert_eq!(pref_kind_for_workflow_event("reject"), WORKFLOW_REJECTED);
213        assert_eq!(pref_kind_for_workflow_event("cancel"), WORKFLOW_REJECTED);
214        assert_eq!(pref_kind_for_workflow_event("unknown"), WORKFLOW_SUBMITTED);
215    }
216
217    #[test]
218    fn all_kinds_lists_six_categories() {
219        assert_eq!(ALL_KINDS.len(), 6);
220        let kinds: Vec<&str> = ALL_KINDS.iter().map(|(_, k, _)| *k).collect();
221        assert!(kinds.contains(&WORKFLOW_SUBMITTED));
222        assert!(kinds.contains(&PAGE_PUBLISHED_SUBSCRIBED));
223    }
224}