package cabana import ( "context" "errors" "fmt" "strings" "sync" "sync/atomic" "time" "git.golem15.com/golem15/summercms/modules/backpack" "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" ) // 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}} } // 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, }, } } // 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 } // 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{} ) 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"} } // 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 } // mailFileRef names a mail file: its path inside the plugin and the plugin. func mailFileRef(code string) (path, plugin string) { plugin, rest, ok := strings.Cut(code, "::") if !ok { return code, "" } rest = strings.TrimPrefix(rest, "mail.") return fmt.Sprintf("views/mail/%s.htm", strings.ReplaceAll(rest, ".", "/")), plugin }