feat(cabana): mail templates screen over postcard overrides
- Settings -> Mail -> Mail templates in the internal pseudo-plugin when postcard's Mailer is published; system.manage_mail_templates and system.manage_mail_layouts registered with no role grants - MailTemplate/MailLayout models, catalog-scoped list and form, layout relation over file and custom layouts, no create or delete - save stamps is_custom, base_hash and customized_at and validates the override through postcard.Editor inside the save transaction - serve-start postcard.SyncIndex through lagoon.OnDatabase, retried on the first mail list request - copy en/pl, README and docs; TestMailScreensSmoke/templates Plan 35-02, task 1
This commit is contained in:
@@ -59,6 +59,7 @@ Use cases:
|
||||
- Form fields on another plugin's controller: a `pact.AdminActionExtension` with `Form` set to a `pact.AdminFormExtension` places fields and tabs in any admin controller's form by its ID. Its fields document is the `fields.yaml` format plus `before:`/`after:` anchors, `zone:` (only the tab zone for now) and a `tabs:` list, compiled at boot with every `fields.yaml` check; extensions apply in plugin activation order and the form is sent in the compiled order, so the SPA adds no ordering. `Hide` removes owner fields, `Permissions` and `Visible` decide per request who sees the fields (schema, show and save alike), widget fields run the extension's `Actions` and partial fields render from its `Dir` through `PartialData`. Extension values leave the save body before any owner path reads them; `Save` runs in the record's save transaction after the owner row is written (`pact.AdminFormErrors` answers 422, its notices join `meta.notices`) and `Load` serves the values on show. A form no extension lays out compiles unchanged. Unknown anchors, duplicate names, anchor cycles, anchors outside `Requires()`, other zones, `fileupload` fields and clashing widget action or partial names stop the boot naming the plugin, the controller and the name.
|
||||
- Plugins screen: Settings → System → Plugins opens the admin SPA route `/system/plugins` (the settings entry carries `path` instead of a controller) for administrators holding `cabana.PermissionViewPlugins` (`backend.view_plugins`, granted to no role in code; superusers always pass). GET `/plugins` lists the plugins the application was built with from the `party.Installed` metadata `summer build` bakes (name, description, version, source, module and package), or only the IDs of `party.Activated` for an application built before that metadata existed, with the framework version and the state of the plugin registry (`plugins.registry_url`, read through `kiosk.RegistryURL`). With the registry configured, cabana (never the SPA) looks up each versioned plugin's releases through `kiosk.Client` and marks an update when `kiosk.NewestCompatible` finds a release newer than the installed version by `kiosk.Newer` (a `git describe` string or a pseudo-version compares by the tag it builds on), with the `summer plugin:update <id>` command; GET `/plugins/marketplace` searches the registry and adds installed and compatibility markers (compatible when `summer plugin:install` can install some release with the built framework, looking up the releases of a plugin whose newest one needs a newer framework; always compatible when the built framework version is not a release) and the `summer plugin:install <id>` command. Registry calls have a 4 second timeout, at most four run at once, and answers are cached in process (searches 5 minutes, at most 256 distinct searches with expired and then the oldest dropped first, releases 15 minutes, failures 1 minute); a failing registry gives `status` unavailable and never a non-200 answer.
|
||||
- Administrators screen: when some plugin registers admin controllers, `cabana.Activate` also compiles the admin's own screens, an internal plugin with ID `summercms.cabana`. Settings → System → Administrators (controller `cabana.AdministratorsControllerID`, permission `cabana.PermissionManageUsers`) lists backend administrators with their role and last sign-in, opens a preview of each, where record actions (the admin's own and contributed ones) are offered, and creates and edits administrators: login, email, names, a password (hashed at `admin.password.bcrypt_cost`, at least 4 characters and at most 72 bytes), the role and per-administrator permission overrides. The server enforces the privilege rules in the save transaction: only a superuser sees superusers or sends the superuser switch, an administrator can neither grant permissions or roles above their own grants nor change an administrator who holds more than they do, their own role, superuser flag, permissions and password are not changed here, and the last active superuser cannot be demoted. A password set for another administrator ends their sessions (personal API tokens stay valid, as with `admin:reset-password`). Administrators are activated, deactivated and restored by record and bulk actions and deleted softly through `deleted_at` (never hard-deleted); the list shows deleted and deactivated rows with their row states and filters deleted ones, and the preview shows a status hint. Deactivating or deleting an administrator ends their sessions and stops their personal API tokens; the last active superuser cannot be demoted, deactivated or deleted on any of these paths (a transaction-scoped advisory lock serializes the check). The permission codes `cabana.PermissionManageUsers` and `cabana.PermissionManageRoles` are registered with no role grant, so after an upgrade only superusers see the screens until an administrator grants them. An application without admin controllers still activates no admin.
|
||||
- Mail screens (Settings → Mail): when the application publishes postcard's Mailer (`postcard.EditorFrom` succeeds; `party.Activate` runs `postcard.Activate`), the internal plugin also registers the mail screens over postcard's tables, the permission codes `cabana.PermissionManageMailTemplates` (`system.manage_mail_templates`) and `cabana.PermissionManageMailLayouts` (`system.manage_mail_layouts`), both granted to no role in code, and their Settings entries in category `backend::lang.settings.category_mail`. Mail templates (controller `cabana.MailTemplatesControllerID`, model `cabana.MailTemplate`) lists the templates of this process's catalog (rows of uninstalled plugins are hidden) with code, subject, description, locale (Default for a name without a locale suffix) and layout, and edits the subject, the Markdown body and the layout (a `relation` over `cabana.MailLayout` rows: every database-only layout and the catalog's file layouts). There is no create and no delete. A save marks the row customized, stamps `base_hash` with the file's current hash and `customized_at`, and validates the result through `postcard.Editor.Validate` inside the save's transaction; a `postcard.DraftError` is a 422 on its field with `backend::lang.mail.invalid_<rule>` (`:message`, `:name`). The index rows are written by `postcard.SyncIndex` through `lagoon.OnDatabase` at activation; a failed sync is logged and retried on the first mail list request of the process.
|
||||
- Danger record actions: `pact.AdminRecordAction.Danger` is served as `danger` on the record response's `cabana.RecordAction` (absent when false, so existing payloads are unchanged); the admin's confirm dialog then uses its danger variant.
|
||||
- Prompted record actions: a `pact.AdminRecordAction` with a `Prompt` (`pact.AdminActionPrompt`) asks the administrator for one text value in its confirm dialog. The record response serves it as `prompt` on the action's `cabana.RecordAction` (absent for every other action, so existing payloads are unchanged), and the action route accepts the body key `payload`, a JSON string, only for such an action: trimmed, not empty and at most `max_length` runes (422 on `payload` with `backend::lang.form.action_prompt_required` or `action_prompt_too_long`, `backend::lang.form.action_prompt_invalid` for another JSON type), then handed to `Run` as `pact.AdminRecordActionInput.Value`. Every other record action keeps refusing `record_id`, `values` and `payload`. A prompt without a label fails boot, owned or contributed.
|
||||
- My account contributions: a plugin implementing `pact.HasAccountContributions` adds sections (`pact.AccountContribution`) to the administrator's own account page, each with a status line and buttons (`pact.AccountAction`). GET `/account/contributions` lists them for the signed-in administrator and POST `/account/contributions/{name}/actions/{action}` runs one for that administrator only, behind the interactive-only guard, the action's permissions and its `Applies` rule, inside a transaction; the answer may carry a URL the admin opens in a new tab. That URL is kept only when it is an absolute `http`/`https` URL with a host or a same-origin path (one leading `/`); anything else, `javascript:` and `data:` included, is dropped and logged without the URL. A section whose `Status` fails is listed with an empty status and `error: true`, and an action whose `Applies` fails is left out and marks its section `error: true` as well; both are logged and the other sections are answered as usual. A status is translated only when it is a phrase key. Names are generic: cabana never names the contributing plugin. The existing `/account*` and `/auth/me` payloads are unchanged. A non-identifier or duplicate section name, an empty label, a duplicate or non-identifier action name, a nil `Run` or an empty action label stops the boot.
|
||||
@@ -304,6 +305,9 @@ func (p *Plugin) AdminFS() fs.FS { return adminFS }
|
||||
| `cabana.SettingsEntry.Path` | The SPA route a settings entry of the admin's own opens (`/system/plugins`); empty, and omitted from JSON, for plugin entries. |
|
||||
| `cabana.MarketplaceResponse` / `cabana.MarketplacePlugin` / `cabana.MarketplaceMeta` | The GET `/plugins/marketplace` answer: the registry's search with installed and compatibility markers and install commands, plus the registry state, total and categories. |
|
||||
| `cabana.AdminPluginsInstalled` / `cabana.AdminPluginsMarketplace` | Swag annotations of GET `/plugins` and GET `/plugins/marketplace`. |
|
||||
| `cabana.PermissionManageMailTemplates` / `cabana.PermissionManageMailLayouts` | The permission codes of the mail screens (`system.manage_mail_templates`: Mail templates, template preview and test send; `system.manage_mail_layouts`: layouts, partials, branding and the image library), granted to no role in code and registered only with the mail screens. |
|
||||
| `cabana.MailTemplatesControllerID` / `cabana.MailLayoutsControllerID` / `cabana.MailPartialsControllerID` / `cabana.MailImagesControllerID` | The admin controller IDs of the mail screens (`summercms.cabana.mailtemplates`, `summercms.cabana.maillayouts`, `summercms.cabana.mailpartials`, `summercms.cabana.mailimages`). |
|
||||
| `cabana.MailTemplate` / `cabana.MailLayout` | GORM models of postcard's `system_mail_templates` and `system_mail_layouts` rows, as the mail screens read and write them. |
|
||||
| `cabana.AdministratorsControllerID` / `cabana.RolesControllerID` | The admin controller IDs of the Administrators (`summercms.cabana.users`) and Roles (`summercms.cabana.roles`) screens; a plugin names the first in `pact.AdminActionExtension.Controller` to add record actions to it. |
|
||||
| `cabana.BackendUser.Fillable` / `cabana.BackendUser.Rules` | The columns the Administrators screen fills from a form (login, email, first and last name) and their base rules. |
|
||||
| `cabana.BackendUserRole.Fillable` / `cabana.BackendUserRole.Rules` | The columns a role form fills (name, code, description) and their base rules. |
|
||||
@@ -404,7 +408,7 @@ TOKEN=$(./bin/acme admin:token:create admin@example.com --name agent --scope blo
|
||||
|
||||
## Dependencies
|
||||
|
||||
- SummerCMS modules: [backpack](../backpack/README.md), [boardwalk](../boardwalk/README.md), [bonfire](../bonfire/README.md), [bouncer](../bouncer/README.md), [diary](../diary/README.md) (component logger `cabana`; the `admin.auth` audit record keeps its message), [kiosk](../kiosk/README.md) (the plugin registry URL and client of the Plugins screen), [lagoon](../lagoon/README.md), [pact](../pact/README.md), [party](../party/README.md), [phrasebook](../phrasebook/README.md), [seaglass](../seaglass/README.md) (sanitizes `richeditor` values), [towel](../towel/README.md).
|
||||
- SummerCMS modules: [backpack](../backpack/README.md), [boardwalk](../boardwalk/README.md), [bonfire](../bonfire/README.md), [bouncer](../bouncer/README.md), [diary](../diary/README.md) (component logger `cabana`; the `admin.auth` audit record keeps its message), [kiosk](../kiosk/README.md) (the plugin registry URL and client of the Plugins screen), [lagoon](../lagoon/README.md), [pact](../pact/README.md), [party](../party/README.md), [phrasebook](../phrasebook/README.md), [postcard](../postcard/README.md) (the mail screens edit its tables through its Editor), [seaglass](../seaglass/README.md) (sanitizes `richeditor` values), [towel](../towel/README.md).
|
||||
- Third-party: `gorm.io/gorm` (with `gorm.io/gorm/clause`), `github.com/goccy/go-yaml` (with its `ast` package), `golang.org/x/net/html` (with its `atom` package; parses rendered partials for the allowlist walk).
|
||||
- Standard library: `bytes`, `context`, `crypto/sha256`, `database/sql`, `encoding/hex`, `encoding/json`, `errors`, `fmt`, `html/template`, `io`, `io/fs`, `log/slog`, `math`, `net`, `net/http`, `net/url`, `path`, `reflect`, `regexp`, `slices`, `sort`, `strconv`, `strings`, `sync`, `time`, `unicode/utf8`.
|
||||
- Tests additionally use `github.com/testcontainers/testcontainers-go` and its `modules/postgres` package, and [signpost](../signpost/README.md) for the dependent dropdown fixture.
|
||||
@@ -432,3 +436,5 @@ The localization of refusals is covered by Docker-free unit tests in `localize_e
|
||||
The Roles form's holders list is covered by the Docker-free TestRolesHoldersPartial in `backend_screens_test.go` (the users partial field on the update form's Administrators tab, the view model guard, links, state lines, escaped holder strings, the empty line and the note) and the Postgres test TestRolesHolders in `roles_postgres_test.go` (superusers hidden from non-superuser editors, D-03; deleted and deactivated holders; preview links only with `cabana.PermissionManageUsers`; the empty role; the 100-row cap with its note; 403 without `cabana.PermissionManageRoles`).
|
||||
|
||||
The Plugins screen is covered by the Docker-free TestPluginsScreenSmoke in `plugins_smoke_test.go`: the installed list from `party.Installed` and the `party.Activated` fallback, 401 and 403 without `cabana.PermissionViewPlugins`, the settings entry with its `path` only for allowed administrators, and against a fake registry the update rule (a git describe version compares by its base tag), unlisted and local plugins, a failing or slow registry, a disabled one (no request), the marketplace search with its validation and the cache windows.
|
||||
|
||||
The mail screens are covered by the Postgres test TestMailScreensSmoke in `mail_screens_smoke_test.go`, on a fixture plugin with two templates, a layout and a partial: the templates list and form, an override that the next send uses, a refused unsafe body that leaves the row unchanged, the permission split and the Settings → Mail tiles per permission.
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
||||
)
|
||||
|
||||
// The admin's own screens for backend administrators and roles (Settings →
|
||||
@@ -27,6 +28,31 @@ const (
|
||||
RolesControllerID = "summercms.cabana.roles"
|
||||
)
|
||||
|
||||
// The mail screens (Settings → Mail), registered by the same pseudo-plugin
|
||||
// whenever the application publishes postcard's Mailer.
|
||||
const (
|
||||
// PermissionManageMailTemplates opens the Mail templates screen, the
|
||||
// template preview and the template test send. No role is granted it in
|
||||
// code.
|
||||
PermissionManageMailTemplates = "system.manage_mail_templates"
|
||||
// PermissionManageMailLayouts opens the Mail layouts, Mail partials, Mail
|
||||
// branding and Mail images screens, because they change every message.
|
||||
// No role is granted it in code.
|
||||
PermissionManageMailLayouts = "system.manage_mail_layouts"
|
||||
// MailTemplatesControllerID is the admin controller ID of the Mail
|
||||
// templates screen.
|
||||
MailTemplatesControllerID = "summercms.cabana.mailtemplates"
|
||||
// MailLayoutsControllerID is the admin controller ID of the Mail layouts
|
||||
// screen.
|
||||
MailLayoutsControllerID = "summercms.cabana.maillayouts"
|
||||
// MailPartialsControllerID is the admin controller ID of the Mail
|
||||
// partials screen.
|
||||
MailPartialsControllerID = "summercms.cabana.mailpartials"
|
||||
// MailImagesControllerID is the admin controller ID of the Mail images
|
||||
// screen, the singleton form of the mail image library.
|
||||
MailImagesControllerID = "summercms.cabana.mailimages"
|
||||
)
|
||||
|
||||
// backendScreensPluginID is the pseudo-plugin's ID. It is also the
|
||||
// migration history ID of the backend tables (lagoon), which is untouched:
|
||||
// the pseudo-plugin declares no migrations.
|
||||
@@ -48,6 +74,10 @@ var backendScreensFS embed.FS
|
||||
type backendScreens struct {
|
||||
app *backpack.App
|
||||
reg *Registry
|
||||
// mail holds the mail screens' state; nil when the application has no
|
||||
// postcard Mailer, and the mail screens, permissions and settings
|
||||
// entries are then not registered.
|
||||
mail *mailScreens
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -74,24 +104,41 @@ func (*backendScreens) AdminFS() fs.FS {
|
||||
}
|
||||
|
||||
func (s *backendScreens) AdminControllers() []pact.AdminController {
|
||||
return []pact.AdminController{usersAdmin{screens: s}, rolesAdmin{screens: s}}
|
||||
out := []pact.AdminController{usersAdmin{screens: s}, rolesAdmin{screens: s}}
|
||||
if s.mail != nil {
|
||||
out = append(out, s.mail.controllers()...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Permissions declares the screen permissions with no role grants (D-04):
|
||||
// an upgrade gives no existing role access to the screens. The Plugins
|
||||
// screen (PermissionViewPlugins) is served by cabana itself, not by an
|
||||
// admin controller.
|
||||
func (*backendScreens) Permissions() []pact.Permission {
|
||||
return []pact.Permission{
|
||||
// admin controller. The two mail codes are declared only with the mail
|
||||
// screens, and with no role grants either.
|
||||
func (s *backendScreens) Permissions() []pact.Permission {
|
||||
out := []pact.Permission{
|
||||
{Code: PermissionManageUsers, Tab: "backend::lang.permissions.tab_system", Label: "backend::lang.permissions.manage_users"},
|
||||
{Code: PermissionManageRoles, Tab: "backend::lang.permissions.tab_system", Label: "backend::lang.permissions.manage_roles"},
|
||||
{Code: PermissionViewPlugins, Tab: "backend::lang.permissions.tab_system", Label: "backend::lang.permissions.view_plugins"},
|
||||
}
|
||||
if s.mail != nil {
|
||||
out = append(out, mailPermissions()...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Settings links the screens from Settings → System; there is no navigation
|
||||
// entry.
|
||||
func (*backendScreens) Settings() []pact.SettingsItem {
|
||||
// Settings links the screens from Settings → System, and the mail screens
|
||||
// from Settings → Mail; there is no navigation entry.
|
||||
func (s *backendScreens) Settings() []pact.SettingsItem {
|
||||
out := s.systemSettings()
|
||||
if s.mail != nil {
|
||||
out = append(out, s.mail.settings()...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (*backendScreens) systemSettings() []pact.SettingsItem {
|
||||
return []pact.SettingsItem{
|
||||
{
|
||||
Code: "administrators",
|
||||
@@ -133,9 +180,14 @@ func (s *backendScreens) registry() *Registry {
|
||||
}
|
||||
|
||||
// withBackendScreens returns a new plugin slice with the pseudo-plugin
|
||||
// appended, and the pseudo-plugin. plugins itself is never modified.
|
||||
// appended, and the pseudo-plugin. plugins itself is never modified. The
|
||||
// mail screens join it when app publishes postcard's Mailer (party.Activate
|
||||
// runs postcard.Activate before any plugin boots).
|
||||
func withBackendScreens(app *backpack.App, plugins []party.Plugin) ([]party.Plugin, *backendScreens) {
|
||||
screens := &backendScreens{app: app}
|
||||
if editor, ok := postcard.EditorFrom(app); ok {
|
||||
screens.mail = &mailScreens{screens: screens, editor: editor}
|
||||
}
|
||||
out := make([]party.Plugin, 0, len(plugins)+1)
|
||||
out = append(out, plugins...)
|
||||
return append(out, screens), screens
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
name: backend::lang.mail.template.name
|
||||
form: ~/plugins/summercms/cabana/models/mailtemplate/fields.yaml
|
||||
modelClass: System\Models\MailTemplate
|
||||
defaultRedirect: summercms/cabana/mailtemplates
|
||||
|
||||
update:
|
||||
redirect: summercms/cabana/mailtemplates/update/:id
|
||||
redirectClose: summercms/cabana/mailtemplates
|
||||
|
||||
messages:
|
||||
update: backend::lang.mail.template.name
|
||||
saved: backend::lang.messages.form.saved
|
||||
@@ -0,0 +1,18 @@
|
||||
list: ~/plugins/summercms/cabana/models/mailtemplate/columns.yaml
|
||||
modelClass: System\Models\MailTemplate
|
||||
title: backend::lang.mail.template.list_title
|
||||
recordUrl: summercms/cabana/mailtemplates/update/:id
|
||||
noRecordsMessage: backend::lang.mail.template.list_empty
|
||||
recordsPerPage: 20
|
||||
showCheckboxes: false
|
||||
defaultSort:
|
||||
column: code
|
||||
direction: asc
|
||||
|
||||
toolbar:
|
||||
buttons: []
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
|
||||
messages:
|
||||
empty: backend::lang.mail.template.list_empty
|
||||
@@ -0,0 +1,23 @@
|
||||
columns:
|
||||
code:
|
||||
label: backend::lang.mail.code
|
||||
searchable: true
|
||||
sortable: true
|
||||
subject:
|
||||
label: backend::lang.mail.template.subject
|
||||
searchable: true
|
||||
description:
|
||||
label: backend::lang.mail.template.description
|
||||
searchable: true
|
||||
locale:
|
||||
label: backend::lang.mail.template.locale
|
||||
sortable: true
|
||||
layout:
|
||||
label: backend::lang.mail.template.layout
|
||||
relation: layout
|
||||
select: name
|
||||
customized_at:
|
||||
label: backend::lang.mail.customized_at
|
||||
type: datetime
|
||||
invisible: true
|
||||
sortable: true
|
||||
@@ -0,0 +1,23 @@
|
||||
fields:
|
||||
subject:
|
||||
label: backend::lang.mail.template.subject
|
||||
comment: backend::lang.mail.template.subject_comment
|
||||
type: text
|
||||
span: left
|
||||
required: true
|
||||
tab: backend::lang.mail.template.tab_template
|
||||
layout:
|
||||
label: backend::lang.mail.template.layout
|
||||
comment: backend::lang.mail.template.layout_comment
|
||||
type: relation
|
||||
nameFrom: name
|
||||
span: right
|
||||
required: true
|
||||
tab: backend::lang.mail.template.tab_template
|
||||
body:
|
||||
label: backend::lang.mail.template.body
|
||||
comment: backend::lang.mail.template.body_comment
|
||||
type: markdown
|
||||
size: giant
|
||||
span: full
|
||||
tab: backend::lang.mail.template.tab_template
|
||||
@@ -2,6 +2,7 @@ package cabana
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
"git.golem15.com/golem15/summercms/modules/boardwalk"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
@@ -162,6 +164,17 @@ func Activate(app *backpack.App, plugins []party.Plugin) (*Routes, error) {
|
||||
if app == nil {
|
||||
return nil, errors.New("cabana: app is nil")
|
||||
}
|
||||
// D-23: every file template, layout and partial gets its index row as
|
||||
// soon as the database is there. The hook never fails the boot; until a
|
||||
// sync succeeded, the first mail list request retries it.
|
||||
if mail := screens.mail; mail != nil {
|
||||
if err := lagoon.OnDatabase(app, func(_ *sql.DB, gdb *gorm.DB) error {
|
||||
mail.syncOnDatabase(gdb)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if tr, ok := app.Lookup[*phrasebook.Translator](); ok && tr != nil {
|
||||
if err := validateMessageKeys(reg, tr); err != nil {
|
||||
return nil, err
|
||||
|
||||
475
modules/cabana/mail_admin.go
Normal file
475
modules/cabana/mail_admin.go
Normal file
@@ -0,0 +1,475 @@
|
||||
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
|
||||
}
|
||||
328
modules/cabana/mail_screens_smoke_test.go
Normal file
328
modules/cabana/mail_screens_smoke_test.go
Normal file
@@ -0,0 +1,328 @@
|
||||
package cabana_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
)
|
||||
|
||||
// The mail screens' paths under the admin API.
|
||||
const (
|
||||
mailTemplatesPath = "/summercms/cabana/mailtemplates"
|
||||
mailLayoutsPath = "/summercms/cabana/maillayouts"
|
||||
mailPartialsPath = "/summercms/cabana/mailpartials"
|
||||
)
|
||||
|
||||
// The fixture plugin's mail.
|
||||
const (
|
||||
blogWelcome = "acme.blog::mail.welcome"
|
||||
blogWelcomeEn = "acme.blog::mail.welcome-en"
|
||||
blogLayout = "acme.blog::mail.layouts.blog"
|
||||
blogCard = "acme.blog::mail.partials.card"
|
||||
)
|
||||
|
||||
// mailBlogPlugin ships two templates (a base and its -en variant), one
|
||||
// layout aliased blog and one partial. files is mutable so a test can change
|
||||
// a file and sync again.
|
||||
type mailBlogPlugin struct{ files fstest.MapFS }
|
||||
|
||||
func (mailBlogPlugin) ID() string { return "acme.blog" }
|
||||
func (mailBlogPlugin) Requires() []string { return nil }
|
||||
func (mailBlogPlugin) Register(*backpack.App) error { return nil }
|
||||
func (mailBlogPlugin) Boot(*backpack.App) error { return nil }
|
||||
func (p mailBlogPlugin) MailTemplatesFS() fs.FS { return p.files }
|
||||
func (mailBlogPlugin) MailTemplates() []string { return []string{blogWelcome, blogWelcomeEn} }
|
||||
func (mailBlogPlugin) MailLayouts() map[string]string {
|
||||
return map[string]string{"blog": blogLayout}
|
||||
}
|
||||
func (p mailBlogPlugin) MailPartialsFS() fs.FS { return p.files }
|
||||
func (mailBlogPlugin) MailPartials() []string { return []string{blogCard} }
|
||||
|
||||
func mailBlogFiles() fstest.MapFS {
|
||||
return fstest.MapFS{
|
||||
"views/mail/welcome.htm": {Data: []byte(`subject = "Witaj, {{ .name }}"
|
||||
description = "Sent after registration"
|
||||
layout = "blog"
|
||||
sample.name = "Ada"
|
||||
==
|
||||
Cześć **{{ .name }}**, dzięki za rejestrację.
|
||||
`)},
|
||||
"views/mail/welcome-en.htm": {Data: []byte(`subject = "Welcome, {{ .name }}"
|
||||
description = "Sent after registration (English)"
|
||||
layout = "blog"
|
||||
sample.name = "Ada"
|
||||
==
|
||||
Hi **{{ .name }}**, thanks for joining.
|
||||
`)},
|
||||
"views/mail/layouts/blog.htm": {Data: []byte(`name = "Blog"
|
||||
==
|
||||
{{ .Content }}
|
||||
|
||||
-- The Acme blog
|
||||
==
|
||||
<div class="blog-mail">{{ .Content }}</div>
|
||||
`)},
|
||||
"views/mail/partials/card.htm": {Data: []byte(`name = "Card"
|
||||
==
|
||||
{{ .title }}
|
||||
==
|
||||
<div class="card">{{ .title }}</div>
|
||||
`)},
|
||||
}
|
||||
}
|
||||
|
||||
// mailSpy is the mail driver of the mail screens' env: it keeps every
|
||||
// message and fails while fail is set.
|
||||
type mailSpy struct {
|
||||
mu sync.Mutex
|
||||
msgs []postcard.RenderedMessage
|
||||
fail atomic.Bool
|
||||
}
|
||||
|
||||
func (d *mailSpy) Send(_ context.Context, msg postcard.RenderedMessage) error {
|
||||
if d.fail.Load() {
|
||||
return errors.New("dial tcp smtp.internal.example:25: connection refused")
|
||||
}
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.msgs = append(d.msgs, msg)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *mailSpy) messages() []postcard.RenderedMessage {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return append([]postcard.RenderedMessage(nil), d.msgs...)
|
||||
}
|
||||
|
||||
// mailEnv is screensEnv with postcard's Mailer published and the fixture
|
||||
// mail plugin booted.
|
||||
type mailEnv struct {
|
||||
*screensEnv
|
||||
blog mailBlogPlugin
|
||||
driver *mailSpy
|
||||
mailer postcard.Mailer
|
||||
}
|
||||
|
||||
// newMailScreensEnv assembles the admin like newScreensEnv, with postcard's
|
||||
// Mailer (over a spy driver and postcard's database override source) and the
|
||||
// acme.blog mail plugin booted before surf.Assemble, as party.Activate does
|
||||
// in an application. Assemble runs the serve-start index sync. The mail
|
||||
// tables are emptied first: they are shared by every test on the database.
|
||||
func newMailScreensEnv(t *testing.T, mutate func(*compass.Config)) *mailEnv {
|
||||
t.Helper()
|
||||
gdb := adminGorm(t)
|
||||
for _, table := range []string{postcard.TemplatesTable, postcard.LayoutsTable, postcard.PartialsTable, postcard.BrandTable, postcard.ImageLibraryTable} {
|
||||
if err := gdb.Exec("DELETE FROM " + table).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: cabana-mail\nlocale: en\nfallback_locale: en\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development", "SUMMER_ADMIN__JWT__SECRET=" + adminTestSecret}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for key, value := range map[string]any{
|
||||
"http.body_limits.default_bytes": 1048576, "http.body_limits.upload_bytes": 8388608,
|
||||
"admin.password.bcrypt_cost": 4, "admin.login.max_attempts": 100000,
|
||||
"app.url": "https://mail.example.test",
|
||||
} {
|
||||
if err := cfg.Set(key, value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(cfg)
|
||||
}
|
||||
app := backpack.New(cfg)
|
||||
if err := lagoon.Publish(app, adminSQL, gdb); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
driver := &mailSpy{}
|
||||
mailer := postcard.NewMailer(nil, driver, postcard.Options{From: "noreply@example.test", Overrides: postcard.NewDBSource(app)})
|
||||
if err := app.Publish[postcard.Mailer](mailer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blog := mailBlogPlugin{files: mailBlogFiles()}
|
||||
if err := postcard.BootPlugin(app, blog); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spy := &pingSpy{}
|
||||
plugins := []party.Plugin{demoPlugin{fsys: demoFS()}, pingPlugin{spy: spy}, blog}
|
||||
if err := phrasebook.Activate(app, plugins); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := surf.Assemble(app, plugins)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &mailEnv{
|
||||
screensEnv: &screensEnv{h: h, app: app, gdb: gdb, stamp: fmt.Sprintf("m%d", time.Now().UnixNano()), spy: spy},
|
||||
blog: blog, driver: driver, mailer: mailer,
|
||||
}
|
||||
}
|
||||
|
||||
// mailRowID is the id of a mail index row by code.
|
||||
func (e *mailEnv) mailRowID(t *testing.T, table, code string) uint {
|
||||
t.Helper()
|
||||
var id uint
|
||||
if err := e.gdb.Raw("SELECT id FROM "+table+" WHERE code = ?", code).Scan(&id).Error; err != nil || id == 0 {
|
||||
t.Fatalf("%s row %s: id=%d err=%v", table, code, id, err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// listRows returns a list response's rows by their code column.
|
||||
func listRows(t *testing.T, body map[string]any) map[string]map[string]any {
|
||||
t.Helper()
|
||||
rows, _ := body["data"].([]any)
|
||||
out := map[string]map[string]any{}
|
||||
for _, row := range rows {
|
||||
fields, _ := row.(map[string]any)
|
||||
code, _ := fields["code"].(string)
|
||||
out[code] = fields
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// templateBody is a full template form save.
|
||||
func templateBody(subject, body string, layout uint) map[string]any {
|
||||
return map[string]any{"subject": subject, "body": body, "layout": layout}
|
||||
}
|
||||
|
||||
func TestMailScreensSmoke(t *testing.T) {
|
||||
env := newMailScreensEnv(t, nil)
|
||||
_, rootToken := env.admin(t, "mail-root", true, "")
|
||||
|
||||
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 {
|
||||
t.Fatalf("templates list = %v", list["data"])
|
||||
}
|
||||
if en["locale"] != "en" || base["locale"] != "Default" {
|
||||
t.Fatalf("locales = %v / %v", base["locale"], en["locale"])
|
||||
}
|
||||
if base["subject"] != "Witaj, {{ .name }}" || base["description"] != "Sent after registration" {
|
||||
t.Fatalf("base row = %v", base)
|
||||
}
|
||||
|
||||
schema := env.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"/schema/form", rootToken, nil)
|
||||
names := []string{}
|
||||
fields, _ := dataOf(schema)["fields"].([]any)
|
||||
for _, item := range fields {
|
||||
field, _ := item.(map[string]any)
|
||||
names = append(names, fmt.Sprint(field["name"]))
|
||||
}
|
||||
if got := strings.Join(names, ","); !strings.Contains(got, "subject,layout,body") {
|
||||
t.Fatalf("template form fields = %s", got)
|
||||
}
|
||||
|
||||
id := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
||||
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
|
||||
path := fmt.Sprintf("%s/%d", mailTemplatesPath, id)
|
||||
saved := env.expect(t, http.StatusOK, http.MethodPut, path, rootToken, templateBody("Hello {{ .name }} from the admin", "Hi **{{ .name }}**.", layoutID))
|
||||
if data := dataOf(saved); data["subject"] != "Hello {{ .name }} from the admin" {
|
||||
t.Fatalf("saved template = %v", data)
|
||||
}
|
||||
var stored cabana.MailTemplate
|
||||
if err := env.gdb.First(&stored, id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file, _ := mailFileHash(t, env, blogWelcome)
|
||||
if !stored.IsCustom || stored.BaseHash == nil || *stored.BaseHash != file || stored.CustomizedAt == nil {
|
||||
t.Fatalf("stored template = %+v", stored)
|
||||
}
|
||||
|
||||
// The next send of the template uses the override.
|
||||
if err := env.mailer.Send(context.Background(), postcard.Message{Template: blogWelcome, To: []string{"reader@example.test"}, Vars: map[string]any{"name": "Grace"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msgs := env.driver.messages()
|
||||
if len(msgs) == 0 || msgs[len(msgs)-1].Subject != "Hello Grace from the admin" {
|
||||
t.Fatalf("sent = %+v", msgs)
|
||||
}
|
||||
|
||||
// Unsafe content is a field line, and nothing is saved.
|
||||
rec := env.call(t, http.MethodPut, path, rootToken, templateBody("Hello", "Hi <script>alert(1)</script>", layoutID))
|
||||
if rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("unsafe save status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
_, details := errorOf(t, rec)
|
||||
if !detailHas(details, "body", "Mail cannot contain scripts") || !detailHas(details, "body", "<script") {
|
||||
t.Fatalf("unsafe save details = %v", details)
|
||||
}
|
||||
var after cabana.MailTemplate
|
||||
if err := env.gdb.First(&after, id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.Subject != stored.Subject || after.Body != stored.Body {
|
||||
t.Fatalf("unsafe save changed the row: %+v", after)
|
||||
}
|
||||
|
||||
// The permission split (D-03).
|
||||
_, layoutsToken := env.admin(t, "mail-layouts", false, `{"system.manage_mail_layouts":1}`)
|
||||
_, templatesToken := env.admin(t, "mail-templates", false, `{"system.manage_mail_templates":1}`)
|
||||
if rec := env.call(t, http.MethodGet, mailTemplatesPath, layoutsToken, nil); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("layouts-only templates list status=%d", rec.Code)
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, templatesToken, nil)
|
||||
|
||||
// No role gained either code from code or migrations.
|
||||
var granted int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM backend_user_roles WHERE permissions LIKE '%system.manage_mail%' AND code NOT LIKE 'code-%'`).Scan(&granted).Error; err != nil || granted != 0 {
|
||||
t.Fatalf("roles granted a mail code: %d err=%v", granted, err)
|
||||
}
|
||||
|
||||
// The templates-only holder sees one Mail tile.
|
||||
settings := env.expect(t, http.StatusOK, http.MethodGet, "/settings", templatesToken, nil)
|
||||
tiles := []string{}
|
||||
entries, _ := settings["data"].([]any)
|
||||
for _, entry := range entries {
|
||||
item, _ := entry.(map[string]any)
|
||||
if item["category"] == "Mail" {
|
||||
tiles = append(tiles, fmt.Sprint(item["code"]))
|
||||
}
|
||||
}
|
||||
if strings.Join(tiles, ",") != "mail_templates" {
|
||||
t.Fatalf("templates-only Mail tiles = %v", tiles)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// mailFileHash is the catalog hash and source of a template file.
|
||||
func mailFileHash(t *testing.T, env *mailEnv, name string) (string, string) {
|
||||
t.Helper()
|
||||
editor, ok := postcard.EditorFrom(env.app)
|
||||
if !ok {
|
||||
t.Fatal("no postcard editor")
|
||||
}
|
||||
file, ok := editor.Catalog().Template(name)
|
||||
if !ok {
|
||||
t.Fatalf("template %s not in the catalog", name)
|
||||
}
|
||||
return file.Hash, file.Source
|
||||
}
|
||||
@@ -138,6 +138,7 @@ relation:
|
||||
settings:
|
||||
title: Settings
|
||||
category_system: "System"
|
||||
category_mail: "Mail"
|
||||
empty: No settings are available.
|
||||
saved: Settings saved
|
||||
back: Back to settings
|
||||
@@ -584,6 +585,39 @@ permissions:
|
||||
manage_roles: "Manage roles"
|
||||
manage_roles_comment: "Create and edit roles and the permissions they grant."
|
||||
view_plugins: "View plugins"
|
||||
manage_mail_templates: "Manage mail templates"
|
||||
manage_mail_templates_comment: "Edit mail templates, preview them and send test messages to yourself."
|
||||
manage_mail_layouts: "Manage mail layouts and branding"
|
||||
manage_mail_layouts_comment: "Edit mail layouts, partials, branding and the mail image library. These change every message the application sends."
|
||||
version:
|
||||
available: "A new version of the admin is available."
|
||||
reload: "Reload"
|
||||
mail:
|
||||
code: "Code"
|
||||
customized_at: "Customized"
|
||||
file_delete: "This comes from a plugin file and cannot be deleted. Reset it to the file version instead."
|
||||
file_missing: "The file of this record is no longer installed, so it cannot be changed."
|
||||
invalid_parse: "This cannot be read as a template: :message"
|
||||
invalid_render: "This does not render with the sample values: :message"
|
||||
invalid_unsafe: "Mail cannot contain scripts, frames, embedded objects, inline event handlers or javascript:, vbscript: or data: addresses. Found: :message"
|
||||
invalid_subject_line: "The subject must be a single line."
|
||||
invalid_layout: "Choose a layout from the list."
|
||||
invalid_partial: "The partial “:name” does not exist."
|
||||
invalid_no_content: "Put {{ .Content }} where the message goes."
|
||||
template:
|
||||
name: "Mail template"
|
||||
list_title: "Mail templates"
|
||||
list_empty: "No mail templates in this view. Clear the search and filters."
|
||||
menu_label: "Mail templates"
|
||||
menu_description: "Edit the subject and content of the mail the application sends."
|
||||
no_create: "Mail templates come from plugin files and cannot be created here."
|
||||
tab_template: "Template"
|
||||
subject: "Subject"
|
||||
subject_comment: "One line. Variables such as {{ .Name }} work here too."
|
||||
description: "Description"
|
||||
locale: "Locale"
|
||||
locale_default: "Default"
|
||||
layout: "Layout"
|
||||
layout_comment: "The layout wraps the message. Custom layouts are listed too."
|
||||
body: "Message"
|
||||
body_comment: "Markdown with variables such as {{ .Name }}. The plain-text version is made from it automatically."
|
||||
|
||||
@@ -148,6 +148,7 @@ relation:
|
||||
settings:
|
||||
title: Ustawienia
|
||||
category_system: "System"
|
||||
category_mail: "Poczta e-mail"
|
||||
empty: Brak dostępnych ustawień.
|
||||
saved: Zapisano ustawienia
|
||||
back: Wróć do ustawień
|
||||
@@ -620,6 +621,39 @@ permissions:
|
||||
manage_roles: "Zarządzanie rolami"
|
||||
manage_roles_comment: "Tworzenie i edycja ról oraz uprawnień, które nadają."
|
||||
view_plugins: "Podgląd wtyczek"
|
||||
manage_mail_templates: "Zarządzanie szablonami wiadomości"
|
||||
manage_mail_templates_comment: "Edycja szablonów wiadomości, ich podgląd i wysyłanie wiadomości testowych do siebie."
|
||||
manage_mail_layouts: "Zarządzanie układami i wyglądem wiadomości"
|
||||
manage_mail_layouts_comment: "Edycja układów, fragmentów i wyglądu wiadomości oraz biblioteki obrazów. Zmiany dotyczą każdej wiadomości wysyłanej przez aplikację."
|
||||
version:
|
||||
available: "Dostępna jest nowa wersja panelu."
|
||||
reload: "Odśwież"
|
||||
mail:
|
||||
code: "Kod"
|
||||
customized_at: "Dostosowano"
|
||||
file_delete: "To pochodzi z pliku wtyczki i nie można tego usunąć. Zamiast tego przywróć wersję z pliku."
|
||||
file_missing: "Plik tego rekordu nie jest już zainstalowany, więc nie można go zmienić."
|
||||
invalid_parse: "Nie można odczytać tego jako szablonu: :message"
|
||||
invalid_render: "To się nie renderuje z przykładowymi wartościami: :message"
|
||||
invalid_unsafe: "Wiadomość nie może zawierać skryptów, ramek, osadzonych obiektów, atrybutów zdarzeń ani adresów javascript:, vbscript: lub data:. Znaleziono: :message"
|
||||
invalid_subject_line: "Temat musi mieścić się w jednym wierszu."
|
||||
invalid_layout: "Wybierz układ z listy."
|
||||
invalid_partial: "Fragment „:name” nie istnieje."
|
||||
invalid_no_content: "Wstaw {{ .Content }} w miejscu treści."
|
||||
template:
|
||||
name: "Szablon wiadomości"
|
||||
list_title: "Szablony wiadomości"
|
||||
list_empty: "Brak szablonów wiadomości w tym widoku. Wyczyść wyszukiwanie i filtry."
|
||||
menu_label: "Szablony wiadomości"
|
||||
menu_description: "Edytuj temat i treść wiadomości wysyłanych przez aplikację."
|
||||
no_create: "Szablony wiadomości pochodzą z plików wtyczek i nie można ich tu tworzyć."
|
||||
tab_template: "Szablon"
|
||||
subject: "Temat"
|
||||
subject_comment: "Jeden wiersz. Zmienne, np. {{ .Name }}, działają także tutaj."
|
||||
description: "Opis"
|
||||
locale: "Język"
|
||||
locale_default: "Domyślny"
|
||||
layout: "Układ"
|
||||
layout_comment: "Układ otacza wiadomość. Na liście są też układy własne."
|
||||
body: "Treść"
|
||||
body_comment: "Markdown ze zmiennymi, np. {{ .Name }}. Wersja tekstowa powstaje z niej automatycznie."
|
||||
|
||||
Reference in New Issue
Block a user