laravel-template-engine 0.5.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! The stored templates.

use std::collections::BTreeMap;

use laravel::Enum;
use laravel::db::Json;
use laravel::model::model;
use laravel::time::Timestamp;
use serde::{Deserialize, Serialize};

/// What a template makes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Enum)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Kind {
    /// An email.
    Mail,
    /// A document, such as an invoice, in HTML or PDF.
    Document,
    /// The text of a notification for one channel, such as `sms` or `telegram`.
    Notification,
}

impl Kind {
    /// The name stored in the table: `mail` or `document`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Kind::Mail => "mail",
            Kind::Document => "document",
            Kind::Notification => "notification",
        }
    }
}

/// A template's text in one language.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Content {
    /// The email's subject. Documents don't use it.
    #[serde(default)]
    pub subject: String,
    /// The email's or the document's HTML.
    #[serde(default)]
    pub body: String,
}

impl Content {
    /// Text with a subject and a body.
    #[must_use]
    pub fn new(subject: impl Into<String>, body: impl Into<String>) -> Self {
        Self {
            subject: subject.into(),
            body: body.into(),
        }
    }
}

/// Who an email goes to and what comes with it.
///
/// `to`, `cc` and `bcc` hold recipient variables of the template type, such as `customer`, and
/// email addresses, such as `accounting@example.com`. Each address in `to` gets its own email, in
/// its own language; the `cc` and `bcc` addresses get a copy of each.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct MailSettings {
    /// The sender, such as `shop@example.com` or `Shop <shop@example.com>`. Empty means the
    /// application's `MAIL_FROM_ADDRESS`.
    pub from: Option<String>,
    /// Where replies go.
    pub reply_to: Option<String>,
    /// Who gets the email.
    pub to: Vec<String>,
    /// Who gets a copy.
    pub cc: Vec<String>,
    /// Who gets a hidden copy.
    pub bcc: Vec<String>,
    /// Keys of document templates of the same type to render and attach.
    pub attach_documents: Vec<i64>,
    /// The layout the email's text goes into, by the name it was registered under.
    pub layout: Option<String>,
}

/// The file format of a document.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DocumentFormat {
    /// A PDF, with the crate's `pdf` feature.
    #[default]
    Pdf,
    /// An HTML page.
    Html,
}

/// The paper's orientation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Orientation {
    /// Taller than wide.
    #[default]
    Portrait,
    /// Wider than tall.
    Landscape,
}

/// The space around a PDF page's text, in millimeters.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Margins {
    /// Above.
    pub top: f32,
    /// On the right.
    pub right: f32,
    /// Below.
    pub bottom: f32,
    /// On the left.
    pub left: f32,
}

impl Default for Margins {
    fn default() -> Self {
        Self::all(15.0)
    }
}

impl Margins {
    /// The same margin on every side.
    #[must_use]
    pub fn all(millimeters: f32) -> Self {
        Self {
            top: millimeters,
            right: millimeters,
            bottom: millimeters,
            left: millimeters,
        }
    }
}

/// How a document is made.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DocumentSettings {
    /// PDF or HTML.
    pub format: DocumentFormat,
    /// The paper size: `a4`, `a5`, `letter`, `legal` and so on.
    pub paper: String,
    /// Portrait or landscape.
    pub orientation: Orientation,
    /// The file's name, a template itself, such as `invoice-{{ order.number }}`. The extension is
    /// added when it's missing.
    pub filename: String,
    /// The layout the document's text goes into, by the name it was registered under.
    pub layout: Option<String>,
    /// The space around the text of a PDF page.
    pub margins: Margins,
    /// The text's font, such as `Times New Roman` or a font registered for PDFs.
    pub font_family: Option<String>,
    /// The text's size in points, such as `12`.
    pub font_size: Option<f32>,
    /// The space between lines, as a multiple of the font size, such as `1.15`.
    pub line_height: Option<f32>,
}

impl Default for DocumentSettings {
    fn default() -> Self {
        Self {
            format: DocumentFormat::Pdf,
            paper: "a4".to_owned(),
            orientation: Orientation::Portrait,
            filename: "document".to_owned(),
            layout: None,
            margins: Margins::default(),
            font_family: None,
            font_size: None,
            line_height: None,
        }
    }
}

/// Which channel a notification template writes for.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct NotificationSettings {
    /// The channel, such as `sms`, `slack` or `telegram`: the name the application's
    /// notification asks for.
    pub channel: String,
}

/// The settings of a template, by its kind.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Settings {
    /// An email's.
    Mail(MailSettings),
    /// A document's.
    Document(DocumentSettings),
    /// A notification's.
    Notification(NotificationSettings),
}

impl Settings {
    /// The default settings of `kind`.
    #[must_use]
    pub fn default_for(kind: Kind) -> Self {
        match kind {
            Kind::Mail => Settings::Mail(MailSettings::default()),
            Kind::Document => Settings::Document(DocumentSettings::default()),
            Kind::Notification => Settings::Notification(NotificationSettings::default()),
        }
    }

    /// Reads the settings of a `kind` template from JSON.
    ///
    /// # Errors
    ///
    /// Fails when the JSON doesn't fit the kind's settings.
    pub fn from_json(kind: Kind, value: &serde_json::Value) -> Result<Self, serde_json::Error> {
        let value = if value.is_null() {
            serde_json::json!({})
        } else {
            value.clone()
        };
        Ok(match kind {
            Kind::Mail => Settings::Mail(serde_json::from_value(value)?),
            Kind::Document => Settings::Document(serde_json::from_value(value)?),
            Kind::Notification => Settings::Notification(serde_json::from_value(value)?),
        })
    }

    /// The settings as JSON.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        match self {
            Settings::Mail(settings) => serde_json::to_value(settings),
            Settings::Document(settings) => serde_json::to_value(settings),
            Settings::Notification(settings) => serde_json::to_value(settings),
        }
        .unwrap_or_default()
    }

    /// The kind these settings belong to.
    #[must_use]
    pub fn kind(&self) -> Kind {
        match self {
            Settings::Mail(_) => Kind::Mail,
            Settings::Document(_) => Kind::Document,
            Settings::Notification(_) => Kind::Notification,
        }
    }
}

/// A stored template: an ordinary Laravel Rust model, so creating, updating and deleting one
/// dispatches `Created<Template>`, `Updated<Template>` and `Deleted<Template>` for audit packages.
///
/// Write templates with [`templates::create`](crate::templates::create) and
/// [`templates::update`](crate::templates::update), which check them first.
#[model(table = "template_engine_templates")]
pub struct Template {
    /// The key.
    pub id: i64,
    /// The template type, such as `order.placed`.
    pub type_key: String,
    /// Email or document.
    pub kind: Kind,
    /// A name for people, such as "Confirmation for the customer".
    pub name: String,
    /// Whether the template is used. Every active email template of a type is sent.
    #[default]
    pub is_active: bool,
    /// The text, by language: `{"uk": {"subject": "...", "body": "..."}}`.
    pub content: Json<BTreeMap<String, Content>>,
    /// The kind's settings as JSON; read them with [`Template::typed_settings`].
    pub settings: serde_json::Value,
    /// When the template was created.
    pub created_at: Option<Timestamp>,
    /// When the template was last changed.
    pub updated_at: Option<Timestamp>,
}

impl Template {
    /// The typed settings.
    ///
    /// # Errors
    ///
    /// Fails when the stored JSON doesn't fit the template's kind.
    pub fn typed_settings(&self) -> laravel::Result<Settings> {
        Settings::from_json(self.kind, &self.settings)
            .map_err(|e| laravel::Error::msg(format!("the settings of template {} are invalid: {e}", self.id)))
    }

    /// The template as input for [`templates::update`](crate::templates::update) or
    /// [`preview`](crate::templates::preview).
    ///
    /// # Errors
    ///
    /// Fails when the stored settings don't fit the template's kind.
    pub fn to_input(&self) -> laravel::Result<TemplateInput> {
        Ok(TemplateInput {
            type_key: self.type_key.clone(),
            name: self.name.clone(),
            is_active: self.is_active,
            content: self.content.0.clone(),
            settings: self.typed_settings()?,
        })
    }
}

/// A template to save, check or preview.
#[derive(Debug, Clone, PartialEq)]
pub struct TemplateInput {
    /// The template type.
    pub type_key: String,
    /// A name for people.
    pub name: String,
    /// Whether the template is used.
    pub is_active: bool,
    /// The text, by language.
    pub content: BTreeMap<String, Content>,
    /// The settings; their variant decides the kind.
    pub settings: Settings,
}

impl TemplateInput {
    /// An active email template of `type_key`, without text.
    #[must_use]
    pub fn mail(type_key: impl Into<String>, name: impl Into<String>) -> Self {
        Self::new(type_key, name, Settings::Mail(MailSettings::default()))
    }

    /// An active document template of `type_key`, without text.
    #[must_use]
    pub fn document(type_key: impl Into<String>, name: impl Into<String>) -> Self {
        Self::new(type_key, name, Settings::Document(DocumentSettings::default()))
    }

    /// An active notification template of `type_key` for `channel`, such as `sms`, without text.
    #[must_use]
    pub fn notification(type_key: impl Into<String>, name: impl Into<String>, channel: impl Into<String>) -> Self {
        let settings = NotificationSettings {
            channel: channel.into(),
        };
        Self::new(type_key, name, Settings::Notification(settings))
    }

    fn new(type_key: impl Into<String>, name: impl Into<String>, settings: Settings) -> Self {
        Self {
            type_key: type_key.into(),
            name: name.into(),
            is_active: true,
            content: BTreeMap::new(),
            settings,
        }
    }

    /// Adds the text in `locale`.
    #[must_use]
    pub fn content(mut self, locale: impl Into<String>, subject: impl Into<String>, body: impl Into<String>) -> Self {
        self.content.insert(locale.into(), Content::new(subject, body));
        self
    }

    /// The kind, from the settings.
    #[must_use]
    pub fn kind(&self) -> Kind {
        self.settings.kind()
    }
}