feat(cabana): mail templates list grouped by template with per-locale status
Gap G-35-1 (supersedes D-05; D-06 reset and D-07 drift per locale): - the templates list keeps one row per template (the base row, or the lowest variant when only variants ship) with a Customized locales column (Default, then locale codes, at most three then +N); - row states and the status filter aggregate over the template's locale versions; the locale filter is removed; - a not-customized locale without a file shows the base row's current subject, body and layout; its info partial says so, its file version compares with the base file, and Reset returns it to the base file (postcard.ResetOverride accepts a fallback-locale code); - copy: mail.template.customized_locales, mail.info_locale_default, mail.info_locale_fallback (en/pl); - tests: TestMailScreensSmoke/locales_list, templates and drift updated, TestMailDrift on the grouped row, TestMailTemplateFilterScopes.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -1,9 +1,11 @@
|
||||
{{- /* Lines at the top of a mail form (mailInfoView): description, file or custom code, status, sample variables, partial call, drift callout. */ -}}
|
||||
{{- /* Lines at the top of a mail form (mailInfoView): description, file or custom code, status, the locale line (Default version, or a locale without a file: backend::lang.mail.info_locale_fallback), sample variables, partial call, drift callout. */ -}}
|
||||
{{- with .Data -}}
|
||||
{{- if .Description }}<p>{{ .Description }}</p>{{ end -}}
|
||||
{{- if .File }}<p class="text-muted">{{ range .File }}{{ if .Code }}<code class="font-mono">{{ .Text }}</code>{{ else }}{{ .Text }}{{ end }}{{ end }}</p>{{ end -}}
|
||||
{{- if .CustomCode }}<p class="text-muted">{{ trans "backend::lang.mail.info_custom_layout" }} <code class="font-mono">{{ .CustomCode }}</code></p>{{ end -}}
|
||||
{{- if .Status }}<p><strong>{{ trans .Status }}</strong></p>{{ end -}}
|
||||
{{- if .LocaleDefault }}<p>{{ trans "backend::lang.mail.info_locale_default" }}</p>{{ end -}}
|
||||
{{- if .LocaleFallback }}<p>{{ .LocaleFallback }}</p>{{ end -}}
|
||||
{{- if .Template }}{{ if .Variables }}<p>{{ trans "backend::lang.mail.info_variables" }} {{ range $i, $name := .Variables }}{{ if $i }}, {{ end }}<code class="font-mono">{{ $name }}</code>{{ end }}</p>{{ else }}<p>{{ trans "backend::lang.mail.info_no_samples" }}</p>{{ end }}{{ end -}}
|
||||
{{- if .Usage }}<p>{{ trans "backend::lang.mail.info_partial_usage" }} <code class="font-mono">{{ .Usage }}</code></p>{{ end -}}
|
||||
{{- if .Outdated }}<div class="summer-callout summer-callout--warning" role="status"><p class="summer-callout__title">{{ trans "backend::lang.mail.drift_title" }}</p><p class="summer-callout__text">{{ trans "backend::lang.mail.drift_text" }}</p></div>{{ end -}}
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
scopes:
|
||||
locale:
|
||||
label: backend::lang.mail.template.locale
|
||||
modelClass: System\Models\MailTemplate
|
||||
nameFrom: code
|
||||
scope: filterLocale
|
||||
status:
|
||||
label: backend::lang.mail.filter_status
|
||||
modelClass: System\Models\MailTemplate
|
||||
|
||||
@@ -9,9 +9,8 @@ columns:
|
||||
description:
|
||||
label: backend::lang.mail.template.description
|
||||
searchable: true
|
||||
locale:
|
||||
label: backend::lang.mail.template.locale
|
||||
sortable: true
|
||||
customized_locales:
|
||||
label: backend::lang.mail.template.customized_locales
|
||||
layout:
|
||||
label: backend::lang.mail.template.layout
|
||||
relation: layout
|
||||
|
||||
@@ -536,6 +536,11 @@ func (s CRUDService) ShowRecord(ctx context.Context, cc *CompiledController, id
|
||||
if err := loadRecord(ctx, tx, cc, target, pk); err != nil {
|
||||
return err
|
||||
}
|
||||
if adjuster, ok := cc.Controller.(recordShowAdjuster); ok && adjuster != nil {
|
||||
if err := adjuster.adjustShownRecord(withTx(ctx, tx), tx, target); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
result, err = projectFullRecord(ctx, tx, cc, target)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -354,27 +354,41 @@ type MailTemplate struct {
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
Layout MailLayout `gorm:"foreignKey:LayoutID"`
|
||||
// CustomizedLocales is the list's Customized locales column: the labels
|
||||
// of the template's customized versions (Default, then locale codes),
|
||||
// filled by the list; it is not stored.
|
||||
CustomizedLocales string `gorm:"-:all;column:customized_locales"`
|
||||
}
|
||||
|
||||
func (MailTemplate) TableName() string { return postcard.TemplatesTable }
|
||||
|
||||
// FilterScopes lists the scopes of the templates list filters.
|
||||
func (MailTemplate) FilterScopes() []string { return []string{mailFilterLocale, mailFilterStatus} }
|
||||
// FilterScopes lists the scopes of the templates list filters: the status.
|
||||
func (MailTemplate) FilterScopes() []string { return []string{mailFilterStatus} }
|
||||
|
||||
// FilterScope narrows the templates list: filterLocale keeps one locale
|
||||
// (default: no locale suffix), filterStatus one status.
|
||||
// FilterScope narrows the templates list to one status of the whole
|
||||
// template: customized when any of its locale versions is, not customized
|
||||
// when none is, outdated when a customized version's file changed since.
|
||||
func (MailTemplate) FilterScope(name string, db *gorm.DB, value any) *gorm.DB {
|
||||
if db == nil {
|
||||
return db
|
||||
}
|
||||
text := strings.TrimSpace(fmt.Sprint(value))
|
||||
if name == mailFilterLocale {
|
||||
if text == mailLocaleDefault {
|
||||
return db.Where(postcard.TemplatesTable + ".locale IS NULL")
|
||||
}
|
||||
return db.Where(postcard.TemplatesTable+".locale = ?", text)
|
||||
if name != mailFilterStatus {
|
||||
return db.Where("1 = 0")
|
||||
}
|
||||
return mailStatusScope(db, name, postcard.TemplatesTable, text)
|
||||
table := postcard.TemplatesTable
|
||||
group := "COALESCE(" + table + ".base_code, " + table + ".code)"
|
||||
groups := func(cond string) string {
|
||||
return "SELECT g.base_code FROM " + table + " g WHERE g.base_code IS NOT NULL AND " + cond
|
||||
}
|
||||
switch strings.TrimSpace(fmt.Sprint(value)) {
|
||||
case mailStatusCustomized:
|
||||
return db.Where(group + " IN (" + groups("g.is_custom") + ")")
|
||||
case mailStatusNotCustomized:
|
||||
return db.Where(group + " NOT IN (" + groups("g.is_custom") + ")")
|
||||
case mailStatusOutdated:
|
||||
return db.Where(group + " IN (" + groups("g.is_custom AND g.base_hash IS DISTINCT FROM g.file_hash") + ")")
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
// Fillable lists the override columns a form writes: subject and body. The
|
||||
@@ -435,6 +449,7 @@ var (
|
||||
_ pact.AdminPartialData = mailTemplatesAdmin{}
|
||||
_ recordDeletable = mailTemplatesAdmin{}
|
||||
_ recordLocaleVariants = mailTemplatesAdmin{}
|
||||
_ recordShowAdjuster = mailTemplatesAdmin{}
|
||||
_ formFooterActions = mailTemplatesAdmin{}
|
||||
)
|
||||
|
||||
@@ -506,10 +521,41 @@ func (c mailTemplatesAdmin) scopeTemplates(db *gorm.DB) *gorm.DB {
|
||||
}
|
||||
|
||||
// ListExtendQuery retries the index sync until it succeeded in this process
|
||||
// and lists the catalog's templates.
|
||||
// and lists one row per template of the catalog (templateRepresentatives).
|
||||
func (c mailTemplatesAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
c.mail.ensureSynced(ctx)
|
||||
return c.scopeTemplates(db)
|
||||
if db == nil {
|
||||
return db
|
||||
}
|
||||
_, locales := c.mail.mailLocales(ctx, c.mail.db())
|
||||
return db.Where(postcard.TemplatesTable+".code IN ?", nonEmpty(c.mail.templateRepresentatives(locales)))
|
||||
}
|
||||
|
||||
// templateRepresentatives are the codes of the rows the templates list
|
||||
// shows, one per template: the base template's own row when the base ships
|
||||
// a file, otherwise the lowest code of its locale variants.
|
||||
func (m *mailScreens) templateRepresentatives(locales []string) []string {
|
||||
byBase := map[string]string{}
|
||||
for _, f := range m.catalog().Templates() {
|
||||
base := postcard.TemplateBase(f.Name, locales)
|
||||
if current, ok := byBase[base]; !ok || f.Name == base || (current != base && f.Name < current) {
|
||||
byBase[base] = f.Name
|
||||
}
|
||||
}
|
||||
out := make([]string, 0, len(byBase))
|
||||
for _, code := range byBase {
|
||||
out = append(out, code)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// templateGroup is the base code a template row's locale versions share.
|
||||
func templateGroup(t *MailTemplate, locales []string) string {
|
||||
if t.BaseCode != nil && *t.BaseCode != "" {
|
||||
return *t.BaseCode
|
||||
}
|
||||
return postcard.TemplateBase(t.Code, locales)
|
||||
}
|
||||
|
||||
// FormExtendQuery scopes every record lookup to the catalog's templates and
|
||||
@@ -529,19 +575,63 @@ func (m *mailScreens) scopeTemplateVersions(db *gorm.DB) *gorm.DB {
|
||||
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
|
||||
// the locale column; sorting still reads the stored column.
|
||||
func (c mailTemplatesAdmin) ListExtendRecords(ctx context.Context, _ *gorm.DB, records []any) error {
|
||||
label := c.mail.message(ctx, mailLang+"template.locale_default", nil)
|
||||
// mailCustomizedLocalesShown is how many customized locales the list names
|
||||
// before it adds " +N".
|
||||
const mailCustomizedLocalesShown = 3
|
||||
|
||||
// ListExtendRecords fills the Customized locales column from one query over
|
||||
// the page's templates: the labels of their customized versions, Default
|
||||
// first, then the locale codes.
|
||||
func (c mailTemplatesAdmin) ListExtendRecords(ctx context.Context, db *gorm.DB, records []any) error {
|
||||
_, locales := c.mail.mailLocales(ctx, c.mail.db())
|
||||
groups := make([]string, 0, len(records))
|
||||
for _, record := range records {
|
||||
t, err := asMailTemplate(record)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t.Locale == nil || *t.Locale == "" {
|
||||
value := label
|
||||
t.Locale = &value
|
||||
groups = append(groups, templateGroup(t, locales))
|
||||
}
|
||||
if len(groups) == 0 || db == nil {
|
||||
return nil
|
||||
}
|
||||
var rows []struct {
|
||||
BaseCode string
|
||||
Code string
|
||||
Locale *string
|
||||
}
|
||||
q := db.Session(&gorm.Session{NewDB: true}).Table(postcard.TemplatesTable).
|
||||
Select("base_code, code, locale").
|
||||
Where(postcard.TemplatesTable+".base_code IN ? AND "+postcard.TemplatesTable+".is_custom", groups)
|
||||
if err := c.mail.scopeTemplateVersions(q).Scan(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
byGroup := map[string][]string{}
|
||||
defaults := map[string]bool{}
|
||||
for _, r := range rows {
|
||||
if r.Code == r.BaseCode {
|
||||
defaults[r.BaseCode] = true
|
||||
continue
|
||||
}
|
||||
label := r.Code
|
||||
if r.Locale != nil && *r.Locale != "" {
|
||||
label = *r.Locale
|
||||
}
|
||||
byGroup[r.BaseCode] = append(byGroup[r.BaseCode], label)
|
||||
}
|
||||
defaultLabel := c.mail.message(ctx, mailLang+"template.locale_default", nil)
|
||||
for i, record := range records {
|
||||
t, _ := asMailTemplate(record)
|
||||
labels := byGroup[groups[i]]
|
||||
sort.Strings(labels)
|
||||
if defaults[groups[i]] {
|
||||
labels = append([]string{defaultLabel}, labels...)
|
||||
}
|
||||
text := strings.Join(labels, ", ")
|
||||
if extra := len(labels) - mailCustomizedLocalesShown; extra > 0 {
|
||||
text = strings.Join(labels[:mailCustomizedLocalesShown], ", ") + " +" + strconv.Itoa(extra)
|
||||
}
|
||||
t.CustomizedLocales = text
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -561,37 +651,54 @@ func (mailTemplatesAdmin) recordDeletable(any) bool { return false }
|
||||
|
||||
func (mailTemplatesAdmin) formFooterActions() {}
|
||||
|
||||
// ListRowStates marks a customized template, and one whose file changed
|
||||
// since, outdated (D-07).
|
||||
func (mailTemplatesAdmin) ListRowStates(_ context.Context, _ *gorm.DB, records []any) ([][]pact.RowState, error) {
|
||||
// ListRowStates marks a template customized when any of its locale
|
||||
// versions is, and outdated as well when a customized version's file
|
||||
// changed since (D-07), from one grouped query over the page.
|
||||
func (c mailTemplatesAdmin) ListRowStates(ctx context.Context, db *gorm.DB, records []any) ([][]pact.RowState, error) {
|
||||
out := make([][]pact.RowState, len(records))
|
||||
for i, record := range records {
|
||||
_, locales := c.mail.mailLocales(ctx, c.mail.db())
|
||||
groups := make([]string, 0, len(records))
|
||||
for _, record := range records {
|
||||
t, err := asMailTemplate(record)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = mailRowStates(true, t.IsCustom, t.BaseHash, t.FileHash)
|
||||
groups = append(groups, templateGroup(t, locales))
|
||||
}
|
||||
if len(groups) == 0 || db == nil {
|
||||
return out, nil
|
||||
}
|
||||
var rows []struct {
|
||||
BaseCode string
|
||||
Custom bool
|
||||
Outdated bool
|
||||
}
|
||||
table := postcard.TemplatesTable
|
||||
q := db.Session(&gorm.Session{NewDB: true}).Table(table).
|
||||
Select("base_code, BOOL_OR(is_custom) AS custom, BOOL_OR(is_custom AND base_hash IS DISTINCT FROM file_hash) AS outdated").
|
||||
Where(table+".base_code IN ?", groups)
|
||||
if err := c.mail.scopeTemplateVersions(q).Group("base_code").Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
states := map[string][]pact.RowState{}
|
||||
for _, r := range rows {
|
||||
switch {
|
||||
case r.Outdated:
|
||||
states[r.BaseCode] = []pact.RowState{pact.RowStateCustomized, pact.RowStateOutdated}
|
||||
case r.Custom:
|
||||
states[r.BaseCode] = []pact.RowState{pact.RowStateCustomized}
|
||||
}
|
||||
}
|
||||
for i, group := range groups {
|
||||
out[i] = states[group]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// FilterOptions serves the locale filter (Default plus every locale a
|
||||
// catalog template carries) and the status filter.
|
||||
func (c mailTemplatesAdmin) FilterOptions(scope string) []pact.Option {
|
||||
switch scope {
|
||||
case mailFilterStatus:
|
||||
// FilterOptions serves the status filter.
|
||||
func (mailTemplatesAdmin) FilterOptions(scope string) []pact.Option {
|
||||
if scope == mailFilterStatus {
|
||||
return mailStatusOptions()
|
||||
case mailFilterLocale:
|
||||
out := []pact.Option{{Value: mailLocaleDefault, Label: mailLang + "template.locale_default"}}
|
||||
seen := map[string]bool{}
|
||||
_, 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
|
||||
out = append(out, pact.Option{Value: locale, Label: locale})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -614,19 +721,23 @@ func (c mailTemplatesAdmin) PartialData(ctx context.Context, name string, record
|
||||
if t == nil || t.ID == 0 {
|
||||
return mailEmptyView(name)
|
||||
}
|
||||
file, ok := c.mail.catalog().Template(t.Code)
|
||||
// A locale that ships no file is based on the base template's file.
|
||||
file, ok := c.mail.catalog().TemplateFor(t.Code)
|
||||
switch name {
|
||||
case mailPartialInfo:
|
||||
view := mailInfoView{Template: true, Customized: t.IsCustom, Outdated: mailOutdated(t.IsCustom, t.BaseHash, t.FileHash)}
|
||||
view.Status = mailStatusKey(t.IsCustom)
|
||||
if ok {
|
||||
view.Description = c.mail.message(ctx, mailLang+"info_description", map[string]string{"text": file.Description})
|
||||
view.File = c.mail.fileLine(ctx, t.Code, file.PluginID)
|
||||
view.File = c.mail.fileLine(ctx, file.Name, file.PluginID)
|
||||
for key := range file.Samples {
|
||||
view.Variables = append(view.Variables, key)
|
||||
}
|
||||
sort.Strings(view.Variables)
|
||||
}
|
||||
if err := c.localeInfo(ctx, t, &view); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return view, nil
|
||||
case mailPartialFileVersion:
|
||||
if !ok {
|
||||
@@ -643,6 +754,68 @@ func (c mailTemplatesAdmin) PartialData(ctx context.Context, name string, record
|
||||
return nil, fmt.Errorf("cabana: mail templates: unknown partial %q", name)
|
||||
}
|
||||
|
||||
// localeInfo sets the info partial's locale line of a template with two or
|
||||
// more locale versions: the default line on the Default version, the
|
||||
// fallback line (:locale) on a locale that ships no file.
|
||||
func (c mailTemplatesAdmin) localeInfo(ctx context.Context, t *MailTemplate, view *mailInfoView) error {
|
||||
db := c.mail.requestDB(ctx)
|
||||
if db == nil {
|
||||
return nil
|
||||
}
|
||||
def, locales := c.mail.mailLocales(ctx, db)
|
||||
base := templateGroup(t, locales)
|
||||
variants, err := c.mail.localeVariants(ctx, db, t, base, def, locales)
|
||||
if err != nil || len(variants) < 2 {
|
||||
return err
|
||||
}
|
||||
if t.Code == base {
|
||||
view.LocaleDefault = true
|
||||
return nil
|
||||
}
|
||||
if _, own := c.mail.catalog().Template(t.Code); !own {
|
||||
locale := t.Code
|
||||
if t.Locale != nil && *t.Locale != "" {
|
||||
locale = *t.Locale
|
||||
}
|
||||
view.LocaleFallback = c.mail.message(ctx, mailLang+"info_locale_fallback", map[string]string{"locale": locale})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// adjustShownRecord shows a locale that ships no file and is not customized
|
||||
// with what that locale sends now: the base template's current subject, body
|
||||
// and layout (its customization when there is one). Only the shown record
|
||||
// changes; nothing is written.
|
||||
func (c mailTemplatesAdmin) adjustShownRecord(_ context.Context, tx *gorm.DB, record any) error {
|
||||
t, err := asMailTemplate(record)
|
||||
if err != nil || t.IsCustom {
|
||||
return err
|
||||
}
|
||||
cat := c.mail.catalog()
|
||||
if _, own := cat.Template(t.Code); own {
|
||||
return nil
|
||||
}
|
||||
file, ok := cat.TemplateFor(t.Code)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
var rows []struct {
|
||||
Subject string
|
||||
Body string
|
||||
LayoutID *uint
|
||||
}
|
||||
if err := tx.Session(&gorm.Session{NewDB: true}).Table(postcard.TemplatesTable).
|
||||
Select("subject, body, layout_id").Where("code = ?", file.Name).Scan(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
t.Subject, t.Body, t.LayoutID = rows[0].Subject, rows[0].Body, rows[0].LayoutID
|
||||
t.Layout = MailLayout{}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FormBeforeUpdate marks the row customized and stamps it with the hash of
|
||||
// the file it is based on, which is what later shows a changed file (D-07).
|
||||
func (c mailTemplatesAdmin) FormBeforeUpdate(_ context.Context, model any) error {
|
||||
@@ -729,6 +902,15 @@ type recordLocaleVariants interface {
|
||||
recordLocaleVariants(ctx context.Context, tx *gorm.DB, record any) ([]RecordLocaleVariant, error)
|
||||
}
|
||||
|
||||
// recordShowAdjuster is implemented by the mail templates controller: the
|
||||
// show response of a locale version that is not customized and ships no
|
||||
// file shows the default version instead of its stored copy. It runs in the
|
||||
// show's transaction after the record is loaded and only changes the loaded
|
||||
// value. Unexported: no other controller's payload changes.
|
||||
type recordShowAdjuster interface {
|
||||
adjustShownRecord(ctx context.Context, tx *gorm.DB, record any) 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.
|
||||
@@ -736,11 +918,9 @@ type formFooterActions interface {
|
||||
formFooterActions()
|
||||
}
|
||||
|
||||
// The mail list filter scopes and values.
|
||||
// The mail list filter scope and values.
|
||||
const (
|
||||
mailFilterLocale = "filterLocale"
|
||||
mailFilterStatus = "filterStatus"
|
||||
mailLocaleDefault = "default"
|
||||
mailFilterStatus = "filterStatus"
|
||||
|
||||
mailStatusCustomized = "customized"
|
||||
mailStatusNotCustomized = "not_customized"
|
||||
@@ -1385,15 +1565,20 @@ const (
|
||||
// custom layout's code), the status, the template's sample variables, a
|
||||
// partial's call, and the drift callout.
|
||||
type mailInfoView struct {
|
||||
Template bool
|
||||
Description string
|
||||
File []mailTextPart
|
||||
CustomCode string
|
||||
Customized bool
|
||||
Status string
|
||||
Variables []string
|
||||
Usage string
|
||||
Outdated bool
|
||||
Template bool
|
||||
// LocaleDefault marks the Default version of a template with locale
|
||||
// versions; LocaleFallback is the translated line of a locale that
|
||||
// ships no file.
|
||||
LocaleDefault bool
|
||||
LocaleFallback string
|
||||
Description string
|
||||
File []mailTextPart
|
||||
CustomCode string
|
||||
Customized bool
|
||||
Status string
|
||||
Variables []string
|
||||
Usage string
|
||||
Outdated bool
|
||||
}
|
||||
|
||||
// mailTextPart is a piece of a translated line; Code pieces are shown as
|
||||
@@ -1558,23 +1743,23 @@ func partialUsage(code, sections string) string {
|
||||
// MailBrandSetting is the settings form over postcard's branding row (id 1).
|
||||
// Saving it switches mail from mail.brandCss to the compiled colours.
|
||||
type MailBrandSetting struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
LogoFileID *uint `gorm:"column:logo_file_id"`
|
||||
BodyBg string `gorm:"column:body_bg"`
|
||||
ContentBg string `gorm:"column:content_bg"`
|
||||
HeaderColor string `gorm:"column:header_color"`
|
||||
FooterColor string `gorm:"column:footer_color"`
|
||||
HeadingColor string `gorm:"column:heading_color"`
|
||||
TextColor string `gorm:"column:text_color"`
|
||||
LinkColor string `gorm:"column:link_color"`
|
||||
ButtonTextColor string `gorm:"column:button_text_color"`
|
||||
ButtonPrimaryBg string `gorm:"column:button_primary_bg"`
|
||||
ButtonPositiveBg string `gorm:"column:button_positive_bg"`
|
||||
ButtonNegativeBg string `gorm:"column:button_negative_bg"`
|
||||
PanelBg string `gorm:"column:panel_bg"`
|
||||
TableBorderColor string `gorm:"column:table_border_color"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
LogoFileID *uint `gorm:"column:logo_file_id"`
|
||||
BodyBg string `gorm:"column:body_bg"`
|
||||
ContentBg string `gorm:"column:content_bg"`
|
||||
HeaderColor string `gorm:"column:header_color"`
|
||||
FooterColor string `gorm:"column:footer_color"`
|
||||
HeadingColor string `gorm:"column:heading_color"`
|
||||
TextColor string `gorm:"column:text_color"`
|
||||
LinkColor string `gorm:"column:link_color"`
|
||||
ButtonTextColor string `gorm:"column:button_text_color"`
|
||||
ButtonPrimaryBg string `gorm:"column:button_primary_bg"`
|
||||
ButtonPositiveBg string `gorm:"column:button_positive_bg"`
|
||||
ButtonNegativeBg string `gorm:"column:button_negative_bg"`
|
||||
PanelBg string `gorm:"column:panel_bg"`
|
||||
TableBorderColor string `gorm:"column:table_border_color"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
func (MailBrandSetting) TableName() string { return postcard.BrandTable }
|
||||
@@ -1764,20 +1949,14 @@ type templateVersion struct {
|
||||
// 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.
|
||||
// sync can be opened without a restart.
|
||||
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
|
||||
}
|
||||
base := templateGroup(t, locales)
|
||||
cat := c.mail.catalog()
|
||||
if _, ok := cat.Template(base); ok {
|
||||
// Under a savepoint: a failure leaves the show working.
|
||||
@@ -1787,13 +1966,22 @@ func (c mailTemplatesAdmin) recordLocaleVariants(ctx context.Context, tx *gorm.D
|
||||
moduleLog.WarnContext(ctx, "cabana: mail locale rows", "template", base, "error", err)
|
||||
}
|
||||
}
|
||||
return c.mail.localeVariants(ctx, tx, t, base, def, locales)
|
||||
}
|
||||
|
||||
// localeVariants are the locale versions of template base, t being the one
|
||||
// shown, in switcher order: 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 (m *mailScreens) localeVariants(ctx context.Context, db *gorm.DB, t *MailTemplate, base, def string, locales []string) ([]RecordLocaleVariant, error) {
|
||||
var rows []templateVersion
|
||||
q := tx.Session(&gorm.Session{NewDB: true}).Table(postcard.TemplatesTable).
|
||||
q := db.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 {
|
||||
if err := m.scopeTemplateVersions(q).Order("code").Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cat := m.catalog()
|
||||
enabled := map[string]bool{}
|
||||
for _, l := range locales {
|
||||
enabled[strings.ToLower(l)] = true
|
||||
@@ -1804,13 +1992,13 @@ func (c mailTemplatesAdmin) recordLocaleVariants(ctx context.Context, tx *gorm.D
|
||||
_, 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))
|
||||
v.States = append(v.States, m.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))
|
||||
v.States = append(v.States, m.message(ctx, mailLang+"state_outdated", nil))
|
||||
}
|
||||
}
|
||||
if r.Code == base {
|
||||
v.Label = c.mail.message(ctx, mailLang+"template.locale_default", nil)
|
||||
v.Label = m.message(ctx, mailLang+"template.locale_default", nil)
|
||||
head = &v
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -82,18 +82,20 @@ sample.name = "Ada"
|
||||
Hi **{{ .name }}**, thanks for joining the Acme blog.
|
||||
`)}
|
||||
next := newMailScreensEnvWith(t, mailEnvOptions{files: files, keep: true})
|
||||
// One list row per template: the drifted en version marks welcome's row.
|
||||
baseID := next.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
||||
list := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[status]=outdated", tok, nil)
|
||||
rows := listRows(t, list)
|
||||
if rows[blogWelcomeEn] == nil {
|
||||
if rows[blogWelcome] == nil || rows[blogWelcome]["customized_locales"] != "en" {
|
||||
t.Fatalf("outdated filter missing row: %#v", list["data"])
|
||||
}
|
||||
if got := fmt.Sprint(rowStates(next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, tok, nil), tmplID)); got != "[customized outdated]" {
|
||||
if got := fmt.Sprint(rowStates(next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, tok, nil), baseID)); got != "[customized outdated]" {
|
||||
t.Fatalf("drifted row states = %s", got)
|
||||
}
|
||||
next.expect(t, http.StatusOK, http.MethodPut, path, tok, map[string]any{
|
||||
"subject": "Custom again {{ .name }}", "body": "Custom body for {{ .name }}", "layout": layoutID,
|
||||
})
|
||||
if got := fmt.Sprint(rowStates(next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, tok, nil), tmplID)); got != "[customized]" {
|
||||
if got := fmt.Sprint(rowStates(next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, tok, nil), baseID)); got != "[customized]" {
|
||||
t.Fatalf("reviewed row states = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,12 +283,13 @@ func TestMailScreensSmoke(t *testing.T) {
|
||||
t.Run("templates", func(t *testing.T) {
|
||||
list := env.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, rootToken, nil)
|
||||
rows := listRows(t, list)
|
||||
base, en := rows[blogWelcome], rows[blogWelcomeEn]
|
||||
if base == nil || en == nil {
|
||||
// One row per template: the -en variant is a version of welcome.
|
||||
base := rows[blogWelcome]
|
||||
if base == nil || rows[blogWelcomeEn] != nil || len(rows) != 1 {
|
||||
t.Fatalf("templates list = %v", list["data"])
|
||||
}
|
||||
if en["locale"] != "en" || base["locale"] != "Default" {
|
||||
t.Fatalf("locales = %v / %v", base["locale"], en["locale"])
|
||||
if _, has := base["locale"]; has || base["customized_locales"] != "" {
|
||||
t.Fatalf("welcome row locale columns = %v", base)
|
||||
}
|
||||
if base["subject"] != "Witaj, {{ .name }}" || base["description"] != "Sent after registration" {
|
||||
t.Fatalf("base row = %v", base)
|
||||
@@ -382,6 +383,141 @@ func TestMailScreensSmoke(t *testing.T) {
|
||||
t.Run("locales", func(t *testing.T) {
|
||||
mailLocalesSmoke(t, rootToken)
|
||||
})
|
||||
t.Run("locales_list", func(t *testing.T) {
|
||||
mailLocalesListSmoke(t, rootToken)
|
||||
})
|
||||
}
|
||||
|
||||
// welcomeListRow is the templates list's row of welcome, after checking it
|
||||
// is the only row of its group.
|
||||
func welcomeListRow(t *testing.T, env *mailEnv, token, query string) map[string]any {
|
||||
t.Helper()
|
||||
list := env.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+query, token, nil)
|
||||
for _, code := range listCodes(list) {
|
||||
if code != blogWelcome && strings.HasPrefix(code, blogWelcome) {
|
||||
t.Fatalf("list%s holds the variant %s: %v", query, code, listCodes(list))
|
||||
}
|
||||
}
|
||||
row := listRows(t, list)[blogWelcome]
|
||||
if row != nil {
|
||||
row["_states"] = fmt.Sprint(rowStates(list, uint(row["id"].(float64))))
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
// mailLocalesListSmoke is G-35-1 in the list and the per-locale states: one
|
||||
// row per template with its customized locales and grouped badges, the
|
||||
// status filter on the group, the default version shown for a locale
|
||||
// without a file, the info and file version partials and reset of such a
|
||||
// locale, and no locale filter.
|
||||
func mailLocalesListSmoke(t *testing.T, rootToken string) {
|
||||
writer := mailLocaleWriter{def: "pl", enabled: []string{"pl", "en", "de", "fr"}}
|
||||
env := newMailScreensEnvWith(t, mailEnvOptions{writer: writer})
|
||||
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
|
||||
baseID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
||||
deID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome+"-de")
|
||||
frID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome+"-fr")
|
||||
dePath := fmt.Sprintf("%s/%d", mailTemplatesPath, deID)
|
||||
basePath := fmt.Sprintf("%s/%d", mailTemplatesPath, baseID)
|
||||
|
||||
// No locale filter any more; the status filter stays.
|
||||
listSchema := env.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"/schema/list", rootToken, nil)
|
||||
scopes := []string{}
|
||||
filters, _ := dataOf(listSchema)["filters"].([]any)
|
||||
for _, item := range filters {
|
||||
filter, _ := item.(map[string]any)
|
||||
scopes = append(scopes, fmt.Sprint(filter["scope"], filter["name"]))
|
||||
}
|
||||
if got := strings.Join(scopes, ","); strings.Contains(got, "ocale") || !strings.Contains(got, "status") {
|
||||
t.Fatalf("templates list filters = %s", got)
|
||||
}
|
||||
|
||||
row := welcomeListRow(t, env, rootToken, "")
|
||||
if row == nil || row["customized_locales"] != "" || row["_states"] != "[]" {
|
||||
t.Fatalf("fresh welcome row = %v", row)
|
||||
}
|
||||
|
||||
// A locale without a file shows the default version.
|
||||
file, _ := mailEditor(t, env).Catalog().Template(blogWelcome)
|
||||
deShow := dataOf(env.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil))
|
||||
if deShow["subject"] != file.Subject || deShow["body"] != file.Body || fmt.Sprint(deShow["layout"]) != fmt.Sprint(layoutID) {
|
||||
t.Fatalf("not customized de show = %v", deShow)
|
||||
}
|
||||
info := partialText(t, env, mailTemplatesPath, "info", rootToken, deID)
|
||||
if !strings.Contains(info, "Locale de has no file of its own") || !strings.Contains(info, "views/mail/welcome.htm") {
|
||||
t.Fatalf("de info partial = %s", info)
|
||||
}
|
||||
if baseInfo := partialText(t, env, mailTemplatesPath, "info", rootToken, baseID); !strings.Contains(baseInfo, "Default version: sent for every locale") {
|
||||
t.Fatalf("default info partial = %s", baseInfo)
|
||||
}
|
||||
if version := partialText(t, env, mailTemplatesPath, "file_version", rootToken, deID); !strings.Contains(version, "dzięki za rejestrację") {
|
||||
t.Fatalf("de file version partial = %s", version)
|
||||
}
|
||||
|
||||
// Saving only de: the template's row is customized, de listed.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, dePath, rootToken, templateBody("Willkommen, {{ .name }}", "Hallo **{{ .name }}**.", layoutID))
|
||||
row = welcomeListRow(t, env, rootToken, "")
|
||||
if row["customized_locales"] != "de" || row["_states"] != "[customized]" {
|
||||
t.Fatalf("welcome row after the de save = %v", row)
|
||||
}
|
||||
if welcomeListRow(t, env, rootToken, "?filter[status]=customized") == nil || welcomeListRow(t, env, rootToken, "?filter[status]=not_customized") != nil {
|
||||
t.Fatal("status filter does not follow the de customization")
|
||||
}
|
||||
if deShow := dataOf(env.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil)); deShow["subject"] != "Willkommen, {{ .name }}" {
|
||||
t.Fatalf("customized de show = %v", deShow)
|
||||
}
|
||||
if version := partialText(t, env, mailTemplatesPath, "file_version", rootToken, deID); !strings.Contains(version, "summer-diff__add") || !strings.Contains(version, "Willkommen") {
|
||||
t.Fatalf("customized de file version = %s", version)
|
||||
}
|
||||
|
||||
// The base file changes in a second process: de is outdated.
|
||||
files := mailBlogFiles()
|
||||
files["views/mail/welcome.htm"] = &fstest.MapFile{Data: []byte(`subject = "Witaj, {{ .name }}"
|
||||
description = "Sent after registration"
|
||||
layout = "blog"
|
||||
sample.name = "Ada"
|
||||
==
|
||||
Cześć **{{ .name }}**, dzięki za rejestrację na blogu.
|
||||
`)}
|
||||
next := newMailScreensEnvWith(t, mailEnvOptions{files: files, keep: true, writer: writer})
|
||||
row = welcomeListRow(t, next, rootToken, "")
|
||||
if row["_states"] != "[customized outdated]" {
|
||||
t.Fatalf("welcome row after the base file changed = %v", row)
|
||||
}
|
||||
if welcomeListRow(t, next, rootToken, "?filter[status]=outdated") == nil {
|
||||
t.Fatal("outdated filter misses welcome")
|
||||
}
|
||||
|
||||
// The base saved too: Default, de; fr shows the base customization.
|
||||
next.expect(t, http.StatusOK, http.MethodPut, basePath, rootToken, templateBody("Witamy, {{ .name }}", "Base.", layoutID))
|
||||
if row = welcomeListRow(t, next, rootToken, ""); row["customized_locales"] != "Default, de" {
|
||||
t.Fatalf("welcome row after the base save = %v", row)
|
||||
}
|
||||
if frShow := dataOf(next.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", mailTemplatesPath, frID), rootToken, nil)); frShow["subject"] != "Witamy, {{ .name }}" || frShow["body"] != "Base." {
|
||||
t.Fatalf("fr show with a customized base = %v", frShow)
|
||||
}
|
||||
|
||||
// Reset of de: not customized, its show back to the default version.
|
||||
if names := recordActionNames(next.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil)); strings.Join(names, ",") != "reset" {
|
||||
t.Fatalf("customized de actions = %v", names)
|
||||
}
|
||||
next.expect(t, http.StatusOK, http.MethodPost, dePath+"/actions/reset", rootToken, map[string]any{})
|
||||
var de cabana.MailTemplate
|
||||
if err := next.gdb.First(&de, deID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if de.IsCustom || de.BaseHash != nil {
|
||||
t.Fatalf("reset de row = %+v", de)
|
||||
}
|
||||
if deShow := dataOf(next.expect(t, http.StatusOK, http.MethodGet, dePath, rootToken, nil)); deShow["subject"] != "Witamy, {{ .name }}" {
|
||||
t.Fatalf("de show after reset = %v", deShow)
|
||||
}
|
||||
if row = welcomeListRow(t, next, rootToken, ""); row["customized_locales"] != "Default" {
|
||||
t.Fatalf("welcome row after the de reset = %v", row)
|
||||
}
|
||||
if err := postcard.ResetOverride(context.Background(), next.gdb, mailEditor(t, next).Catalog(), postcard.KindTemplate, blogWelcome+"-fr"); err != nil {
|
||||
t.Fatalf("ResetOverride of a fallback-locale code: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// localeVariants returns a show response's meta.localeVariants.
|
||||
@@ -695,16 +831,18 @@ sample.name = "Ada"
|
||||
Hi **{{ .name }}**, thanks for joining the Acme blog.
|
||||
`)}
|
||||
next := newMailScreensEnvWith(t, mailEnvOptions{files: files, keep: true})
|
||||
// The list row is the template's: its states are the group's.
|
||||
baseID := next.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
||||
list := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, rootToken, nil)
|
||||
if got := fmt.Sprint(rowStates(list, id)); got != "[customized outdated]" {
|
||||
if got := fmt.Sprint(rowStates(list, baseID)); got != "[customized outdated]" {
|
||||
t.Fatalf("drifted row states = %s", got)
|
||||
}
|
||||
filtered := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[status]=outdated", rootToken, nil)
|
||||
if codes := listCodes(filtered); strings.Join(codes, ",") != blogWelcomeEn {
|
||||
if codes := listCodes(filtered); strings.Join(codes, ",") != blogWelcome {
|
||||
t.Fatalf("outdated filter = %v", codes)
|
||||
}
|
||||
customized := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[status]=customized", rootToken, nil)
|
||||
if codes := listCodes(customized); strings.Join(codes, ",") != blogWelcomeEn {
|
||||
if codes := listCodes(customized); strings.Join(codes, ",") != blogWelcome {
|
||||
t.Fatalf("customized filter = %v", codes)
|
||||
}
|
||||
info := partialText(t, next, mailTemplatesPath, "info", rootToken, id)
|
||||
@@ -715,12 +853,8 @@ Hi **{{ .name }}**, thanks for joining the Acme blog.
|
||||
if !strings.Contains(version, "summer-diff__add") || !strings.Contains(version, "summer-diff__del") || !strings.Contains(version, "thanks for joining the Acme blog") {
|
||||
t.Fatalf("file version partial = %s", version)
|
||||
}
|
||||
localeFilter := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[locale]=en", rootToken, nil)
|
||||
if codes := listCodes(localeFilter); strings.Join(codes, ",") != blogWelcomeEn {
|
||||
t.Fatalf("locale filter = %v", codes)
|
||||
}
|
||||
next.expect(t, http.StatusOK, http.MethodPut, path, rootToken, templateBody("Welcome aboard, {{ .name }}", "Hi **{{ .name }}**, glad you joined.", blogID))
|
||||
if got := fmt.Sprint(rowStates(next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, rootToken, nil), id)); got != "[customized]" {
|
||||
if got := fmt.Sprint(rowStates(next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, rootToken, nil), baseID)); got != "[customized]" {
|
||||
t.Fatalf("reviewed row states = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -121,3 +121,11 @@ type stubMailFieldController struct{}
|
||||
func (stubMailFieldController) ID() string { return "acme.mail.drafts" }
|
||||
func (stubMailFieldController) ModelName() string { return "Draft" }
|
||||
func (stubMailFieldController) ConfigDir() string { return "controllers/mail" }
|
||||
|
||||
// TestMailTemplateFilterScopes: one row per template leaves no locale
|
||||
// filter; the status filter is the only scope (G-35-1).
|
||||
func TestMailTemplateFilterScopes(t *testing.T) {
|
||||
if got := strings.Join(cabana.MailTemplate{}.FilterScopes(), ","); got != "filterStatus" {
|
||||
t.Fatalf("MailTemplate filter scopes = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user