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:
@@ -169,11 +169,11 @@ The log lines carry the component `postcard`. In a test, pass any `postcard.Over
|
||||
|
||||
Every application with an admin gets the mail screens in Settings → Mail, with no setup in the application or its plugins. They are served by the admin itself (cabana) over postcard's tables:
|
||||
|
||||
- **Mail templates** lists every template the application's plugins register, one row per file, so `acme.blog::mail.welcome` and `acme.blog::mail.welcome-en` are separate rows. The list shows the code, the subject, the file's description, the locale (the suffix after the last dash when it is one of the application's locales, otherwise Default) and the layout. The form edits the subject, the Markdown message and the layout, chosen from every file layout and every layout created in the admin. The description stays the file's.
|
||||
- **Mail templates** lists every template the application's plugins register, one row per template however many locales the application has: `acme.blog::mail.welcome` and its `acme.blog::mail.welcome-en` variant are one row. The list shows the code, the subject, the file's description, the customized locales (Default and the locale codes whose version was customized, at most three and then +N) and the layout. The Customized and File changed badges and the status filter (customized, not customized, file changed) are about the whole template: any of its locale versions. The form edits the subject, the Markdown message and the layout, chosen from every file layout and every layout created in the admin. The description stays the file's. A **Language** select under the title switches between the template's versions: Default (the template's own file), every locale with its own file, and every other locale of the application. A locale with neither a file nor a customization shows the default version, which is what it sends; saving it creates that locale's own version, and Reset to file version returns it to the default version. The application's locales are the admin's translation locales plus the content locales of a translate plugin, when one is installed.
|
||||
|
||||
The screen needs `system.manage_mail_templates` (see [Users and permissions](../backend/users-and-permissions.md#permissions)). Templates come from files, so the list has no create and no delete.
|
||||
|
||||
The rows exist before anyone edits a template: when the admin starts, it writes an index row for every file template, layout and partial (`postcard.SyncIndex`), and keeps a row that is not customized equal to its file. A row whose plugin is no longer installed stays in the table but is not listed. If the tables are not there yet when the admin starts, the first open of a mail list writes the rows.
|
||||
The rows exist before anyone edits a template: when the admin starts, it writes an index row for every file template, layout and partial (`postcard.SyncIndex`) and for every locale a template ships no file for (`postcard.EnsureLocaleRows`), and keeps a row that is not customized equal to its file. A row whose plugin is no longer installed stays in the table but is not listed. If the tables are not there yet when the admin starts, the first open of a mail list writes the rows.
|
||||
|
||||
Saving a template stores your subject, message and layout in its row and marks it customized, together with the hash of the file the change was based on. From then on your version is sent instead of the file, until the template is reset to the file version. A save is checked the way a send would render it (`postcard.Editor.Validate`): a message that does not parse, does not render with the sample values or fails the safety checks is refused with a line under the field, and nothing is stored.
|
||||
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -624,6 +624,8 @@ mail:
|
||||
info_custom_layout: "Custom layout. It exists only in the database and can be deleted."
|
||||
info_variables: "Variables with sample values:"
|
||||
info_no_samples: "This file declares no sample values. Variables show as [name] in the preview."
|
||||
info_locale_default: "Default version: sent for every locale that has neither its own file nor a customized version."
|
||||
info_locale_fallback: "Locale :locale has no file of its own. Until you customize it, the default version is sent."
|
||||
info_partial_usage: "Use it in a template or layout with:"
|
||||
drift_title: "The file changed after this was customized"
|
||||
drift_text: "A plugin update changed the file. Your version is still sent. Compare both on the File version tab, then save your version again to mark the change as reviewed, or reset to the file version."
|
||||
@@ -648,6 +650,7 @@ mail:
|
||||
description: "Description"
|
||||
locale: "Locale"
|
||||
locale_default: "Default"
|
||||
customized_locales: "Customized locales"
|
||||
layout: "Layout"
|
||||
layout_comment: "The layout wraps the message. Custom layouts are listed too."
|
||||
body: "Message"
|
||||
|
||||
@@ -660,6 +660,8 @@ mail:
|
||||
info_custom_layout: "Układ własny. Istnieje tylko w bazie danych i można go usunąć."
|
||||
info_variables: "Zmienne z przykładowymi wartościami:"
|
||||
info_no_samples: "Ten plik nie deklaruje przykładowych wartości. W podglądzie zmienne są pokazane jako [nazwa]."
|
||||
info_locale_default: "Wersja domyślna: wysyłana dla każdego języka, który nie ma własnego pliku ani dostosowanej wersji."
|
||||
info_locale_fallback: "Język :locale nie ma własnego pliku. Dopóki go nie dostosujesz, wysyłana jest wersja domyślna."
|
||||
info_partial_usage: "Użyj go w szablonie lub układzie tak:"
|
||||
drift_title: "Plik zmienił się po dostosowaniu"
|
||||
drift_text: "Aktualizacja wtyczki zmieniła plik. Nadal wysyłana jest Twoja wersja. Porównaj obie w zakładce Wersja z pliku, a potem zapisz swoją wersję ponownie, aby oznaczyć zmianę jako sprawdzoną, albo przywróć wersję z pliku."
|
||||
@@ -684,6 +686,7 @@ mail:
|
||||
description: "Opis"
|
||||
locale: "Język"
|
||||
locale_default: "Domyślny"
|
||||
customized_locales: "Dostosowane języki"
|
||||
layout: "Układ"
|
||||
layout_comment: "Układ otacza wiadomość. Na liście są też układy własne."
|
||||
body: "Treść"
|
||||
|
||||
@@ -360,7 +360,7 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
|
||||
|
||||
`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.
|
||||
`postcard.ResetOverride` returns one row to its file version and clears `is_custom`, `base_hash` and `customized_at`. The file version of a locale row without a file of its own is the base template's file, so its reset makes it send the default-locale version again. A database-only layout has no file version and is refused.
|
||||
|
||||
`postcard.FormatTemplate`, `postcard.FormatLayout` and `postcard.FormatPartial` write content in the file format, so a file version and an override can be compared line by line. `postcard.TemplateLocale` reads the locale from a name such as `acme.blog::mail.welcome-en`, given the application's locales.
|
||||
|
||||
|
||||
@@ -564,8 +564,10 @@ func rowName(title, full string) string {
|
||||
// ResetOverride returns one file-backed row to its file version: the content
|
||||
// columns mirror the file again and is_custom, base_hash and customized_at
|
||||
// are cleared. kind is KindTemplate, KindLayout or KindPartial and code the
|
||||
// row's code. A database-only layout has no file version: it is refused, and
|
||||
// so is a code cat does not hold.
|
||||
// row's code. The file version of a fallback-locale template row (a
|
||||
// <template>-<locale> code whose locale ships no file) is the base
|
||||
// template's file (Catalog.TemplateFor). A database-only layout has no file
|
||||
// version: it is refused, and so is a code cat does not hold.
|
||||
func ResetOverride(ctx context.Context, db *gorm.DB, cat *Catalog, kind Kind, code string) error {
|
||||
if db == nil {
|
||||
return fmt.Errorf("postcard: reset %s: database is nil", code)
|
||||
@@ -577,7 +579,8 @@ func ResetOverride(ctx context.Context, db *gorm.DB, cat *Catalog, kind Kind, co
|
||||
var res *gorm.DB
|
||||
switch kind {
|
||||
case KindTemplate:
|
||||
f, ok := cat.Template(code)
|
||||
// A fallback-locale row returns to the base template's file.
|
||||
f, ok := cat.TemplateFor(code)
|
||||
if !ok {
|
||||
return fmt.Errorf("postcard: reset %s: no file version", code)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user