feat(postcard): mail branding and the logo URL

- Brand, DefaultBrand and CompileBrandCSS: thirteen colours, each checked
  as a six-digit hex colour, compiled into CSS for plain elements and the
  built-in layouts and partials
- once the branding row exists its compiled CSS replaces mail.brandCss;
  mail.css still follows, and the file version sent after a failing
  override keeps the Branding
- layouts get logoUrl, built per send from storage.uploads.public_url or
  app.url through attach.AbsolutePublicURL; a logo that cannot be shown is
  left out with a rate-limited warning
- Editor previews and validates a Branding draft (rule colour)

Plan 35-01, task 5.
This commit is contained in:
Jakub Zych
2026-11-13 11:06:43 +01:00
parent 935e4bf64f
commit 2bf9081c1b
10 changed files with 974 additions and 27 deletions

View File

@@ -14,7 +14,7 @@ A plugin implements `pact.HasMailTemplates`: it returns its embedded `views/mail
The file format is WinterCMS's: an INI header with the `subject`, the `layout` alias and a `description`, a `==` line, then a Markdown body with Go template variables such as `{{ .name }}`. A layout has a header, a text wrapper and an HTML wrapper, separated by `==` lines, each with `{{ .Content }}` where the message goes. A template without a `layout` uses the built-in `default` layout; see [Built-in layouts](#built-in-layouts).
Each message gets an HTML part, rendered from the Markdown, and a plain-text part. `mail.css` and `mail.brandCss` are inlined into the layout's style block.
Each message gets an HTML part, rendered from the Markdown, and a plain-text part. `mail.css` and the brand CSS go into the layout's style block; see [Branding](#branding).
## Partials
@@ -61,6 +61,20 @@ Three layouts are available to every plugin's templates without declaring an ali
A plugin's own alias wins over `system` and `minimal`; `default` cannot be redefined.
## Branding
A layout's style block has a brand slot, `{{ .brandCss }}`, before `{{ .css }}`. Until the branding settings are saved for the first time, the brand slot holds `mail.brandCss` from the configuration. From the first save on, it holds CSS that postcard compiles from the saved colours, and `mail.brandCss` is no longer used. `mail.css` is applied either way.
The settings are thirteen colours: the page and content backgrounds, the header, footer, heading, text and link colours, the button text and the primary, positive and negative button backgrounds, the panel background and the table border. Each is a six-digit hexadecimal colour such as `#2da7c7`, and one left empty takes WinterCMS's default. The compiled CSS styles plain elements (the page, links, headings, paragraphs, tables) as well as the built-in layouts and partials, so it shows in any layout that has the style block.
The settings also hold a logo. A layout shows it where it uses `{{ .logoUrl }}`:
```text
{{ if .logoUrl }}<img src="{{ .logoUrl }}" alt="">{{ end }}
```
A mail client needs an absolute address, so the logo's URL is built at send time from the configuration: `storage.uploads.public_url` when it is set, otherwise `app.url` with `storage.uploads.public_path_prefix`; see [Absolute URLs for mail](storage.md#absolute-urls-for-mail). Set one of them, or the logo is left out and a warning is logged.
## Sample values for previews
A preview of a template has no caller to pass its variables. A template can therefore give sample values in its header, one key per variable: `sample.` followed by the variable's path, in the variable's own case.

View File

@@ -12,7 +12,7 @@ postcard is the mail layer of SummerCMS. Plugins that implement `pact.HasMailTem
## Role in the framework
A service module on `backpack`, `compass` and `pact`; `party` registers the templates plugins contribute, and `lagoon` runs `postcard.Migrations` with the framework's other migrations. postcard does not import `lagoon`: it finds the database through `backpack`. It is separate so mail rendering and delivery can be tested and swapped (memory, log, SMTP) without touching the code that sends.
A service module on `backpack`, `compass` and `pact`; `party` registers the templates plugins contribute, and `lagoon` runs `postcard.Migrations` with the framework's other migrations. postcard does not import `lagoon`: it finds the database through `backpack`, and uses only lagoon's `attach` package, for the logo's URL. It is separate so mail rendering and delivery can be tested and swapped (memory, log, SMTP) without touching the code that sends.
Use cases:
@@ -26,10 +26,11 @@ Use cases:
- 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). 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.
- Every message gets an HTML part (Markdown converted with goldmark) and a plain-text part. The brand CSS (`mail.brandCss`, or the saved Branding) and `mail.css` go 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, 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.
- Branding: once the branding settings have been saved, the brand CSS is compiled from their colours (`postcard.CompileBrandCSS`) and replaces `mail.brandCss`, and layouts get the logo's absolute URL as `{{ .logoUrl }}`.
- Sample values: a template's header may give its variables sample values with `sample.<path>` keys. Previews and save checks use them, and show every other variable as a visible `[path]` placeholder.
- An editor API for admin code (`postcard.Editor`): validate, preview and test-send an unsaved draft of a template, layout or partial through the same render path as a real send; one index row per file (`postcard.SyncIndex`) with a hash of the file for detecting that it changed under an override, and reset to the file version (`postcard.ResetOverride`).
- No locale selection: callers pass the full template name, including any locale suffix.
@@ -229,6 +230,41 @@ func newTestMailer(cat *postcard.Catalog, driver postcard.Driver) postcard.Maile
}
```
### Branding
Layouts have two CSS slots, `{{ .brandCss }}` and `{{ .css }}`, and a logo slot, `{{ .logoUrl }}`. What fills the brand slot depends on the row with `id` 1 of `system_mail_brand_settings`:
- While the row does not exist, the slot holds `mail.brandCss` from the configuration and `{{ .logoUrl }}` is empty, so an application that never saves Branding is unchanged.
- Once the row exists, the slot holds `postcard.CompileBrandCSS` of the row's colours, and `mail.brandCss` is no longer used. An empty colour column is that colour's default (`postcard.DefaultBrand`).
`mail.css` fills `{{ .css }}` in both cases, after the brand CSS, with a layout's own CSS before it.
The compiled CSS styles the page, links, headings, paragraphs and tables, and the classes of the built-in layouts and partials (`button button-primary`, `panel`, `table`, `subcopy`, `layout-system` and others), so the colours also apply in a plugin's layout that has the style block and no brand classes of its own. A colour must be a six-digit hexadecimal colour such as `#2da7c7`; `postcard.CompileBrandCSS` refuses anything else with an error naming the column. If a stored colour is invalid at send time, a warning is logged and `mail.brandCss` is used.
| Column | `postcard.Brand` field | Default |
|--------|------------------------|---------|
| `body_bg` | `BodyBg` | `#f5f8fa` |
| `content_bg` | `ContentBg` | `#ffffff` |
| `header_color` | `HeaderColor` | `#bbbfc3` |
| `footer_color` | `FooterColor` | `#aeaeae` |
| `heading_color` | `HeadingColor` | `#2f3133` |
| `text_color` | `TextColor` | `#74787e` |
| `link_color` | `LinkColor` | `#2da7c7` |
| `button_text_color` | `ButtonTextColor` | `#ffffff` |
| `button_primary_bg` | `ButtonPrimaryBg` | `#d66829` |
| `button_positive_bg` | `ButtonPositiveBg` | `#52a838` |
| `button_negative_bg` | `ButtonNegativeBg` | `#e01346` |
| `panel_bg` | `PanelBg` | `#edeff2` |
| `table_border_color` | `TableBorderColor` | `#edeff2` |
The row's `logo_file_id` names a public `system_files` row. Its URL is not stored: on every send it is built from the configuration with `attach.AbsolutePublicURL`, from `storage.uploads.public_url`, or from `app.url` and `storage.uploads.public_path_prefix`, so a worker process and `serve` produce the same absolute URL and a changed CDN address applies at once. When the file is missing or not public, or neither base is configured, `{{ .logoUrl }}` is empty, a warning is logged at most once a minute, and the mail is sent. A layout that shows the logo guards it:
```text
{{ if .logoUrl }}<img src="{{ .logoUrl }}" alt="">{{ end }}
```
A mail that falls back to its file version because an override failed still gets the Branding.
### Sample values
A preview has no caller to supply variables, so a template can carry sample values in its header. A key is `sample.` followed by the variable's path, and the path keeps its case, because template variables are case-sensitive:
@@ -289,8 +325,9 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
| `postcard.KindTemplate` | The template's full name | `Subject`, `Body`, `Layout` (a layout code; empty keeps the file's layout) | The template with its sample values and placeholders. |
| `postcard.KindLayout` | The layout's code | `HTML`, `Text`, `CSS` | The layout around postcard's sample message. |
| `postcard.KindPartial` | The partial's full name | `HTML`, `Text` | A message that is one call of the partial, with a placeholder for every argument it reads. |
| `postcard.KindBrand` | Not used | `Brand` (nil is the default brand) | The sample message in the default layout, with the draft's colours and logo in place of the saved Branding. |
`postcard.Editor.Validate` returns nil or a `postcard.DraftError`. `postcard.DraftError.Field` is the form field at fault: `subject`, `layout` or `body` for a template, `content_html`, `content_text` or `content_css` for a layout or a partial. `postcard.DraftError.Rule` is one of:
`postcard.Editor.Validate` returns nil or a `postcard.DraftError`. `postcard.DraftError.Field` is the form field at fault: `subject`, `layout` or `body` for a template, `content_html`, `content_text` or `content_css` for a layout or a partial, the colour's column for Branding. `postcard.DraftError.Rule` is one of:
| Rule | Meaning |
|------|---------|
@@ -301,6 +338,7 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
| `layout` | The template's layout code names no layout. |
| `partial` | A call names a partial that does not exist; `postcard.DraftError.Name` holds the name. |
| `no_content` | A layout wrapper does not use `{{ .Content }}`. |
| `colour` | A Branding colour is not a six-digit hexadecimal colour; the field is its column, such as `button_primary_bg`. |
`postcard.DraftError.Message` carries the template parser's, the renderer's or the safety check's own text and nothing else. The safety checks are the ones a send runs, so text such as `metadata:` is refused at save as it would be at send, and the message shows where. A template body is also refused when its source contains one of the unsafe tags, which Markdown would otherwise drop without notice.
@@ -338,16 +376,19 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
| `postcard.SMTPConfig` | Host, port, credentials, TLS policy and timeout for the SMTP driver. |
| `postcard.FailDriver` | Driver whose `postcard.FailDriver.Send` always returns `postcard.FailDriver.Err`. |
| `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.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`, partial content by name in `postcard.Overrides.Partials` and the saved Branding in `postcard.Overrides.Brand` (nil while it has never been saved). |
| `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 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.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. It builds the Branding logo's URL from the app's configuration. |
| `postcard.Brand` | The Branding: thirteen colours and `postcard.Brand.LogoURL`, the logo's absolute URL. |
| `postcard.DefaultBrand` | WinterCMS's default mail colours. |
| `postcard.CompileBrandCSS` | Checks a brand's colours and returns the brand CSS compiled from them. |
| `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. |
| `postcard.SyncIndex` | Upserts one index row per file template, layout and partial of a catalog; mirrors the file into rows that are not customized and refreshes `file_hash` on all. |
| `postcard.ResetOverride` | Returns one file-backed row to its file version. Takes the row's `postcard.Kind` and code. |
| `postcard.Kind` | What a draft or a row is: `postcard.KindTemplate`, `postcard.KindLayout`, `postcard.KindPartial` or `postcard.KindBrand` (reserved for the branding settings; the editor does not render it yet). |
| `postcard.Kind` | What a draft or a row is: `postcard.KindTemplate`, `postcard.KindLayout`, `postcard.KindPartial` or `postcard.KindBrand` (a Branding draft; it has no index row). |
| `postcard.Editor` | Validates, previews and test-sends drafts with the mailer's catalog, configuration, override source and driver. |
| `postcard.EditorFrom` | Returns the editor of the mailer published on an app. |
| `postcard.Editor.Catalog` | The mailer's catalog. |
@@ -364,14 +405,14 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
## Configuration
`postcard.Activate` reads these keys from the app's [compass](../compass/README.md) config:
`postcard.Activate` reads these keys from the app's [compass](../compass/README.md) config. The Branding logo's URL also reads `storage.uploads.public_url`, `storage.uploads.public_path_prefix` and `app.url`, which belong to [lagoon](../lagoon/README.md)'s `attach` and to the application.
| Key | Default | Controls |
|-----|---------|----------|
| `mail.driver` | `memory` | Delivery driver: `memory`, `log` or `smtp`. Any other value fails at boot. |
| `mail.from` | empty | Sender address. Required by the SMTP driver. |
| `mail.css` | empty | CSS inlined into the layout. |
| `mail.brandCss` | empty | Brand CSS inlined before `mail.css`. |
| `mail.css` | empty | CSS placed in the layout's style block, after the brand CSS. Always applied. |
| `mail.brandCss` | empty | Brand CSS placed before `mail.css`. Used only until the branding settings are saved; from then on the CSS compiled from their colours replaces it (see [Branding](#branding)). |
| `mail.smtp.host` | none | SMTP host. Required when `mail.driver` is `smtp`. |
| `mail.smtp.port` | `587` | SMTP port. |
| `mail.smtp.username` | empty | SMTP user. When set, PLAIN authentication is used. |
@@ -393,7 +434,7 @@ 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).
- 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), and the `attach` package of [lagoon](../lagoon/README.md) (`attach.AbsolutePublicURL` and `attach.BlobKey` for the logo's URL; lagoon itself is not imported).
- 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`, `crypto/sha256`, `database/sql`, `embed`, `encoding/hex`, `errors`, `fmt`, `html/template`, `io/fs`, `log/slog`, `net/mail`, `regexp`, `sort`, `strconv`, `strings`, `sync`, `text/template` (and `text/template/parse`), `time`.
- Tests additionally use `github.com/testcontainers/testcontainers-go` (Mailpit and Postgres containers), `gorm.io/driver/postgres` and `github.com/jackc/pgx/v5`.

View File

@@ -0,0 +1,201 @@
/* Base */
body, body *:not(html):not(style):not(br):not(tr):not(code) {
font-family: Avenir, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
background-color: {{ .BodyBg }};
color: {{ .TextColor }};
height: 100%;
line-height: 1.4;
margin: 0;
width: 100% !important;
word-break: break-word;
-webkit-text-size-adjust: none;
}
p, ul, ol, blockquote {
line-height: 1.4;
text-align: left;
}
a {
color: {{ .LinkColor }};
}
a img {
border: none;
}
/* Typography */
h1 {
color: {{ .HeadingColor }};
font-size: 19px;
font-weight: bold;
margin-top: 0;
text-align: left;
}
h2 {
color: {{ .HeadingColor }};
font-size: 16px;
font-weight: bold;
margin-top: 0;
text-align: left;
}
h3 {
color: {{ .HeadingColor }};
font-size: 14px;
font-weight: bold;
margin-top: 0;
text-align: left;
}
p {
color: {{ .TextColor }};
font-size: 16px;
line-height: 1.5em;
margin-top: 0;
text-align: left;
}
code {
color: {{ .TextColor }};
font-size: 16px;
line-height: 1.5em;
word-break: break-all;
}
p.sub {
font-size: 12px;
}
img {
max-width: 100%;
}
.break-all, .break-all * {
word-break: break-all;
}
/* Layout */
.wrapper {
background-color: {{ .BodyBg }};
margin: 0;
padding: 0;
width: 100%;
}
.content {
margin: 0;
padding: 0;
width: 100%;
}
/* Header */
.header {
padding: 25px 0;
text-align: center;
}
.header a, .header span {
color: {{ .HeaderColor }};
font-size: 19px;
font-weight: bold;
text-decoration: none;
}
/* Body */
.body {
background-color: {{ .ContentBg }};
border-bottom: 1px solid {{ .TableBorderColor }};
border-top: 1px solid {{ .TableBorderColor }};
margin: 0;
padding: 0;
width: 100%;
}
.inner-body {
background-color: {{ .ContentBg }};
margin: 0 auto;
padding: 0;
width: 570px;
}
.content-cell {
padding: 35px;
}
.wrapper.layout-system .content-cell {
padding: 35px 0;
}
/* Subcopy */
.subcopy {
border-top: 1px solid {{ .TableBorderColor }};
margin-top: 25px;
padding-top: 25px;
}
.subcopy p {
font-size: 12px;
}
/* Footer */
.footer {
margin: 0 auto;
padding: 0;
text-align: center;
width: 570px;
}
.footer p {
color: {{ .FooterColor }};
font-size: 12px;
text-align: center;
}
/* Tables */
.table table {
border-collapse: collapse;
margin: 30px auto;
width: 100%;
}
.table th {
border-bottom: 1px solid {{ .TableBorderColor }};
padding-bottom: 8px;
}
.table td {
color: {{ .TextColor }};
font-size: 15px;
line-height: 18px;
padding: 10px 0;
}
/* Buttons */
.action {
margin: 30px auto;
padding: 0;
text-align: center;
width: 100%;
}
.button {
border-radius: 3px;
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.16);
color: {{ .ButtonTextColor }};
display: inline-block;
text-decoration: none;
-webkit-text-size-adjust: none;
}
.button-primary {
background-color: {{ .ButtonPrimaryBg }};
border-top: 10px solid {{ .ButtonPrimaryBg }};
border-right: 18px solid {{ .ButtonPrimaryBg }};
border-bottom: 10px solid {{ .ButtonPrimaryBg }};
border-left: 18px solid {{ .ButtonPrimaryBg }};
}
.button-positive {
background-color: {{ .ButtonPositiveBg }};
border-top: 10px solid {{ .ButtonPositiveBg }};
border-right: 18px solid {{ .ButtonPositiveBg }};
border-bottom: 10px solid {{ .ButtonPositiveBg }};
border-left: 18px solid {{ .ButtonPositiveBg }};
}
.button-negative {
background-color: {{ .ButtonNegativeBg }};
border-top: 10px solid {{ .ButtonNegativeBg }};
border-right: 18px solid {{ .ButtonNegativeBg }};
border-bottom: 10px solid {{ .ButtonNegativeBg }};
border-left: 18px solid {{ .ButtonNegativeBg }};
}
/* Panels */
.panel {
margin: 0 0 21px;
}
.panel-content {
background-color: {{ .PanelBg }};
padding: 16px;
}
.panel-item {
padding: 0;
}
.panel-item p:last-of-type {
margin-bottom: 0;
padding-bottom: 0;
}

128
modules/postcard/brand.go Normal file
View File

@@ -0,0 +1,128 @@
package postcard
import (
"bytes"
_ "embed"
"regexp"
"strings"
"sync"
texttemplate "text/template"
)
// Brand is the mail branding: the colours the brand CSS is compiled from
// and the logo layouts show. A colour is a six-digit hexadecimal colour such
// as #2da7c7; an empty colour is that field's default.
type Brand struct {
BodyBg string
ContentBg string
HeaderColor string
FooterColor string
HeadingColor string
TextColor string
LinkColor string
ButtonTextColor string
ButtonPrimaryBg string
ButtonPositiveBg string
ButtonNegativeBg string
PanelBg string
TableBorderColor string
// LogoURL is the absolute URL of the logo, given to layouts as
// {{ .logoUrl }}. It is not part of the CSS.
LogoURL string
}
// DefaultBrand returns WinterCMS's default mail colours.
func DefaultBrand() Brand {
return Brand{
BodyBg: "#f5f8fa",
ContentBg: "#ffffff",
HeaderColor: "#bbbfc3",
FooterColor: "#aeaeae",
HeadingColor: "#2f3133",
TextColor: "#74787e",
LinkColor: "#2da7c7",
ButtonTextColor: "#ffffff",
ButtonPrimaryBg: "#d66829",
ButtonPositiveBg: "#52a838",
ButtonNegativeBg: "#e01346",
PanelBg: "#edeff2",
TableBorderColor: "#edeff2",
}
}
// brandColours lists a brand's colours in the order they are checked, each
// under the name of its column in the branding table.
func brandColours(b *Brand) []brandColour {
return []brandColour{
{"body_bg", &b.BodyBg},
{"content_bg", &b.ContentBg},
{"header_color", &b.HeaderColor},
{"footer_color", &b.FooterColor},
{"heading_color", &b.HeadingColor},
{"text_color", &b.TextColor},
{"link_color", &b.LinkColor},
{"button_text_color", &b.ButtonTextColor},
{"button_primary_bg", &b.ButtonPrimaryBg},
{"button_positive_bg", &b.ButtonPositiveBg},
{"button_negative_bg", &b.ButtonNegativeBg},
{"panel_bg", &b.PanelBg},
{"table_border_color", &b.TableBorderColor},
}
}
type brandColour struct {
column string
value *string
}
// brandColourError is a brand colour that is not a six-digit hexadecimal
// colour. The value is left out: it may be anything.
type brandColourError struct {
column string
}
func (e *brandColourError) Error() string {
return "postcard: brand colour " + e.column + " must be a six-digit hexadecimal colour such as #2da7c7"
}
var hexColour = regexp.MustCompile(`^#[0-9a-f]{6}$`)
//go:embed assets/brand.css.tmpl
var brandCSSSource string
var (
brandCSSOnce sync.Once
brandCSSTemplate *texttemplate.Template
)
// CompileBrandCSS returns the brand CSS for b: styles for the page, links,
// headings, paragraphs and tables and for the classes of the built-in
// layouts and partials (button, panel, table, subcopy), so that the colours
// also show in a plugin's layout that carries no class of its own. Every
// colour must be a six-digit hexadecimal colour; upper-case digits are
// accepted and written lower-case, and an empty colour is that field's
// default. The error of an invalid colour names its column, such as
// button_primary_bg.
func CompileBrandCSS(b Brand) (string, error) {
def := DefaultBrand()
defaults := brandColours(&def)
for i, c := range brandColours(&b) {
colour := strings.ToLower(*c.value)
if colour == "" {
colour = *defaults[i].value
}
// Nothing but a checked colour reaches the style block.
if !hexColour.MatchString(colour) {
return "", &brandColourError{column: c.column}
}
*c.value = colour
}
brandCSSOnce.Do(func() {
brandCSSTemplate = texttemplate.Must(texttemplate.New("brand.css").Parse(brandCSSSource))
})
var buf bytes.Buffer
if err := brandCSSTemplate.Execute(&buf, b); err != nil {
return "", err
}
return buf.String(), nil
}

View File

@@ -0,0 +1,400 @@
package postcard
import (
"context"
"errors"
"path/filepath"
"reflect"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"github.com/go-gormigrate/gormigrate/v2"
)
// brandCfg writes config files and opens them: files maps a config file
// name such as mail.yaml to its content.
func brandCfg(t *testing.T, files map[string]string) *compass.Config {
t.Helper()
dir := t.TempDir()
for name, body := range files {
writeFile(t, filepath.Join(dir, name), body)
}
return loadMailCfg(t, dir, nil)
}
// styleBlock returns the content of the first style element of html.
func styleBlock(t *testing.T, html string) string {
t.Helper()
_, rest, ok := strings.Cut(html, "<style")
if !ok {
t.Fatalf("no style block in %q", html)
}
_, rest, _ = strings.Cut(rest, ">")
css, _, _ := strings.Cut(rest, "</style>")
return css
}
// TestMailBrandSmoke covers Branding: the compiled brand CSS and its colour
// checks, the precedence over mail.brandCss once the settings row exists,
// the logo URL built at send time from configuration, and the editor's
// preview of unsaved colours.
func TestMailBrandSmoke(t *testing.T) {
ctx := context.Background()
t.Run("absolute_url", func(t *testing.T) {
const key = "abc/def/123/abcdef123456.png"
cases := []struct {
name string
files map[string]string
want string
}{
{"public_url", map[string]string{"storage.yaml": "uploads:\n public_url: https://cdn.example.com/u\n", "app.yaml": "url: https://acme.test\n"}, "https://cdn.example.com/u/" + key},
{"public_url trailing slash", map[string]string{"storage.yaml": "uploads:\n public_url: https://cdn.example.com/u/\n"}, "https://cdn.example.com/u/" + key},
{"app.url and the default prefix", map[string]string{"app.yaml": "url: https://acme.test\n"}, "https://acme.test/storage/uploads/" + key},
{"app.url with a path and a prefix", map[string]string{"app.yaml": "url: https://acme.test/shop/\n", "storage.yaml": "uploads:\n public_path_prefix: /files/\n"}, "https://acme.test/shop/files/" + key},
}
for _, tc := range cases {
got, err := attach.AbsolutePublicURL(brandCfg(t, tc.files), "/"+key)
if err != nil || got != tc.want {
t.Errorf("%s: %q, %v; want %q", tc.name, got, err, tc.want)
}
}
for name, files := range map[string]map[string]string{
"neither": {"mail.yaml": "driver: memory\n"},
"relative app.url": {"app.yaml": "url: /shop\n"},
"app.url no scheme": {"app.yaml": "url: acme.test\n"},
"app.url ftp": {"app.yaml": "url: ftp://acme.test\n"},
} {
if got, err := attach.AbsolutePublicURL(brandCfg(t, files), key); !errors.Is(err, attach.ErrNoAbsoluteURL) || got != "" {
t.Errorf("%s: %q, %v; want ErrNoAbsoluteURL", name, got, err)
}
}
if _, err := attach.AbsolutePublicURL(nil, key); !errors.Is(err, attach.ErrNoAbsoluteURL) {
t.Errorf("nil config: %v", err)
}
if _, err := attach.AbsolutePublicURL(brandCfg(t, map[string]string{"storage.yaml": "uploads:\n public_url: cdn.example.com\n", "app.yaml": "url: https://acme.test\n"}), key); err == nil || errors.Is(err, attach.ErrNoAbsoluteURL) {
t.Errorf("a malformed public_url = %v, want its own error", err)
}
})
t.Run("defaults", func(t *testing.T) {
want := Brand{
BodyBg: "#f5f8fa", ContentBg: "#ffffff", HeaderColor: "#bbbfc3", FooterColor: "#aeaeae",
HeadingColor: "#2f3133", TextColor: "#74787e", LinkColor: "#2da7c7", ButtonTextColor: "#ffffff",
ButtonPrimaryBg: "#d66829", ButtonPositiveBg: "#52a838", ButtonNegativeBg: "#e01346",
PanelBg: "#edeff2", TableBorderColor: "#edeff2",
}
if got := DefaultBrand(); got != want {
t.Errorf("DefaultBrand() = %+v, want %+v", got, want)
}
})
t.Run("compile", func(t *testing.T) {
// Thirteen distinct colours, so each one can be found in the output.
b := Brand{
BodyBg: "#010101", ContentBg: "#020202", HeaderColor: "#030303", FooterColor: "#040404",
HeadingColor: "#050505", TextColor: "#060606", LinkColor: "#070707", ButtonTextColor: "#080808",
ButtonPrimaryBg: "#090909", ButtonPositiveBg: "#0a0a0a", ButtonNegativeBg: "#0b0b0b",
PanelBg: "#0c0c0c", TableBorderColor: "#0d0d0d",
}
css, err := CompileBrandCSS(b)
if err != nil {
t.Fatalf("CompileBrandCSS: %v", err)
}
v := reflect.ValueOf(b)
for i := range v.NumField() {
if colour := v.Field(i).String(); colour != "" && !strings.Contains(css, colour) {
t.Errorf("compiled CSS lacks %s (%s)", v.Type().Field(i).Name, colour)
}
}
for _, want := range []string{
"body {", "background-color: #010101", "a {\n\tcolor: #070707", "h1 {\n\tcolor: #050505",
".button-primary {\n\tbackground-color: #090909", ".button-positive {\n\tbackground-color: #0a0a0a",
".button-negative {\n\tbackground-color: #0b0b0b", ".panel-content {\n\tbackground-color: #0c0c0c",
".table th {\n\tborder-bottom: 1px solid #0d0d0d", ".subcopy {", ".footer p {\n\tcolor: #040404",
".header a, .header span {\n\tcolor: #030303", ".body {\n\tbackground-color: #020202",
} {
if !strings.Contains(css, want) {
t.Errorf("compiled CSS lacks %q", want)
}
}
if err := validateHTML("<style>" + css + "</style>"); err != nil {
t.Errorf("the compiled CSS fails the mail safety checks: %v", err)
}
if strings.Contains(css, "<") || strings.Contains(css, "{{") {
t.Errorf("compiled CSS holds markup or an unexecuted action:\n%s", css)
}
def, err := CompileBrandCSS(DefaultBrand())
if err != nil {
t.Fatal(err)
}
for _, colour := range []string{"#f5f8fa", "#ffffff", "#bbbfc3", "#aeaeae", "#2f3133", "#74787e", "#2da7c7", "#d66829", "#52a838", "#e01346", "#edeff2"} {
if !strings.Contains(def, colour) {
t.Errorf("default CSS lacks %s", colour)
}
}
// An empty colour is that field's default; the zero Brand is the default brand.
if zero, err := CompileBrandCSS(Brand{}); err != nil || zero != def {
t.Errorf("CompileBrandCSS(Brand{}) differs from the default brand: %v", err)
}
// Upper-case hex is accepted and emitted lower-case.
upper, err := CompileBrandCSS(Brand{ButtonPrimaryBg: "#AB12CD"})
if err != nil || !strings.Contains(upper, "#ab12cd") || strings.Contains(upper, "#AB12CD") {
t.Errorf("upper-case hex: %v", err)
}
// The logo URL is not a colour and does not reach the CSS.
if with, err := CompileBrandCSS(Brand{LogoURL: "https://cdn.example.com/logo.png"}); err != nil || with != def {
t.Errorf("LogoURL changed the CSS: %v", err)
}
bad := map[string]string{
"short hex": "#ABC",
"name": "red",
"style end": "#fff</style><script>",
"no hash": "aabbcc",
"eight": "#aabbccdd",
"expression": "#aabbcc;} body{display:none",
"spaces": " #aabbcc",
}
for name, colour := range bad {
_, err := CompileBrandCSS(Brand{PanelBg: colour})
if err == nil || !strings.Contains(err.Error(), "panel_bg") {
t.Errorf("%s (%q): error = %v, want one naming panel_bg", name, colour, err)
}
if err != nil && strings.Contains(err.Error(), "<script>") {
t.Errorf("%s: the error repeats the value: %v", name, err)
}
}
if _, err := CompileBrandCSS(Brand{BodyBg: "x", LinkColor: "y"}); err == nil || !strings.Contains(err.Error(), "body_bg") {
t.Errorf("the first bad field is not named: %v", err)
}
})
t.Run("preview", func(t *testing.T) {
ed, drv := newEditor(t, nil)
ed.m.opts.CSS, ed.m.opts.BrandCSS = "p{margin:1px}", ".cfg{color:blue}"
draft := Draft{Kind: KindBrand, Brand: &Brand{LinkColor: "#112233", ButtonPrimaryBg: "#445566"}}
if problem := ed.Validate(ctx, draft); problem != nil {
t.Fatalf("a valid brand draft was refused: %+v", problem)
}
got, err := ed.Preview(ctx, draft)
if err != nil {
t.Fatalf("Preview: %v", err)
}
css := styleBlock(t, got.HTML)
if !strings.Contains(css, "color: #112233") || !strings.Contains(css, "background-color: #445566") {
t.Errorf("the draft colours are not in the style block:\n%s", css)
}
if strings.Contains(css, ".cfg{color:blue}") || !strings.HasSuffix(css, "p{margin:1px}") {
t.Errorf("the draft CSS must replace mail.brandCss and leave mail.css after it:\n%s", css)
}
for _, want := range []string{`<div class="content-body"><h1>`, `class="button button-primary"`, `<table class="panel`} {
if !strings.Contains(got.HTML, want) {
t.Errorf("brand preview lacks %q:\n%s", want, got.HTML)
}
}
if got.Subject == "" || got.Text == "" {
t.Errorf("brand preview = %+v", got)
}
// A draft without colours previews the defaults.
if got, err = ed.Preview(ctx, Draft{Kind: KindBrand}); err != nil || !strings.Contains(got.HTML, "#d66829") {
t.Errorf("a brand draft without colours: %v", err)
}
bad := ed.Validate(ctx, Draft{Kind: KindBrand, Brand: &Brand{ButtonPrimaryBg: "red"}})
if bad == nil || bad.Field != "button_primary_bg" || bad.Rule != "colour" {
t.Errorf("an invalid colour = %+v, want field button_primary_bg rule colour", bad)
}
var de *DraftError
if _, err := ed.Preview(ctx, Draft{Kind: KindBrand, Brand: &Brand{TableBorderColor: "#12"}}); !errors.As(err, &de) || de.Field != "table_border_color" {
t.Errorf("Preview with an invalid colour = %v", err)
}
// The logo of the draft reaches a layout that uses logoUrl, and the
// saved Branding of the source is replaced by the draft.
ed, _ = newEditor(t, &Overrides{
Brand: &Brand{LinkColor: "#999999", LogoURL: "https://cdn.example.com/saved.png"},
Layouts: map[string]LayoutOverride{defaultLayoutName: {HTML: `<img src="{{ .logoUrl }}" alt=""><style>{{ .brandCss }}</style>{{ .Content }}`, Text: "{{ .logoUrl }}\n{{ .Content }}"}},
})
got, err = ed.Preview(ctx, Draft{Kind: KindBrand, Brand: &Brand{LinkColor: "#112233", LogoURL: "https://cdn.example.com/u/logo.png"}})
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(got.HTML, `<img src="https://cdn.example.com/u/logo.png" alt="">`) || !strings.Contains(got.HTML, "#112233") || strings.Contains(got.HTML, "#999999") {
t.Errorf("brand preview with a logo:\n%s", got.HTML)
}
if !strings.HasPrefix(got.Text, "https://cdn.example.com/u/logo.png\n") {
t.Errorf("text = %q", got.Text)
}
// Other drafts are previewed with the saved Branding.
got, err = ed.Preview(ctx, Draft{Kind: KindTemplate, Name: editorWelcome, Subject: "x", Body: "Hi.", Layout: defaultLayoutName})
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(got.HTML, `<img src="https://cdn.example.com/saved.png" alt="">`) || !strings.Contains(got.HTML, "#999999") {
t.Errorf("a template preview does not use the saved Branding:\n%s", got.HTML)
}
// A test send of a brand draft goes to the one address.
ed, drv = newEditor(t, nil)
if err := ed.SendDraft(ctx, draft, "admin@example.com"); err != nil {
t.Fatalf("SendDraft: %v", err)
}
if msg := lastMessage(t, drv); len(msg.To) != 1 || msg.To[0] != "admin@example.com" || !strings.Contains(msg.HTML, "#445566") {
t.Errorf("brand draft mail = %+v", msg)
}
})
t.Run("precedence", func(t *testing.T) {
gdb := mailPostgres(t)
cfg := brandCfg(t, map[string]string{"mail.yaml": "driver: memory\ncss: \"p{margin:1px}\"\nbrandCss: \".cfg{color:blue}\"\n"})
m, drv, logs := bootMailAppCfg(t, gdb, cfg)
// No Branding row: the configured brand CSS, as before.
sendFixture(t, m, acmeNotice, "")
if css := styleBlock(t, lastMessage(t, drv).HTML); css != ".cfg{color:blue}p{margin:1px}" {
t.Errorf("without a Branding row the style block = %q, want mail.brandCss then mail.css", css)
}
// The row exists: its compiled colours replace mail.brandCss.
if err := gdb.Exec(`INSERT INTO ` + BrandTable + ` (id, link_color) VALUES (1, '#112233')`).Error; err != nil {
t.Fatal(err)
}
sendFixture(t, m, acmeNotice, "")
css := styleBlock(t, lastMessage(t, drv).HTML)
want, err := CompileBrandCSS(Brand{LinkColor: "#112233"})
if err != nil {
t.Fatal(err)
}
if css != want+"p{margin:1px}" {
t.Errorf("with a Branding row the style block is not the compiled CSS followed by mail.css:\n%s", css)
}
if strings.Contains(css, ".cfg{color:blue}") || !strings.Contains(css, "color: #112233") || !strings.Contains(css, "#d66829") {
t.Errorf("style block = %q", css)
}
if logs.Len() != 0 {
t.Errorf("unexpected log output:\n%s", logs)
}
// A failing template override falls back to the file version, which
// still carries the Branding.
customizeTemplate(t, gdb, acmeNotice, "Hello", "{{ .order.code }}", "")
sendFixture(t, m, acmeNotice, "")
got := lastMessage(t, drv)
if got.Subject != "Notice" || styleBlock(t, got.HTML) != want+"p{margin:1px}" {
t.Errorf("the file version sent after a failing override lost the Branding: %+v", got)
}
if !strings.Contains(logs.String(), "override failed") {
t.Errorf("log = %q, want the override failure", logs)
}
// A colour that is not valid keeps mail.brandCss and says so.
logs.Reset()
if err := gdb.Exec(`UPDATE ` + TemplatesTable + ` SET is_custom = FALSE`).Error; err != nil {
t.Fatal(err)
}
if err := gdb.Exec(`UPDATE ` + BrandTable + ` SET panel_bg = 'red' WHERE id = 1`).Error; err != nil {
t.Fatal(err)
}
sendFixture(t, m, acmeNotice, "")
if css := styleBlock(t, lastMessage(t, drv).HTML); css != ".cfg{color:blue}p{margin:1px}" {
t.Errorf("with an invalid colour the style block = %q, want the configured CSS", css)
}
if out := logs.String(); !strings.Contains(out, "level=WARN") || !strings.Contains(out, "panel_bg") {
t.Errorf("log = %q, want a warning naming panel_bg", out)
}
// The source reports the row as it is, without a template name too.
ov, err := NewDBSource(appWith(t, gdb)).MailOverrides(ctx, "")
if err != nil || ov.Brand == nil || ov.Brand.LinkColor != "#112233" || ov.Brand.PanelBg != "red" || ov.Brand.LogoURL != "" {
t.Errorf("Brand from the source = %+v, %v", ov.Brand, err)
}
})
t.Run("logo", func(t *testing.T) {
gdb := mailPostgres(t)
if err := gormigrate.New(gdb, &gormigrate.Options{TableName: "attach_migrations", IDColumnName: "id", IDColumnSize: 255}, attach.Migrations).Migrate(); err != nil {
t.Fatalf("attach migrations: %v", err)
}
stmts := []string{
`INSERT INTO system_files (id, disk_name, file_name, file_size, content_type, is_public) VALUES
(7, 'abcdef123456.png', 'logo.png', 10, 'image/png', TRUE),
(8, 'fedcba654321.png', 'private.png', 10, 'image/png', FALSE)`,
`INSERT INTO ` + BrandTable + ` (id, logo_file_id) VALUES (1, 7)`,
// A layout that shows the logo, for the welcome template.
`INSERT INTO ` + LayoutsTable + ` (code, source, name, content_html, content_text, is_custom) VALUES
('acme.blog::mail.layouts.blog', 'acme.blog', 'Blog', '{{ if .logoUrl }}<img src="{{ .logoUrl }}" alt="">{{ end }}<div>{{ .Content }}</div>', '[{{ .logoUrl }}] {{ .Content }}', TRUE)`,
}
for _, stmt := range stmts {
if err := gdb.Exec(stmt).Error; err != nil {
t.Fatal(err)
}
}
const key = "abc/def/123/abcdef123456.png"
send := func(files map[string]string) (RenderedMessage, string) {
t.Helper()
m, drv, logs := bootMailAppCfg(t, gdb, brandCfg(t, files))
sendWelcome(t, m, "")
return lastMessage(t, drv), logs.String()
}
// storage.uploads.public_url wins; no bucket was opened in this process.
got, logged := send(map[string]string{"storage.yaml": "uploads:\n public_url: https://cdn.example.com/u\n", "app.yaml": "url: https://acme.test\n"})
if !strings.HasPrefix(got.HTML, `<img src="https://cdn.example.com/u/`+key+`" alt=""><div>`) || !strings.HasPrefix(got.Text, "[https://cdn.example.com/u/"+key+"] ") {
t.Errorf("logo from public_url: %q / %q", got.HTML, got.Text)
}
if logged != "" {
t.Errorf("unexpected log output: %s", logged)
}
// Otherwise app.url and the public path prefix.
got, _ = send(map[string]string{"app.yaml": "url: https://acme.test\n"})
if !strings.HasPrefix(got.HTML, `<img src="https://acme.test/storage/uploads/`+key+`" alt=""><div>`) {
t.Errorf("logo from app.url: %q", got.HTML)
}
// Neither is configured: no logo, a warning, the mail is sent.
got, logged = send(map[string]string{"mail.yaml": "driver: memory\n"})
if !strings.HasPrefix(got.HTML, "<div><p>Hi <strong>Ada</strong>") || !strings.HasPrefix(got.Text, "[] ") {
t.Errorf("without a base URL: %q / %q", got.HTML, got.Text)
}
if !strings.Contains(logged, "level=WARN") || !strings.Contains(logged, "logo") {
t.Errorf("log = %q, want a warning about the logo", logged)
}
// A file that is not public, and a file that is gone.
for name, id := range map[string]int{"not public": 8, "missing": 99} {
if err := gdb.Exec(`UPDATE `+BrandTable+` SET logo_file_id = ? WHERE id = 1`, id).Error; err != nil {
t.Fatal(err)
}
got, logged = send(map[string]string{"app.yaml": "url: https://acme.test\n"})
if !strings.HasPrefix(got.HTML, "<div><p>Hi <strong>Ada</strong>") || strings.Contains(got.HTML, "<img") {
t.Errorf("%s: %q", name, got.HTML)
}
if !strings.Contains(logged, "level=WARN") || !strings.Contains(logged, "logo") {
t.Errorf("%s: log = %q, want a warning about the logo", name, logged)
}
}
// No logo chosen: no warning.
if err := gdb.Exec(`UPDATE ` + BrandTable + ` SET logo_file_id = NULL WHERE id = 1`).Error; err != nil {
t.Fatal(err)
}
if got, logged = send(map[string]string{"app.yaml": "url: https://acme.test\n"}); strings.Contains(got.HTML, "<img") || logged != "" {
t.Errorf("without a logo: %q, log %q", got.HTML, logged)
}
// The files table missing altogether does not lose the other overrides.
if err := gdb.Exec(`UPDATE ` + BrandTable + ` SET logo_file_id = 7, link_color = '#112233' WHERE id = 1`).Error; err != nil {
t.Fatal(err)
}
if err := gdb.Exec(`DROP TABLE system_files`).Error; err != nil {
t.Fatal(err)
}
ov, err := NewDBSource(appWithCfg(t, gdb, brandCfg(t, map[string]string{"app.yaml": "url: https://acme.test\n"}))).MailOverrides(ctx, acmeWelcome)
if err != nil || ov.Brand == nil || ov.Brand.LinkColor != "#112233" || ov.Brand.LogoURL != "" || len(ov.Layouts) != 1 {
t.Errorf("overrides without system_files = %+v, %v", ov, err)
}
})
}

View File

@@ -44,6 +44,9 @@ type Draft struct {
HTML string
Text string
CSS string
// Brand is a branding draft. Nil is the default brand.
Brand *Brand
}
// The rules a DraftError reports.
@@ -55,6 +58,7 @@ const (
ruleLayout = "layout"
rulePartial = "partial"
ruleNoContent = "no_content"
ruleColour = "colour"
)
// The fields a DraftError names: the columns an admin form binds.
@@ -71,10 +75,10 @@ const (
type DraftError struct {
// Field is the form field at fault: subject, layout or body for a
// template, content_html, content_text or content_css for a layout or a
// partial.
// partial, the colour's column such as button_primary_bg for Branding.
Field string
// Rule is what failed: parse, render, unsafe, subject_line, layout,
// partial or no_content.
// partial, no_content or colour.
Rule string
// Message is the parser's, renderer's or safety check's own text, and
// for the unsafe rule the text that matched. It carries nothing else.
@@ -144,8 +148,9 @@ func (e *Editor) Validate(ctx context.Context, d Draft) *DraftError {
// Preview renders a draft: a template with its sample values and visible
// [name] placeholders, a layout around postcard's sample message, a partial
// called with placeholder arguments. Layouts, partials and other pieces the
// draft does not carry come from the mailer's override source, as in a send.
// called with placeholder arguments, Branding as the sample message in the
// default layout. Layouts, partials, Branding and other pieces the draft
// does not carry come from the mailer's override source, as in a send.
// A problem with the draft is returned as a *DraftError.
func (e *Editor) Preview(ctx context.Context, d Draft) (Preview, error) {
msg, err := e.render(ctx, d)
@@ -187,8 +192,10 @@ func (e *Editor) render(ctx context.Context, d Draft) (RenderedMessage, error) {
// stored override of a template being edited is replaced by the draft.
ov := m.overrides(ctx, "")
ov.Template = nil
opts := renderOptions{css: m.opts.CSS, brandCSS: m.opts.BrandCSS}
opts := m.options(ov.Brand)
switch d.Kind {
case KindBrand:
return e.renderBrand(d, ov, opts)
case KindTemplate:
return e.renderTemplate(d, ov, opts)
case KindLayout:
@@ -301,6 +308,25 @@ func (e *Editor) renderPartial(d Draft, ov Overrides, opts renderOptions) (Rende
return msg, nil
}
// renderBrand renders the sample message in the default layout with the
// draft's colours and logo in place of the saved Branding.
func (e *Editor) renderBrand(d Draft, ov Overrides, opts renderOptions) (RenderedMessage, error) {
brand := DefaultBrand()
if d.Brand != nil {
brand = *d.Brand
}
css, err := CompileBrandCSS(brand)
if err != nil {
return RenderedMessage{}, err
}
opts.brandCSS, opts.logoURL = css, brand.LogoURL
opts.overrides = ov
sample := sampleMessage()
return e.m.catalog.renderFrom(Message{
Vars: placeholderVars(sample.samples, sample.subject, sample.body),
}, renderSource{name: sample.name, subject: sample.subject, body: sample.body}, opts)
}
// usesContent reports whether a layout wrapper reads .Content, and whether
// the wrapper parsed at all.
func usesContent(src string) (uses, parsed bool) {
@@ -366,6 +392,10 @@ func draftErrorFor(d Draft, err error) *DraftError {
if errors.As(err, &de) {
return de
}
var colour *brandColourError
if errors.As(err, &colour) {
return &DraftError{Field: colour.column, Rule: ruleColour}
}
part := ""
var re *renderError
if errors.As(err, &re) {

View File

@@ -101,11 +101,13 @@ func (m *mailer) Send(ctx context.Context, msg Message) error {
// overrides, or overrides that fail to render or to pass the safety checks,
// it renders the file version.
func (m *mailer) render(ctx context.Context, msg Message) (RenderedMessage, error) {
file := renderOptions{css: m.opts.CSS, brandCSS: m.opts.BrandCSS}
if _, err := m.catalog.lookupTemplate(msg.Template); err != nil {
return RenderedMessage{}, err
}
ov := m.overrides(ctx, msg.Template)
// The file version carries the Branding too: it is not an override of a
// file, and a failing override must not change how the mail looks.
file := m.options(ov.Brand)
if ov.empty() {
return m.catalog.render(msg, file)
}
@@ -130,6 +132,26 @@ func (m *mailer) render(ctx context.Context, msg Message) (RenderedMessage, erro
return rendered, nil
}
// options returns the render options of the file version: mail.css, and
// either the saved Branding (its compiled CSS and its logo) or, while none
// has been saved, mail.brandCss. A Branding whose colours do not compile
// keeps mail.brandCss.
func (m *mailer) options(brand *Brand) renderOptions {
opts := renderOptions{css: m.opts.CSS, brandCSS: m.opts.BrandCSS}
if brand == nil {
return opts
}
opts.logoURL = brand.LogoURL
css, err := CompileBrandCSS(*brand)
if err != nil {
m.warn(err.Error(), "postcard: mail branding is not valid, using mail.brandCss",
slog.String("error", err.Error()))
return opts
}
opts.brandCSS = css
return opts
}
// overrides asks the source once. A failed lookup (no connection, tables not
// migrated yet) is a warning, not a send failure: the file version is sent.
func (m *mailer) overrides(ctx context.Context, template string) Overrides {
@@ -144,6 +166,9 @@ func (m *mailer) overrides(ctx context.Context, template string) Overrides {
)
return Overrides{}
}
for _, warning := range ov.warnings {
m.warn(warning, "postcard: "+warning, slog.String("template", template))
}
return ov
}

View File

@@ -16,6 +16,7 @@ import (
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/compass"
"github.com/go-gormigrate/gormigrate/v2"
_ "github.com/jackc/pgx/v5/stdlib"
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
@@ -111,6 +112,8 @@ layout = "blog"
==
Hi **{{ .name }}**, thanks for joining.
`)},
// notice uses postcard's default layout, which has the style block.
"views/mail/notice.htm": {Data: []byte("subject = \"Notice\"\n==\nA note for {{ .name }}.\n")},
"views/mail/layouts/blog.htm": {Data: []byte(`name = "Blog"
==
{{ .Content }}
@@ -122,20 +125,31 @@ Hi **{{ .name }}**, thanks for joining.
}
}
func (acmeBlog) MailTemplates() []string { return []string{"acme.blog::mail.welcome"} }
func (acmeBlog) MailTemplates() []string {
return []string{"acme.blog::mail.welcome", "acme.blog::mail.notice"}
}
func (acmeBlog) MailLayouts() map[string]string {
return map[string]string{"blog": "acme.blog::mail.layouts.blog"}
}
const acmeWelcome = "acme.blog::mail.welcome"
const (
acmeWelcome = "acme.blog::mail.welcome"
acmeNotice = "acme.blog::mail.notice"
)
// bootMailApp activates postcard on a fresh app the way party does, boots
// the fixture plugin and returns the published mailer with its log captured.
// gdb may be nil: the app then has no database.
func bootMailApp(t *testing.T, gdb *gorm.DB) (*mailer, *MemoryDriver, *bytes.Buffer) {
t.Helper()
app := backpack.New(nil)
return bootMailAppCfg(t, gdb, nil)
}
// bootMailAppCfg is bootMailApp for an app with configuration.
func bootMailAppCfg(t *testing.T, gdb *gorm.DB, cfg *compass.Config) (*mailer, *MemoryDriver, *bytes.Buffer) {
t.Helper()
app := backpack.New(cfg)
if gdb != nil {
if err := app.Publish(gdb); err != nil {
t.Fatal(err)
@@ -168,7 +182,13 @@ func bootMailApp(t *testing.T, gdb *gorm.DB) (*mailer, *MemoryDriver, *bytes.Buf
// appWith returns an app that publishes gdb.
func appWith(t *testing.T, gdb *gorm.DB) *backpack.App {
t.Helper()
app := backpack.New(nil)
return appWithCfg(t, gdb, nil)
}
// appWithCfg returns an app with configuration that publishes gdb.
func appWithCfg(t *testing.T, gdb *gorm.DB, cfg *compass.Config) *backpack.App {
t.Helper()
app := backpack.New(cfg)
if err := app.Publish(gdb); err != nil {
t.Fatal(err)
}
@@ -178,6 +198,12 @@ func appWith(t *testing.T, gdb *gorm.DB) *backpack.App {
// customizeWelcome turns the welcome template's index row into an override.
// layoutCode names the layout row to point at; empty leaves layout_id NULL.
func customizeWelcome(t *testing.T, gdb *gorm.DB, subject, body, layoutCode string) {
t.Helper()
customizeTemplate(t, gdb, acmeWelcome, subject, body, layoutCode)
}
// customizeTemplate is customizeWelcome for any template of the fixture.
func customizeTemplate(t *testing.T, gdb *gorm.DB, code, subject, body, layoutCode string) {
t.Helper()
var layoutID any
if layoutCode != "" {
@@ -191,16 +217,22 @@ ON CONFLICT (code) DO UPDATE SET code = EXCLUDED.code RETURNING id`, layoutCode)
err := gdb.Exec(`INSERT INTO `+TemplatesTable+` (code, source, subject, body, layout_id, is_custom, customized_at)
VALUES (?, 'acme.blog', ?, ?, ?, TRUE, NOW())
ON CONFLICT (code) DO UPDATE SET subject = EXCLUDED.subject, body = EXCLUDED.body,
layout_id = EXCLUDED.layout_id, is_custom = TRUE`, acmeWelcome, subject, body, layoutID).Error
layout_id = EXCLUDED.layout_id, is_custom = TRUE`, code, subject, body, layoutID).Error
if err != nil {
t.Fatalf("template row: %v", err)
}
}
func sendWelcome(t *testing.T, m Mailer, subject string) {
t.Helper()
sendFixture(t, m, acmeWelcome, subject)
}
// sendFixture sends one of the fixture's templates to ada@example.com.
func sendFixture(t *testing.T, m Mailer, template, subject string) {
t.Helper()
err := m.Send(context.Background(), Message{
Template: acmeWelcome,
Template: template,
To: []string{"ada@example.com"},
Vars: map[string]any{"name": "Ada"},
Subject: subject,

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"github.com/go-gormigrate/gormigrate/v2"
"gorm.io/gorm"
"gorm.io/gorm/logger"
@@ -147,9 +148,17 @@ type Overrides struct {
Layouts map[string]LayoutOverride
// Partials holds the customized sections of partials by full name.
Partials map[string]PartialOverride
// Brand is the saved Branding, or nil while it has never been saved.
// Its LogoURL is already absolute.
Brand *Brand
// warnings are problems the source worked around, for the mailer to
// log: a logo that cannot be shown, for example.
warnings []string
}
// empty reports whether o changes nothing about a render.
// empty reports whether o holds no override of a file. Branding is not one:
// it applies to the file version too.
func (o Overrides) empty() bool {
return o.Template == nil && len(o.Layouts) == 0 && len(o.Partials) == 0
}
@@ -184,8 +193,10 @@ type PartialOverride struct {
// database. With no database published it returns no overrides and no error.
//
// One call reads, in one read-only transaction, the customized row of the
// template, every customized file layout and every database-only layout, and
// every customized partial.
// template, every customized file layout and every database-only layout,
// every customized partial, and the Branding row. The logo's URL is built
// here, from the application's configuration (attach.AbsolutePublicURL), so
// it is the same in every process.
func NewDBSource(app *backpack.App) OverrideSource {
return &dbSource{app: app}
}
@@ -257,7 +268,7 @@ WHERE t.code = ? AND t.is_custom`, name).Scan(&rows).Error
}
out.Partials[p.Code] = PartialOverride{HTML: p.ContentHTML, Text: p.ContentText}
}
return nil
return s.brand(tx, &out)
}, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead})
if err != nil {
return Overrides{}, fmt.Errorf("postcard: mail overrides: %w", err)
@@ -265,6 +276,67 @@ WHERE t.code = ? AND t.is_custom`, name).Scan(&rows).Error
return out, nil
}
// brand reads the Branding row into out.Brand: nil while the row does not
// exist, which is what keeps mail.brandCss in use until Branding is saved.
func (s *dbSource) brand(tx *gorm.DB, out *Overrides) error {
var rows []struct {
LogoFileID *int64
BodyBg string
ContentBg string
HeaderColor string
FooterColor string
HeadingColor string
TextColor string
LinkColor string
ButtonTextColor string
ButtonPrimaryBg string
ButtonPositiveBg string
ButtonNegativeBg string
PanelBg string
TableBorderColor string
}
err := tx.Raw(`SELECT logo_file_id, body_bg, content_bg, header_color, footer_color, heading_color, text_color,
link_color, button_text_color, button_primary_bg, button_positive_bg, button_negative_bg, panel_bg, table_border_color
FROM ` + BrandTable + ` WHERE id = 1`).Scan(&rows).Error
if err != nil {
return err
}
if len(rows) == 0 {
return nil
}
r := rows[0]
out.Brand = &Brand{
BodyBg: r.BodyBg, ContentBg: r.ContentBg, HeaderColor: r.HeaderColor, FooterColor: r.FooterColor,
HeadingColor: r.HeadingColor, TextColor: r.TextColor, LinkColor: r.LinkColor, ButtonTextColor: r.ButtonTextColor,
ButtonPrimaryBg: r.ButtonPrimaryBg, ButtonPositiveBg: r.ButtonPositiveBg, ButtonNegativeBg: r.ButtonNegativeBg,
PanelBg: r.PanelBg, TableBorderColor: r.TableBorderColor,
}
if r.LogoFileID == nil {
return nil
}
// A logo that cannot be shown is left out and reported; the mail and
// the other overrides are not affected. The files table is read under
// a savepoint, so a failure there does not abort the transaction.
var disks []string
err = tx.Transaction(func(sp *gorm.DB) error {
return sp.Raw(`SELECT disk_name FROM system_files WHERE id = ? AND is_public`, *r.LogoFileID).Scan(&disks).Error
})
switch {
case err != nil:
out.warnings = append(out.warnings, "mail branding logo: the file cannot be read: "+err.Error())
case len(disks) == 0:
out.warnings = append(out.warnings, "mail branding logo: the file is missing or is not public")
default:
logo, err := attach.AbsolutePublicURL(s.app.Config, attach.BlobKey(disks[0]))
if err != nil {
out.warnings = append(out.warnings, "mail branding logo: "+err.Error())
break
}
out.Brand.LogoURL = logo
}
return nil
}
// syncLockKey names the advisory lock that serializes SyncIndex runs.
const syncLockKey = "summercms.postcard.sync"

View File

@@ -465,6 +465,8 @@ func parseHeader(header string) (fields, samples map[string]string, err error) {
type renderOptions struct {
css string
brandCSS string
// logoURL is the Branding logo's absolute URL, or empty.
logoURL string
// overrides are the database overrides to apply; the zero value renders
// the file version.
overrides Overrides
@@ -615,6 +617,7 @@ func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions)
"Subject": subject,
"css": css,
"brandCss": opts.brandCSS,
"logoUrl": opts.logoURL,
}, texttemplate.FuncMap{"partial": partials.textCall})
if err != nil {
return out, partLayoutText, err
@@ -624,6 +627,7 @@ func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions)
"Subject": subject,
"css": template.CSS(css),
"brandCss": template.CSS(opts.brandCSS),
"logoUrl": opts.logoURL,
}, template.FuncMap{"partial": partials.htmlCall})
if err != nil {
return out, partLayoutHTML, err