use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::template::{Content, Kind, Settings, Template, TemplateInput};
use crate::templates;
use crate::validate::Issue;
pub const FORMAT: u32 = 1;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExportFile {
pub format: u32,
pub templates: Vec<ExportedTemplate>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExportedTemplate {
pub type_key: String,
pub kind: Kind,
pub name: String,
pub is_active: bool,
pub content: BTreeMap<String, Content>,
pub settings: serde_json::Value,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attach_documents: Vec<String>,
}
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,
})
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ImportOptions {
pub overwrite: bool,
pub dry_run: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Created,
Updated,
Kept,
Failed(Vec<Issue>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportEntry {
pub type_key: String,
pub name: String,
pub outcome: Outcome,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImportReport {
pub entries: Vec<ImportEntry>,
}
impl ImportReport {
#[must_use]
pub fn has_failures(&self) -> bool {
self.entries.iter().any(|e| matches!(e.outcome, Outcome::Failed(_)))
}
}
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();
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),
_ 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)
}