feat(mail): one admin record per mail template with a locale switcher
Gap G-35-1 (supersedes D-05), tracer slice: - postcard: migration 202611130001_mail_template_base_code (base_code column and index); SyncIndex writes base_code; EnsureLocaleRows creates the <template>-<locale> rows of locales that ship no file; TemplateBase and Catalog.TemplateFor; send, preview and validation resolve a missing <template>-<locale> to the locale's customization, else the base's customization, else the base file. Names with their own file send as before. - cabana: mail locales are the translator's plus the TranslationWriter's enabled locales; sync ensures the locale rows and re-syncs when the locale set changes; record lookups admit fallback-locale rows; the record title is the base code; RecordMeta.LocaleVariants (RecordLocaleVariant) on the show and update responses. - admin: LocaleVariantSwitcher in the update form header, from meta.localeVariants, behind the unsaved-changes confirm. - tests: TestMailOverrideSmoke/locale_fallback, TestMailScreensSmoke/locales, LocaleVariantSwitcher.test.ts.
This commit is contained in:
@@ -33,7 +33,7 @@ Use cases:
|
||||
- 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.
|
||||
- No locale selection: callers pass the full template name, including any locale suffix. A `<template>-<locale>` name whose locale ships no file sends the default-locale version (see "Locale variants").
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -103,6 +103,14 @@ func TestWelcomeMail(t *testing.T) {
|
||||
}
|
||||
```
|
||||
|
||||
### Locale variants
|
||||
|
||||
postcard picks no locale: the caller passes the full name, such as `acme.blog::mail.welcome-en` for English. A locale variant is a file whose name is the template's name, a dash and the locale (`welcome-en.htm`). A name with its own file always renders that file, as it always did.
|
||||
|
||||
A name the catalog does not hold, of the form `<template>-<tag>` where `<template>` is a registered template and `<tag>` is a locale tag (two letters, optionally followed by `-` or `_` and a 2 to 8 character alphanumeric subtag: `de`, `pt-BR`; case does not matter), renders the template's file, the default-locale version. Its subject, body and layout come from, in this order: the customized row of the name itself (an administrator wrote that locale's version), the customized row of the template, the template's file. When several registered templates match, the longest name wins. Any other unknown name fails with `postcard: unknown template <name>`. The rule needs no list of locales, so a worker that only runs postcard sends the same mail as the admin previews. `postcard.Catalog.TemplateFor` returns the file a name renders from; its `Name` is the base template's for a name without a file of its own.
|
||||
|
||||
`postcard.EnsureLocaleRows` gives such locales their index rows, so an administrator can open and customize them (see "Index rows, drift and reset").
|
||||
|
||||
### 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`:
|
||||
@@ -348,7 +356,9 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
|
||||
|
||||
`postcard.Catalog.Templates`, `postcard.Catalog.Layouts` and `postcard.Catalog.Partials` list the files as `postcard.TemplateFile`, `postcard.LayoutFile` and `postcard.PartialFile` values; each carries its `Source` and a `Hash`, the SHA-256 of the file's text with CRLF line endings normalized, so the same file hashes the same on every platform.
|
||||
|
||||
`postcard.SyncIndex` gives every file a row in its table, keyed by `code`. A row that is not customized mirrors the file, so lists and forms show the file version. A customized row keeps its content; only `source`, `description`, `locale`, `name` and `file_hash` follow the file. An override stores the hash of the file it was written against in `base_hash`, so it is outdated when `base_hash` and `file_hash` differ. `postcard.SyncIndex` never deletes a row, leaves database-only layouts alone, writes nothing when a row already matches, and may run in several processes at once. It needs the tables: when they are not migrated yet it returns the error.
|
||||
`postcard.SyncIndex` gives every file a row in its table, keyed by `code`. A row that is not customized mirrors the file, so lists and forms show the file version. A customized row keeps its content; only `source`, `description`, `locale`, `base_code`, `name` and `file_hash` follow the file. `base_code` groups the locale variants of one template: it is the code with its locale suffix stripped (`postcard.TemplateBase`), so `acme.blog::mail.welcome` and `acme.blog::mail.welcome-en` share the base `acme.blog::mail.welcome`. An override stores the hash of the file it was written against in `base_hash`, so it is outdated when `base_hash` and `file_hash` differ. `postcard.SyncIndex` never deletes a row, leaves database-only layouts alone, writes nothing when a row already matches, and may run in several processes at once. It needs the tables: when they are not migrated yet it returns the error.
|
||||
|
||||
`postcard.EnsureLocaleRows` adds the rows of the locales a template ships no file for: for every base template and every given locale except the default one, the row `<template>-<locale>` with that locale, the template as `base_code`, and the template file's subject, body, layout and hash. Such a row sends the default-locale version until it is customized (see "Locale variants"); its `file_hash` follows the template's file, so a customized one shows as outdated when that file changes. The default locale gets no row: the template's own file is its version. Like `postcard.SyncIndex` it writes nothing for a matching row, deletes nothing and is safe to run in several processes at once; it can be limited to some templates.
|
||||
|
||||
`postcard.ResetOverride` returns one row to its file version and clears `is_custom`, `base_hash` and `customized_at`. A database-only layout has no file version and is refused.
|
||||
|
||||
@@ -386,7 +396,8 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
|
||||
| `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.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` and the template's `base_code` on all. |
|
||||
| `postcard.EnsureLocaleRows` | Upserts the row `<template>-<locale>` of every locale (except the default) a base template ships no file for, from the template's file; optionally limited to some templates. |
|
||||
| `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` (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. |
|
||||
@@ -400,8 +411,10 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
|
||||
| `postcard.TemplateFile`, `postcard.LayoutFile`, `postcard.PartialFile` | A registered file with its parts, its normalized `Source` and its `Hash`. `postcard.TemplateFile.Samples` holds the sample values and `postcard.TemplateFile.Layout` the full name of the file's layout. |
|
||||
| `postcard.Catalog.Templates`, `postcard.Catalog.Layouts`, `postcard.Catalog.Partials` | The registered files, sorted by name. |
|
||||
| `postcard.Catalog.Template`, `postcard.Catalog.Layout`, `postcard.Catalog.Partial` | One registered file by full name. |
|
||||
| `postcard.Catalog.TemplateFor` | The file a template name renders from: its own file, or the base template's file for a `<template>-<locale>` name whose locale ships none. |
|
||||
| `postcard.FormatTemplate`, `postcard.FormatLayout`, `postcard.FormatPartial` | Content written in the file format, for display and comparison. |
|
||||
| `postcard.TemplateLocale` | The locale suffix of a template name, when it is one of the given locales. |
|
||||
| `postcard.TemplateBase` | A template name without the locale suffix `postcard.TemplateLocale` finds: the `base_code` its locale variants share. |
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
@@ -208,7 +208,8 @@ func (e *Editor) render(ctx context.Context, d Draft) (RenderedMessage, error) {
|
||||
|
||||
func (e *Editor) renderTemplate(d Draft, ov Overrides, opts renderOptions) (RenderedMessage, error) {
|
||||
cat := e.m.catalog
|
||||
t, err := cat.lookupTemplate(d.Name)
|
||||
// A fallback-locale name renders the base file with its samples.
|
||||
t, err := cat.resolveTemplate(d.Name)
|
||||
if err != nil {
|
||||
return RenderedMessage{}, err
|
||||
}
|
||||
|
||||
@@ -64,11 +64,14 @@ func NewMailer(cat *Catalog, driver Driver, opts Options) Mailer {
|
||||
return &mailer{catalog: cat, driver: driver, opts: opts, source: opts.Overrides}
|
||||
}
|
||||
|
||||
// Send renders msg.Template and delivers it. It performs no locale selection;
|
||||
// the caller must pass the full dotted name, including any -en suffix. A
|
||||
// database override of the template is applied when the mailer has an
|
||||
// OverrideSource; an override that cannot be read or does not render is
|
||||
// logged and the file version is sent instead.
|
||||
// Send renders msg.Template and delivers it. It picks no locale: the caller
|
||||
// passes the full dotted name, including any -en suffix. A <template>-<locale>
|
||||
// name whose locale ships no file resolves to the default-locale version:
|
||||
// that name's customized row when there is one, else the base template's
|
||||
// customized row, else the base template's file. A database override of the
|
||||
// template is applied when the mailer has an OverrideSource; an override
|
||||
// that cannot be read or does not render is logged and the file version is
|
||||
// sent instead.
|
||||
func (m *mailer) Send(ctx context.Context, msg Message) error {
|
||||
if m == nil {
|
||||
return fmt.Errorf("postcard: mailer is nil")
|
||||
@@ -101,10 +104,17 @@ 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) {
|
||||
if _, err := m.catalog.lookupTemplate(msg.Template); err != nil {
|
||||
t, err := m.catalog.resolveTemplate(msg.Template)
|
||||
if err != nil {
|
||||
return RenderedMessage{}, err
|
||||
}
|
||||
ov := m.overrides(ctx, msg.Template)
|
||||
if t.name != msg.Template && ov.Template == nil {
|
||||
// A fallback-locale name with no customization of its own sends the
|
||||
// base's. Layouts, partials and Branding are the same in both
|
||||
// answers; only the template override is taken.
|
||||
ov.Template = m.overrides(ctx, t.name).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)
|
||||
|
||||
@@ -528,11 +528,99 @@ func TestMailOverrideSmoke(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("locale_fallback", func(t *testing.T) {
|
||||
gdb := mailPostgres(t)
|
||||
m, drv, logs := bootMailApp(t, gdb)
|
||||
// welcome-en ships its own file; de and fr do not.
|
||||
enFS := fstest.MapFS{"views/mail/welcome-en.htm": {Data: []byte("subject = \"English {{ .name }}\"\nlayout = \"blog\"\n==\nHello {{ .name }}.\n")}}
|
||||
if err := m.catalog.Register("acme.blog", enFS, []string{acmeWelcome + "-en"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
locales := []string{"pl", "en", "de"}
|
||||
if err := SyncIndex(ctx, gdb, m.catalog, locales); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := EnsureLocaleRows(ctx, gdb, m.catalog, "pl", locales); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var rows []struct {
|
||||
Code string
|
||||
Locale *string
|
||||
BaseCode *string
|
||||
Subject string
|
||||
FileHash string
|
||||
}
|
||||
if err := gdb.Raw(`SELECT code, locale, base_code, subject, file_hash FROM `+TemplatesTable+` WHERE base_code = ? ORDER BY code`, acmeWelcome).Scan(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base, _ := m.catalog.Template(acmeWelcome)
|
||||
if len(rows) != 3 || rows[0].Code != acmeWelcome || rows[1].Code != acmeWelcome+"-de" || rows[2].Code != acmeWelcome+"-en" {
|
||||
t.Fatalf("welcome group rows = %+v, want welcome, welcome-de, welcome-en", rows)
|
||||
}
|
||||
if de := rows[1]; de.Locale == nil || *de.Locale != "de" || de.Subject != base.Subject || de.FileHash != base.Hash {
|
||||
t.Errorf("fallback row = %+v, want locale de with the base file's subject and hash", de)
|
||||
}
|
||||
// Idempotent: a second run writes nothing new.
|
||||
if err := EnsureLocaleRows(ctx, gdb, m.catalog, "pl", locales, acmeWelcome); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var n int64
|
||||
gdb.Raw(`SELECT COUNT(*) FROM ` + TemplatesTable).Scan(&n)
|
||||
if n != 6 { // welcome, welcome-de, welcome-en, notice, notice-de, notice-en
|
||||
t.Errorf("%d template rows after a second ensure, want 6", n)
|
||||
}
|
||||
|
||||
// fr has no row: the base file.
|
||||
sendFixture(t, m, acmeWelcome+"-fr", "")
|
||||
if got := lastMessage(t, drv); got.Subject != "Welcome, Ada" {
|
||||
t.Errorf("welcome-fr subject = %q, want the base file's", got.Subject)
|
||||
}
|
||||
// de customized: its own row.
|
||||
if err := gdb.Exec(`UPDATE `+TemplatesTable+` SET subject = 'Willkommen {{ .name }}', is_custom = TRUE, base_hash = file_hash WHERE code = ?`, acmeWelcome+"-de").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sendFixture(t, m, acmeWelcome+"-de", "")
|
||||
if got := lastMessage(t, drv); got.Subject != "Willkommen Ada" || !strings.Contains(got.HTML, "blog-mail") {
|
||||
t.Errorf("welcome-de = %q / %q, want its customization in the blog layout", got.Subject, got.HTML)
|
||||
}
|
||||
// The base customized: fr now sends it, de keeps its own.
|
||||
customizeWelcome(t, gdb, "Base {{ .name }}", "Base body.", "acme.blog::mail.layouts.blog")
|
||||
sendFixture(t, m, acmeWelcome+"-fr", "")
|
||||
if got := lastMessage(t, drv); got.Subject != "Base Ada" {
|
||||
t.Errorf("welcome-fr after the base was customized = %q", got.Subject)
|
||||
}
|
||||
sendFixture(t, m, acmeWelcome+"-de", "")
|
||||
if got := lastMessage(t, drv); got.Subject != "Willkommen Ada" {
|
||||
t.Errorf("welcome-de after the base was customized = %q", got.Subject)
|
||||
}
|
||||
// A name with its own file is unchanged.
|
||||
sendFixture(t, m, acmeWelcome+"-en", "")
|
||||
if got := lastMessage(t, drv); got.Subject != "English Ada" {
|
||||
t.Errorf("welcome-en = %q, want its own file", got.Subject)
|
||||
}
|
||||
// Neither a base nor a locale tag: unknown, with today's text.
|
||||
for _, name := range []string{"acme.blog::mail.missing-de", acmeWelcome + "-deutsch", acmeWelcome + "x"} {
|
||||
err := m.Send(ctx, Message{Template: name, To: []string{"ada@example.com"}})
|
||||
if err == nil || !strings.Contains(err.Error(), "unknown template "+name) {
|
||||
t.Errorf("Send of %s = %v", name, err)
|
||||
}
|
||||
}
|
||||
if f, ok := m.catalog.TemplateFor(acmeWelcome + "-pt-BR"); !ok || f.Name != acmeWelcome {
|
||||
t.Errorf("TemplateFor(welcome-pt-BR) = %q, %v", f.Name, ok)
|
||||
}
|
||||
if logs.Len() != 0 {
|
||||
t.Errorf("unexpected log output:\n%s", logs)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("migrations_roll_back", func(t *testing.T) {
|
||||
gdb := mailPostgres(t)
|
||||
mig := gormigrate.New(gdb, gormigrate.DefaultOptions, Migrations)
|
||||
if err := mig.RollbackLast(); err != nil {
|
||||
t.Fatalf("rollback: %v", err)
|
||||
for range Migrations {
|
||||
if err := mig.RollbackLast(); err != nil {
|
||||
t.Fatalf("rollback: %v", err)
|
||||
}
|
||||
}
|
||||
var n int64
|
||||
if err := gdb.Raw(`SELECT COUNT(*) FROM information_schema.tables WHERE table_name LIKE 'system_mail_%'`).Scan(&n).Error; err != nil {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
@@ -127,6 +128,33 @@ var Migrations = []*gormigrate.Migration{
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
// base_code groups the locale variants of one template: the code
|
||||
// with its locale suffix stripped (TemplateBase).
|
||||
ID: "202611130001_mail_template_base_code",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
for _, stmt := range []string{
|
||||
`ALTER TABLE ` + TemplatesTable + ` ADD COLUMN base_code TEXT`,
|
||||
`CREATE INDEX ` + TemplatesTable + `_base_code_index ON ` + TemplatesTable + ` (base_code)`,
|
||||
} {
|
||||
if err := tx.Exec(stmt).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
for _, stmt := range []string{
|
||||
`DROP INDEX IF EXISTS ` + TemplatesTable + `_base_code_index`,
|
||||
`ALTER TABLE ` + TemplatesTable + ` DROP COLUMN IF EXISTS base_code`,
|
||||
} {
|
||||
if err := tx.Exec(stmt).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// OverrideSource supplies the database overrides one render needs.
|
||||
@@ -347,10 +375,11 @@ const syncLockKey = "summercms.postcard.sync"
|
||||
//
|
||||
// For a row that is not customized the content columns mirror the file. For
|
||||
// a customized row they are left alone: only source, description, locale,
|
||||
// name and file_hash follow the file, which is what makes a changed file
|
||||
// show as a difference between base_hash and file_hash. No row is deleted,
|
||||
// database-only layouts are not touched, and a row that already matches is
|
||||
// not written. locales are the application's locales, for TemplateLocale.
|
||||
// base_code, name and file_hash follow the file, which is what makes a
|
||||
// changed file show as a difference between base_hash and file_hash. No row
|
||||
// is deleted, database-only layouts are not touched, and a row that already
|
||||
// matches is not written. locales are the application's locales, for
|
||||
// TemplateLocale and TemplateBase.
|
||||
//
|
||||
// It is safe to call from several processes at once. It fails when the
|
||||
// tables are not migrated yet; the caller decides when to try again.
|
||||
@@ -387,24 +416,7 @@ WHERE t.source IS DISTINCT FROM EXCLUDED.source
|
||||
}
|
||||
}
|
||||
for _, f := range templates {
|
||||
if err := tx.Exec(`INSERT INTO `+TemplatesTable+` AS t (code, source, locale, description, subject, body, layout_id, file_hash)
|
||||
VALUES (?, ?, NULLIF(?, ''), ?, ?, ?, (SELECT id FROM `+LayoutsTable+` WHERE code = ?), ?)
|
||||
ON CONFLICT (code) DO UPDATE SET
|
||||
source = EXCLUDED.source,
|
||||
locale = EXCLUDED.locale,
|
||||
description = EXCLUDED.description,
|
||||
file_hash = EXCLUDED.file_hash,
|
||||
subject = CASE WHEN t.is_custom THEN t.subject ELSE EXCLUDED.subject END,
|
||||
body = CASE WHEN t.is_custom THEN t.body ELSE EXCLUDED.body END,
|
||||
layout_id = CASE WHEN t.is_custom THEN t.layout_id ELSE EXCLUDED.layout_id END,
|
||||
updated_at = NOW()
|
||||
WHERE t.source IS DISTINCT FROM EXCLUDED.source
|
||||
OR t.locale IS DISTINCT FROM EXCLUDED.locale
|
||||
OR t.description IS DISTINCT FROM EXCLUDED.description
|
||||
OR t.file_hash IS DISTINCT FROM EXCLUDED.file_hash
|
||||
OR (NOT t.is_custom AND (t.subject, t.body, t.layout_id)
|
||||
IS DISTINCT FROM (EXCLUDED.subject, EXCLUDED.body, EXCLUDED.layout_id))`,
|
||||
f.Name, f.PluginID, TemplateLocale(f.Name, locales), f.Description, f.Subject, f.Body, f.Layout, f.Hash).Error; err != nil {
|
||||
if err := upsertTemplateRow(tx, f.Name, f.PluginID, TemplateLocale(f.Name, locales), TemplateBase(f.Name, locales), f); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -435,6 +447,111 @@ WHERE t.source IS DISTINCT FROM EXCLUDED.source
|
||||
return nil
|
||||
}
|
||||
|
||||
// upsertTemplateRow writes the index row code of a template whose file
|
||||
// version is f: the template's own file, or the base's for a
|
||||
// fallback-locale row. A customized row keeps its content columns.
|
||||
func upsertTemplateRow(tx *gorm.DB, code, source, locale, base string, f TemplateFile) error {
|
||||
return tx.Exec(`INSERT INTO `+TemplatesTable+` AS t (code, source, locale, base_code, description, subject, body, layout_id, file_hash)
|
||||
VALUES (?, ?, NULLIF(?, ''), ?, ?, ?, ?, (SELECT id FROM `+LayoutsTable+` WHERE code = ?), ?)
|
||||
ON CONFLICT (code) DO UPDATE SET
|
||||
source = EXCLUDED.source,
|
||||
locale = EXCLUDED.locale,
|
||||
base_code = EXCLUDED.base_code,
|
||||
description = EXCLUDED.description,
|
||||
file_hash = EXCLUDED.file_hash,
|
||||
subject = CASE WHEN t.is_custom THEN t.subject ELSE EXCLUDED.subject END,
|
||||
body = CASE WHEN t.is_custom THEN t.body ELSE EXCLUDED.body END,
|
||||
layout_id = CASE WHEN t.is_custom THEN t.layout_id ELSE EXCLUDED.layout_id END,
|
||||
updated_at = NOW()
|
||||
WHERE t.source IS DISTINCT FROM EXCLUDED.source
|
||||
OR t.locale IS DISTINCT FROM EXCLUDED.locale
|
||||
OR t.base_code IS DISTINCT FROM EXCLUDED.base_code
|
||||
OR t.description IS DISTINCT FROM EXCLUDED.description
|
||||
OR t.file_hash IS DISTINCT FROM EXCLUDED.file_hash
|
||||
OR (NOT t.is_custom AND (t.subject, t.body, t.layout_id)
|
||||
IS DISTINCT FROM (EXCLUDED.subject, EXCLUDED.body, EXCLUDED.layout_id))`,
|
||||
code, source, locale, base, f.Description, f.Subject, f.Body, f.Layout, f.Hash).Error
|
||||
}
|
||||
|
||||
// EnsureLocaleRows gives every locale of a template that ships no file of
|
||||
// its own an index row, so that the locale can be opened and customized in
|
||||
// the admin. For every base template of cat (a template whose TemplateBase
|
||||
// is itself; all of them when bases is empty, else only those listed) and
|
||||
// every locale in locales other than defaultLocale for which cat holds no
|
||||
// <base>-<locale> file, it upserts the row <base>-<locale>: source, locale,
|
||||
// base_code, description, subject, body and layout from the base file, and
|
||||
// file_hash the base file's hash. A customized row keeps its content
|
||||
// columns while file_hash, description and base_code follow the base, so a
|
||||
// changed base file shows as drift. A matching row is not written and no row
|
||||
// is deleted. defaultLocale gets no row: the base file is its version.
|
||||
//
|
||||
// It takes the same advisory lock as SyncIndex and fails, like it, when the
|
||||
// tables are not migrated yet.
|
||||
func EnsureLocaleRows(ctx context.Context, db *gorm.DB, cat *Catalog, defaultLocale string, locales []string, bases ...string) error {
|
||||
if db == nil {
|
||||
return fmt.Errorf("postcard: ensure locale rows: database is nil")
|
||||
}
|
||||
if cat == nil {
|
||||
return fmt.Errorf("postcard: ensure locale rows: catalog is nil")
|
||||
}
|
||||
all := locales
|
||||
if defaultLocale != "" {
|
||||
all = append([]string{defaultLocale}, locales...)
|
||||
}
|
||||
templates := cat.Templates()
|
||||
have := make(map[string]bool, len(templates))
|
||||
for _, f := range templates {
|
||||
have[strings.ToLower(f.Name)] = true
|
||||
}
|
||||
only := make(map[string]bool, len(bases))
|
||||
for _, b := range bases {
|
||||
only[b] = true
|
||||
}
|
||||
type row struct {
|
||||
code, locale string
|
||||
base TemplateFile
|
||||
}
|
||||
var rows []row
|
||||
for _, f := range templates {
|
||||
if TemplateBase(f.Name, all) != f.Name || (len(only) > 0 && !only[f.Name]) {
|
||||
continue
|
||||
}
|
||||
for _, locale := range locales {
|
||||
if locale == "" || strings.EqualFold(locale, defaultLocale) {
|
||||
continue
|
||||
}
|
||||
code := f.Name + "-" + locale
|
||||
if have[strings.ToLower(code)] {
|
||||
continue
|
||||
}
|
||||
// Only a code a send resolves to this base gets a row: a
|
||||
// locale tag the send rule does not accept would never be used.
|
||||
if to, ok := cat.TemplateFor(code); !ok || to.Name != f.Name {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, row{code: code, locale: locale, base: f})
|
||||
}
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Exec(`SELECT pg_advisory_xact_lock(hashtext(?))`, syncLockKey).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range rows {
|
||||
if err := upsertTemplateRow(tx, r.code, r.base.PluginID, r.locale, r.base.Name, r.base); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("postcard: ensure locale rows: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rowName is the name column of a layout or partial row: the name in the
|
||||
// file's header, or the full name when the header has none.
|
||||
func rowName(title, full string) string {
|
||||
|
||||
@@ -240,14 +240,47 @@ func (c *Catalog) resolveLayoutLocked(t *parsedTemplate) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Catalog) lookupTemplate(name string) (*parsedTemplate, error) {
|
||||
// localeTag matches the locale tag a fallback-locale name ends in: a
|
||||
// two-letter language, optionally followed by a dash or an underscore and
|
||||
// a 2-8 character alphanumeric subtag (de, pt-BR, zh_Hant).
|
||||
var localeTag = regexp.MustCompile(`^[A-Za-z]{2}(?:[-_][A-Za-z0-9]{2,8})?$`)
|
||||
|
||||
// resolveTemplate is the lookup every send, preview and validation goes
|
||||
// through. A name with its own file is that file. A name the catalog does
|
||||
// not hold of the form <base>-<tag>, where <base> is a registered template
|
||||
// and <tag> a locale tag, is the base's file: a locale that ships no file
|
||||
// of its own sends the default-locale version. When several bases match,
|
||||
// the longest one wins. Any other name is an unknown template.
|
||||
func (c *Catalog) resolveTemplate(name string) (*parsedTemplate, error) {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
t, ok := c.templates[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("postcard: unknown template %s", name)
|
||||
if t, ok := c.templates[name]; ok {
|
||||
return t, nil
|
||||
}
|
||||
return t, nil
|
||||
if t := c.fallbackLocked(name); t != nil {
|
||||
return t, nil
|
||||
}
|
||||
return nil, fmt.Errorf("postcard: unknown template %s", name)
|
||||
}
|
||||
|
||||
// fallbackLocked returns the base template a fallback-locale name resolves
|
||||
// to, or nil. The caller holds c.mu.
|
||||
func (c *Catalog) fallbackLocked(name string) *parsedTemplate {
|
||||
_, rest, ok := strings.Cut(name, "::")
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// The tag holds no dot, so the dash is in the last dotted segment.
|
||||
start := len(name) - len(rest) + strings.LastIndex(rest, ".") + 1
|
||||
for i := len(name) - 1; i > start; i-- {
|
||||
if name[i] != '-' || !localeTag.MatchString(name[i+1:]) {
|
||||
continue
|
||||
}
|
||||
if t, ok := c.templates[name[:i]]; ok {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RegisterPartials loads declared partial names from fsys. Each name must
|
||||
@@ -490,7 +523,7 @@ type renderSource struct {
|
||||
// render renders msg.Template: the file version, or the file version with
|
||||
// opts.overrides applied. Both go through renderFrom.
|
||||
func (c *Catalog) render(msg Message, opts renderOptions) (RenderedMessage, error) {
|
||||
t, err := c.lookupTemplate(msg.Template)
|
||||
t, err := c.resolveTemplate(msg.Template)
|
||||
if err != nil {
|
||||
return RenderedMessage{}, err
|
||||
}
|
||||
@@ -869,6 +902,19 @@ func (c *Catalog) Template(name string) (TemplateFile, bool) {
|
||||
return t.file(), true
|
||||
}
|
||||
|
||||
// TemplateFor returns the file a template name renders from: the name's
|
||||
// own file, or, for a <template>-<locale> name whose locale ships no file,
|
||||
// the file of the base template (see the send-resolution rule in the
|
||||
// package README). The returned Name is the base's in the second case,
|
||||
// which is how a caller tells the two apart.
|
||||
func (c *Catalog) TemplateFor(name string) (TemplateFile, bool) {
|
||||
t, err := c.resolveTemplate(name)
|
||||
if err != nil {
|
||||
return TemplateFile{}, false
|
||||
}
|
||||
return t.file(), true
|
||||
}
|
||||
|
||||
// Layout returns the registered layout of that full name.
|
||||
func (c *Catalog) Layout(name string) (LayoutFile, bool) {
|
||||
c.mu.RLock()
|
||||
@@ -939,3 +985,15 @@ func TemplateLocale(name string, locales []string) string {
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// TemplateBase returns the name of the template a locale variant belongs
|
||||
// to: name without the locale suffix TemplateLocale finds in it, or name
|
||||
// itself when it has none. acme.blog::mail.welcome-en and
|
||||
// acme.blog::mail.welcome share the base acme.blog::mail.welcome.
|
||||
func TemplateBase(name string, locales []string) string {
|
||||
locale := TemplateLocale(name, locales)
|
||||
if locale == "" {
|
||||
return name
|
||||
}
|
||||
return name[:len(name)-len(locale)-1]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user