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

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