Skip to main content

laravel_template_engine/
template.rs

1//! The stored templates.
2
3use std::collections::BTreeMap;
4
5use laravel::Enum;
6use laravel::db::Json;
7use laravel::model::model;
8use laravel::time::Timestamp;
9use serde::{Deserialize, Serialize};
10
11/// What a template makes.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Enum)]
13#[serde(rename_all = "snake_case")]
14#[non_exhaustive]
15pub enum Kind {
16    /// An email.
17    Mail,
18    /// A document, such as an invoice, in HTML or PDF.
19    Document,
20    /// The text of a notification for one channel, such as `sms` or `telegram`.
21    Notification,
22}
23
24impl Kind {
25    /// The name stored in the table: `mail` or `document`.
26    #[must_use]
27    pub fn as_str(self) -> &'static str {
28        match self {
29            Kind::Mail => "mail",
30            Kind::Document => "document",
31            Kind::Notification => "notification",
32        }
33    }
34}
35
36/// A template's text in one language.
37#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
38pub struct Content {
39    /// The email's subject. Documents don't use it.
40    #[serde(default)]
41    pub subject: String,
42    /// The email's or the document's HTML.
43    #[serde(default)]
44    pub body: String,
45}
46
47impl Content {
48    /// Text with a subject and a body.
49    #[must_use]
50    pub fn new(subject: impl Into<String>, body: impl Into<String>) -> Self {
51        Self {
52            subject: subject.into(),
53            body: body.into(),
54        }
55    }
56}
57
58/// Who an email goes to and what comes with it.
59///
60/// `to`, `cc` and `bcc` hold recipient variables of the template type, such as `customer`, and
61/// email addresses, such as `accounting@example.com`. Each address in `to` gets its own email, in
62/// its own language; the `cc` and `bcc` addresses get a copy of each.
63#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(default, deny_unknown_fields)]
65pub struct MailSettings {
66    /// The sender, such as `shop@example.com` or `Shop <shop@example.com>`. Empty means the
67    /// application's `MAIL_FROM_ADDRESS`.
68    pub from: Option<String>,
69    /// Where replies go.
70    pub reply_to: Option<String>,
71    /// Who gets the email.
72    pub to: Vec<String>,
73    /// Who gets a copy.
74    pub cc: Vec<String>,
75    /// Who gets a hidden copy.
76    pub bcc: Vec<String>,
77    /// Keys of document templates of the same type to render and attach.
78    pub attach_documents: Vec<i64>,
79    /// The layout the email's text goes into, by the name it was registered under.
80    pub layout: Option<String>,
81}
82
83/// The file format of a document.
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(rename_all = "snake_case")]
86#[non_exhaustive]
87pub enum DocumentFormat {
88    /// A PDF, with the crate's `pdf` feature.
89    #[default]
90    Pdf,
91    /// An HTML page.
92    Html,
93}
94
95/// The paper's orientation.
96#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(rename_all = "snake_case")]
98pub enum Orientation {
99    /// Taller than wide.
100    #[default]
101    Portrait,
102    /// Wider than tall.
103    Landscape,
104}
105
106/// The space around a PDF page's text, in millimeters.
107#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
108#[serde(default, deny_unknown_fields)]
109pub struct Margins {
110    /// Above.
111    pub top: f32,
112    /// On the right.
113    pub right: f32,
114    /// Below.
115    pub bottom: f32,
116    /// On the left.
117    pub left: f32,
118}
119
120impl Default for Margins {
121    fn default() -> Self {
122        Self::all(15.0)
123    }
124}
125
126impl Margins {
127    /// The same margin on every side.
128    #[must_use]
129    pub fn all(millimeters: f32) -> Self {
130        Self {
131            top: millimeters,
132            right: millimeters,
133            bottom: millimeters,
134            left: millimeters,
135        }
136    }
137}
138
139/// How a document is made.
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141#[serde(default, deny_unknown_fields)]
142pub struct DocumentSettings {
143    /// PDF or HTML.
144    pub format: DocumentFormat,
145    /// The paper size: `a4`, `a5`, `letter`, `legal` and so on.
146    pub paper: String,
147    /// Portrait or landscape.
148    pub orientation: Orientation,
149    /// The file's name, a template itself, such as `invoice-{{ order.number }}`. The extension is
150    /// added when it's missing.
151    pub filename: String,
152    /// The layout the document's text goes into, by the name it was registered under.
153    pub layout: Option<String>,
154    /// The space around the text of a PDF page.
155    pub margins: Margins,
156    /// The text's font, such as `Times New Roman` or a font registered for PDFs.
157    pub font_family: Option<String>,
158    /// The text's size in points, such as `12`.
159    pub font_size: Option<f32>,
160    /// The space between lines, as a multiple of the font size, such as `1.15`.
161    pub line_height: Option<f32>,
162}
163
164impl Default for DocumentSettings {
165    fn default() -> Self {
166        Self {
167            format: DocumentFormat::Pdf,
168            paper: "a4".to_owned(),
169            orientation: Orientation::Portrait,
170            filename: "document".to_owned(),
171            layout: None,
172            margins: Margins::default(),
173            font_family: None,
174            font_size: None,
175            line_height: None,
176        }
177    }
178}
179
180/// Which channel a notification template writes for.
181#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(default, deny_unknown_fields)]
183pub struct NotificationSettings {
184    /// The channel, such as `sms`, `slack` or `telegram`: the name the application's
185    /// notification asks for.
186    pub channel: String,
187}
188
189/// The settings of a template, by its kind.
190#[derive(Debug, Clone, PartialEq)]
191#[non_exhaustive]
192pub enum Settings {
193    /// An email's.
194    Mail(MailSettings),
195    /// A document's.
196    Document(DocumentSettings),
197    /// A notification's.
198    Notification(NotificationSettings),
199}
200
201impl Settings {
202    /// The default settings of `kind`.
203    #[must_use]
204    pub fn default_for(kind: Kind) -> Self {
205        match kind {
206            Kind::Mail => Settings::Mail(MailSettings::default()),
207            Kind::Document => Settings::Document(DocumentSettings::default()),
208            Kind::Notification => Settings::Notification(NotificationSettings::default()),
209        }
210    }
211
212    /// Reads the settings of a `kind` template from JSON.
213    ///
214    /// # Errors
215    ///
216    /// Fails when the JSON doesn't fit the kind's settings.
217    pub fn from_json(kind: Kind, value: &serde_json::Value) -> Result<Self, serde_json::Error> {
218        let value = if value.is_null() {
219            serde_json::json!({})
220        } else {
221            value.clone()
222        };
223        Ok(match kind {
224            Kind::Mail => Settings::Mail(serde_json::from_value(value)?),
225            Kind::Document => Settings::Document(serde_json::from_value(value)?),
226            Kind::Notification => Settings::Notification(serde_json::from_value(value)?),
227        })
228    }
229
230    /// The settings as JSON.
231    #[must_use]
232    pub fn to_json(&self) -> serde_json::Value {
233        match self {
234            Settings::Mail(settings) => serde_json::to_value(settings),
235            Settings::Document(settings) => serde_json::to_value(settings),
236            Settings::Notification(settings) => serde_json::to_value(settings),
237        }
238        .unwrap_or_default()
239    }
240
241    /// The kind these settings belong to.
242    #[must_use]
243    pub fn kind(&self) -> Kind {
244        match self {
245            Settings::Mail(_) => Kind::Mail,
246            Settings::Document(_) => Kind::Document,
247            Settings::Notification(_) => Kind::Notification,
248        }
249    }
250}
251
252/// A stored template: an ordinary Laravel Rust model, so creating, updating and deleting one
253/// dispatches `Created<Template>`, `Updated<Template>` and `Deleted<Template>` for audit packages.
254///
255/// Write templates with [`templates::create`](crate::templates::create) and
256/// [`templates::update`](crate::templates::update), which check them first.
257#[model(table = "template_engine_templates")]
258pub struct Template {
259    /// The key.
260    pub id: i64,
261    /// The template type, such as `order.placed`.
262    pub type_key: String,
263    /// Email or document.
264    pub kind: Kind,
265    /// A name for people, such as "Confirmation for the customer".
266    pub name: String,
267    /// Whether the template is used. Every active email template of a type is sent.
268    #[default]
269    pub is_active: bool,
270    /// The text, by language: `{"uk": {"subject": "...", "body": "..."}}`.
271    pub content: Json<BTreeMap<String, Content>>,
272    /// The kind's settings as JSON; read them with [`Template::typed_settings`].
273    pub settings: serde_json::Value,
274    /// When the template was created.
275    pub created_at: Option<Timestamp>,
276    /// When the template was last changed.
277    pub updated_at: Option<Timestamp>,
278}
279
280impl Template {
281    /// The typed settings.
282    ///
283    /// # Errors
284    ///
285    /// Fails when the stored JSON doesn't fit the template's kind.
286    pub fn typed_settings(&self) -> laravel::Result<Settings> {
287        Settings::from_json(self.kind, &self.settings)
288            .map_err(|e| laravel::Error::msg(format!("the settings of template {} are invalid: {e}", self.id)))
289    }
290
291    /// The template as input for [`templates::update`](crate::templates::update) or
292    /// [`preview`](crate::templates::preview).
293    ///
294    /// # Errors
295    ///
296    /// Fails when the stored settings don't fit the template's kind.
297    pub fn to_input(&self) -> laravel::Result<TemplateInput> {
298        Ok(TemplateInput {
299            type_key: self.type_key.clone(),
300            name: self.name.clone(),
301            is_active: self.is_active,
302            content: self.content.0.clone(),
303            settings: self.typed_settings()?,
304        })
305    }
306}
307
308/// A template to save, check or preview.
309#[derive(Debug, Clone, PartialEq)]
310pub struct TemplateInput {
311    /// The template type.
312    pub type_key: String,
313    /// A name for people.
314    pub name: String,
315    /// Whether the template is used.
316    pub is_active: bool,
317    /// The text, by language.
318    pub content: BTreeMap<String, Content>,
319    /// The settings; their variant decides the kind.
320    pub settings: Settings,
321}
322
323impl TemplateInput {
324    /// An active email template of `type_key`, without text.
325    #[must_use]
326    pub fn mail(type_key: impl Into<String>, name: impl Into<String>) -> Self {
327        Self::new(type_key, name, Settings::Mail(MailSettings::default()))
328    }
329
330    /// An active document template of `type_key`, without text.
331    #[must_use]
332    pub fn document(type_key: impl Into<String>, name: impl Into<String>) -> Self {
333        Self::new(type_key, name, Settings::Document(DocumentSettings::default()))
334    }
335
336    /// An active notification template of `type_key` for `channel`, such as `sms`, without text.
337    #[must_use]
338    pub fn notification(type_key: impl Into<String>, name: impl Into<String>, channel: impl Into<String>) -> Self {
339        let settings = NotificationSettings {
340            channel: channel.into(),
341        };
342        Self::new(type_key, name, Settings::Notification(settings))
343    }
344
345    fn new(type_key: impl Into<String>, name: impl Into<String>, settings: Settings) -> Self {
346        Self {
347            type_key: type_key.into(),
348            name: name.into(),
349            is_active: true,
350            content: BTreeMap::new(),
351            settings,
352        }
353    }
354
355    /// Adds the text in `locale`.
356    #[must_use]
357    pub fn content(mut self, locale: impl Into<String>, subject: impl Into<String>, body: impl Into<String>) -> Self {
358        self.content.insert(locale.into(), Content::new(subject, body));
359        self
360    }
361
362    /// The kind, from the settings.
363    #[must_use]
364    pub fn kind(&self) -> Kind {
365        self.settings.kind()
366    }
367}