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:
Jakub Zych
2026-11-13 20:29:42 +01:00
parent 9afe95ccef
commit 52c9c7eb18
22 changed files with 920 additions and 63 deletions

View File

@@ -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 {