laravel-template-engine 0.2.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! Making documents from templates.

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};

/// Makes a document from `data` with its type's active document template.
///
/// ```no_run
/// # use laravel_template_engine::{Recipient, TemplateData};
/// # use serde::Serialize;
/// # #[derive(Serialize, TemplateData)]
/// # #[template(key = "order.placed", example = OrderPlaced::example)]
/// # struct OrderPlaced { customer: Recipient, number: String }
/// # impl OrderPlaced { fn example() -> Self { Self { customer: Recipient::new("a@example.com"), number: "1".into() } } }
/// # async fn invoice(order: OrderPlaced) -> laravel::Result<laravel::http::Download> {
/// let invoice = laravel_template_engine::document(&order).named("Invoice").locale("uk").render().await?;
/// Ok(invoice.into_download())
/// # }
/// ```
#[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),
}

/// A document from [`document`], to adjust before it's rendered.
#[derive(Debug)]
pub struct PendingDocument {
    type_key: &'static str,
    data: serde_json::Result<serde_json::Value>,
    choice: Choice,
    locale: Option<String>,
}

impl PendingDocument {
    /// Uses the type's active document template called `name`, for types with several.
    #[must_use]
    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.choice = Choice::Named(name.into());
        self
    }

    /// Uses the document template with key `id`.
    #[must_use]
    pub fn template(mut self, id: i64) -> Self {
        self.choice = Choice::Id(id);
        self
    }

    /// Renders the text in `locale`, or the closest language the template has.
    #[must_use]
    pub fn locale(mut self, locale: impl Into<String>) -> Self {
        self.locale = Some(locale.into());
        self
    }

    /// Renders the document.
    ///
    /// # Errors
    ///
    /// Fails with [`TemplateError::NoDocument`] when no template fits, [`TemplateError::Render`]
    /// when it doesn't render, or when the database fails.
    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())
                }
            }
        }
    }
}