laravel-template-engine 0.5.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! The package's console commands.

use laravel::console::{Console, command};
use laravel::db::Json;
use laravel::model::create;

use crate::defaults::DefaultTemplate;
use crate::schema::types;
use crate::template::{Settings, Template};
use crate::transfer::{self, ExportFile, ImportOptions, Outcome};

/// Create the templates the template types come with. Templates that already exist (by type
/// and name) are left as they are, so changes people made are kept.
#[command("template-engine:install-defaults")]
pub async fn install_defaults(console: &mut Console) -> laravel::Result<()> {
    let mut created = 0;
    for info in types() {
        let defaults = info.defaults();
        // Documents first, so emails can attach them by name.
        let (documents, emails): (Vec<DefaultTemplate>, Vec<DefaultTemplate>) = defaults
            .into_iter()
            .partition(|d| matches!(d.settings, Settings::Document(_)));
        for default in documents.into_iter().chain(emails) {
            if install(info.key, default, console).await? {
                created += 1;
            }
        }
    }
    console.success(format!("Created {created} template(s)."));
    Ok(())
}

async fn install(type_key: &str, default: DefaultTemplate, console: &mut Console) -> laravel::Result<bool> {
    let existing = Template::query()
        .filter(Template::type_key.eq(type_key) & Template::name.eq(default.name.as_str()))
        .first()
        .await?;
    if existing.is_some() {
        console.line(format!("Kept {type_key}: {}", default.name));
        return Ok(false);
    }

    let mut settings = default.settings;
    if let Settings::Mail(mail) = &mut settings {
        for name in &default.attach_documents {
            let document = Template::query()
                .filter(Template::type_key.eq(type_key) & Template::name.eq(name.as_str()))
                .first()
                .await?;
            match document {
                Some(document) => mail.attach_documents.push(document.id),
                None => console.warn(format!(
                    "{type_key}: {} attaches `{name}`, which doesn't exist.",
                    default.name
                )),
            }
        }
    }
    let kind = settings.kind();
    let settings = settings.to_json();
    let content = Json(default.content);
    let name = default.name;
    create!(Template {
        type_key: type_key.to_owned(),
        kind,
        name: name.clone(),
        is_active: true,
        content,
        settings,
        ..
    })
    .await?;
    console.info(format!("Created {type_key}: {name}"));
    Ok(true)
}

/// Write the templates to a JSON file, to import them in another environment.
#[command("template-engine:export")]
pub async fn export(
    /// Only the templates of this type, such as `order.placed`.
    #[arg(long = "type")]
    type_key: Option<String>,
    /// The file to write. Without it, the JSON goes to the output.
    #[arg(long)]
    path: Option<String>,
    console: &mut Console,
) -> laravel::Result<()> {
    let file = transfer::export(type_key.as_deref()).await?;
    let json = serde_json::to_string_pretty(&file).map_err(|e| laravel::Error::msg(e.to_string()))?;
    match path {
        Some(path) => {
            std::fs::write(&path, json).map_err(|e| laravel::Error::msg(format!("can't write `{path}`: {e}")))?;
            console.success(format!("Exported {} template(s) to {path}.", file.templates.len()));
        }
        None => console.line(json),
    }
    Ok(())
}

/// Import templates from a file `template-engine:export` wrote. Templates that exist (same type
/// and name) are kept unless `--overwrite` is given.
#[command("template-engine:import")]
pub async fn import(
    /// The JSON file to read.
    path: String,
    /// Replace templates that already exist.
    #[arg(long)]
    overwrite: bool,
    /// Report what would happen, and change nothing.
    #[arg(long)]
    dry_run: bool,
    console: &mut Console,
) -> laravel::Result<u8> {
    let json = std::fs::read_to_string(&path).map_err(|e| laravel::Error::msg(format!("can't read `{path}`: {e}")))?;
    let file: ExportFile =
        serde_json::from_str(&json).map_err(|e| laravel::Error::msg(format!("`{path}` isn't an export file: {e}")))?;
    let report = transfer::import(&file, ImportOptions { overwrite, dry_run }).await?;
    let (created, updated) = if dry_run {
        ("Would create", "Would update")
    } else {
        ("Created", "Updated")
    };
    for entry in &report.entries {
        let label = format!("{}: {}", entry.type_key, entry.name);
        match &entry.outcome {
            Outcome::Created => console.info(format!("{created} {label}")),
            Outcome::Updated => console.info(format!("{updated} {label}")),
            Outcome::Kept => console.line(format!("Kept {label}")),
            Outcome::Failed(issues) => {
                console.error(format!("Left out {label}:"));
                for issue in issues {
                    console.error(format!("  {issue}"));
                }
            }
        }
    }
    Ok(u8::from(report.has_failures()))
}