use crate::TemplateError;
use crate::assets::assets;
use crate::mail::rendered_event;
use crate::render::{Document, current_config, pick_locale, render_document, sandbox};
use crate::schema::TemplateType;
use crate::template::{Kind, Settings, Template};
#[must_use]
pub fn document<T: TemplateType>(data: &T) -> PendingDocument {
PendingDocument {
type_key: T::KEY,
data: serde_json::to_value(data),
choice: Choice::Only,
locale: None,
}
}
#[derive(Debug)]
enum Choice {
Only,
Named(String),
Id(i64),
}
#[derive(Debug)]
pub struct PendingDocument {
type_key: &'static str,
data: serde_json::Result<serde_json::Value>,
choice: Choice,
locale: Option<String>,
}
impl PendingDocument {
#[must_use]
pub fn named(mut self, name: impl Into<String>) -> Self {
self.choice = Choice::Named(name.into());
self
}
#[must_use]
pub fn template(mut self, id: i64) -> Self {
self.choice = Choice::Id(id);
self
}
#[must_use]
pub fn locale(mut self, locale: impl Into<String>) -> Self {
self.locale = Some(locale.into());
self
}
pub async fn render(self) -> laravel::Result<Document> {
let template = self.find().await?;
let type_key = self.type_key;
let data = self
.data
.map_err(|e| laravel::Error::msg(format!("the data of `{type_key}` doesn't serialize: {e}")))?;
let Settings::Document(settings) = template.typed_settings()? else {
return Err(TemplateError::NoDocument {
type_key: type_key.to_owned(),
found: 0,
}
.into());
};
let config = current_config();
let (locale, content) = pick_locale(&template.content.0, self.locale.as_deref(), &config.locale)
.ok_or_else(|| TemplateError::Render("the template has no text".to_owned()))?;
let assets = assets().await?;
let sandbox = sandbox(locale, &assets, &config);
let document = render_document(&sandbox, locale, content, &settings, &data, &assets)?;
rendered_event(&template, locale).await?;
Ok(document)
}
async fn find(&self) -> laravel::Result<Template> {
let of_type = Template::type_key.eq(self.type_key) & Template::kind.eq(Kind::Document);
let missing = |found| TemplateError::NoDocument {
type_key: self.type_key.to_owned(),
found,
};
match &self.choice {
Choice::Id(id) => Template::query()
.filter(of_type & Template::id.eq(*id))
.first()
.await?
.ok_or_else(|| missing(0).into()),
Choice::Named(name) => Template::query()
.filter(of_type & Template::is_active.eq(true) & Template::name.eq(name.as_str()))
.first()
.await?
.ok_or_else(|| missing(0).into()),
Choice::Only => {
let mut found = Template::query()
.filter(of_type & Template::is_active.eq(true))
.get()
.await?;
if found.len() == 1 {
Ok(found.remove(0))
} else {
Err(missing(found.len()).into())
}
}
}
}
}