laravel-template-engine 0.5.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! Moving templates between environments, such as from staging to production.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::template::{Content, Kind, Settings, Template, TemplateInput};
use crate::templates;
use crate::validate::Issue;

/// The version of the export format.
pub const FORMAT: u32 = 1;

/// Templates as a file: what [`export`] makes and [`import`] reads.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExportFile {
    /// The version of the format, [`FORMAT`].
    pub format: u32,
    /// The templates, documents before emails.
    pub templates: Vec<ExportedTemplate>,
}

/// One template in an [`ExportFile`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExportedTemplate {
    /// The template type.
    pub type_key: String,
    /// Email or document.
    pub kind: Kind,
    /// The name, which identifies the template within its type.
    pub name: String,
    /// Whether it's used.
    pub is_active: bool,
    /// The text, by language.
    pub content: BTreeMap<String, Content>,
    /// The settings, without `attach_documents`.
    pub settings: serde_json::Value,
    /// The documents an email attaches, by name: keys differ between environments.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attach_documents: Vec<String>,
}

/// The templates of `type_key`, or all of them, as a file.
///
/// # Errors
///
/// Fails when the database fails.
pub async fn export(type_key: Option<&str>) -> laravel::Result<ExportFile> {
    let all = Template::query().order_by(Template::id.asc()).get().await?;
    let name_of = |id: i64| all.iter().find(|t| t.id == id).map(|t| t.name.clone());
    let mut templates: Vec<ExportedTemplate> = all
        .iter()
        .filter(|t| type_key.is_none_or(|key| t.type_key == key))
        .map(|template| {
            let mut settings = template.settings.clone();
            let attach: Vec<i64> = settings
                .get("attach_documents")
                .and_then(|ids| serde_json::from_value(ids.clone()).ok())
                .unwrap_or_default();
            if let Some(map) = settings.as_object_mut() {
                map.remove("attach_documents");
            }
            ExportedTemplate {
                type_key: template.type_key.clone(),
                kind: template.kind,
                name: template.name.clone(),
                is_active: template.is_active,
                content: template.content.0.clone(),
                settings,
                attach_documents: attach.into_iter().filter_map(name_of).collect(),
            }
        })
        .collect();
    templates.sort_by_key(|t| (t.type_key.clone(), t.kind == Kind::Mail, t.name.clone()));
    Ok(ExportFile {
        format: FORMAT,
        templates,
    })
}

/// How [`import`] treats templates that already exist.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ImportOptions {
    /// Replace templates of the same type and name. Without it they are kept as they are.
    pub overwrite: bool,
    /// Check everything and report, but change nothing.
    pub dry_run: bool,
}

/// What happened to one template of an import.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// It was created.
    Created,
    /// It existed and was replaced.
    Updated,
    /// It existed and was kept as it was.
    Kept,
    /// It has mistakes, or its type doesn't exist here, so it was left out.
    Failed(Vec<Issue>),
}

/// One line of an [`ImportReport`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportEntry {
    /// The template type.
    pub type_key: String,
    /// The template's name.
    pub name: String,
    /// What happened.
    pub outcome: Outcome,
}

/// What [`import`] did, template by template.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImportReport {
    /// One entry per template of the file.
    pub entries: Vec<ImportEntry>,
}

impl ImportReport {
    /// Whether any template was left out.
    #[must_use]
    pub fn has_failures(&self) -> bool {
        self.entries.iter().any(|e| matches!(e.outcome, Outcome::Failed(_)))
    }
}

/// Imports the templates of `file`. A template is the same as an existing one when its type and
/// name are. Each is checked and saved like an edit, so it dispatches the model's events.
///
/// # Errors
///
/// Fails when the file's format is newer than this version knows, or the database fails.
pub async fn import(file: &ExportFile, options: ImportOptions) -> laravel::Result<ImportReport> {
    if file.format > FORMAT {
        return Err(laravel::Error::msg(format!(
            "the file's format is {}, newer than this version of laravel-template-engine reads ({FORMAT})",
            file.format
        )));
    }
    let mut report = ImportReport::default();
    // Documents first, so emails can attach the ones the same file brings.
    let mut ordered: Vec<&ExportedTemplate> = file.templates.iter().collect();
    ordered.sort_by_key(|t| t.kind == Kind::Mail);
    for exported in ordered {
        let outcome = import_one(exported, file, options).await?;
        report.entries.push(ImportEntry {
            type_key: exported.type_key.clone(),
            name: exported.name.clone(),
            outcome,
        });
    }
    Ok(report)
}

async fn import_one(
    exported: &ExportedTemplate,
    file: &ExportFile,
    options: ImportOptions,
) -> laravel::Result<Outcome> {
    let mut settings = match Settings::from_json(exported.kind, &exported.settings) {
        Ok(settings) => settings,
        Err(error) => {
            let issue = Issue {
                field: "settings".to_owned(),
                line: None,
                column: None,
                code: "invalid_settings",
                message: format!("The settings don't fit a {} template: {error}.", exported.kind.as_str()),
                suggestion: None,
            };
            return Ok(Outcome::Failed(vec![issue]));
        }
    };
    if let Settings::Mail(mail) = &mut settings {
        for name in &exported.attach_documents {
            match find(&exported.type_key, name).await? {
                Some(document) if document.kind == Kind::Document => mail.attach_documents.push(document.id),
                // In a dry run the file's own documents don't exist yet; they would by now.
                _ if options.dry_run && brings_document(file, &exported.type_key, name) => {}
                _ => {
                    let issue = Issue {
                        field: "attach_documents".to_owned(),
                        line: None,
                        column: None,
                        code: "unknown_document",
                        message: format!("There's no document template `{name}` of this type."),
                        suggestion: None,
                    };
                    return Ok(Outcome::Failed(vec![issue]));
                }
            }
        }
    }
    let input = TemplateInput {
        type_key: exported.type_key.clone(),
        name: exported.name.clone(),
        is_active: exported.is_active,
        content: exported.content.clone(),
        settings,
    };
    let issues = templates::check(&input).await?;
    if !issues.is_empty() {
        return Ok(Outcome::Failed(issues));
    }

    let existing = find(&exported.type_key, &exported.name).await?;
    match existing {
        Some(_) if !options.overwrite => Ok(Outcome::Kept),
        Some(_) if options.dry_run => Ok(Outcome::Updated),
        Some(template) => {
            templates::update(template, input).await?;
            Ok(Outcome::Updated)
        }
        None if options.dry_run => Ok(Outcome::Created),
        None => {
            templates::create(input).await?;
            Ok(Outcome::Created)
        }
    }
}

async fn find(type_key: &str, name: &str) -> laravel::Result<Option<Template>> {
    Template::query()
        .filter(Template::type_key.eq(type_key) & Template::name.eq(name))
        .first()
        .await
}

fn brings_document(file: &ExportFile, type_key: &str, name: &str) -> bool {
    file.templates
        .iter()
        .any(|t| t.kind == Kind::Document && t.type_key == type_key && t.name == name)
}