laravel-template-engine 0.2.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! What an editor needs: checking, saving, previewing and test sends.

use laravel::db::Json;
use laravel::model::{create, update};

use crate::assets::{Assets, assets, inline_images};
use crate::config::config;
use crate::mail::deliver;
use crate::render::{RenderedMail, pick_locale, render_document, sandbox};
use crate::sandbox::FilterSpec;
use crate::schema::find_type;
use crate::template::{Kind, Settings, Template, TemplateInput};
use crate::validate::{Issue, check_input};
use crate::{Document, Recipient, TemplateError};

/// Checks a template: the syntax of every text, that each variable exists in its type, that
/// `for` goes over lists, the filters and their arguments, and the settings. An empty list means
/// the template can be saved.
///
/// # Errors
///
/// Fails when the database can't be read to check attached documents.
pub async fn check(input: &TemplateInput) -> laravel::Result<Vec<Issue>> {
    let assets = assets().await?;
    let mut issues = check_input(
        input,
        &specs(&assets),
        &assets.image_names(),
        &assets.layout_names(),
        &config(),
    );
    if let Settings::Mail(mail) = &input.settings {
        for (i, id) in mail.attach_documents.iter().enumerate() {
            let field = format!("settings.attach_documents.{i}");
            match Template::find(*id).await? {
                Some(t) if t.kind == Kind::Document && t.type_key == input.type_key => {}
                Some(_) => issues.push(issue(
                    field,
                    "unknown_document",
                    format!("Template {id} isn't a document of this type."),
                )),
                None => issues.push(issue(
                    field,
                    "unknown_document",
                    format!("There's no document template {id}."),
                )),
            }
        }
    }
    Ok(issues)
}

fn issue(field: String, code: &'static str, message: String) -> Issue {
    Issue {
        field,
        line: None,
        column: None,
        code,
        message,
        suggestion: None,
    }
}

async fn ensure_valid(input: &TemplateInput) -> laravel::Result<()> {
    let issues = check(input).await?;
    if issues.is_empty() {
        Ok(())
    } else {
        Err(TemplateError::Invalid(issues).into())
    }
}

/// Checks and saves a new template. Dispatches `Created<Template>`.
///
/// # Errors
///
/// Fails with [`TemplateError::Invalid`] and the issues when the template has mistakes, or when
/// the database fails.
pub async fn create(input: TemplateInput) -> laravel::Result<Template> {
    ensure_valid(&input).await?;
    let content = Json(input.content);
    let settings = input.settings.to_json();
    let kind = input.settings.kind();
    create!(Template {
        type_key: input.type_key,
        kind,
        name: input.name,
        is_active: input.is_active,
        content,
        settings,
        ..
    })
    .await
}

/// Checks and saves changes to a template. Dispatches `Updated<Template>`.
///
/// # Errors
///
/// Fails with [`TemplateError::Invalid`] and the issues when the template has mistakes, or when
/// the database fails.
pub async fn update(mut template: Template, input: TemplateInput) -> laravel::Result<Template> {
    ensure_valid(&input).await?;
    let content = Json(input.content);
    let settings = input.settings.to_json();
    let kind = input.settings.kind();
    update!(template {
        type_key: input.type_key,
        kind,
        name: input.name,
        is_active: input.is_active,
        content,
        settings,
    })
    .await?;
    Ok(template)
}

/// A rendered preview.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Preview {
    /// An email: subject, HTML and text.
    Mail(RenderedMail),
    /// A document. With the `pdf` feature its bytes are the PDF; its `html` is there either way.
    Document(Document),
}

/// Renders a template, saved or not, with its type's example data, in `locale` or the closest
/// language it has.
///
/// # Errors
///
/// Fails with [`TemplateError::Invalid`] when the template has mistakes, or
/// [`TemplateError::Render`] when it doesn't render.
pub async fn preview(input: &TemplateInput, locale: Option<&str>) -> laravel::Result<Preview> {
    let assets = assets().await?;
    let issues = check_input(
        input,
        &specs(&assets),
        &assets.image_names(),
        &assets.layout_names(),
        &config(),
    );
    if !issues.is_empty() {
        return Err(TemplateError::Invalid(issues).into());
    }
    let info = find_type(&input.type_key).ok_or_else(|| TemplateError::UnknownType(input.type_key.clone()))?;
    let data = info.example()?;
    let config = config();
    let (chosen, content) = pick_locale(&input.content, locale, &config.locale)
        .ok_or_else(|| TemplateError::Render("the template has no text".to_owned()))?;
    let sandbox = sandbox(chosen, &assets, &config);
    match &input.settings {
        Settings::Mail(settings) => {
            let layout = assets.layout(settings.layout.as_deref());
            let mut mail = crate::render::render_mail(&sandbox, chosen, content, &data, layout)?;
            // A browser shows the pictures the email attaches as `data:` URIs.
            mail.html = inline_images(&mail.html, &assets);
            Ok(Preview::Mail(mail))
        }
        Settings::Document(settings) => Ok(Preview::Document(render_document(
            &sandbox, chosen, content, settings, &data, &assets,
        )?)),
    }
}

fn specs(assets: &Assets) -> Vec<FilterSpec> {
    assets.filters.iter().map(|f| f.spec.clone()).collect()
}

/// Sends a saved email template to `address` only, with its type's example data, now rather than
/// through the queue. The subject starts with `TEMPLATE_ENGINE_TEST_PREFIX`; the template's own
/// recipients get nothing.
///
/// # Errors
///
/// Fails when the template isn't an email template, doesn't render, or the mailer fails.
pub async fn send_test(template_id: i64, address: &str, locale: Option<&str>) -> laravel::Result<()> {
    let template = Template::find(template_id)
        .await?
        .ok_or(TemplateError::NotFound(template_id))?;
    let info = find_type(&template.type_key).ok_or_else(|| TemplateError::UnknownType(template.type_key.clone()))?;
    let data = info.example()?;
    let mut to = Recipient::new(address);
    to.locale = locale.map(ToOwned::to_owned);
    let mut template = template;
    // Only the given address: the template's own `cc` and `bcc` are left out of a test.
    if let Ok(Settings::Mail(mut settings)) = template.typed_settings() {
        settings.cc.clear();
        settings.bcc.clear();
        template.settings = Settings::Mail(settings).to_json();
    }
    deliver(&template, &data, &to, Vec::new(), Some(&config().test_prefix)).await
}