Skip to main content

laravel_template_engine/
notification.rs

1//! Notification texts: people write them, Laravel's notifications deliver them over any channel.
2
3use std::fmt;
4
5use crate::TemplateError;
6use crate::assets::{Assets, assets};
7use crate::config::TemplateEngineConfig;
8use crate::events::TemplateRendered;
9use crate::render::{current_config, pick_locale, render_text, sandbox};
10use crate::sandbox::Escape;
11use crate::schema::TemplateType;
12use crate::template::{Kind, Settings, Template};
13
14/// A notification's text for one channel, rendered.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct RenderedText {
17    /// The language of the text that was used.
18    pub locale: String,
19    /// The title, for channels that have one, such as push; often empty.
20    pub subject: String,
21    /// The text.
22    pub body: String,
23}
24
25/// A channel notification templates can write for, such as `sms`, `slack` or `telegram`.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Channel {
28    /// The name the application's notification asks for.
29    pub name: String,
30    /// What it is, for the people editing templates.
31    pub description: String,
32}
33
34/// The channels every application knows: Laravel's own `sms` and `slack`.
35pub(crate) fn builtin_channels() -> Vec<Channel> {
36    vec![
37        Channel {
38            name: "sms".to_owned(),
39            description: "Text message".to_owned(),
40        },
41        Channel {
42            name: "slack".to_owned(),
43            description: "Slack".to_owned(),
44        },
45    ]
46}
47
48/// The active notification templates of one type with its data, ready to render a text per
49/// channel and language. Load it before sending a Laravel notification, keep it in the
50/// notification, and render in its channel methods, which can't wait for the database:
51///
52/// ```no_run
53/// # use laravel_template_engine::{NotificationTexts, Recipient, TemplateData};
54/// # use serde::Serialize;
55/// # #[derive(Serialize, TemplateData)]
56/// # #[template(key = "order.shipped", example = OrderShipped::example)]
57/// # pub struct OrderShipped { customer: Recipient, number: String }
58/// # impl OrderShipped { fn example() -> Self { Self { customer: Recipient::new("a@example.com"), number: "1".into() } } }
59/// # async fn run(shipped: OrderShipped) -> laravel::Result<()> {
60/// let texts = laravel_template_engine::notification(&shipped).await?;
61/// let sms = texts.text("sms", Some("uk"))?;
62/// # Ok(())
63/// # }
64/// ```
65#[derive(Clone)]
66pub struct NotificationTexts {
67    type_key: &'static str,
68    data: serde_json::Value,
69    templates: Vec<Template>,
70    assets: Assets,
71    config: TemplateEngineConfig,
72}
73
74impl fmt::Debug for NotificationTexts {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.debug_struct("NotificationTexts")
77            .field("type_key", &self.type_key)
78            .field("channels", &self.channels())
79            .finish_non_exhaustive()
80    }
81}
82
83/// Loads the active notification templates of `data`'s type.
84///
85/// # Errors
86///
87/// Fails when the data doesn't serialize or the database fails.
88pub async fn notification<T: TemplateType>(data: &T) -> laravel::Result<NotificationTexts> {
89    let data = serde_json::to_value(data)
90        .map_err(|e| laravel::Error::msg(format!("the data of `{}` doesn't serialize: {e}", T::KEY)))?;
91    let templates = Template::query()
92        .filter(Template::type_key.eq(T::KEY) & Template::kind.eq(Kind::Notification) & Template::is_active.eq(true))
93        .order_by(Template::id.asc())
94        .get()
95        .await?;
96    Ok(NotificationTexts {
97        type_key: T::KEY,
98        data,
99        templates,
100        assets: assets().await?,
101        config: current_config(),
102    })
103}
104
105impl NotificationTexts {
106    /// The channels there is an active template for.
107    #[must_use]
108    pub fn channels(&self) -> Vec<String> {
109        self.templates
110            .iter()
111            .filter_map(|t| channel_of(t).map(ToOwned::to_owned))
112            .collect()
113    }
114
115    /// The text for `channel` in `locale`, or the closest language the template has; `None`
116    /// when no active template writes for the channel.
117    ///
118    /// # Errors
119    ///
120    /// Fails when the template doesn't render.
121    pub fn render(&self, channel: &str, locale: Option<&str>) -> laravel::Result<Option<RenderedText>> {
122        let Some(template) = self.templates.iter().find(|t| channel_of(t) == Some(channel)) else {
123            return Ok(None);
124        };
125        let (chosen, content) = pick_locale(&template.content.0, locale, &self.config.locale)
126            .ok_or_else(|| TemplateError::Render("the template has no text".to_owned()))?;
127        let sandbox = sandbox(chosen, &self.assets, &self.config);
128        let subject = render_text(&sandbox, "subject", &content.subject, &self.data, Escape::None)?;
129        let body = render_text(&sandbox, "body", &content.body, &self.data, Escape::None)?;
130        laravel::event::dispatch_background(TemplateRendered {
131            template_id: template.id,
132            type_key: template.type_key.clone(),
133            kind: Kind::Notification,
134            locale: chosen.to_owned(),
135        })?;
136        Ok(Some(RenderedText {
137            locale: chosen.to_owned(),
138            subject: subject.trim().to_owned(),
139            body: body.trim().to_owned(),
140        }))
141    }
142
143    /// The text for `channel` in `locale`, for a notification's channel method.
144    ///
145    /// # Errors
146    ///
147    /// Fails with [`TemplateError::NoNotification`] when no active template writes for the
148    /// channel, which aborts the notification, or when the template doesn't render.
149    pub fn text(&self, channel: &str, locale: Option<&str>) -> laravel::Result<String> {
150        self.render(channel, locale)?.map(|text| text.body).ok_or_else(|| {
151            TemplateError::NoNotification {
152                type_key: self.type_key.to_owned(),
153                channel: channel.to_owned(),
154            }
155            .into()
156        })
157    }
158}
159
160fn channel_of(template: &Template) -> Option<&str> {
161    template.settings.get("channel").and_then(serde_json::Value::as_str)
162}
163
164pub(crate) fn settings_channel(settings: &Settings) -> Option<&str> {
165    match settings {
166        Settings::Notification(notification) => Some(notification.channel.as_str()),
167        _ => None,
168    }
169}