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

File diff suppressed because one or more lines are too long

View File

@@ -554,6 +554,12 @@ func (s CRUDService) ShowRecord(ctx context.Context, cc *CompiledController, id
deletable := decider.recordDeletable(target)
result.Meta.Deletable = &deletable
}
if lister, ok := cc.Controller.(recordLocaleVariants); ok && lister != nil {
result.Meta.LocaleVariants, err = lister.recordLocaleVariants(withTx(ctx, tx), tx, target)
if err != nil {
return err
}
}
result.Meta.Actions, err = s.offeredRecordActions(withTx(ctx, tx), cc, target)
return err
})
@@ -983,7 +989,14 @@ func (s CRUDService) save(ctx context.Context, cc *CompiledController, id any, i
if err := hydratePluginFields(ctx, tx, cc, s.writer, target, result.Data, op); err != nil {
return err
}
return hydrateFormExtensions(ctx, extensionHydrate{Tx: tx, Tr: s.tr, Writer: s.writer, CC: cc, Target: target, Op: op, Visible: visible}, result.Data)
if err := hydrateFormExtensions(ctx, extensionHydrate{Tx: tx, Tr: s.tr, Writer: s.writer, CC: cc, Target: target, Op: op, Visible: visible}, result.Data); err != nil {
return err
}
// The saved version's states changed: the switcher shows them.
if lister, ok := cc.Controller.(recordLocaleVariants); ok && lister != nil && update {
result.Meta.LocaleVariants, err = lister.recordLocaleVariants(withTx(ctx, tx), tx, target)
}
return err
})
if err != nil {
return RecordResult{}, err

View File

@@ -35,6 +35,9 @@ type mailScreens struct {
syncMu sync.Mutex
synced atomic.Bool
// syncedLocales is the mail locale set of the last successful sync
// (mailLocaleKey); a different set syncs again. Guarded by syncMu.
syncedLocales string
}
// mailPermissions are the two mail codes, with no role grants (D-03).
@@ -161,20 +164,63 @@ func (m *mailScreens) translator() *phrasebook.Translator {
return tr
}
// locales are the application's locales, for postcard.TemplateLocale: the
// locales the translator's catalog holds, none without a translator.
func (m *mailScreens) locales() []string {
return m.translator().Locales("")
// mailLocales are the application's mail locales and its default locale:
// the locales the translator's catalog holds plus, when a TranslationWriter
// is published and answers, its enabled locales. The default is the
// writer's default locale, else the translator's locale. locales is sorted
// and includes the default. db is the handle the writer reads with; nil
// leaves the writer out.
func (m *mailScreens) mailLocales(ctx context.Context, db *gorm.DB) (def string, locales []string) {
tr := m.translator()
def = tr.Locale()
seen := map[string]bool{}
add := func(codes ...string) {
for _, code := range codes {
if code = strings.TrimSpace(code); code != "" && !seen[code] {
seen[code] = true
locales = append(locales, code)
}
}
}
add(tr.Locales("")...)
if app := m.application(); app != nil && db != nil {
if w, ok := app.Lookup[TranslationWriter](); ok && w != nil {
if codes, err := w.EnabledLocales(ctx, db); err == nil {
add(codes...)
} else {
moduleLog.WarnContext(ctx, "cabana: mail locales: enabled locales", "error", err)
}
if code, err := w.DefaultLocale(ctx, db); err == nil && strings.TrimSpace(code) != "" {
def = strings.TrimSpace(code)
}
}
}
add(def)
sort.Strings(locales)
return def, locales
}
// mailLocaleKey identifies a mail locale set, to tell whether the index was
// synced with the current one.
func mailLocaleKey(def string, locales []string) string {
return def + "|" + strings.Join(locales, ",")
}
// sync writes the index rows of every file template, layout and partial
// (postcard.SyncIndex) and remembers that it succeeded.
// (postcard.SyncIndex), then the rows of the locales a template ships no
// file for (postcard.EnsureLocaleRows), and remembers the locale set it
// succeeded with.
func (m *mailScreens) sync(ctx context.Context, gdb *gorm.DB) error {
m.syncMu.Lock()
defer m.syncMu.Unlock()
if err := postcard.SyncIndex(ctx, gdb, m.catalog(), m.locales()); err != nil {
def, locales := m.mailLocales(ctx, gdb)
if err := postcard.SyncIndex(ctx, gdb, m.catalog(), locales); err != nil {
return err
}
if err := postcard.EnsureLocaleRows(ctx, gdb, m.catalog(), def, locales); err != nil {
return err
}
m.syncedLocales = mailLocaleKey(def, locales)
m.synced.Store(true)
return nil
}
@@ -190,16 +236,25 @@ func (m *mailScreens) syncOnDatabase(gdb *gorm.DB) {
}
// ensureSynced retries the index sync until it has succeeded once in this
// process. It is called before a mail list is read.
// process, and syncs again when the mail locales changed since (a locale
// enabled through a translate plugin, for example). It is called before a
// mail list is read.
func (m *mailScreens) ensureSynced(ctx context.Context) {
if m.synced.Load() {
return
}
gdb := m.db()
if gdb == nil {
return
}
if err := m.sync(ctx, gdb.Session(&gorm.Session{NewDB: true}).WithContext(ctx)); err != nil {
db := gdb.Session(&gorm.Session{NewDB: true}).WithContext(ctx)
if m.synced.Load() {
def, locales := m.mailLocales(ctx, db)
m.syncMu.Lock()
current := m.syncedLocales == mailLocaleKey(def, locales)
m.syncMu.Unlock()
if current {
return
}
}
if err := m.sync(ctx, db); err != nil {
moduleLog.WarnContext(ctx, "cabana: mail index sync failed", "error", err)
}
}
@@ -279,10 +334,13 @@ func nonEmpty(codes []string) []string {
}
// MailTemplate is a row of postcard's templates table: one per file
// template, its override columns set while the template is customized.
// template and one per locale a template ships no file for (a fallback-locale
// row), its override columns set while that version is customized. BaseCode
// groups the locale versions of one template.
type MailTemplate struct {
ID uint `gorm:"column:id;primaryKey"`
Code string `gorm:"column:code"`
BaseCode *string `gorm:"column:base_code"`
Source string `gorm:"column:source"`
Locale *string `gorm:"column:locale"`
Description string `gorm:"column:description"`
@@ -376,6 +434,7 @@ var (
_ pact.HasAdminRecordActions = mailTemplatesAdmin{}
_ pact.AdminPartialData = mailTemplatesAdmin{}
_ recordDeletable = mailTemplatesAdmin{}
_ recordLocaleVariants = mailTemplatesAdmin{}
_ formFooterActions = mailTemplatesAdmin{}
)
@@ -400,12 +459,16 @@ func asMailTemplate(model any) (*MailTemplate, error) {
return t, nil
}
// FormRecordTitle names a template by its code.
// FormRecordTitle names a template by its base code: every locale version
// of a template carries the same title, the switcher tells them apart.
func (mailTemplatesAdmin) FormRecordTitle(_ context.Context, _ *gorm.DB, record any) (string, error) {
t, err := asMailTemplate(record)
if err != nil {
return "", err
}
if t.BaseCode != nil && *t.BaseCode != "" {
return *t.BaseCode, nil
}
return t.Code, nil
}
@@ -449,9 +512,21 @@ func (c mailTemplatesAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *g
return c.scopeTemplates(db)
}
// FormExtendQuery applies the catalog scope to every record lookup.
// FormExtendQuery scopes every record lookup to the catalog's templates and
// their fallback-locale rows (base_code a catalog template).
func (c mailTemplatesAdmin) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
return c.scopeTemplates(db)
return c.mail.scopeTemplateVersions(db)
}
// scopeTemplateVersions limits a templates query to the rows a record lookup
// may open: a catalog template's own row, or a row whose base_code is a
// catalog template (a locale that ships no file).
func (m *mailScreens) scopeTemplateVersions(db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
codes := nonEmpty(m.templateCodes())
return db.Where("("+postcard.TemplatesTable+".code IN ? OR "+postcard.TemplatesTable+".base_code IN ?)", codes, codes)
}
// ListExtendRecords shows a template without a locale suffix as Default in
@@ -509,7 +584,7 @@ func (c mailTemplatesAdmin) FilterOptions(scope string) []pact.Option {
case mailFilterLocale:
out := []pact.Option{{Value: mailLocaleDefault, Label: mailLang + "template.locale_default"}}
seen := map[string]bool{}
locales := c.mail.locales()
_, locales := c.mail.mailLocales(context.Background(), c.mail.db())
for _, f := range c.mail.catalog().Templates() {
if locale := postcard.TemplateLocale(f.Name, locales); locale != "" && !seen[locale] {
seen[locale] = true
@@ -575,7 +650,8 @@ func (c mailTemplatesAdmin) FormBeforeUpdate(_ context.Context, model any) error
if err != nil {
return err
}
file, ok := c.mail.catalog().Template(t.Code)
// A fallback-locale row is based on the base template's file.
file, ok := c.mail.catalog().TemplateFor(t.Code)
if !ok {
return &ForbiddenError{Message: mailLang + "file_missing"}
}
@@ -644,6 +720,15 @@ type recordDeletable interface {
recordDeletable(record any) bool
}
// recordLocaleVariants is implemented by the mail templates controller,
// whose records are the locale versions of a template: the show response
// then carries meta.localeVariants, the versions of the record's template
// for the form's locale switcher. Unexported: no other controller's payload
// changes.
type recordLocaleVariants interface {
recordLocaleVariants(ctx context.Context, tx *gorm.DB, record any) ([]RecordLocaleVariant, error)
}
// formFooterActions marks a controller whose config_form.yaml declares
// recordActions without a preview block: the admin offers them in the
// update form's footer instead. Only the mail controllers implement it.
@@ -1665,3 +1750,87 @@ func injectLayoutCreateDefaults(reg *Registry, editor *postcard.Editor) {
}
}
}
// templateVersion is one row of a template's locale group.
type templateVersion struct {
ID uint
Code string
Locale *string
IsCustom bool
BaseHash *string
FileHash *string
}
// recordLocaleVariants lists the locale versions of the record's template
// for the switcher. It first gives the template's missing locales their rows
// (postcard.EnsureLocaleRows, idempotent), so a locale enabled since the last
// sync can be opened without a restart. The order is Default (the base
// file), then by locale code every locale with its own file, every other
// mail locale except the default, and any customized version of a locale
// that is no longer enabled.
func (c mailTemplatesAdmin) recordLocaleVariants(ctx context.Context, tx *gorm.DB, record any) ([]RecordLocaleVariant, error) {
t, err := asMailTemplate(record)
if err != nil {
return nil, err
}
def, locales := c.mail.mailLocales(ctx, tx)
base := postcard.TemplateBase(t.Code, locales)
if t.BaseCode != nil && *t.BaseCode != "" {
base = *t.BaseCode
}
cat := c.mail.catalog()
if _, ok := cat.Template(base); ok {
// Under a savepoint: a failure leaves the show working.
if err := tx.Transaction(func(sp *gorm.DB) error {
return postcard.EnsureLocaleRows(ctx, sp, cat, def, locales, base)
}); err != nil {
moduleLog.WarnContext(ctx, "cabana: mail locale rows", "template", base, "error", err)
}
}
var rows []templateVersion
q := tx.Session(&gorm.Session{NewDB: true}).Table(postcard.TemplatesTable).
Select("id, code, locale, is_custom, base_hash, file_hash").
Where(postcard.TemplatesTable+".base_code = ? OR "+postcard.TemplatesTable+".code = ?", base, base)
if err := c.mail.scopeTemplateVersions(q).Order("code").Scan(&rows).Error; err != nil {
return nil, err
}
enabled := map[string]bool{}
for _, l := range locales {
enabled[strings.ToLower(l)] = true
}
var head *RecordLocaleVariant
var rest []RecordLocaleVariant
for _, r := range rows {
_, fileBacked := cat.Template(r.Code)
v := RecordLocaleVariant{ID: r.ID, States: []string{}, Current: r.ID == t.ID}
if r.IsCustom {
v.States = append(v.States, c.mail.message(ctx, mailLang+"state_customized", nil))
if mailOutdated(true, r.BaseHash, r.FileHash) {
v.States = append(v.States, c.mail.message(ctx, mailLang+"state_outdated", nil))
}
}
if r.Code == base {
v.Label = c.mail.message(ctx, mailLang+"template.locale_default", nil)
head = &v
continue
}
if r.Locale != nil {
v.Locale = *r.Locale
}
v.Label = v.Locale
if v.Label == "" {
v.Label = r.Code
}
if !fileBacked && !r.IsCustom && (!enabled[strings.ToLower(v.Locale)] || strings.EqualFold(v.Locale, def)) {
// A fallback row of a locale no longer enabled, not customized.
continue
}
rest = append(rest, v)
}
sort.SliceStable(rest, func(i, j int) bool { return rest[i].Locale < rest[j].Locale })
out := make([]RecordLocaleVariant, 0, len(rest)+1)
if head != nil {
out = append(out, *head)
}
return append(out, rest...), nil
}

View File

@@ -510,7 +510,8 @@ func (s *service) mailTemplateDraft(ctx context.Context, id uint64, values map[s
return postcard.Draft{}, err
}
if editor, ok := postcard.EditorFrom(s.app); ok && editor != nil {
if _, ok := editor.Catalog().Template(name); !ok {
// A fallback-locale row previews and sends with its base file.
if _, ok := editor.Catalog().TemplateFor(name); !ok {
return postcard.Draft{}, recordNotFound{}
}
}

View File

@@ -30,6 +30,7 @@ import (
"git.golem15.com/golem15/summercms/modules/postcard"
"git.golem15.com/golem15/summercms/modules/surf"
"gocloud.dev/blob/memblob"
"gorm.io/gorm"
)
// The mail screens' paths under the admin API.
@@ -147,6 +148,31 @@ type mailEnvOptions struct {
files fstest.MapFS
keep bool
mutate func(*compass.Config)
// writer, when set, is published as the cabana.TranslationWriter: the
// application's content locales, which the mail locales include.
writer cabana.TranslationWriter
}
// mailLocaleWriter is a TranslationWriter that only answers the locales.
type mailLocaleWriter struct {
def string
enabled []string
}
func (w mailLocaleWriter) DefaultLocale(context.Context, *gorm.DB) (string, error) {
return w.def, nil
}
func (w mailLocaleWriter) EnabledLocales(context.Context, *gorm.DB) ([]string, error) {
return w.enabled, nil
}
func (mailLocaleWriter) WriteTranslated(context.Context, *gorm.DB, any, string, string, string) error {
return nil
}
func (mailLocaleWriter) TranslatedExact(context.Context, *gorm.DB, any, string, string) (string, bool, error) {
return "", false, nil
}
func newMailScreensEnvWith(t *testing.T, opts mailEnvOptions) *mailEnv {
@@ -202,6 +228,11 @@ func newMailScreensEnvWith(t *testing.T, opts mailEnvOptions) *mailEnv {
if err := postcard.BootPlugin(app, blog); err != nil {
t.Fatal(err)
}
if opts.writer != nil {
if err := app.Publish[cabana.TranslationWriter](opts.writer); err != nil {
t.Fatal(err)
}
}
spy := &pingSpy{}
plugins := []party.Plugin{demoPlugin{fsys: demoFS()}, pingPlugin{spy: spy}, blog}
if err := phrasebook.Activate(app, plugins); err != nil {
@@ -346,6 +377,115 @@ func TestMailScreensSmoke(t *testing.T) {
})
mailLayoutsAndPartials(t, env, rootToken)
// Runs last: its env empties the mail tables.
t.Run("locales", func(t *testing.T) {
mailLocalesSmoke(t, rootToken)
})
}
// localeVariants returns a show response's meta.localeVariants.
func localeVariants(t *testing.T, show map[string]any) []map[string]any {
t.Helper()
meta, _ := show["meta"].(map[string]any)
items, _ := meta["localeVariants"].([]any)
out := make([]map[string]any, 0, len(items))
for _, item := range items {
v, _ := item.(map[string]any)
out = append(out, v)
}
return out
}
// variantSummary is "label[states]*" per variant, * marking the current one.
func variantSummary(variants []map[string]any) string {
parts := make([]string, 0, len(variants))
for _, v := range variants {
part := fmt.Sprintf("%v%v", v["label"], v["states"])
if v["current"] == true {
part += "*"
}
parts = append(parts, part)
}
return strings.Join(parts, " ")
}
// mailLocalesSmoke is G-35-1 end to end: on an application whose content
// locales are pl (default), en and de, the welcome template's form lists
// Default, de (no file) and en (its own file); the de version is opened,
// saved and sent for acme.blog::mail.welcome-de.
func mailLocalesSmoke(t *testing.T, rootToken string) {
env := newMailScreensEnvWith(t, mailEnvOptions{writer: mailLocaleWriter{def: "pl", enabled: []string{"pl", "en", "de"}}})
ctx := context.Background()
baseID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
show := env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", mailTemplatesPath, baseID), rootToken, nil)
variants := localeVariants(t, show)
if got := variantSummary(variants); got != "Default[]* de[] en[]" {
t.Fatalf("welcome variants = %s", got)
}
deID := uint(variants[1]["id"].(float64))
if deID != env.mailRowID(t, postcard.TemplatesTable, blogWelcome+"-de") || variants[1]["locale"] != "de" || variants[0]["locale"] != "" {
t.Fatalf("de variant = %v", variants[1])
}
dePath := fmt.Sprintf("%s/%d", mailTemplatesPath, deID)
deShow := env.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil)
if meta, _ := deShow["meta"].(map[string]any); meta["title"] != blogWelcome {
t.Fatalf("de title = %v, want the base code", meta["title"])
}
if got := variantSummary(localeVariants(t, deShow)); got != "Default[] de[]* en[]" {
t.Fatalf("de variants = %s", got)
}
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
env.expect(t, http.StatusOK, http.MethodPut, dePath, rootToken, templateBody("Willkommen, {{ .name }}", "Hallo **{{ .name }}**.", layoutID))
var stored cabana.MailTemplate
if err := env.gdb.First(&stored, deID).Error; err != nil {
t.Fatal(err)
}
baseHash, _ := mailFileHash(t, env, blogWelcome)
if !stored.IsCustom || stored.BaseHash == nil || *stored.BaseHash != baseHash {
t.Fatalf("stored de row = %+v, want customized against the base file", stored)
}
after := localeVariants(t, env.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil))
if got := variantSummary(after); got != "Default[] de[Customized]* en[]" {
t.Fatalf("variants after the de save = %s", got)
}
send := func(name string) postcard.RenderedMessage {
t.Helper()
if err := env.mailer.Send(ctx, postcard.Message{Template: name, To: []string{"reader@example.test"}, Vars: map[string]any{"name": "Grace"}}); err != nil {
t.Fatalf("Send %s: %v", name, err)
}
msgs := env.driver.messages()
return msgs[len(msgs)-1]
}
if got := send(blogWelcome + "-de"); got.Subject != "Willkommen, Grace" || !strings.Contains(got.HTML, "blog-mail") {
t.Fatalf("welcome-de sent %q / %q", got.Subject, got.HTML)
}
if got := send(blogWelcome); got.Subject != "Witaj, Grace" {
t.Fatalf("welcome sent %q, want the base file", got.Subject)
}
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
"mode": "template",
"id": deID,
"values": map[string]any{
"subject": "Vorschau",
"body": "Hallo **{{ .name }}**",
"layout": layoutID,
},
})
// An id outside the catalog's templates and their locale rows is a 404.
var orphan uint
if err := env.gdb.Raw(`INSERT INTO ` + postcard.TemplatesTable + ` (code, source, base_code) VALUES ('acme.gone::mail.x-de', 'acme.gone', 'acme.gone::mail.x') RETURNING id`).Scan(&orphan).Error; err != nil {
t.Fatal(err)
}
if rec := env.call(t, http.MethodGet, fmt.Sprintf("%s/%d", mailTemplatesPath, orphan), rootToken, nil); rec.Code != http.StatusNotFound {
t.Fatalf("orphan row status = %d", rec.Code)
}
}
// mailEditor is the env's postcard editor.

View File

@@ -119,6 +119,23 @@ type RecordMeta struct {
// screens: a custom layout can be deleted, a file-backed row cannot)
// carries it; it is omitted otherwise, and Delete then shows as before.
Deletable *bool `json:"deletable,omitempty"`
// LocaleVariants are the locale versions of the record for the update
// form's locale switcher, in display order. Only the show and update
// responses of a controller whose records have locale versions (the mail
// templates screen) carry it; it is omitted otherwise.
LocaleVariants []RecordLocaleVariant `json:"localeVariants,omitempty"`
}
// RecordLocaleVariant is one locale version of a record: the row id to open,
// its locale code (empty for the default version), the label to show and the
// state words (customized, file changed), both translated in the request
// locale, and whether it is the record being shown.
type RecordLocaleVariant struct {
ID uint `json:"id"`
Locale string `json:"locale"`
Label string `json:"label"`
States []string `json:"states"`
Current bool `json:"current"`
}
// FieldNotice is one save notice: the field it is about, the content locale