laravel-template-engine 0.5.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! Notification texts: people write them, Laravel's notifications deliver them over any channel.

use std::fmt;

use crate::TemplateError;
use crate::assets::{Assets, assets};
use crate::config::TemplateEngineConfig;
use crate::events::TemplateRendered;
use crate::render::{current_config, pick_locale, render_text, sandbox};
use crate::sandbox::Escape;
use crate::schema::TemplateType;
use crate::template::{Kind, Settings, Template};

/// A notification's text for one channel, rendered.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedText {
    /// The language of the text that was used.
    pub locale: String,
    /// The title, for channels that have one, such as push; often empty.
    pub subject: String,
    /// The text.
    pub body: String,
}

/// A channel notification templates can write for, such as `sms`, `slack` or `telegram`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Channel {
    /// The name the application's notification asks for.
    pub name: String,
    /// What it is, for the people editing templates.
    pub description: String,
}

/// The channels every application knows: Laravel's own `sms` and `slack`.
pub(crate) fn builtin_channels() -> Vec<Channel> {
    vec![
        Channel {
            name: "sms".to_owned(),
            description: "Text message".to_owned(),
        },
        Channel {
            name: "slack".to_owned(),
            description: "Slack".to_owned(),
        },
    ]
}

/// The active notification templates of one type with its data, ready to render a text per
/// channel and language. Load it before sending a Laravel notification, keep it in the
/// notification, and render in its channel methods, which can't wait for the database:
///
/// ```no_run
/// # use laravel_template_engine::{NotificationTexts, Recipient, TemplateData};
/// # use serde::Serialize;
/// # #[derive(Serialize, TemplateData)]
/// # #[template(key = "order.shipped", example = OrderShipped::example)]
/// # pub struct OrderShipped { customer: Recipient, number: String }
/// # impl OrderShipped { fn example() -> Self { Self { customer: Recipient::new("a@example.com"), number: "1".into() } } }
/// # async fn run(shipped: OrderShipped) -> laravel::Result<()> {
/// let texts = laravel_template_engine::notification(&shipped).await?;
/// let sms = texts.text("sms", Some("uk"))?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct NotificationTexts {
    type_key: &'static str,
    data: serde_json::Value,
    templates: Vec<Template>,
    assets: Assets,
    config: TemplateEngineConfig,
}

impl fmt::Debug for NotificationTexts {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NotificationTexts")
            .field("type_key", &self.type_key)
            .field("channels", &self.channels())
            .finish_non_exhaustive()
    }
}

/// Loads the active notification templates of `data`'s type.
///
/// # Errors
///
/// Fails when the data doesn't serialize or the database fails.
pub async fn notification<T: TemplateType>(data: &T) -> laravel::Result<NotificationTexts> {
    let data = serde_json::to_value(data)
        .map_err(|e| laravel::Error::msg(format!("the data of `{}` doesn't serialize: {e}", T::KEY)))?;
    let templates = Template::query()
        .filter(Template::type_key.eq(T::KEY) & Template::kind.eq(Kind::Notification) & Template::is_active.eq(true))
        .order_by(Template::id.asc())
        .get()
        .await?;
    Ok(NotificationTexts {
        type_key: T::KEY,
        data,
        templates,
        assets: assets().await?,
        config: current_config(),
    })
}

impl NotificationTexts {
    /// The channels there is an active template for.
    #[must_use]
    pub fn channels(&self) -> Vec<String> {
        self.templates
            .iter()
            .filter_map(|t| channel_of(t).map(ToOwned::to_owned))
            .collect()
    }

    /// The text for `channel` in `locale`, or the closest language the template has; `None`
    /// when no active template writes for the channel.
    ///
    /// # Errors
    ///
    /// Fails when the template doesn't render.
    pub fn render(&self, channel: &str, locale: Option<&str>) -> laravel::Result<Option<RenderedText>> {
        let Some(template) = self.templates.iter().find(|t| channel_of(t) == Some(channel)) else {
            return Ok(None);
        };
        let (chosen, content) = pick_locale(&template.content.0, locale, &self.config.locale)
            .ok_or_else(|| TemplateError::Render("the template has no text".to_owned()))?;
        let sandbox = sandbox(chosen, &self.assets, &self.config);
        let subject = render_text(&sandbox, "subject", &content.subject, &self.data, Escape::None)?;
        let body = render_text(&sandbox, "body", &content.body, &self.data, Escape::None)?;
        laravel::event::dispatch_background(TemplateRendered {
            template_id: template.id,
            type_key: template.type_key.clone(),
            kind: Kind::Notification,
            locale: chosen.to_owned(),
        })?;
        Ok(Some(RenderedText {
            locale: chosen.to_owned(),
            subject: subject.trim().to_owned(),
            body: body.trim().to_owned(),
        }))
    }

    /// The text for `channel` in `locale`, for a notification's channel method.
    ///
    /// # Errors
    ///
    /// Fails with [`TemplateError::NoNotification`] when no active template writes for the
    /// channel, which aborts the notification, or when the template doesn't render.
    pub fn text(&self, channel: &str, locale: Option<&str>) -> laravel::Result<String> {
        self.render(channel, locale)?.map(|text| text.body).ok_or_else(|| {
            TemplateError::NoNotification {
                type_key: self.type_key.to_owned(),
                channel: channel.to_owned(),
            }
            .into()
        })
    }
}

fn channel_of(template: &Template) -> Option<&str> {
    template.settings.get("channel").and_then(serde_json::Value::as_str)
}

pub(crate) fn settings_channel(settings: &Settings) -> Option<&str> {
    match settings {
        Settings::Notification(notification) => Some(notification.channel.as_str()),
        _ => None,
    }
}