feat(postcard): mail partials, built-in layouts and layout and partial overrides

- pact.HasMailPartials: plugins declare <plugin>::mail.partials.<name>,
  loaded from views/mail/partials/<name>.htm; HasMailTemplates is unchanged
- bodies and layouts call {{ partial "name" "key" value ... }}; a call in a
  Markdown body leaves a per-render random token swapped after goldmark, so
  raw HTML stays disabled for bodies
- built-in partials button, panel, table and subcopy, built-in layouts
  system and minimal next to the unchanged default, reachable by alias
  after a plugin's own aliases
- NewDBSource also reads customized and database-only layouts and
  customized partials; a layout's CSS goes before mail.css

Plan 35-01, task 3.
This commit is contained in:
Jakub Zych
2026-11-13 10:38:14 +01:00
parent 7e5d2c74af
commit 5df1ec27cf
17 changed files with 1273 additions and 71 deletions

View File

@@ -8,7 +8,7 @@ Transactional mail from plugin-owned Markdown templates and layouts, delivered t
## Overview
postcard is the mail layer of SummerCMS. Plugins that implement `pact.HasMailTemplates` ship WinterCMS-shaped mail files under `views/mail/`; at boot, `postcard.Activate` publishes one app-scoped `postcard.Mailer` built from the compass `mail.*` config, and `postcard.BootPlugin` registers each plugin's templates and layouts as the plugin boots. Callers then send a template by its dotted name with a map of variables. postcard also owns the mail tables that hold administrators' edits: when a template has a customized row, the mailer sends that override, and the plugin's file otherwise. It is the counterpart of WinterCMS's `Mail::send` with `views/mail/*.htm` templates and mail layouts.
postcard is the mail layer of SummerCMS. Plugins that implement `pact.HasMailTemplates` ship WinterCMS-shaped mail files under `views/mail/`, and plugins that implement `pact.HasMailPartials` ship reusable blocks for them; at boot, `postcard.Activate` publishes one app-scoped `postcard.Mailer` built from the compass `mail.*` config, and `postcard.BootPlugin` registers each plugin's templates, layouts and partials as the plugin boots. Callers then send a template by its dotted name with a map of variables. postcard also owns the mail tables that hold administrators' edits: when a template, layout or partial has a customized row, the mailer uses that override, and the plugin's file otherwise. It is the counterpart of WinterCMS's `Mail::send` with `views/mail/*.htm` templates and mail layouts.
## Role in the framework
@@ -24,11 +24,12 @@ Use cases:
- Templates named `<plugin>::mail.<name>` and loaded from `views/mail/<name>.htm` (dots become directories). A plugin may only register names in its own namespace; missing files, duplicates and unknown layout aliases fail at boot.
- WinterCMS file format: an INI header (`subject`, `layout`, `description`), a `==` separator, then a Markdown body rendered with Go `html/template` variables such as `{{ .name }}`.
- Layouts with a header, a text wrapper and an HTML wrapper, referenced from templates by a short alias (`pact.HasMailTemplates` maps aliases to full names). A neutral default layout is built in.
- Layouts with a header, a text wrapper and an HTML wrapper, referenced from templates by a short alias (`pact.HasMailTemplates` maps aliases to full names). Three layouts are built in and usable from any plugin's templates: `default`, `system` and `minimal`.
- Partials: reusable blocks named `<plugin>::mail.partials.<name>`, loaded from `views/mail/partials/<name>.htm` and declared through `pact.HasMailPartials`. Bodies and layouts call them with `{{ partial "<name>" "key" value }}`. The partials `button`, `panel`, `table` and `subcopy` are built in.
- Every message gets an HTML part (Markdown converted with goldmark) and a plain-text part. `mail.css` and `mail.brandCss` are inlined into the layout's style block.
- Safety checks: rendered HTML with script, iframe, object or embed tags, inline event handlers or `javascript:`/`vbscript:`/`data:` URLs is rejected; CR/LF in the subject or address headers is rejected; addresses are parsed with `net/mail`.
- Drivers behind the `postcard.Driver` interface: `postcard.MemoryDriver` (keeps messages for tests), `postcard.LogDriver` (logs headers and the text part through `log/slog`, never the HTML or credentials), `postcard.SMTPDriver` (go-mail with an explicit TLS policy) and `postcard.FailDriver` (a deterministic failure for tests).
- Database overrides: a customized row of `system_mail_templates` replaces a template's subject, body and layout. The mailer reads it on every send, with no cache, in every process that publishes a `*gorm.DB`. A missing database, tables that are not migrated yet, or an override that does not render or fails the safety checks sends the file version.
- Database overrides: a customized row of `system_mail_templates` replaces a template's subject, body and layout, a customized row of `system_mail_layouts` or `system_mail_partials` replaces a layout or a partial, and `system_mail_layouts` also holds layouts that exist only in the database. The mailer reads them on every send, with no cache, in every process that publishes a `*gorm.DB`. A missing database, tables that are not migrated yet, or an override that does not render or fails the safety checks sends the file version.
- No locale selection: callers pass the full template name, including any locale suffix.
## Usage
@@ -99,6 +100,83 @@ func TestWelcomeMail(t *testing.T) {
}
```
### Partials
A partial is a block of mail that several templates and layouts share, such as a button. Its file has the layout format: a header with a `name`, a `==` line, the text section, a `==` line, then the HTML section. A plugin ships `views/mail/partials/note.htm`:
```text
name = "Note"
==
NOTE: {{ .text }}
==
<div class="note">{{ .text }}</div>
```
and declares it next to its templates:
```go
package blog
import (
"embed"
"io/fs"
"git.golem15.com/golem15/summercms/modules/pact"
)
//go:embed views/mail
var mailFS embed.FS
type Plugin struct{}
var _ pact.HasMailPartials = Plugin{}
func (Plugin) ID() string { return "acme.blog" }
func (Plugin) MailPartialsFS() fs.FS { return mailFS }
func (Plugin) MailPartials() []string {
return []string{"acme.blog::mail.partials.note"}
}
```
A name must be in the plugin's own namespace and under `mail.partials.`; a name outside either, a missing file or a duplicate fails `postcard.BootPlugin` with the dotted name. A plugin may implement `pact.HasMailPartials` without `pact.HasMailTemplates`, and any plugin's templates may call its partials.
A template body or a layout calls a partial with its name followed by pairs of a key and a value, which become the partial's variables:
```text
subject = "Your order {{ .code }}"
==
Thanks for your order.
{{ partial "button" "url" .link "body" "Track the order" "type" "positive" }}
{{ partial "acme.blog::mail.partials.note" "text" .note }}
```
A bare name such as `button` is one of postcard's built-in partials; a plugin's partial is called by its full name. The HTML section goes into the HTML part and the text section into the plain-text part. An unknown name, an odd number of key and value arguments or a key that is not a string fails the render with the partial's name.
Inside a partial's HTML section, `{{ markdown .body }}` renders a value as Markdown, tables included; in the text section it returns the value unchanged. A partial cannot call `partial`.
Markdown drops raw HTML, so a call in a body does not insert the partial's HTML directly. It leaves a token of letters and digits, `MAILPARTIAL` followed by a random value drawn for that one render, and postcard swaps the token for the rendered partial after the body has been converted. A variable's value cannot contain that token, so text that only looks like one stays text. Put a call on its own line, with blank lines around it, to get the partial as a block of its own. Markdown rendering of bodies is unchanged: raw HTML in a body is still dropped.
### Built-in layouts and partials
| Layout alias | Full name | Renders |
|--------------|-----------|---------|
| `default` | `postcard::mail.layouts.default` | The message in a `content-body` block. Used when a template names no layout. |
| `system` | `postcard::mail.layouts.system` | WinterCMS's system layout: the message in a centred table, followed by a note that the message is automatic. |
| `minimal` | `postcard::mail.layouts.minimal` | The message directly in the page body. |
A template selects one with `layout = "system"`. A plugin's own alias of the same name wins, except `default`, which plugins cannot redefine. Every built-in layout has the `{{ .brandCss }}{{ .css }}` style block.
| Partial | Arguments | Renders |
|---------|-----------|---------|
| `button` | `url`, `body`, `type` (`primary` by default, `positive` or `negative`) | A link styled as a button (`button button-<type>`); in text, the label and the address. |
| `panel` | `body` (Markdown) | A highlighted block (`panel`). |
| `table` | `body` (a Markdown table) | A table in a `table` block. |
| `subcopy` | `body` (Markdown) | Small print under a rule (`subcopy`). |
### Overrides from the admin
postcard owns the tables `system_mail_templates`, `system_mail_layouts`, `system_mail_partials`, `system_mail_brand_settings` and `system_mail_image_library` (`postcard.Migrations`). A row of `system_mail_templates` with `is_custom` set is an override of the template named in its `code`: its `subject` and `body` replace the file's, and the row its `layout_id` points at names the layout. The body has the same format as in the file, Markdown with Go template variables.
@@ -111,11 +189,13 @@ The subject is taken from the first of these that is set:
2. the override's subject;
3. the file's subject.
Layouts and partials are overridden the same way. A row of `system_mail_layouts` with `is_custom` set and a full layout name in `code` replaces that layout's HTML and text wrappers; a row with another `code` is a layout that exists only in the database, which a template override can select. A layout row's `content_css` is placed before `mail.css` in the layout's `{{ .css }}` slot. A row of `system_mail_partials` with `is_custom` set replaces the HTML and text sections of the partial named in its `code`.
An override never stops mail:
- With no `*gorm.DB` published, the file version is sent.
- When the lookup fails (no connection, or the tables are not migrated yet), the file version is sent and a warning is logged, at most once a minute per distinct error.
- When the override does not parse, fails while rendering (for example it uses a field of a variable the caller does not pass) or fails the safety checks, the error is logged as `postcard: override failed, sending the file version` with the template name, and the file version is sent.
- When an override (of the template, its layout or a partial it calls) does not parse, fails while rendering (for example it uses a field of a variable the caller does not pass) or fails the safety checks, the error is logged as `postcard: override failed, sending the file version` with the template name, and the message is sent from the files alone.
- When the override's layout no longer exists, the message is rendered in the default layout and a warning is logged.
`postcard.NewMailer` takes a source through `postcard.Options.Overrides`; any `postcard.OverrideSource` works, which is how a test supplies overrides without a database:
@@ -152,14 +232,15 @@ func newTestMailer(cat *postcard.Catalog, driver postcard.Driver) postcard.Maile
| Identifier | Description |
|------------|-------------|
| `postcard.Activate` | Builds the driver from config and publishes the app-scoped `postcard.Mailer` before plugins boot. The mailer reads overrides through `postcard.NewDBSource`. |
| `postcard.BootPlugin` | Registers a booting plugin's declared templates and layouts with the published mailer. |
| `postcard.BootPlugin` | Registers a booting plugin's declared partials (`pact.HasMailPartials`) and its templates and layouts (`pact.HasMailTemplates`) with the published mailer. |
| `postcard.Mailer` | Sends a registered template through the configured driver. |
| `postcard.NewMailer` | Builds a mailer from a catalog, a driver and `postcard.Options`. |
| `postcard.Message` | What callers send: template name, recipients, reply-to, variables and an optional subject override. |
| `postcard.Options` | Mailer settings: sender address, CSS, brand CSS and, in `postcard.Options.Overrides`, the source of database overrides (nil sends the file versions). |
| `postcard.Catalog` | Registered templates and layouts, including the built-in default layout. |
| `postcard.NewCatalog` | Returns a catalog holding only the default layout. |
| `postcard.Catalog` | Registered templates, layouts and partials, including the built-in ones. |
| `postcard.NewCatalog` | Returns a catalog holding the built-in layouts and partials and no template. |
| `postcard.Catalog.Register` | Loads a plugin's templates and layout aliases from an `fs.FS`. |
| `postcard.Catalog.RegisterPartials` | Loads a plugin's partials from an `fs.FS`. |
| `postcard.Driver` | Delivers a `postcard.RenderedMessage`. |
| `postcard.RenderedMessage` | The validated payload a driver transmits: headers, HTML part and text part. |
| `postcard.NewMemoryDriver` | In-memory driver; `postcard.MemoryDriver.Messages` returns what was sent. |
@@ -170,8 +251,8 @@ func newTestMailer(cat *postcard.Catalog, driver postcard.Driver) postcard.Maile
| `postcard.OverrideSource` | Supplies the database overrides of one render. `postcard.OverrideSource.MailOverrides` takes the template name; an empty name asks for everything except a template override. |
| `postcard.Overrides` | What a source returns: the template override in `postcard.Overrides.Template` (nil when there is none), layout content by code in `postcard.Overrides.Layouts` and partial content by name in `postcard.Overrides.Partials`. |
| `postcard.TemplateOverride` | A template's customized subject, body and layout code. An empty `postcard.TemplateOverride.Layout` keeps the file's layout. |
| `postcard.LayoutOverride` | A layout's name, HTML wrapper, text wrapper and CSS as stored in the database. |
| `postcard.PartialOverride` | A partial's HTML and text sections as stored in the database. |
| `postcard.LayoutOverride` | A layout's name, HTML wrapper, text wrapper and CSS from the database. In `postcard.Overrides.Layouts` under a file layout's full name it replaces that layout; under another code it is a database-only layout. |
| `postcard.PartialOverride` | A partial's HTML and text sections from the database, in `postcard.Overrides.Partials` under the partial's full name. |
| `postcard.NewDBSource` | The source over postcard's tables. It looks the `*gorm.DB` up on the app at every call and returns no overrides when none is published. |
| `postcard.Migrations` | The gormigrate set that creates the mail tables; lagoon runs it under the `summercms.postcard` history. |
| `postcard.TemplatesTable`, `postcard.LayoutsTable`, `postcard.PartialsTable`, `postcard.BrandTable`, `postcard.ImageLibraryTable` | The names of the mail tables, for code that defines models over them. |
@@ -208,8 +289,8 @@ mail:
## Dependencies
- SummerCMS modules: [backpack](../backpack/README.md), [compass](../compass/README.md), [diary](../diary/README.md) (component logger `postcard` when the app publishes no logger), [pact](../pact/README.md).
- Third-party: `github.com/wneessen/go-mail` (SMTP), `github.com/yuin/goldmark` (Markdown), `gorm.io/gorm` (reading overrides), `github.com/go-gormigrate/gormigrate/v2` (the mail tables' migrations).
- Standard library: `bytes`, `context`, `embed`, `fmt`, `html/template`, `io/fs`, `log/slog`, `net/mail`, `regexp`, `strings`, `sync`, `text/template`, `time`.
- Third-party: `github.com/wneessen/go-mail` (SMTP), `github.com/yuin/goldmark` (Markdown, and its table extension inside partials), `gorm.io/gorm` (reading overrides), `github.com/go-gormigrate/gormigrate/v2` (the mail tables' migrations).
- Standard library: `bytes`, `context`, `crypto/rand`, `database/sql`, `embed`, `encoding/hex`, `fmt`, `html/template`, `io/fs`, `log/slog`, `net/mail`, `regexp`, `strconv`, `strings`, `sync`, `text/template`, `time`.
- Tests additionally use `github.com/testcontainers/testcontainers-go` (Mailpit and Postgres containers), `gorm.io/driver/postgres` and `github.com/jackc/pgx/v5`.
## Testing