laravel-template-engine 0.5.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Sending emails made from templates.

use laravel::mail::{Address, Attachment, Message};
use laravel::queue::Queueable;
use laravel::queue::job;
use serde::{Deserialize, Serialize};

use crate::assets::{Assets, assets, embed_images};
use crate::events::{TemplateMessageFailed, TemplateMessageSent, TemplateRendered};
use crate::render::{RenderedMail, current_config, pick_locale, render_document, render_mail, sandbox};
use crate::schema::TemplateType;
use crate::template::{Kind, Settings, Template};
use crate::validate::parse_address;
use crate::{Recipient, TemplateError};

/// A file to attach to every email of a send, on top of the documents the templates attach.
/// It travels through the queue, so it names a file or holds its bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MailAttachment {
    source: Source,
    name: Option<String>,
    content_type: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
enum Source {
    Storage { disk: Option<String>, path: String },
    Path(String),
    Bytes { bytes: Vec<u8>, name: String },
}

impl MailAttachment {
    /// A file on the default storage disk.
    #[must_use]
    pub fn storage(path: impl Into<String>) -> Self {
        Self::new(Source::Storage {
            disk: None,
            path: path.into(),
        })
    }

    /// A file on the storage disk `disk`.
    #[must_use]
    pub fn storage_disk(disk: impl Into<String>, path: impl Into<String>) -> Self {
        Self::new(Source::Storage {
            disk: Some(disk.into()),
            path: path.into(),
        })
    }

    /// A file on the server, relative to the application's base path.
    #[must_use]
    pub fn path(path: impl Into<String>) -> Self {
        Self::new(Source::Path(path.into()))
    }

    /// Bytes in memory. They go into the queue's payload, so keep them small; use a storage file
    /// for large ones.
    #[must_use]
    pub fn bytes(bytes: impl Into<Vec<u8>>, name: impl Into<String>) -> Self {
        Self::new(Source::Bytes {
            bytes: bytes.into(),
            name: name.into(),
        })
    }

    fn new(source: Source) -> Self {
        Self {
            source,
            name: None,
            content_type: None,
        }
    }

    /// The name the recipient sees.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// The MIME type, when the name doesn't tell it.
    #[must_use]
    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
        self.content_type = Some(content_type.into());
        self
    }

    fn into_attachment(self) -> Attachment {
        let attachment = match self.source {
            Source::Storage { disk: Some(disk), path } => Attachment::from_storage_disk(disk, path),
            Source::Storage { disk: None, path } => Attachment::from_storage(path),
            Source::Path(path) => Attachment::from_path(path),
            Source::Bytes { bytes, name } => Attachment::from_bytes(bytes, name),
        };
        let attachment = match self.name {
            Some(name) => attachment.name(name),
            None => attachment,
        };
        match self.content_type {
            Some(content_type) => attachment.content_type(content_type),
            None => attachment,
        }
    }
}

/// Sends the emails of every active email template of `data`'s type, through the queue. Each
/// address in a template's `to` gets its own email in its own language. Returns how many emails
/// were queued.
///
/// ```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 run() -> laravel::Result<()> {
/// let order = OrderPlaced { customer: Recipient::new("olena@example.com").locale("uk"), number: "1042".into() };
/// laravel_template_engine::send(order).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Fails when the data doesn't serialize, or the database or the queue fails.
pub async fn send<T: TemplateType>(data: T) -> laravel::Result<usize> {
    mail(data).send().await
}

/// An email send to adjust before it goes, for example with attachments.
#[must_use]
pub fn mail<T: TemplateType>(data: T) -> PendingTemplateMail {
    PendingTemplateMail {
        type_key: T::KEY,
        data: serde_json::to_value(data),
        attachments: Vec::new(),
        headers: Vec::new(),
        template_id: None,
    }
}

/// An email send from [`mail`].
#[derive(Debug)]
pub struct PendingTemplateMail {
    type_key: &'static str,
    data: serde_json::Result<serde_json::Value>,
    attachments: Vec<MailAttachment>,
    headers: Vec<(String, String)>,
    template_id: Option<i64>,
}

impl PendingTemplateMail {
    /// Attaches a file to every email of this send.
    #[must_use]
    pub fn attach(mut self, attachment: MailAttachment) -> Self {
        self.attachments.push(attachment);
        self
    }

    /// Adds a header to every email of this send, such as `List-Unsubscribe` for a newsletter.
    #[must_use]
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// Sends only the template `id`, whether it is active or not, instead of every active email
    /// template of the type. Useful when people pick the template, as for a newsletter. A template
    /// of another type or kind sends nothing.
    #[must_use]
    pub fn template(mut self, id: i64) -> Self {
        self.template_id = Some(id);
        self
    }

    /// Queues the emails. Returns how many were queued.
    ///
    /// # Errors
    ///
    /// Fails when the data doesn't serialize, or the database or the queue fails.
    pub async fn send(self) -> laravel::Result<usize> {
        let data = self
            .data
            .map_err(|e| laravel::Error::msg(format!("the data of `{}` doesn't serialize: {e}", self.type_key)))?;
        let chosen = Template::type_key.eq(self.type_key) & Template::kind.eq(Kind::Mail);
        let chosen = match self.template_id {
            Some(id) => chosen & Template::id.eq(id),
            None => chosen & Template::is_active.eq(true),
        };
        let templates = Template::query()
            .filter(chosen)
            .order_by(Template::id.asc())
            .get()
            .await?;
        let config = current_config();
        let mut queued = 0;
        for template in templates {
            let Ok(Settings::Mail(settings)) = template.typed_settings() else {
                continue;
            };
            for to in resolve(&settings.to, &data) {
                let job = SendTemplateMail {
                    template_id: template.id,
                    data: data.clone(),
                    to,
                    attachments: self.attachments.clone(),
                    headers: self.headers.clone(),
                };
                let mut pending = job.dispatch();
                if let Some(connection) = config.queue_connection.clone().filter(|c| !c.is_empty()) {
                    pending = pending.on_connection(connection);
                }
                if let Some(queue) = config.queue.clone().filter(|q| !q.is_empty()) {
                    pending = pending.on_queue(queue);
                }
                pending.await?;
                queued += 1;
            }
        }
        Ok(queued)
    }
}

/// The queued job that renders one email and sends it. Rendering happens in the worker, so the
/// email uses the template as it is when it goes out.
#[derive(Debug, Queueable)]
pub struct SendTemplateMail {
    /// The template.
    pub template_id: i64,
    /// The template type's data, as JSON.
    pub data: serde_json::Value,
    /// Who gets the email.
    pub to: Recipient,
    /// Files to attach.
    pub attachments: Vec<MailAttachment>,
    /// Headers to add, as `(name, value)`. Jobs queued before 0.4.0 have none.
    #[serde(default)]
    pub headers: Vec<(String, String)>,
}

#[job(name = "template-engine.send-mail", tries = 3, backoff = [10.seconds(), 1.minutes()])]
impl SendTemplateMail {
    async fn handle(self) -> laravel::Result<()> {
        // A template deleted after the email was queued sends nothing.
        let Some(template) = Template::find(self.template_id).await? else {
            return Ok(());
        };
        deliver(&template, &self.data, &self.to, self.attachments, &self.headers, None).await
    }
}

/// Renders and sends one email, dispatching the events. Errors that a retry can't fix, such as a
/// template that doesn't render, are reported with [`TemplateMessageFailed`] but don't fail the
/// job.
pub(crate) async fn deliver(
    template: &Template,
    data: &serde_json::Value,
    to: &Recipient,
    attachments: Vec<MailAttachment>,
    headers: &[(String, String)],
    subject_prefix: Option<&str>,
) -> laravel::Result<()> {
    let failed = |locale: Option<String>, error: String| TemplateMessageFailed {
        template_id: template.id,
        type_key: template.type_key.clone(),
        kind: Kind::Mail,
        locale,
        recipient: to.email.clone(),
        error,
    };

    let message = match build(template, data, to, attachments, headers, subject_prefix).await {
        Ok(message) => message,
        Err((locale, error)) => {
            failed(locale, error.to_string()).dispatch().await?;
            return if subject_prefix.is_some() { Err(error) } else { Ok(()) };
        }
    };
    let (message, locale) = message;
    if let Err(error) = laravel::mail::send(message).await {
        failed(Some(locale), error.to_string()).dispatch().await?;
        return Err(error);
    }
    TemplateMessageSent {
        template_id: template.id,
        type_key: template.type_key.clone(),
        kind: Kind::Mail,
        locale,
        recipient: to.email.clone(),
    }
    .dispatch()
    .await
}

type BuildError = (Option<String>, laravel::Error);

async fn build(
    template: &Template,
    data: &serde_json::Value,
    to: &Recipient,
    attachments: Vec<MailAttachment>,
    headers: &[(String, String)],
    subject_prefix: Option<&str>,
) -> Result<(Message, String), BuildError> {
    let settings = match template.typed_settings() {
        Ok(Settings::Mail(settings)) => settings,
        Ok(_) => return Err((None, laravel::Error::msg("the template isn't an email template"))),
        Err(error) => return Err((None, error)),
    };
    let assets = assets().await.map_err(|e| (None, e))?;
    let (rendered, documents) = render_for(
        template,
        data,
        to.locale.as_deref(),
        &settings.attach_documents,
        &assets,
    )
    .await
    .map_err(|e| (None, e))?;
    let locale = rendered.locale.clone();

    let subject = format!("{}{}", subject_prefix.unwrap_or(""), rendered.subject);
    let (html, images) = embed_images(&rendered.html, &assets);
    let mut message = Message::new()
        .to(to.address())
        .subject(subject)
        .html(html)
        .text(rendered.text);
    for image in images {
        let attachment =
            Attachment::from_bytes(image.bytes.to_vec(), image.file_name()).content_type(image.content_type);
        message = message.embed(image.name, attachment);
    }
    if let Some((email, name)) = settings.from.as_deref().and_then(parse_address) {
        message = message.from(address(email, name));
    }
    if let Some((email, name)) = settings.reply_to.as_deref().and_then(parse_address) {
        message = message.reply_to(address(email, name));
    }
    let cc: Vec<Address> = resolve(&settings.cc, data).iter().map(Recipient::address).collect();
    if !cc.is_empty() {
        message = message.cc(cc);
    }
    let bcc: Vec<Address> = resolve(&settings.bcc, data).iter().map(Recipient::address).collect();
    if !bcc.is_empty() {
        message = message.bcc(bcc);
    }
    for document in documents {
        message = message.attach(document.into_attachment());
    }
    for attachment in attachments {
        message = message.attach(attachment.into_attachment());
    }
    for (name, value) in headers {
        message = message.header(name, value);
    }
    Ok((message, locale))
}

fn address(email: String, name: Option<String>) -> Address {
    match name {
        Some(name) => Address::new(email).with_name(name),
        None => Address::new(email),
    }
}

/// Renders an email and the documents it attaches, and dispatches [`TemplateRendered`] for each.
pub(crate) async fn render_for(
    template: &Template,
    data: &serde_json::Value,
    wanted: Option<&str>,
    attach: &[i64],
    assets: &Assets,
) -> laravel::Result<(RenderedMail, Vec<crate::Document>)> {
    let config = current_config();
    let (locale, content) = pick_locale(&template.content.0, wanted, &config.locale)
        .ok_or_else(|| TemplateError::Render("the template has no text".to_owned()))?;
    let layout = match template.typed_settings()? {
        Settings::Mail(settings) => settings.layout,
        _ => None,
    };
    let rendered = render_mail(
        &sandbox(locale, assets, &config),
        locale,
        content,
        data,
        assets.layout(layout.as_deref()),
    )?;
    rendered_event(template, locale).await?;

    let mut documents = Vec::new();
    for id in attach {
        let Some(document) = Template::find(*id).await? else {
            continue;
        };
        if document.kind != Kind::Document || document.type_key != template.type_key {
            continue;
        }
        let Ok(Settings::Document(settings)) = document.typed_settings() else {
            continue;
        };
        let Some((doc_locale, doc_content)) = pick_locale(&document.content.0, Some(locale), &config.locale) else {
            continue;
        };
        let sandbox = sandbox(doc_locale, assets, &config);
        documents.push(render_document(
            &sandbox,
            doc_locale,
            doc_content,
            &settings,
            data,
            assets,
        )?);
        rendered_event(&document, doc_locale).await?;
    }
    Ok((rendered, documents))
}

pub(crate) async fn rendered_event(template: &Template, locale: &str) -> laravel::Result<()> {
    TemplateRendered {
        template_id: template.id,
        type_key: template.type_key.clone(),
        kind: template.kind,
        locale: locale.to_owned(),
    }
    .dispatch()
    .await
}

/// The recipients a `to`, `cc` or `bcc` list names: addresses as they are, recipient variables
/// read from the data. Missing optional recipients are skipped.
pub(crate) fn resolve(entries: &[String], data: &serde_json::Value) -> Vec<Recipient> {
    let mut recipients: Vec<Recipient> = Vec::new();
    for entry in entries {
        let entry = entry.trim();
        if entry.contains('@') {
            if let Some((email, name)) = parse_address(entry) {
                recipients.push(Recipient {
                    email,
                    name,
                    locale: None,
                });
            }
            continue;
        }
        let mut value = data;
        for part in entry.split('.') {
            value = value.get(part).unwrap_or(&serde_json::Value::Null);
        }
        let found: Vec<Recipient> = match value {
            serde_json::Value::Array(items) => items
                .iter()
                .filter_map(|item| serde_json::from_value(item.clone()).ok())
                .collect(),
            serde_json::Value::Object(_) => serde_json::from_value(value.clone()).into_iter().collect(),
            _ => Vec::new(),
        };
        recipients.extend(found.into_iter().filter(|r| !r.email.trim().is_empty()));
    }
    let mut seen = std::collections::HashSet::new();
    recipients.retain(|r| seen.insert(r.email.to_ascii_lowercase()));
    recipients
}