Files
summercms/modules/cabana/mail_admin.go

1668 lines
56 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cabana
import (
"context"
"encoding/json"
"errors"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"git.golem15.com/golem15/summercms/modules/postcard"
"git.golem15.com/golem15/summercms/modules/towel"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// mailLang prefixes the phrase keys of the mail screens.
const mailLang = "backend::lang.mail."
// mailScreens is the state the mail screens share: the postcard editor the
// application's Mailer exposes, and whether this process has synced the
// mail index rows (postcard.SyncIndex) yet.
type mailScreens struct {
screens *backendScreens
editor *postcard.Editor
syncMu sync.Mutex
synced atomic.Bool
}
// mailPermissions are the two mail codes, with no role grants (D-03).
func mailPermissions() []pact.Permission {
return []pact.Permission{
{Code: PermissionManageMailTemplates, Tab: "backend::lang.permissions.tab_system", Label: "backend::lang.permissions.manage_mail_templates"},
{Code: PermissionManageMailLayouts, Tab: "backend::lang.permissions.tab_system", Label: "backend::lang.permissions.manage_mail_layouts"},
}
}
func (m *mailScreens) controllers() []pact.AdminController {
return []pact.AdminController{
mailTemplatesAdmin{mail: m},
mailLayoutsAdmin{mail: m},
mailPartialsAdmin{mail: m},
mailImagesAdmin{mail: m},
}
}
// settings are the Settings → Mail entries.
func (m *mailScreens) settings() []pact.SettingsItem {
return []pact.SettingsItem{
{
Code: "mail_templates",
Label: mailLang + "template.menu_label",
Description: mailLang + "template.menu_description",
Category: mailCategory,
Icon: "mail",
Order: 200,
Permissions: []string{PermissionManageMailTemplates},
Controller: MailTemplatesControllerID,
},
{
Code: "mail_layouts",
Label: mailLang + "layout.menu_label",
Description: mailLang + "layout.menu_description",
Category: mailCategory,
Icon: "layout-grid",
Order: 210,
Permissions: []string{PermissionManageMailLayouts},
Controller: MailLayoutsControllerID,
},
{
Code: "mail_partials",
Label: mailLang + "partial.menu_label",
Description: mailLang + "partial.menu_description",
Category: mailCategory,
Icon: "puzzle",
Order: 220,
Permissions: []string{PermissionManageMailLayouts},
Controller: MailPartialsControllerID,
},
{
Code: "mail_brand",
Label: mailLang + "brand.menu_label",
Description: mailLang + "brand.menu_description",
Category: mailCategory,
Icon: "palette",
Order: 230,
Permissions: []string{PermissionManageMailLayouts},
Form: "models/mailbrandsetting/fields.yaml",
NewModel: func() any { return &MailBrandSetting{} },
},
{
Code: "mail_images",
Label: mailLang + "images.menu_label",
Description: mailLang + "images.menu_description",
Category: mailCategory,
Icon: "image",
Order: 240,
Permissions: []string{PermissionManageMailLayouts},
Controller: MailImagesControllerID,
},
}
}
// mailCategory is the Settings category of the mail screens.
const mailCategory = "backend::lang.settings.category_mail"
// application is the activating app, or nil.
func (m *mailScreens) application() *backpack.App {
if m == nil {
return nil
}
return m.screens.application()
}
// catalog is the Mailer's file catalog.
func (m *mailScreens) catalog() *postcard.Catalog {
return m.editor.Catalog()
}
// db is the application pool, or nil without one.
func (m *mailScreens) db() *gorm.DB {
app := m.application()
if app == nil {
return nil
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok {
return nil
}
return gdb
}
// requestDB is the write transaction on ctx, else the application pool.
func (m *mailScreens) requestDB(ctx context.Context) *gorm.DB {
if tx, ok := TxFromContext(ctx); ok {
return tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx)
}
if gdb := m.db(); gdb != nil {
return gdb.Session(&gorm.Session{NewDB: true}).WithContext(ctx)
}
return nil
}
// translator is the application's translator, or nil.
func (m *mailScreens) translator() *phrasebook.Translator {
app := m.application()
if app == nil {
return nil
}
tr, _ := app.Lookup[*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("")
}
// sync writes the index rows of every file template, layout and partial
// (postcard.SyncIndex) and remembers that it succeeded.
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 {
return err
}
m.synced.Store(true)
return nil
}
// syncOnDatabase is the serve-start sync (D-23), run through
// lagoon.OnDatabase. A failure (the tables not migrated yet, for example)
// is logged and never fails the boot: the first mail list request retries.
func (m *mailScreens) syncOnDatabase(gdb *gorm.DB) {
ctx := context.Background()
if err := m.sync(ctx, gdb.Session(&gorm.Session{NewDB: true}).WithContext(ctx)); err != nil {
moduleLog.Warn("cabana: mail index sync failed; the first mail list request retries", "error", err)
}
}
// ensureSynced retries the index sync until it has succeeded once in this
// process. 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 {
moduleLog.WarnContext(ctx, "cabana: mail index sync failed", "error", err)
}
}
// message translates a backend phrase key in the request locale with
// params; the key itself is returned without a translator.
func (m *mailScreens) message(ctx context.Context, key string, params map[string]string) string {
tr := m.translator()
if tr == nil || !tr.Has(key) {
return key
}
return tr.Get(towel.WithLocale(ctx, schemaLocale(ctx, tr)), key, params)
}
// choice translates a plural backend phrase key in the request locale.
func (m *mailScreens) choice(ctx context.Context, key string, count int64, params map[string]string) string {
tr := m.translator()
if tr == nil || !tr.Has(key) {
return key
}
return tr.Choice(towel.WithLocale(ctx, schemaLocale(ctx, tr)), key, count, params)
}
// draftFailure turns postcard's verdict on a draft into the 422 field line
// of the edited field: the translated rule text, with the parser's or the
// checker's own text as :message and the partial as :name.
func (m *mailScreens) draftFailure(ctx context.Context, de *postcard.DraftError) error {
field := de.Field
if field == "" {
field = "body"
}
text := m.draftMessage(ctx, de)
return &ValidationError{Details: map[string]any{field: []string{text}}}
}
// draftMessage is the translated text of a draft failure.
func (m *mailScreens) draftMessage(ctx context.Context, de *postcard.DraftError) string {
return m.message(ctx, mailLang+"invalid_"+de.Rule, map[string]string{"message": de.Message, "name": de.Name})
}
// templateCodes are the full names of the templates in this process's
// catalog: a row whose code is not among them is hidden (D-23).
func (m *mailScreens) templateCodes() []string {
files := m.catalog().Templates()
out := make([]string, 0, len(files))
for _, f := range files {
out = append(out, f.Name)
}
return out
}
// layoutCodes are the full names of the layouts in this process's catalog.
func (m *mailScreens) layoutCodes() []string {
files := m.catalog().Layouts()
out := make([]string, 0, len(files))
for _, f := range files {
out = append(out, f.Name)
}
return out
}
// scopeLayouts limits a layouts query to the layouts this process can send:
// every database-only layout, and the file layouts of its catalog.
func (m *mailScreens) scopeLayouts(db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
return db.Where("("+postcard.LayoutsTable+".source IS NULL OR "+postcard.LayoutsTable+".code IN ?)", nonEmpty(m.layoutCodes()))
}
// nonEmpty keeps an IN list from being empty, which matches nothing.
func nonEmpty(codes []string) []string {
if len(codes) == 0 {
return []string{""}
}
return codes
}
// MailTemplate is a row of postcard's templates table: one per file
// template, its override columns set while the template is customized.
type MailTemplate struct {
ID uint `gorm:"column:id;primaryKey"`
Code string `gorm:"column:code"`
Source string `gorm:"column:source"`
Locale *string `gorm:"column:locale"`
Description string `gorm:"column:description"`
Subject string `gorm:"column:subject"`
Body string `gorm:"column:body"`
LayoutID *uint `gorm:"column:layout_id"`
IsCustom bool `gorm:"column:is_custom"`
FileHash *string `gorm:"column:file_hash"`
BaseHash *string `gorm:"column:base_hash"`
CustomizedAt *time.Time `gorm:"column:customized_at"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
Layout MailLayout `gorm:"foreignKey:LayoutID"`
}
func (MailTemplate) TableName() string { return postcard.TemplatesTable }
// FilterScopes lists the scopes of the templates list filters.
func (MailTemplate) FilterScopes() []string { return []string{mailFilterLocale, mailFilterStatus} }
// FilterScope narrows the templates list: filterLocale keeps one locale
// (default: no locale suffix), filterStatus one status.
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)
}
return mailStatusScope(db, name, postcard.TemplatesTable, text)
}
// Fillable lists the override columns a form writes: subject and body. The
// layout is written through the layout relation field.
func (MailTemplate) Fillable() []string { return []string{"subject", "body"} }
// Rules require a subject.
func (MailTemplate) Rules() map[string]string {
return map[string]string{"subject": "required"}
}
// MailLayout is a row of postcard's layouts table: a file layout's index
// row, or a database-only (custom) layout, whose source is NULL.
type MailLayout struct {
ID uint `gorm:"column:id;primaryKey"`
Code string `gorm:"column:code"`
Source *string `gorm:"column:source"`
Name string `gorm:"column:name"`
ContentHTML string `gorm:"column:content_html"`
ContentText string `gorm:"column:content_text"`
ContentCSS string `gorm:"column:content_css"`
IsCustom bool `gorm:"column:is_custom"`
FileHash *string `gorm:"column:file_hash"`
BaseHash *string `gorm:"column:base_hash"`
// CustomizedAt is when the layout was last saved from the admin.
CustomizedAt *time.Time `gorm:"column:customized_at"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
func (MailLayout) TableName() string { return postcard.LayoutsTable }
// mailTemplatesAdmin is the Mail templates screen
// (summercms.cabana.mailtemplates) over postcard's templates table. Every
// route needs system.manage_mail_templates. Templates come from plugin
// files: rows are never created or deleted here, only customized.
type mailTemplatesAdmin struct {
mail *mailScreens
}
var (
_ pact.AdminController = mailTemplatesAdmin{}
_ pact.AdminPermissioned = mailTemplatesAdmin{}
_ pact.AdminRecordSource = mailTemplatesAdmin{}
_ pact.FormRecordTitle = mailTemplatesAdmin{}
_ FieldRelationProvider = mailTemplatesAdmin{}
_ pact.RelationExtendOptionsQuery = mailTemplatesAdmin{}
_ pact.ListExtendQuery = mailTemplatesAdmin{}
_ pact.ListExtendRecords = mailTemplatesAdmin{}
_ pact.FormExtendQuery = mailTemplatesAdmin{}
_ pact.FormBeforeCreate = mailTemplatesAdmin{}
_ pact.FormBeforeUpdate = mailTemplatesAdmin{}
_ pact.FormAfterUpdate = mailTemplatesAdmin{}
_ pact.FormBeforeDelete = mailTemplatesAdmin{}
_ pact.ListRowStates = mailTemplatesAdmin{}
_ pact.FilterOptions = mailTemplatesAdmin{}
_ pact.HasAdminRecordActions = mailTemplatesAdmin{}
_ pact.AdminPartialData = mailTemplatesAdmin{}
_ recordDeletable = mailTemplatesAdmin{}
_ formFooterActions = mailTemplatesAdmin{}
)
func (mailTemplatesAdmin) ID() string { return MailTemplatesControllerID }
func (mailTemplatesAdmin) ModelName() string { return `System\Models\MailTemplate` }
func (mailTemplatesAdmin) ConfigDir() string { return "controllers/mailtemplates" }
func (mailTemplatesAdmin) RequiredPermissions() []string {
return []string{PermissionManageMailTemplates}
}
func (mailTemplatesAdmin) NewRecord() any { return &MailTemplate{} }
// asMailTemplate asserts a hook's model.
func asMailTemplate(model any) (*MailTemplate, error) {
t, ok := model.(*MailTemplate)
if !ok || t == nil {
return nil, errors.New("cabana: mail templates: record is not a mail template")
}
return t, nil
}
// FormRecordTitle names a template by its code.
func (mailTemplatesAdmin) FormRecordTitle(_ context.Context, _ *gorm.DB, record any) (string, error) {
t, err := asMailTemplate(record)
if err != nil {
return "", err
}
return t.Code, nil
}
// mailLayoutField is the template form's layout picker.
const mailLayoutField = "layout"
// AdminFieldRelations binds the layout picker to layout_id.
func (mailTemplatesAdmin) AdminFieldRelations() []FieldRelationContract {
return []FieldRelationContract{{
Field: mailLayoutField,
Kind: "belongsTo",
NewRelated: func() any { return &MailLayout{} },
ForeignKey: "layout_id",
LabelColumn: "name",
}}
}
// RelationExtendOptionsQuery offers the layouts this process can send: every
// custom layout and the file layouts of its catalog. A save checks the
// submitted id against the same query.
func (c mailTemplatesAdmin) RelationExtendOptionsQuery(_ context.Context, field string, db *gorm.DB) *gorm.DB {
if field != mailLayoutField {
return db
}
return c.mail.scopeLayouts(db)
}
// scopeTemplates hides the rows of templates this process's catalog does
// not hold (a plugin that was removed, for example).
func (c mailTemplatesAdmin) scopeTemplates(db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
return db.Where(postcard.TemplatesTable+".code IN ?", nonEmpty(c.mail.templateCodes()))
}
// ListExtendQuery retries the index sync until it succeeded in this process
// and lists the catalog's templates.
func (c mailTemplatesAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB {
c.mail.ensureSynced(ctx)
return c.scopeTemplates(db)
}
// FormExtendQuery applies the catalog scope to every record lookup.
func (c mailTemplatesAdmin) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
return c.scopeTemplates(db)
}
// 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)
for _, record := range records {
t, err := asMailTemplate(record)
if err != nil {
return err
}
if t.Locale == nil || *t.Locale == "" {
value := label
t.Locale = &value
}
}
return nil
}
// FormBeforeCreate refuses: templates come from plugin files.
func (mailTemplatesAdmin) FormBeforeCreate(context.Context, any) error {
return &ForbiddenError{Message: mailLang + "template.no_create"}
}
// FormBeforeDelete refuses: a template's row belongs to its file; Reset to
// file version removes an override.
func (mailTemplatesAdmin) FormBeforeDelete(context.Context, any) error {
return &ForbiddenError{Message: mailLang + "file_delete"}
}
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) {
out := make([][]pact.RowState, len(records))
for i, record := range records {
t, err := asMailTemplate(record)
if err != nil {
return nil, err
}
out[i] = mailRowStates(true, t.IsCustom, t.BaseHash, t.FileHash)
}
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:
return mailStatusOptions()
case mailFilterLocale:
out := []pact.Option{{Value: mailLocaleDefault, Label: mailLang + "template.locale_default"}}
seen := map[string]bool{}
locales := c.mail.locales()
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
}
// AdminRecordActions is Reset to file version on a customized template.
func (c mailTemplatesAdmin) AdminRecordActions() []pact.AdminRecordAction {
return []pact.AdminRecordAction{c.mail.resetAction(postcard.KindTemplate, PermissionManageMailTemplates, mailLang+"template.reset_confirm",
func(record any) (string, bool, error) {
t, err := asMailTemplate(record)
if err != nil {
return "", false, err
}
return t.Code, t.IsCustom, nil
})}
}
// PartialData serves the form's info and file_version partials.
func (c mailTemplatesAdmin) PartialData(ctx context.Context, name string, record any) (any, error) {
t, _ := record.(*MailTemplate)
if t == nil || t.ID == 0 {
return mailEmptyView(name)
}
file, ok := c.mail.catalog().Template(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)
for key := range file.Samples {
view.Variables = append(view.Variables, key)
}
sort.Strings(view.Variables)
}
return view, nil
case mailPartialFileVersion:
if !ok {
return mailFileVersionView{}, nil
}
layout, err := c.mail.layoutCodeRead(ctx, t.LayoutID)
if err != nil {
return nil, err
}
return mailFileVersion(t.IsCustom,
postcard.FormatTemplate(file.Subject, file.Layout, file.Body),
postcard.FormatTemplate(t.Subject, layout, t.Body), file.Source), nil
}
return nil, fmt.Errorf("cabana: mail templates: unknown partial %q", name)
}
// 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 {
t, err := asMailTemplate(model)
if err != nil {
return err
}
file, ok := c.mail.catalog().Template(t.Code)
if !ok {
return &ForbiddenError{Message: mailLang + "file_missing"}
}
now := time.Now().UTC()
hash := file.Hash
t.IsCustom = true
t.BaseHash = &hash
t.FileHash = &hash
t.CustomizedAt = &now
return nil
}
// FormAfterUpdate validates the saved override through postcard, after the
// layout relation was assigned and inside the save's transaction: a draft
// postcard would not send rolls the save back with a field line (D-13).
func (c mailTemplatesAdmin) FormAfterUpdate(ctx context.Context, model any) error {
t, err := asMailTemplate(model)
if err != nil {
return err
}
layout, err := c.mail.layoutCode(ctx, t.LayoutID)
if err != nil {
return err
}
draft := postcard.Draft{Kind: postcard.KindTemplate, Name: t.Code, Subject: t.Subject, Body: t.Body, Layout: layout}
if de := c.mail.editor.Validate(ctx, draft); de != nil {
return c.mail.draftFailure(ctx, de)
}
return nil
}
// layoutCode reads the code of the layout row id through the request's
// transaction; "" when id is nil.
func (m *mailScreens) layoutCode(ctx context.Context, id *uint) (string, error) {
if id == nil || *id == 0 {
return "", nil
}
db := m.requestDB(ctx)
if db == nil {
return "", errors.New("cabana: mail: database handle is missing")
}
var codes []string
if err := db.Table(postcard.LayoutsTable).Where("id = ?", *id).Pluck("code", &codes).Error; err != nil {
return "", err
}
if len(codes) == 0 {
return "", &ValidationError{Details: map[string]any{mailLayoutField: []string{m.message(ctx, mailLang+"invalid_layout", nil)}}}
}
return codes[0], nil
}
// layoutCodeRead is layoutCode for display: "" when the row is gone.
func (m *mailScreens) layoutCodeRead(ctx context.Context, id *uint) (string, error) {
code, err := m.layoutCode(ctx, id)
var invalid *ValidationError
if errors.As(err, &invalid) {
return "", nil
}
return code, err
}
// recordDeletable is implemented by the mail controllers, which decide per
// record whether the form offers Delete; the show response then carries
// meta.deletable. Other controllers do not implement it and send no key.
type recordDeletable interface {
recordDeletable(record any) bool
}
// 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.
type formFooterActions interface {
formFooterActions()
}
// The mail list filter scopes and values.
const (
mailFilterLocale = "filterLocale"
mailFilterStatus = "filterStatus"
mailLocaleDefault = "default"
mailStatusCustomized = "customized"
mailStatusNotCustomized = "not_customized"
mailStatusOutdated = "outdated"
)
// mailStatusOptions are the status filter's choices.
func mailStatusOptions() []pact.Option {
return []pact.Option{
{Value: mailStatusCustomized, Label: mailLang + "filter_customized"},
{Value: mailStatusNotCustomized, Label: mailLang + "filter_not_customized"},
{Value: mailStatusOutdated, Label: mailLang + "filter_outdated"},
}
}
// mailStatusScope narrows a mail list on table to one status: customized
// (a file-backed row with an override), not customized, or outdated (an
// override whose file changed since). Any other scope matches nothing.
func mailStatusScope(db *gorm.DB, name, table, value string) *gorm.DB {
if name != mailFilterStatus {
return db.Where("1 = 0")
}
switch value {
case mailStatusCustomized:
return db.Where(table + ".is_custom AND " + table + ".source IS NOT NULL")
case mailStatusNotCustomized:
return db.Where("NOT " + table + ".is_custom")
case mailStatusOutdated:
return db.Where(table + ".is_custom AND " + table + ".source IS NOT NULL AND " + table + ".base_hash IS DISTINCT FROM " + table + ".file_hash")
}
return db
}
// mailOutdated reports an override whose file changed after it was saved.
func mailOutdated(custom bool, base, file *string) bool {
if !custom {
return false
}
if base == nil || file == nil {
return base != file
}
return *base != *file
}
// mailRowStates are a file-backed row's states: customized while it holds
// an override, and outdated as well when its file changed since.
func mailRowStates(fileBacked, custom bool, base, file *string) []pact.RowState {
if !fileBacked || !custom {
return nil
}
if mailOutdated(custom, base, file) {
return []pact.RowState{pact.RowStateCustomized, pact.RowStateOutdated}
}
return []pact.RowState{pact.RowStateCustomized}
}
// mailStatusKey is the info partial's status line.
func mailStatusKey(custom bool) string {
if custom {
return mailLang + "info_customized"
}
return mailLang + "info_not_customized"
}
// resetAction is Reset to file version for kind: offered on a file-backed
// row that holds an override (row reports the code and whether it applies),
// it returns the row to its file through postcard.ResetOverride inside the
// action's transaction.
func (m *mailScreens) resetAction(kind postcard.Kind, permission, confirm string, row func(record any) (string, bool, error)) pact.AdminRecordAction {
return pact.AdminRecordAction{
Name: "reset",
Label: mailLang + "reset",
Confirm: confirm,
Permissions: []string{permission},
Danger: true,
Applies: func(_ context.Context, record any) (bool, error) {
_, applies, err := row(record)
return applies, err
},
Run: func(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
code, applies, err := row(in.Record)
if err != nil {
return pact.AdminRecordActionResult{}, err
}
if !applies {
return pact.AdminRecordActionResult{}, &ForbiddenError{Message: mailLang + "reset_unavailable"}
}
tx, ok := TxFromContext(ctx)
if !ok {
return pact.AdminRecordActionResult{}, errors.New("cabana: mail: a reset needs its transaction")
}
if err := postcard.ResetOverride(ctx, tx.Session(&gorm.Session{NewDB: true}), m.catalog(), kind, code); err != nil {
return pact.AdminRecordActionResult{}, err
}
return pact.AdminRecordActionResult{Message: mailLang + "reset_done"}, nil
},
}
}
// stamp marks a file-backed row customized against the file hash.
func stamp(custom *bool, base, file **string, at **time.Time, hash string) {
now := time.Now().UTC()
*custom = true
value := hash
*base = &value
current := hash
*file = &current
*at = &now
}
// MailLayout methods: the layouts screen's form, rules and filter.
// Fillable lists the columns the layout form writes. code is written only
// when a custom layout is created (its field's context is create).
func (MailLayout) Fillable() []string {
return []string{"name", "code", "content_html", "content_text", "content_css"}
}
// Rules require a name and a code.
func (MailLayout) Rules() map[string]string {
return map[string]string{"name": "required|max:255", "code": "required|max:255"}
}
// FilterScopes lists the layouts list filter scope.
func (MailLayout) FilterScopes() []string { return []string{mailFilterStatus} }
// FilterScope narrows the layouts list to one status.
func (MailLayout) FilterScope(name string, db *gorm.DB, value any) *gorm.DB {
if db == nil {
return db
}
return mailStatusScope(db, name, postcard.LayoutsTable, strings.TrimSpace(fmt.Sprint(value)))
}
// mailLayoutsAdmin is the Mail layouts screen (summercms.cabana.maillayouts):
// every file layout, which can be customized and reset, and the custom
// layouts that exist only in the database, which can be created and
// deleted. Every route needs system.manage_mail_layouts.
type mailLayoutsAdmin struct {
mail *mailScreens
}
var (
_ pact.AdminController = mailLayoutsAdmin{}
_ pact.AdminPermissioned = mailLayoutsAdmin{}
_ pact.AdminRecordSource = mailLayoutsAdmin{}
_ pact.FormRecordTitle = mailLayoutsAdmin{}
_ pact.ListExtendQuery = mailLayoutsAdmin{}
_ pact.ListExtendRecords = mailLayoutsAdmin{}
_ pact.FormExtendQuery = mailLayoutsAdmin{}
_ pact.FormBeforeCreate = mailLayoutsAdmin{}
_ pact.FormAfterCreate = mailLayoutsAdmin{}
_ pact.FormBeforeUpdate = mailLayoutsAdmin{}
_ pact.FormAfterUpdate = mailLayoutsAdmin{}
_ pact.FormBeforeDelete = mailLayoutsAdmin{}
_ pact.ListRowStates = mailLayoutsAdmin{}
_ pact.FilterOptions = mailLayoutsAdmin{}
_ pact.HasAdminRecordActions = mailLayoutsAdmin{}
_ pact.AdminPartialData = mailLayoutsAdmin{}
_ recordDeletable = mailLayoutsAdmin{}
_ formFooterActions = mailLayoutsAdmin{}
)
func (mailLayoutsAdmin) ID() string { return MailLayoutsControllerID }
func (mailLayoutsAdmin) ModelName() string { return `System\Models\MailLayout` }
func (mailLayoutsAdmin) ConfigDir() string { return "controllers/maillayouts" }
func (mailLayoutsAdmin) RequiredPermissions() []string {
return []string{PermissionManageMailLayouts}
}
func (mailLayoutsAdmin) NewRecord() any { return &MailLayout{} }
func (mailLayoutsAdmin) formFooterActions() {}
func asMailLayout(model any) (*MailLayout, error) {
l, ok := model.(*MailLayout)
if !ok || l == nil {
return nil, errors.New("cabana: mail layouts: record is not a mail layout")
}
return l, nil
}
// recordDeletable: only a custom layout can be deleted.
func (mailLayoutsAdmin) recordDeletable(record any) bool {
l, err := asMailLayout(record)
return err == nil && l.Source == nil
}
// FormRecordTitle names a layout by its name.
func (mailLayoutsAdmin) FormRecordTitle(_ context.Context, _ *gorm.DB, record any) (string, error) {
l, err := asMailLayout(record)
if err != nil {
return "", err
}
return l.Name, nil
}
// mailDefaultLayout is postcard's built-in default layout, listed first.
const mailDefaultLayout = "postcard::mail.layouts.default"
// ListExtendQuery retries the index sync, lists the layouts this process can
// send and puts postcard's default layout first.
func (c mailLayoutsAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB {
c.mail.ensureSynced(ctx)
// A raw column: an OrderBy expression would be dropped when the list's
// own sort is merged into the clause. The SQL is a constant.
return c.mail.scopeLayouts(db).Order(clause.OrderByColumn{Column: clause.Column{
Name: "CASE WHEN " + postcard.LayoutsTable + ".code = '" + mailDefaultLayout + "' THEN 0 ELSE 1 END", Raw: true,
}})
}
// FormExtendQuery applies the catalog scope to every record lookup.
func (c mailLayoutsAdmin) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
return c.mail.scopeLayouts(db)
}
// ListExtendRecords shows a custom layout's source as Custom.
func (c mailLayoutsAdmin) ListExtendRecords(ctx context.Context, _ *gorm.DB, records []any) error {
label := c.mail.message(ctx, mailLang+"source_custom", nil)
for _, record := range records {
l, err := asMailLayout(record)
if err != nil {
return err
}
if l.Source == nil {
value := label
l.Source = &value
}
}
return nil
}
// ListRowStates marks customized file layouts (and outdated ones); custom
// layouts carry no state.
func (mailLayoutsAdmin) ListRowStates(_ context.Context, _ *gorm.DB, records []any) ([][]pact.RowState, error) {
out := make([][]pact.RowState, len(records))
for i, record := range records {
l, err := asMailLayout(record)
if err != nil {
return nil, err
}
out[i] = mailRowStates(l.Source != nil, l.IsCustom, l.BaseHash, l.FileHash)
}
return out, nil
}
// FilterOptions serves the status filter.
func (mailLayoutsAdmin) FilterOptions(scope string) []pact.Option {
if scope == mailFilterStatus {
return mailStatusOptions()
}
return nil
}
// mailLayoutCode is the format of a custom layout's code.
var mailLayoutCode = regexp.MustCompile(`^[a-z0-9-]+$`)
// FormBeforeCreate creates a custom layout: the code must be lowercase
// letters, digits and dashes and free, and the row has no source.
func (c mailLayoutsAdmin) FormBeforeCreate(ctx context.Context, model any) error {
l, err := asMailLayout(model)
if err != nil {
return err
}
l.Code = strings.TrimSpace(l.Code)
if !mailLayoutCode.MatchString(l.Code) {
return &ValidationError{Details: map[string]any{"code": []string{c.mail.message(ctx, mailLang+"layout.code_format", nil)}}}
}
db := c.mail.requestDB(ctx)
if db == nil {
return errors.New("cabana: mail layouts: database handle is missing")
}
var taken int64
if err := db.Table(postcard.LayoutsTable).Where("code = ?", l.Code).Count(&taken).Error; err != nil {
return err
}
if taken > 0 {
return &ValidationError{Details: map[string]any{"code": []string{c.mail.message(ctx, mailLang+"layout.code_taken", nil)}}}
}
now := time.Now().UTC()
l.Source = nil
l.IsCustom = true
l.FileHash, l.BaseHash = nil, nil
l.CustomizedAt = &now
return nil
}
// FormAfterCreate validates the new layout through postcard.
func (c mailLayoutsAdmin) FormAfterCreate(ctx context.Context, model any) error {
return c.validate(ctx, model)
}
// FormBeforeUpdate stamps a file layout customized against its file (its
// name stays the file's: the index sync owns it); a custom layout records
// when it was saved.
func (c mailLayoutsAdmin) FormBeforeUpdate(_ context.Context, model any) error {
l, err := asMailLayout(model)
if err != nil {
return err
}
if l.Source == nil {
now := time.Now().UTC()
l.IsCustom = true
l.CustomizedAt = &now
return nil
}
file, ok := c.mail.catalog().Layout(l.Code)
if !ok {
return &ForbiddenError{Message: mailLang + "file_missing"}
}
l.Name = mailRowName(file.Title, file.Name)
stamp(&l.IsCustom, &l.BaseHash, &l.FileHash, &l.CustomizedAt, file.Hash)
return nil
}
// FormAfterUpdate validates the saved layout through postcard (D-13).
func (c mailLayoutsAdmin) FormAfterUpdate(ctx context.Context, model any) error {
return c.validate(ctx, model)
}
func (c mailLayoutsAdmin) validate(ctx context.Context, model any) error {
l, err := asMailLayout(model)
if err != nil {
return err
}
draft := postcard.Draft{Kind: postcard.KindLayout, Name: l.Code, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS}
if de := c.mail.editor.Validate(ctx, draft); de != nil {
return c.mail.draftFailure(ctx, de)
}
return nil
}
// FormBeforeDelete refuses a file layout and a custom layout that templates
// still use, naming the layout and how many (D-08). The foreign key's ON
// DELETE RESTRICT stays the backstop.
func (c mailLayoutsAdmin) FormBeforeDelete(ctx context.Context, model any) error {
l, err := asMailLayout(model)
if err != nil {
return err
}
if l.Source != nil {
return &ForbiddenError{Message: mailLang + "file_delete"}
}
db := c.mail.requestDB(ctx)
if db == nil {
return errors.New("cabana: mail layouts: database handle is missing")
}
var users int64
if err := db.Table(postcard.TemplatesTable).Where("layout_id = ?", l.ID).Count(&users).Error; err != nil {
return err
}
if users == 0 {
return nil
}
return &ForbiddenError{Message: c.mail.choice(ctx, mailLang+"layout.delete_in_use", users, map[string]string{"name": l.Name, "count": strconv.FormatInt(users, 10)})}
}
// AdminRecordActions is Reset to file version on a customized file layout.
func (c mailLayoutsAdmin) AdminRecordActions() []pact.AdminRecordAction {
return []pact.AdminRecordAction{c.mail.resetAction(postcard.KindLayout, PermissionManageMailLayouts, mailLang+"layout.reset_confirm",
func(record any) (string, bool, error) {
l, err := asMailLayout(record)
if err != nil {
return "", false, err
}
return l.Code, l.Source != nil && l.IsCustom, nil
})}
}
// PartialData serves the form's info and file_version partials.
func (c mailLayoutsAdmin) PartialData(ctx context.Context, name string, record any) (any, error) {
l, _ := record.(*MailLayout)
if l == nil || l.ID == 0 {
return mailEmptyView(name)
}
if l.Source == nil {
switch name {
case mailPartialInfo:
return mailInfoView{CustomCode: l.Code}, nil
case mailPartialFileVersion:
return mailFileVersionView{CustomLayout: true}, nil
}
return nil, fmt.Errorf("cabana: mail layouts: unknown partial %q", name)
}
file, ok := c.mail.catalog().Layout(l.Code)
switch name {
case mailPartialInfo:
view := mailInfoView{Customized: l.IsCustom, Status: mailStatusKey(l.IsCustom), Outdated: mailOutdated(l.IsCustom, l.BaseHash, l.FileHash)}
if ok {
view.File = c.mail.fileLine(ctx, l.Code, file.PluginID)
}
return view, nil
case mailPartialFileVersion:
if !ok {
return mailFileVersionView{}, nil
}
return mailFileVersion(l.IsCustom,
postcard.FormatLayout(mailRowName(file.Title, file.Name), file.Text, file.HTML, ""),
postcard.FormatLayout(l.Name, l.ContentText, l.ContentHTML, l.ContentCSS), file.Source), nil
}
return nil, fmt.Errorf("cabana: mail layouts: unknown partial %q", name)
}
// mailRowName is the name of a file layout's or partial's row: the file
// header's name, else the full name (as postcard.SyncIndex writes it).
func mailRowName(title, full string) string {
if title != "" {
return title
}
return full
}
// MailPartial is a row of postcard's partials table: one per file partial,
// its content columns holding the override while it is customized.
type MailPartial struct {
ID uint `gorm:"column:id;primaryKey"`
Code string `gorm:"column:code"`
Source string `gorm:"column:source"`
Name string `gorm:"column:name"`
ContentHTML string `gorm:"column:content_html"`
ContentText string `gorm:"column:content_text"`
IsCustom bool `gorm:"column:is_custom"`
FileHash *string `gorm:"column:file_hash"`
BaseHash *string `gorm:"column:base_hash"`
CustomizedAt *time.Time `gorm:"column:customized_at"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
func (MailPartial) TableName() string { return postcard.PartialsTable }
// Fillable lists the columns the partial form writes.
func (MailPartial) Fillable() []string { return []string{"content_html", "content_text"} }
// Rules has no base rule: postcard's draft check validates a partial.
func (MailPartial) Rules() map[string]string { return map[string]string{} }
// FilterScopes lists the partials list filter scope.
func (MailPartial) FilterScopes() []string { return []string{mailFilterStatus} }
// FilterScope narrows the partials list to one status.
func (MailPartial) FilterScope(name string, db *gorm.DB, value any) *gorm.DB {
if db == nil {
return db
}
return mailStatusScope(db, name, postcard.PartialsTable, strings.TrimSpace(fmt.Sprint(value)))
}
// mailPartialsAdmin is the Mail partials screen
// (summercms.cabana.mailpartials): every file partial, customized and reset
// here, never created or deleted. Every route needs
// system.manage_mail_layouts.
type mailPartialsAdmin struct {
mail *mailScreens
}
var (
_ pact.AdminController = mailPartialsAdmin{}
_ pact.AdminPermissioned = mailPartialsAdmin{}
_ pact.AdminRecordSource = mailPartialsAdmin{}
_ pact.FormRecordTitle = mailPartialsAdmin{}
_ pact.ListExtendQuery = mailPartialsAdmin{}
_ pact.FormExtendQuery = mailPartialsAdmin{}
_ pact.FormBeforeCreate = mailPartialsAdmin{}
_ pact.FormBeforeUpdate = mailPartialsAdmin{}
_ pact.FormAfterUpdate = mailPartialsAdmin{}
_ pact.FormBeforeDelete = mailPartialsAdmin{}
_ pact.ListRowStates = mailPartialsAdmin{}
_ pact.FilterOptions = mailPartialsAdmin{}
_ pact.HasAdminRecordActions = mailPartialsAdmin{}
_ pact.AdminPartialData = mailPartialsAdmin{}
_ recordDeletable = mailPartialsAdmin{}
_ formFooterActions = mailPartialsAdmin{}
)
func (mailPartialsAdmin) ID() string { return MailPartialsControllerID }
func (mailPartialsAdmin) ModelName() string { return `System\Models\MailPartial` }
func (mailPartialsAdmin) ConfigDir() string { return "controllers/mailpartials" }
func (mailPartialsAdmin) RequiredPermissions() []string {
return []string{PermissionManageMailLayouts}
}
func (mailPartialsAdmin) NewRecord() any { return &MailPartial{} }
func (mailPartialsAdmin) recordDeletable(any) bool { return false }
func (mailPartialsAdmin) formFooterActions() {}
func asMailPartial(model any) (*MailPartial, error) {
p, ok := model.(*MailPartial)
if !ok || p == nil {
return nil, errors.New("cabana: mail partials: record is not a mail partial")
}
return p, nil
}
// FormRecordTitle names a partial by its code.
func (mailPartialsAdmin) FormRecordTitle(_ context.Context, _ *gorm.DB, record any) (string, error) {
p, err := asMailPartial(record)
if err != nil {
return "", err
}
return p.Code, nil
}
// scopePartials hides the rows of partials this process's catalog does not
// hold.
func (c mailPartialsAdmin) scopePartials(db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
files := c.mail.catalog().Partials()
codes := make([]string, 0, len(files))
for _, f := range files {
codes = append(codes, f.Name)
}
return db.Where(postcard.PartialsTable+".code IN ?", nonEmpty(codes))
}
// ListExtendQuery retries the index sync and lists the catalog's partials.
func (c mailPartialsAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB {
c.mail.ensureSynced(ctx)
return c.scopePartials(db)
}
// FormExtendQuery applies the catalog scope to every record lookup.
func (c mailPartialsAdmin) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
return c.scopePartials(db)
}
// ListRowStates marks customized partials (and outdated ones).
func (mailPartialsAdmin) ListRowStates(_ context.Context, _ *gorm.DB, records []any) ([][]pact.RowState, error) {
out := make([][]pact.RowState, len(records))
for i, record := range records {
p, err := asMailPartial(record)
if err != nil {
return nil, err
}
out[i] = mailRowStates(true, p.IsCustom, p.BaseHash, p.FileHash)
}
return out, nil
}
// FilterOptions serves the status filter.
func (mailPartialsAdmin) FilterOptions(scope string) []pact.Option {
if scope == mailFilterStatus {
return mailStatusOptions()
}
return nil
}
// FormBeforeCreate refuses: partials come from files.
func (mailPartialsAdmin) FormBeforeCreate(context.Context, any) error {
return &ForbiddenError{Message: mailLang + "partial.no_create"}
}
// FormBeforeDelete refuses: a partial's row belongs to its file.
func (mailPartialsAdmin) FormBeforeDelete(context.Context, any) error {
return &ForbiddenError{Message: mailLang + "file_delete"}
}
// FormBeforeUpdate stamps the partial customized against its file.
func (c mailPartialsAdmin) FormBeforeUpdate(_ context.Context, model any) error {
p, err := asMailPartial(model)
if err != nil {
return err
}
file, ok := c.mail.catalog().Partial(p.Code)
if !ok {
return &ForbiddenError{Message: mailLang + "file_missing"}
}
stamp(&p.IsCustom, &p.BaseHash, &p.FileHash, &p.CustomizedAt, file.Hash)
return nil
}
// FormAfterUpdate validates the saved partial through postcard (D-13).
func (c mailPartialsAdmin) FormAfterUpdate(ctx context.Context, model any) error {
p, err := asMailPartial(model)
if err != nil {
return err
}
draft := postcard.Draft{Kind: postcard.KindPartial, Name: p.Code, HTML: p.ContentHTML, Text: p.ContentText}
if de := c.mail.editor.Validate(ctx, draft); de != nil {
return c.mail.draftFailure(ctx, de)
}
return nil
}
// AdminRecordActions is Reset to file version on a customized partial.
func (c mailPartialsAdmin) AdminRecordActions() []pact.AdminRecordAction {
return []pact.AdminRecordAction{c.mail.resetAction(postcard.KindPartial, PermissionManageMailLayouts, mailLang+"partial.reset_confirm",
func(record any) (string, bool, error) {
p, err := asMailPartial(record)
if err != nil {
return "", false, err
}
return p.Code, p.IsCustom, nil
})}
}
// PartialData serves the form's info and file_version partials.
func (c mailPartialsAdmin) PartialData(ctx context.Context, name string, record any) (any, error) {
p, _ := record.(*MailPartial)
if p == nil || p.ID == 0 {
return mailEmptyView(name)
}
file, ok := c.mail.catalog().Partial(p.Code)
switch name {
case mailPartialInfo:
view := mailInfoView{Customized: p.IsCustom, Status: mailStatusKey(p.IsCustom), Outdated: mailOutdated(p.IsCustom, p.BaseHash, p.FileHash)}
if ok {
view.File = c.mail.fileLine(ctx, p.Code, file.PluginID)
view.Usage = partialUsage(p.Code, file.HTML+"\n"+file.Text)
}
return view, nil
case mailPartialFileVersion:
if !ok {
return mailFileVersionView{}, nil
}
return mailFileVersion(p.IsCustom,
postcard.FormatPartial(mailRowName(file.Title, file.Name), file.Text, file.HTML),
postcard.FormatPartial(p.Name, p.ContentText, p.ContentHTML), file.Source), nil
}
return nil, fmt.Errorf("cabana: mail partials: unknown partial %q", name)
}
// The form partials of the mail screens (controllers/mail*/_info.htm and
// _file_version.htm).
const (
mailPartialInfo = "info"
mailPartialFileVersion = "file_version"
)
// mailInfoView is the view model of _info.htm, the lines at the top of a
// mail form: the template's description, the file it comes from (or a
// 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
}
// mailTextPart is a piece of a translated line; Code pieces are shown as
// code.
type mailTextPart struct {
Text string
Code bool
}
// mailFileVersionView is the view model of _file_version.htm: the line diff
// of the override against the file and the file's own text. A custom layout
// has no file.
type mailFileVersionView struct {
Show bool
CustomLayout bool
Customized bool
Identical bool
Diff []mailDiffRow
Content []string
}
// mailDiffRow is one rendered diff line: its class and its prefixed text.
type mailDiffRow struct {
Class string
Text string
}
// mailEmptyView is the view of a partial without a record (a create form).
func mailEmptyView(name string) (any, error) {
switch name {
case mailPartialInfo:
return mailInfoView{}, nil
case mailPartialFileVersion:
return mailFileVersionView{}, nil
}
return nil, fmt.Errorf("cabana: mail: unknown partial %q", name)
}
// diffContext is the number of unchanged lines kept around each change.
const diffContext = 3
// mailFileVersion compares the serialized override (mine) with the
// serialized file (theirs); source is the file's own text.
func mailFileVersion(custom bool, theirs, mine, source string) mailFileVersionView {
view := mailFileVersionView{Show: true, Customized: custom, Content: splitLines(source)}
if !custom {
return view
}
if theirs == mine {
view.Identical = true
return view
}
for _, line := range lineDiff(splitLines(theirs), splitLines(mine), diffContext) {
switch line.Kind {
case diffAdd:
view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__add", Text: "+ " + line.Text})
case diffDel:
view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__del", Text: "− " + line.Text})
case diffGap:
view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__ctx", Text: " …"})
default:
view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__ctx", Text: " " + line.Text})
}
}
return view
}
// splitLines splits text into lines; a trailing newline adds no empty line,
// and an empty line is a space so that it keeps its height.
func splitLines(text string) []string {
text = strings.TrimSuffix(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
if text == "" {
return nil
}
lines := strings.Split(text, "\n")
for i, line := range lines {
if line == "" {
lines[i] = " "
}
}
return lines
}
// fileLine is the translated "File: :path in :plugin" line, with the path
// and the plugin as code pieces.
func (m *mailScreens) fileLine(ctx context.Context, code, plugin string) []mailTextPart {
const pathMark, pluginMark = "\x00path\x00", "\x00plugin\x00"
text := m.message(ctx, mailLang+"info_file", map[string]string{"path": pathMark, "plugin": pluginMark})
path := mailFilePath(code)
var out []mailTextPart
for text != "" {
i := strings.IndexByte(text, 0)
if i < 0 {
out = append(out, mailTextPart{Text: text})
break
}
if i > 0 {
out = append(out, mailTextPart{Text: text[:i]})
}
rest := text[i:]
switch {
case strings.HasPrefix(rest, pathMark):
out = append(out, mailTextPart{Text: path, Code: true})
text = rest[len(pathMark):]
case strings.HasPrefix(rest, pluginMark):
out = append(out, mailTextPart{Text: plugin, Code: true})
text = rest[len(pluginMark):]
default:
out = append(out, mailTextPart{Text: rest[1:]})
text = ""
}
}
return out
}
// mailFilePath is the file of a mail name inside its plugin:
// acme.blog::mail.layouts.blog is views/mail/layouts/blog.htm.
func mailFilePath(code string) string {
_, rest, ok := strings.Cut(code, "::")
if !ok {
return code
}
rest = strings.TrimPrefix(rest, "mail.")
return "views/mail/" + strings.ReplaceAll(rest, ".", "/") + ".htm"
}
// builtinPartialPrefix is the name prefix of postcard's own partials, which
// a call names by their bare name.
const builtinPartialPrefix = "postcard::mail.partials."
// partialArg matches a top-level variable (.name) inside a template action.
var (
partialAction = regexp.MustCompile(`\{\{-?(.*?)-?\}\}`)
partialArg = regexp.MustCompile(`(?:^|[\s(|])\.([A-Za-z_][A-Za-z0-9_]*)`)
)
// partialUsage is the call of a partial in a body or a layout: its bare
// name for a built-in, else its full name, then a key and a value for every
// variable its sections read.
func partialUsage(code, sections string) string {
name := strings.TrimPrefix(code, builtinPartialPrefix)
seen := map[string]bool{}
var keys []string
for _, action := range partialAction.FindAllStringSubmatch(sections, -1) {
for _, arg := range partialArg.FindAllStringSubmatch(action[1], -1) {
if !seen[arg[1]] {
seen[arg[1]] = true
keys = append(keys, arg[1])
}
}
}
sort.Strings(keys)
var b strings.Builder
b.WriteString(`{{ partial "` + name + `"`)
for _, key := range keys {
b.WriteString(` "` + key + `" .` + key)
}
b.WriteString(" }}")
return b.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"`
}
func (MailBrandSetting) TableName() string { return postcard.BrandTable }
func (MailBrandSetting) Fillable() []string {
return []string{
"logo_file_id", "body_bg", "content_bg", "header_color", "footer_color",
"heading_color", "text_color", "link_color", "button_text_color",
"button_primary_bg", "button_positive_bg", "button_negative_bg",
"panel_bg", "table_border_color",
}
}
func (MailBrandSetting) Rules() map[string]string {
return map[string]string{
"logo_file_id": "nullable",
"body_bg": "nullable",
"content_bg": "nullable",
"header_color": "nullable",
"footer_color": "nullable",
"heading_color": "nullable",
"text_color": "nullable",
"link_color": "nullable",
"button_text_color": "nullable",
"button_primary_bg": "nullable",
"button_positive_bg": "nullable",
"button_negative_bg": "nullable",
"panel_bg": "nullable",
"table_border_color": "nullable",
}
}
var brandColourPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`)
// BeforeValidate lower-cases colours, refuses anything but #rrggbb or empty,
// and checks logo_file_id is null or a library image.
func (b *MailBrandSetting) BeforeValidate(tx *gorm.DB) error {
details := map[string]any{}
for _, col := range []struct {
name string
value *string
}{
{"body_bg", &b.BodyBg},
{"content_bg", &b.ContentBg},
{"header_color", &b.HeaderColor},
{"footer_color", &b.FooterColor},
{"heading_color", &b.HeadingColor},
{"text_color", &b.TextColor},
{"link_color", &b.LinkColor},
{"button_text_color", &b.ButtonTextColor},
{"button_primary_bg", &b.ButtonPrimaryBg},
{"button_positive_bg", &b.ButtonPositiveBg},
{"button_negative_bg", &b.ButtonNegativeBg},
{"panel_bg", &b.PanelBg},
{"table_border_color", &b.TableBorderColor},
} {
colour := strings.ToLower(strings.TrimSpace(*col.value))
*col.value = colour
if colour == "" {
continue
}
if !brandColourPattern.MatchString(colour) {
details[col.name] = []string{"backend::lang.colorpicker.invalid"}
}
}
if b.LogoFileID != nil {
var n int64
if err := tx.Session(&gorm.Session{NewDB: true}).
Table("system_files").
Where("id = ? AND attachment_type = ? AND field = ?", *b.LogoFileID, mailImageLibraryMorph, "images").
Count(&n).Error; err != nil {
return err
}
if n == 0 {
details["logo_file_id"] = []string{"backend::lang.mailimage.missing"}
}
}
if len(details) > 0 {
return &ValidationError{Details: details}
}
return nil
}
// mailImageLibraryMorph is the attachment_type of the mail image library host.
const mailImageLibraryMorph = `System\Models\MailImageLibrary`
// MailImageLibrary is the one-row host of the mail image library's attachMany
// images relation.
type MailImageLibrary struct {
ID uint `gorm:"column:id;primaryKey"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
func (MailImageLibrary) TableName() string { return postcard.ImageLibraryTable }
func (MailImageLibrary) MorphName() string { return mailImageLibraryMorph }
func (MailImageLibrary) AttachRelations() []attach.Relation {
return []attach.Relation{{Name: "images", Many: true, Public: true}}
}
func (MailImageLibrary) Fillable() []string { return nil }
func (MailImageLibrary) Rules() map[string]string { return nil }
// mailImagesAdmin is the Mail images singleton screen.
type mailImagesAdmin struct {
mail *mailScreens
}
var (
_ pact.AdminController = mailImagesAdmin{}
_ pact.AdminPermissioned = mailImagesAdmin{}
_ pact.AdminSingleton = mailImagesAdmin{}
)
func (mailImagesAdmin) ID() string { return MailImagesControllerID }
func (mailImagesAdmin) ModelName() string { return `System\Models\MailImageLibrary` }
func (mailImagesAdmin) ConfigDir() string { return "controllers/mailimages" }
func (mailImagesAdmin) RequiredPermissions() []string {
return []string{PermissionManageMailLayouts}
}
func (mailImagesAdmin) NewRecord() any { return &MailImageLibrary{} }
// SingletonRecord returns the library host row, creating it when absent.
func (mailImagesAdmin) SingletonRecord(ctx context.Context, db *gorm.DB) (any, error) {
var row MailImageLibrary
err := db.WithContext(ctx).Order("id").Limit(1).Take(&row).Error
if err == nil {
return &row, nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
row = MailImageLibrary{}
if err := db.WithContext(ctx).Create(&row).Error; err != nil {
return nil, err
}
return &row, nil
}
// injectLayoutCreateDefaults copies postcard's default layout into the create
// form defaults of the layouts controller, so the YAML carries no copy of it.
func injectLayoutCreateDefaults(reg *Registry, editor *postcard.Editor) {
if reg == nil || editor == nil {
return
}
cc, ok := reg.Get(MailLayoutsControllerID)
if !ok || cc == nil || cc.Form == nil {
return
}
file, ok := editor.Catalog().Layout(mailDefaultLayout)
if !ok {
return
}
set := map[string]string{
"content_html": file.HTML,
"content_text": file.Text,
"content_css": "",
}
for i := range cc.Form.Fields {
if raw, ok := set[cc.Form.Fields[i].Name]; ok {
encoded, err := json.Marshal(raw)
if err != nil {
continue
}
cc.Form.Fields[i].Default = &jsonScalar{raw: encoded}
}
}
}