Files
summercms/modules/postcard/store.go
Jakub Zych 7e5d2c74af feat(postcard): database overrides for mail templates with file fallback
- postcard owns the system_mail_* tables (postcard.Migrations), run by lagoon
  as the framework set summercms.postcard after system_files
- Send asks an OverrideSource once per message; NewDBSource reads the
  customized template row through the *gorm.DB published on the app
- a failed lookup, missing tables or an override that does not render or
  fails the safety checks sends the file version and is logged
- the caller's Message.Subject still wins; Mailer, Message, NewMailer,
  Catalog.Register and BootPlugin keep their signatures

Plan 35-01, task 2 (tracer).
2026-11-13 10:26:10 +01:00

222 lines
7.1 KiB
Go

package postcard
import (
"context"
"fmt"
"git.golem15.com/golem15/summercms/modules/backpack"
"github.com/go-gormigrate/gormigrate/v2"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// The mail tables postcard owns. Admin code builds its models over these
// names; postcard itself reads them with plain SQL.
const (
// TemplatesTable holds one row per mail template.
TemplatesTable = "system_mail_templates"
// LayoutsTable holds one row per mail layout, file-backed or database-only.
LayoutsTable = "system_mail_layouts"
// PartialsTable holds one row per mail partial.
PartialsTable = "system_mail_partials"
// BrandTable holds the mail branding settings (a single row, id 1).
BrandTable = "system_mail_brand_settings"
// ImageLibraryTable holds the one row the mail image library attaches
// its files to.
ImageLibraryTable = "system_mail_image_library"
)
// Migrations creates the mail tables. lagoon runs it as a framework set
// under the summercms.postcard history, after the system_files set.
//
// A row is an override only while is_custom is true. file_hash is the hash
// of the current file and base_hash the hash of the file the override was
// written against, so a customized row is outdated when the two differ.
var Migrations = []*gormigrate.Migration{
{
ID: "202611060001_create_system_mail_tables",
Migrate: func(tx *gorm.DB) error {
stmts := []string{
`CREATE TABLE ` + LayoutsTable + ` (
id SERIAL PRIMARY KEY,
code TEXT NOT NULL UNIQUE,
source TEXT,
name TEXT NOT NULL,
content_html TEXT NOT NULL DEFAULT '',
content_text TEXT NOT NULL DEFAULT '',
content_css TEXT NOT NULL DEFAULT '',
is_custom BOOLEAN NOT NULL DEFAULT FALSE,
file_hash TEXT,
base_hash TEXT,
customized_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`CREATE TABLE ` + TemplatesTable + ` (
id SERIAL PRIMARY KEY,
code TEXT NOT NULL UNIQUE,
source TEXT NOT NULL,
locale TEXT,
description TEXT NOT NULL DEFAULT '',
subject TEXT NOT NULL DEFAULT '',
body TEXT NOT NULL DEFAULT '',
layout_id INTEGER REFERENCES ` + LayoutsTable + `(id) ON DELETE RESTRICT,
is_custom BOOLEAN NOT NULL DEFAULT FALSE,
file_hash TEXT,
base_hash TEXT,
customized_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`CREATE INDEX ` + TemplatesTable + `_layout_id_index ON ` + TemplatesTable + ` (layout_id)`,
`CREATE TABLE ` + PartialsTable + ` (
id SERIAL PRIMARY KEY,
code TEXT NOT NULL UNIQUE,
source TEXT NOT NULL,
name TEXT NOT NULL DEFAULT '',
content_html TEXT NOT NULL DEFAULT '',
content_text TEXT NOT NULL DEFAULT '',
is_custom BOOLEAN NOT NULL DEFAULT FALSE,
file_hash TEXT,
base_hash TEXT,
customized_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`CREATE TABLE ` + BrandTable + ` (
id INTEGER PRIMARY KEY,
logo_file_id INTEGER,
body_bg TEXT NOT NULL DEFAULT '',
content_bg TEXT NOT NULL DEFAULT '',
header_color TEXT NOT NULL DEFAULT '',
footer_color TEXT NOT NULL DEFAULT '',
heading_color TEXT NOT NULL DEFAULT '',
text_color TEXT NOT NULL DEFAULT '',
link_color TEXT NOT NULL DEFAULT '',
button_text_color TEXT NOT NULL DEFAULT '',
button_primary_bg TEXT NOT NULL DEFAULT '',
button_positive_bg TEXT NOT NULL DEFAULT '',
button_negative_bg TEXT NOT NULL DEFAULT '',
panel_bg TEXT NOT NULL DEFAULT '',
table_border_color TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`CREATE TABLE ` + ImageLibraryTable + ` (
id SERIAL PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
}
for _, stmt := range stmts {
if err := tx.Exec(stmt).Error; err != nil {
return err
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
// Templates first: they reference layouts.
for _, table := range []string{ImageLibraryTable, BrandTable, PartialsTable, TemplatesTable, LayoutsTable} {
if err := tx.Exec("DROP TABLE IF EXISTS " + table).Error; err != nil {
return err
}
}
return nil
},
},
}
// OverrideSource supplies the database overrides one render needs.
type OverrideSource interface {
// MailOverrides returns the overrides for one send of template. An
// empty template asks for everything except a template override. A nil
// or empty field means the file version is used.
MailOverrides(ctx context.Context, template string) (Overrides, error)
}
// Overrides is what an OverrideSource returns for one render.
type Overrides struct {
// Template is the customized subject, body and layout of the template
// being sent, or nil.
Template *TemplateOverride
// Layouts holds layout content by layout code.
Layouts map[string]LayoutOverride
// Partials holds partial content by partial name.
Partials map[string]PartialOverride
}
// empty reports whether o changes nothing about a render.
func (o Overrides) empty() bool {
return o.Template == nil && len(o.Layouts) == 0 && len(o.Partials) == 0
}
// TemplateOverride replaces a template's subject, body and layout.
type TemplateOverride struct {
Subject string
Body string
// Layout is a layout code: the full name of a file layout or the code
// of a database-only one. Empty keeps the file's layout.
Layout string
}
// LayoutOverride replaces a layout's wrappers and adds its CSS.
type LayoutOverride struct {
Name string
HTML string
Text string
CSS string
}
// PartialOverride replaces a partial's HTML and text sections.
type PartialOverride struct {
HTML string
Text string
}
// NewDBSource returns the OverrideSource that reads postcard's tables. It
// looks the *gorm.DB up on app at every call and never caches a row, so an
// edit is effective on the next send in every process that shares the
// database. With no database published it returns no overrides and no error.
func NewDBSource(app *backpack.App) OverrideSource {
return &dbSource{app: app}
}
type dbSource struct {
app *backpack.App
}
// MailOverrides implements OverrideSource. name is the template's full name.
func (s *dbSource) MailOverrides(ctx context.Context, name string) (Overrides, error) {
var out Overrides
if s == nil || s.app == nil {
return out, nil
}
gdb, ok := s.app.Lookup[*gorm.DB]()
if !ok || gdb == nil {
return out, nil
}
// The mailer reports a failed lookup itself, rate-limited; GORM's own
// error line per send would repeat it for every message.
db := gdb.Session(&gorm.Session{Logger: gdb.Logger.LogMode(logger.Silent)}).WithContext(ctx)
if name == "" {
return out, nil
}
var rows []struct {
Subject string
Body string
Layout string
}
err := db.Raw(`SELECT t.subject, t.body, COALESCE(l.code, '') AS layout
FROM `+TemplatesTable+` t
LEFT JOIN `+LayoutsTable+` l ON l.id = t.layout_id
WHERE t.code = ? AND t.is_custom`, name).Scan(&rows).Error
if err != nil {
return Overrides{}, fmt.Errorf("postcard: mail overrides: %w", err)
}
if len(rows) > 0 {
out.Template = &TemplateOverride{Subject: rows[0].Subject, Body: rows[0].Body, Layout: rows[0].Layout}
}
return out, nil
}