feat(cabana): mail layouts and partials screens with reset, drift and custom layouts

- Layouts and partials controllers with catalog scoping, reset action and File version diff
- Custom layout create/delete with in-use refusal; meta.deletable and customized/outdated row states
- List schema golden fixtures updated for the two new row-state message keys

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-13 12:33:20 +01:00
parent 7efb9ed7ad
commit 83f76cc3f7
35 changed files with 1868 additions and 18 deletions

View File

@@ -33,7 +33,7 @@ Use cases:
- Invisible columns and filter choices: `invisible: true` in `columns.yaml` keeps a column searchable and sortable on the server while the schema flags it, the SPA does not render it and list rows do not carry it. The choices of a scope filter are served by the controller when it implements `pact.FilterOptions`, else by the model.
- Computed columns: a controller implementing `pact.ListExtendRecords` is called once per list page, after the records are loaded and before their columns are read, so a column of a field gorm ignores (a `-` tag with a column name) shows the value the hook set. Such a column compiles unsortable; `sortable: true` or `searchable: true` on it fails the boot. A hook error fails the list with the generic 500.
- Record title: a controller implementing `pact.FormRecordTitle` names a record; the show, create and update responses carry it as `meta.title` (`RecordMeta.Title`), and the admin heads the form and preview screens with it instead of the first text field's value.
- Row state: a controller implementing `pact.ListRowStates` is called once per list page with the page's records and the list's database handle. The list response carries `meta.row_states`, keyed by row id, with values from the fixed set `deleted`, `negative`, `disabled` in that order; a value outside the set is dropped and logged, rows without a state are left out, and a controller without the hook sends no `row_states` key. The badge texts are the list messages `rowStateDeleted`, `rowStateNegative` and `rowStateDisabled`, defaulting to `backend::lang.messages.list.row_state_*`. A soft-deleted record that the controller's `pact.ListExtendQuery` and `pact.FormExtendQuery` include can be shown, updated (it stays soft-deleted), targeted by bulk and record actions and removed for good by the controller's `pact.FormAfterDelete`.
- Row state: a controller implementing `pact.ListRowStates` is called once per list page with the page's records and the list's database handle. The list response carries `meta.row_states`, keyed by row id, with values from the fixed set `deleted`, `negative`, `disabled`, `customized`, `outdated` in that order; a value outside the set is dropped and logged, rows without a state are left out, and a controller without the hook sends no `row_states` key. The badge texts are the list messages `rowStateDeleted`, `rowStateNegative`, `rowStateDisabled`, `rowStateCustomized` and `rowStateOutdated`, defaulting to `backend::lang.messages.list.row_state_*`. A soft-deleted record that the controller's `pact.ListExtendQuery` and `pact.FormExtendQuery` include can be shown, updated (it stays soft-deleted), targeted by bulk and record actions and removed for good by the controller's `pact.FormAfterDelete`.
- Record actions: `recordActions` in `config_form.yaml` lists names the controller registers through `pact.HasAdminRecordActions`, a third action namespace with the same reserved names. It needs the form's `preview` block: record actions are offered on the preview screen, and a form that declares them without one fails boot. The show response's `meta.actions` (`cabana.RecordAction` entries with localized `label` and `confirm`) carries only the declared actions the requesting administrator may run and whose `Applies` reports true for the record; the key is absent when none is offered, and create and update responses never carry it. The action route loads the record through `pact.FormExtendQuery` with a row lock in one transaction (one 404 for a missing and an out-of-scope id), checks `Applies` again (409 when it reports false) and then runs the action. An unknown or duplicate name, or an action without a label, fails boot. Each run is logged with the controller, action, administrator and record id.
- Preview screen: a `preview` mapping in `config_form.yaml` (`preview: {}`, or with `headerPartial: <name>` for a status hint) gives the form a read-only record screen in the admin SPA. The form schema reports it as `preview` (`cabana.FormPreview`), fields with `context: preview` are shown only there and are never written by a save, `messages.preview` and `messages.edit` name the screen's subtitle and edit button, and `recordUrl` and the form redirects may point at it as `.../preview/:id`. An empty `preview:` key or an unknown key inside it fails boot.
- Plugin field types: a plugin implementing `pact.HasFormFieldTypes` registers admin form field types under short aliases that any controller's `fields.yaml` uses as `type:`. Boot checks the aliases (no built-in type, no alias claimed by two plugins), the element prefix, the scripts and styles and each field's option keys and `CheckOptions`. A save runs the type's `Decode` inside the save transaction after the record is loaded: the decoded value is stored, a `pact.FormFieldError` is a 422 on the field, any other error an opaque 500, and the notices a type returns are localized into the response's `meta.notices` (`cabana.FieldNotice`), which is absent when no type reported anything. Show and save responses serve the value through the type's `Load`. A translatable type's value is a locale map stored through the same lift, `cabana.TranslationWriter` and hydrate path as `mlmarkdown`, decoded and loaded per locale. On update, a value equal to the one the form was served for that field and locale is neither decoded nor written. Form hooks read what a save wrote through `cabana.FieldWritesFromContext`. A list column may name a plugin alias as its `type` and shows the type's `ListValue`. The cabana-owned upload route hands an element's file to the type's `Upload`. The form schema carries `element`, `translatable` and `typeOptions` for such a field; a type's `pact.FormFieldType.RequestOptions`, called once per schema request for each type the form uses, adds per-request options under the fields.yaml ones (a fields.yaml key wins, an error is logged and serves the fields.yaml options only). Settings and relation forms refuse plugin field types (supported in controller forms only). See [Plugin field types](../../docs/backend/field-types.md).
@@ -59,7 +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.
- 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. Mail layouts (`cabana.MailLayoutsControllerID`, model `cabana.MailLayout`) lists postcard's default layout first, then the file layouts and the custom (database-only, `source` NULL, shown as Custom) layouts by name; it creates custom layouts (code `^[a-z0-9-]+$`, free, create-only) and deletes them, refusing one that template rows still reference with a `cabana.ForbiddenError` whose message names the layout and the count (CLDR plural). Mail partials (`cabana.MailPartialsControllerID`, model `cabana.MailPartial`) edits the partials' HTML and text sections. Both need `cabana.PermissionManageMailLayouts`; saves are stamped and validated as templates are. On all three, the record action `reset` (danger, offered on a customized file-backed row) calls `postcard.ResetOverride` in the action's transaction; rows from files are never deleted. The list row states are `customized` (an override) and `outdated` (an override whose `base_hash` differs from the file's `file_hash`), the lists have a status filter (customized, not customized, outdated) and templates a locale filter, and the forms carry the `info` and `file_version` partials: the file, the status, the sample variables or the partial's call, the drift callout, and a 3-line-context LCS line diff of the serialized override (`postcard.FormatTemplate`, `FormatLayout`, `FormatPartial`) against the file, skipped above 2000 lines per side. The mail controllers declare `recordActions` without a preview block: the admin offers them in the update form's footer, a boot rule only these internal controllers are exempt from.
- 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.
@@ -307,7 +307,8 @@ func (p *Plugin) AdminFS() fs.FS { return adminFS }
| `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.MailTemplate` / `cabana.MailLayout` / `cabana.MailPartial` | GORM models of postcard's `system_mail_templates`, `system_mail_layouts` and `system_mail_partials` rows, as the mail screens read and write them, with their filter scopes. |
| `cabana.RecordMeta.Deletable` | Whether the record's form offers Delete (`meta.deletable`): sent only by controllers that decide it per record, the mail screens (false for templates, partials and file layouts, true for custom layouts), and omitted for every other controller. |
| `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. |
@@ -437,4 +438,4 @@ The Roles form's holders list is covered by the Docker-free TestRolesHoldersPart
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.
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; layouts (order, custom layout create, code format and uniqueness, the `{{ .Content }}` check, a customized layout in the next send), partials (parse error, usage line), reset, the in-use delete refusal, `meta.deletable`, drift (a second process booted over a changed file: row states, the status and locale filters, the info and file version partials, a save that clears the drift) and the line diff.

View File

@@ -0,0 +1,11 @@
{{- /* The File version tab (mailFileVersionView): the line diff of the override against the file, then the file itself. */ -}}
{{- with .Data -}}
{{- if .CustomLayout }}<p class="text-muted">{{ trans "backend::lang.mail.info_custom_layout" }}</p>{{ end -}}
{{- if .Show -}}
{{- if .Customized -}}
{{- if .Identical }}<p>{{ trans "backend::lang.mail.file_identical" }}</p>
{{- else if .Diff }}<p><strong>{{ trans "backend::lang.mail.file_changes" }}</strong></p><p class="text-muted">{{ trans "backend::lang.mail.file_legend" }}</p><pre class="summer-diff">{{ range .Diff }}<span class="{{ .Class }}">{{ .Text }}</span>{{ end }}</pre>{{ end -}}
{{- else }}<p class="text-muted">{{ trans "backend::lang.mail.file_not_customized" }}</p>{{ end -}}
<p><strong>{{ trans "backend::lang.mail.file_content" }}</strong></p><pre class="summer-diff">{{ range .Content }}<span class="summer-diff__ctx">{{ . }}</span>{{ end }}</pre>
{{- end -}}
{{- end -}}

View File

@@ -0,0 +1,10 @@
{{- /* Lines at the top of a mail form (mailInfoView): description, file or custom code, status, sample variables, partial call, drift callout. */ -}}
{{- with .Data -}}
{{- if .Description }}<p>{{ .Description }}</p>{{ end -}}
{{- if .File }}<p class="text-muted">{{ range .File }}{{ if .Code }}<code class="font-mono">{{ .Text }}</code>{{ else }}{{ .Text }}{{ end }}{{ end }}</p>{{ end -}}
{{- if .CustomCode }}<p class="text-muted">{{ trans "backend::lang.mail.info_custom_layout" }} <code class="font-mono">{{ .CustomCode }}</code></p>{{ end -}}
{{- if .Status }}<p><strong>{{ trans .Status }}</strong></p>{{ end -}}
{{- if .Template }}{{ if .Variables }}<p>{{ trans "backend::lang.mail.info_variables" }} {{ range $i, $name := .Variables }}{{ if $i }}, {{ end }}<code class="font-mono">{{ $name }}</code>{{ end }}</p>{{ else }}<p>{{ trans "backend::lang.mail.info_no_samples" }}</p>{{ end }}{{ end -}}
{{- if .Usage }}<p>{{ trans "backend::lang.mail.info_partial_usage" }} <code class="font-mono">{{ .Usage }}</code></p>{{ end -}}
{{- if .Outdated }}<div class="summer-callout summer-callout--warning" role="status"><p class="summer-callout__title">{{ trans "backend::lang.mail.drift_title" }}</p><p class="summer-callout__text">{{ trans "backend::lang.mail.drift_text" }}</p></div>{{ end -}}
{{- end -}}

View File

@@ -0,0 +1,6 @@
scopes:
status:
label: backend::lang.mail.filter_status
modelClass: System\Models\MailLayout
nameFrom: code
scope: filterStatus

View File

@@ -0,0 +1,21 @@
name: backend::lang.mail.layout.name
form: ~/plugins/summercms/cabana/models/maillayout/fields.yaml
modelClass: System\Models\MailLayout
defaultRedirect: summercms/cabana/maillayouts
create:
redirect: summercms/cabana/maillayouts/update/:id
redirectClose: summercms/cabana/maillayouts
update:
redirect: summercms/cabana/maillayouts/update/:id
redirectClose: summercms/cabana/maillayouts
recordActions: [reset]
messages:
create: backend::lang.mail.layout.new
update: backend::lang.mail.layout.name
saved: backend::lang.messages.form.saved
deleteConfirm: backend::lang.mail.layout.delete_confirm
deleted: backend::lang.messages.form.deleted

View File

@@ -0,0 +1,22 @@
list: ~/plugins/summercms/cabana/models/maillayout/columns.yaml
modelClass: System\Models\MailLayout
title: backend::lang.mail.layout.list_title
recordUrl: summercms/cabana/maillayouts/update/:id
noRecordsMessage: backend::lang.mail.layout.list_empty
recordsPerPage: 20
showCheckboxes: false
filter: config_filter.yaml
defaultSort:
column: name
direction: asc
toolbar:
buttons: [create]
search:
prompt: backend::lang.list.search_prompt
messages:
create: backend::lang.mail.layout.new
empty: backend::lang.mail.layout.list_empty
rowStateCustomized: backend::lang.mail.state_customized
rowStateOutdated: backend::lang.mail.state_outdated

View File

@@ -0,0 +1,11 @@
{{- /* The File version tab (mailFileVersionView): the line diff of the override against the file, then the file itself. */ -}}
{{- with .Data -}}
{{- if .CustomLayout }}<p class="text-muted">{{ trans "backend::lang.mail.info_custom_layout" }}</p>{{ end -}}
{{- if .Show -}}
{{- if .Customized -}}
{{- if .Identical }}<p>{{ trans "backend::lang.mail.file_identical" }}</p>
{{- else if .Diff }}<p><strong>{{ trans "backend::lang.mail.file_changes" }}</strong></p><p class="text-muted">{{ trans "backend::lang.mail.file_legend" }}</p><pre class="summer-diff">{{ range .Diff }}<span class="{{ .Class }}">{{ .Text }}</span>{{ end }}</pre>{{ end -}}
{{- else }}<p class="text-muted">{{ trans "backend::lang.mail.file_not_customized" }}</p>{{ end -}}
<p><strong>{{ trans "backend::lang.mail.file_content" }}</strong></p><pre class="summer-diff">{{ range .Content }}<span class="summer-diff__ctx">{{ . }}</span>{{ end }}</pre>
{{- end -}}
{{- end -}}

View File

@@ -0,0 +1,10 @@
{{- /* Lines at the top of a mail form (mailInfoView): description, file or custom code, status, sample variables, partial call, drift callout. */ -}}
{{- with .Data -}}
{{- if .Description }}<p>{{ .Description }}</p>{{ end -}}
{{- if .File }}<p class="text-muted">{{ range .File }}{{ if .Code }}<code class="font-mono">{{ .Text }}</code>{{ else }}{{ .Text }}{{ end }}{{ end }}</p>{{ end -}}
{{- if .CustomCode }}<p class="text-muted">{{ trans "backend::lang.mail.info_custom_layout" }} <code class="font-mono">{{ .CustomCode }}</code></p>{{ end -}}
{{- if .Status }}<p><strong>{{ trans .Status }}</strong></p>{{ end -}}
{{- if .Template }}{{ if .Variables }}<p>{{ trans "backend::lang.mail.info_variables" }} {{ range $i, $name := .Variables }}{{ if $i }}, {{ end }}<code class="font-mono">{{ $name }}</code>{{ end }}</p>{{ else }}<p>{{ trans "backend::lang.mail.info_no_samples" }}</p>{{ end }}{{ end -}}
{{- if .Usage }}<p>{{ trans "backend::lang.mail.info_partial_usage" }} <code class="font-mono">{{ .Usage }}</code></p>{{ end -}}
{{- if .Outdated }}<div class="summer-callout summer-callout--warning" role="status"><p class="summer-callout__title">{{ trans "backend::lang.mail.drift_title" }}</p><p class="summer-callout__text">{{ trans "backend::lang.mail.drift_text" }}</p></div>{{ end -}}
{{- end -}}

View File

@@ -0,0 +1,6 @@
scopes:
status:
label: backend::lang.mail.filter_status
modelClass: System\Models\MailPartial
nameFrom: code
scope: filterStatus

View File

@@ -0,0 +1,14 @@
name: backend::lang.mail.partial.name
form: ~/plugins/summercms/cabana/models/mailpartial/fields.yaml
modelClass: System\Models\MailPartial
defaultRedirect: summercms/cabana/mailpartials
update:
redirect: summercms/cabana/mailpartials/update/:id
redirectClose: summercms/cabana/mailpartials
recordActions: [reset]
messages:
update: backend::lang.mail.partial.name
saved: backend::lang.messages.form.saved

View File

@@ -0,0 +1,21 @@
list: ~/plugins/summercms/cabana/models/mailpartial/columns.yaml
modelClass: System\Models\MailPartial
title: backend::lang.mail.partial.list_title
recordUrl: summercms/cabana/mailpartials/update/:id
noRecordsMessage: backend::lang.mail.partial.list_empty
recordsPerPage: 20
showCheckboxes: false
filter: config_filter.yaml
defaultSort:
column: code
direction: asc
toolbar:
buttons: []
search:
prompt: backend::lang.list.search_prompt
messages:
empty: backend::lang.mail.partial.list_empty
rowStateCustomized: backend::lang.mail.state_customized
rowStateOutdated: backend::lang.mail.state_outdated

View File

@@ -0,0 +1,11 @@
{{- /* The File version tab (mailFileVersionView): the line diff of the override against the file, then the file itself. */ -}}
{{- with .Data -}}
{{- if .CustomLayout }}<p class="text-muted">{{ trans "backend::lang.mail.info_custom_layout" }}</p>{{ end -}}
{{- if .Show -}}
{{- if .Customized -}}
{{- if .Identical }}<p>{{ trans "backend::lang.mail.file_identical" }}</p>
{{- else if .Diff }}<p><strong>{{ trans "backend::lang.mail.file_changes" }}</strong></p><p class="text-muted">{{ trans "backend::lang.mail.file_legend" }}</p><pre class="summer-diff">{{ range .Diff }}<span class="{{ .Class }}">{{ .Text }}</span>{{ end }}</pre>{{ end -}}
{{- else }}<p class="text-muted">{{ trans "backend::lang.mail.file_not_customized" }}</p>{{ end -}}
<p><strong>{{ trans "backend::lang.mail.file_content" }}</strong></p><pre class="summer-diff">{{ range .Content }}<span class="summer-diff__ctx">{{ . }}</span>{{ end }}</pre>
{{- end -}}
{{- end -}}

View File

@@ -0,0 +1,10 @@
{{- /* Lines at the top of a mail form (mailInfoView): description, file or custom code, status, sample variables, partial call, drift callout. */ -}}
{{- with .Data -}}
{{- if .Description }}<p>{{ .Description }}</p>{{ end -}}
{{- if .File }}<p class="text-muted">{{ range .File }}{{ if .Code }}<code class="font-mono">{{ .Text }}</code>{{ else }}{{ .Text }}{{ end }}{{ end }}</p>{{ end -}}
{{- if .CustomCode }}<p class="text-muted">{{ trans "backend::lang.mail.info_custom_layout" }} <code class="font-mono">{{ .CustomCode }}</code></p>{{ end -}}
{{- if .Status }}<p><strong>{{ trans .Status }}</strong></p>{{ end -}}
{{- if .Template }}{{ if .Variables }}<p>{{ trans "backend::lang.mail.info_variables" }} {{ range $i, $name := .Variables }}{{ if $i }}, {{ end }}<code class="font-mono">{{ $name }}</code>{{ end }}</p>{{ else }}<p>{{ trans "backend::lang.mail.info_no_samples" }}</p>{{ end }}{{ end -}}
{{- if .Usage }}<p>{{ trans "backend::lang.mail.info_partial_usage" }} <code class="font-mono">{{ .Usage }}</code></p>{{ end -}}
{{- if .Outdated }}<div class="summer-callout summer-callout--warning" role="status"><p class="summer-callout__title">{{ trans "backend::lang.mail.drift_title" }}</p><p class="summer-callout__text">{{ trans "backend::lang.mail.drift_text" }}</p></div>{{ end -}}
{{- end -}}

View File

@@ -0,0 +1,11 @@
scopes:
locale:
label: backend::lang.mail.template.locale
modelClass: System\Models\MailTemplate
nameFrom: code
scope: filterLocale
status:
label: backend::lang.mail.filter_status
modelClass: System\Models\MailTemplate
nameFrom: code
scope: filterStatus

View File

@@ -7,6 +7,8 @@ update:
redirect: summercms/cabana/mailtemplates/update/:id
redirectClose: summercms/cabana/mailtemplates
recordActions: [reset]
messages:
update: backend::lang.mail.template.name
saved: backend::lang.messages.form.saved

View File

@@ -5,6 +5,7 @@ recordUrl: summercms/cabana/mailtemplates/update/:id
noRecordsMessage: backend::lang.mail.template.list_empty
recordsPerPage: 20
showCheckboxes: false
filter: config_filter.yaml
defaultSort:
column: code
direction: asc
@@ -16,3 +17,5 @@ toolbar:
messages:
empty: backend::lang.mail.template.list_empty
rowStateCustomized: backend::lang.mail.state_customized
rowStateOutdated: backend::lang.mail.state_outdated

View File

@@ -0,0 +1,17 @@
columns:
name:
label: backend::lang.mail.name_field
searchable: true
sortable: true
code:
label: backend::lang.mail.code
searchable: true
sortable: true
source:
label: backend::lang.mail.source
sortable: true
customized_at:
label: backend::lang.mail.customized_at
type: datetime
invisible: true
sortable: true

View File

@@ -0,0 +1,51 @@
fields:
_info:
type: partial
path: info
span: full
context: update
tab: backend::lang.mail.layout.tab_html
name:
label: backend::lang.mail.name_field
type: text
span: left
required: true
tab: backend::lang.mail.layout.tab_html
code:
label: backend::lang.mail.code
comment: backend::lang.mail.layout.code_comment
type: text
span: right
required: true
context: create
tab: backend::lang.mail.layout.tab_html
preset:
type: slug
field: name
content_html:
label: backend::lang.mail.layout.html
comment: backend::lang.mail.layout.html_comment
type: textarea
size: giant
span: full
tab: backend::lang.mail.layout.tab_html
content_text:
label: backend::lang.mail.layout.text
comment: backend::lang.mail.layout.text_comment
type: textarea
size: huge
span: full
tab: backend::lang.mail.layout.tab_text
content_css:
label: backend::lang.mail.layout.css
comment: backend::lang.mail.layout.css_comment
type: textarea
size: huge
span: full
tab: backend::lang.mail.layout.tab_css
_file_version:
type: partial
path: file_version
span: full
context: update
tab: backend::lang.mail.tab_file_version

View File

@@ -0,0 +1,13 @@
columns:
code:
label: backend::lang.mail.code
searchable: true
sortable: true
source:
label: backend::lang.mail.source
sortable: true
customized_at:
label: backend::lang.mail.customized_at
type: datetime
invisible: true
sortable: true

View File

@@ -0,0 +1,26 @@
fields:
_info:
type: partial
path: info
span: full
tab: backend::lang.mail.partial.tab_html
content_html:
label: backend::lang.mail.partial.html
comment: backend::lang.mail.partial.html_comment
type: textarea
size: huge
span: full
tab: backend::lang.mail.partial.tab_html
content_text:
label: backend::lang.mail.partial.text
comment: backend::lang.mail.partial.text_comment
type: textarea
size: large
span: full
tab: backend::lang.mail.partial.tab_text
_file_version:
type: partial
path: file_version
span: full
context: update
tab: backend::lang.mail.tab_file_version

View File

@@ -1,4 +1,9 @@
fields:
_info:
type: partial
path: info
span: full
tab: backend::lang.mail.template.tab_template
subject:
label: backend::lang.mail.template.subject
comment: backend::lang.mail.template.subject_comment
@@ -21,3 +26,9 @@ fields:
size: giant
span: full
tab: backend::lang.mail.template.tab_template
_file_version:
type: partial
path: file_version
span: full
context: update
tab: backend::lang.mail.tab_file_version

View File

@@ -550,6 +550,10 @@ func (s CRUDService) ShowRecord(ctx context.Context, cc *CompiledController, id
if err := hydrateFormExtensions(withTx(ctx, tx), extensionHydrate{Tx: tx, Tr: s.tr, Writer: s.writer, CC: cc, Target: target, Op: "update", Visible: visible}, result.Data); err != nil {
return err
}
if decider, ok := cc.Controller.(recordDeletable); ok && decider != nil {
deletable := decider.recordDeletable(target)
result.Meta.Deletable = &deletable
}
result.Meta.Actions, err = s.offeredRecordActions(withTx(ctx, tx), cc, target)
return err
})

View File

@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/pact"
@@ -107,3 +108,24 @@ func IsReorderStale(err error) bool {
// last-superuser race tests hold it in a transaction of their own, so both
// racing requests queue on it before either counts the other superusers.
const SuperuserLockKey = superuserLockKey
// LineDiffForTest renders lineDiff(a, b, context) as "|"-joined lines with
// their two-character prefixes ("+ ", "- ", " "); a gap between hunks is
// "...", and no diff (above the line cap) is "".
func LineDiffForTest(a, b []string, context int) string {
lines := lineDiff(a, b, context)
out := make([]string, 0, len(lines))
for _, line := range lines {
switch line.Kind {
case diffAdd:
out = append(out, "+ "+line.Text)
case diffDel:
out = append(out, "- "+line.Text)
case diffGap:
out = append(out, "...")
default:
out = append(out, " "+line.Text)
}
}
return strings.Join(out, "|")
}

View File

@@ -93,7 +93,10 @@ func compileExtension(pluginID string, cc *CompiledController, fsys fs.FS) error
formFile = "config_form.yaml"
}
// Record actions are offered on the preview screen only (D-10, D-11).
if len(cc.Form.recordActions) > 0 && cc.Form.preview == nil {
// The admin's own mail screens have no preview screen and offer them in
// the update form's footer instead (formFooterActions).
_, footer := cc.Controller.(formFooterActions)
if len(cc.Form.recordActions) > 0 && cc.Form.preview == nil && !footer {
return bootErr(pluginID, id, formFile, fmt.Errorf("recordActions needs a preview block (record actions are offered on the preview screen)"))
}
for _, name := range cc.Form.recordActions {

View File

@@ -42,7 +42,7 @@ const allColumnsJSON = `{"title":"demo.lang.widgets","modelClass":"Widget","reco
// defaultListMessagesJSON is a compiled list's messages block when the YAML
// declares none: every key is a framework default phrase key (D-13).
const defaultListMessagesJSON = `"messages":{"recordCount":{"other":"backend::lang.messages.list.record_count"},"create":{"other":"backend::lang.messages.list.create"},"searchPrompt":{"other":"backend::lang.list.search_prompt"},"empty":{"other":"backend::lang.list.no_records"},"emptySearch":{"other":"backend::lang.messages.list.empty_search"},"emptySearchHint":{"other":"backend::lang.messages.list.empty_search_hint"},"selected":{"other":"backend::lang.messages.list.selected"},"deleteSelected":{"other":"backend::lang.list.delete_selected"},"deleteConfirm":{"other":"backend::lang.messages.list.delete_confirm"},"deleted":{"other":"backend::lang.messages.list.deleted"},"rowStateDeleted":{"other":"backend::lang.messages.list.row_state_deleted"},"rowStateNegative":{"other":"backend::lang.messages.list.row_state_negative"},"rowStateDisabled":{"other":"backend::lang.messages.list.row_state_disabled"}}`
const defaultListMessagesJSON = `"messages":{"recordCount":{"other":"backend::lang.messages.list.record_count"},"create":{"other":"backend::lang.messages.list.create"},"searchPrompt":{"other":"backend::lang.list.search_prompt"},"empty":{"other":"backend::lang.list.no_records"},"emptySearch":{"other":"backend::lang.messages.list.empty_search"},"emptySearchHint":{"other":"backend::lang.messages.list.empty_search_hint"},"selected":{"other":"backend::lang.messages.list.selected"},"deleteSelected":{"other":"backend::lang.list.delete_selected"},"deleteConfirm":{"other":"backend::lang.messages.list.delete_confirm"},"deleted":{"other":"backend::lang.messages.list.deleted"},"rowStateDeleted":{"other":"backend::lang.messages.list.row_state_deleted"},"rowStateNegative":{"other":"backend::lang.messages.list.row_state_negative"},"rowStateDisabled":{"other":"backend::lang.messages.list.row_state_disabled"},"rowStateCustomized":{"other":"backend::lang.messages.list.row_state_customized"},"rowStateOutdated":{"other":"backend::lang.messages.list.row_state_outdated"}}`
func TestListSchemaCompile(t *testing.T) {
columns := readListFixture(t, "testdata/list/all_columns.yaml")

File diff suppressed because it is too large Load Diff

124
modules/cabana/mail_diff.go Normal file
View File

@@ -0,0 +1,124 @@
package cabana
// diffKind is what one line of a line diff is.
type diffKind int
const (
// diffCtx is a line both sides have.
diffCtx diffKind = iota
// diffAdd is a line only the new side has.
diffAdd
// diffDel is a line only the old side has.
diffDel
// diffGap stands for unchanged lines left out between two hunks.
diffGap
)
// diffLine is one line of a line diff.
type diffLine struct {
Kind diffKind
Text string
}
// diffMaxLines caps each side of a line diff: above it no diff is computed
// (the LCS table grows with the product of the sides), and the File version
// tab shows the file content alone.
const diffMaxLines = 2000
// lineDiff is the unified line diff from a (old) to b (new) with context
// unchanged lines around each change, computed with a longest common
// subsequence over the lines after trimming the common prefix and suffix.
// Unchanged runs longer than twice the context are cut to a diffGap line. It
// returns nil when the sides are equal and when either side has more than
// diffMaxLines lines.
func lineDiff(a, b []string, context int) []diffLine {
if len(a) > diffMaxLines || len(b) > diffMaxLines {
return nil
}
if context < 0 {
context = 0
}
prefix := 0
for prefix < len(a) && prefix < len(b) && a[prefix] == b[prefix] {
prefix++
}
suffix := 0
for suffix < len(a)-prefix && suffix < len(b)-prefix && a[len(a)-1-suffix] == b[len(b)-1-suffix] {
suffix++
}
if prefix == len(a) && prefix == len(b) {
return nil
}
ma, mb := a[prefix:len(a)-suffix], b[prefix:len(b)-suffix]
n, m := len(ma), len(mb)
// lcs[i*(m+1)+j] is the LCS length of ma[i:] and mb[j:]; both sides are
// capped at diffMaxLines, so the value fits in 16 bits.
lcs := make([]uint16, (n+1)*(m+1))
at := func(i, j int) uint16 { return lcs[i*(m+1)+j] }
for i := n - 1; i >= 0; i-- {
for j := m - 1; j >= 0; j-- {
switch {
case ma[i] == mb[j]:
lcs[i*(m+1)+j] = at(i+1, j+1) + 1
case at(i+1, j) >= at(i, j+1):
lcs[i*(m+1)+j] = at(i+1, j)
default:
lcs[i*(m+1)+j] = at(i, j+1)
}
}
}
full := make([]diffLine, 0, len(a)+len(b))
for _, line := range a[:prefix] {
full = append(full, diffLine{Kind: diffCtx, Text: line})
}
i, j := 0, 0
for i < n || j < m {
switch {
case i < n && j < m && ma[i] == mb[j]:
full = append(full, diffLine{Kind: diffCtx, Text: ma[i]})
i++
j++
case j < m && (i == n || at(i, j+1) > at(i+1, j)):
full = append(full, diffLine{Kind: diffAdd, Text: mb[j]})
j++
default:
full = append(full, diffLine{Kind: diffDel, Text: ma[i]})
i++
}
}
for _, line := range a[len(a)-suffix:] {
full = append(full, diffLine{Kind: diffCtx, Text: line})
}
return hunks(full, context)
}
// hunks keeps the changed lines of a full diff and up to context unchanged
// lines on each side of them; every other run of unchanged lines becomes
// one diffGap line, except at the start and the end, where it is dropped.
func hunks(full []diffLine, context int) []diffLine {
keep := make([]bool, len(full))
for idx, line := range full {
if line.Kind == diffCtx {
continue
}
for k := idx - context; k <= idx+context; k++ {
if k >= 0 && k < len(full) {
keep[k] = true
}
}
}
out := make([]diffLine, 0, len(full))
gap := false
for idx, line := range full {
if keep[idx] {
if gap && len(out) > 0 {
out = append(out, diffLine{Kind: diffGap})
}
gap = false
out = append(out, line)
continue
}
gap = true
}
return out
}

View File

@@ -130,10 +130,27 @@ type mailEnv struct {
// 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()
return newMailScreensEnvWith(t, mailEnvOptions{mutate: mutate})
}
// mailEnvOptions configure newMailScreensEnvWith: files replaces the
// fixture plugin's files, keep leaves the mail tables as they are (a second
// process on the same database), mutate changes the configuration.
type mailEnvOptions struct {
files fstest.MapFS
keep bool
mutate func(*compass.Config)
}
func newMailScreensEnvWith(t *testing.T, opts mailEnvOptions) *mailEnv {
t.Helper()
mutate := opts.mutate
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)
if !opts.keep {
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()
@@ -165,7 +182,11 @@ func newMailScreensEnv(t *testing.T, mutate func(*compass.Config)) *mailEnv {
if err := app.Publish[postcard.Mailer](mailer); err != nil {
t.Fatal(err)
}
blog := mailBlogPlugin{files: mailBlogFiles()}
files := opts.files
if files == nil {
files = mailBlogFiles()
}
blog := mailBlogPlugin{files: files}
if err := postcard.BootPlugin(app, blog); err != nil {
t.Fatal(err)
}
@@ -311,6 +332,260 @@ func TestMailScreensSmoke(t *testing.T) {
t.Fatalf("templates-only Mail tiles = %v", tiles)
}
})
mailLayoutsAndPartials(t, env, rootToken)
}
// mailEditor is the env's postcard editor.
func mailEditor(t *testing.T, env *mailEnv) *postcard.Editor {
t.Helper()
editor, ok := postcard.EditorFrom(env.app)
if !ok {
t.Fatal("no postcard editor")
}
return editor
}
// listCodes are a list response's code column values in row order.
func listCodes(body map[string]any) []string {
rows, _ := body["data"].([]any)
out := []string{}
for _, row := range rows {
fields, _ := row.(map[string]any)
out = append(out, fmt.Sprint(fields["code"]))
}
return out
}
// partialText is a partial response as text, for contains checks.
func partialText(t *testing.T, env *mailEnv, path, name, token string, id uint) string {
t.Helper()
rec := env.call(t, http.MethodGet, fmt.Sprintf("%s/partials/%s?id=%d", path, name, id), token, nil)
if rec.Code != http.StatusOK {
t.Fatalf("partial %s status=%d body=%s", name, rec.Code, rec.Body.String())
}
return rec.Body.String()
}
// mailLayoutsAndPartials runs the Task 2 behaviour: layouts, partials,
// reset, delete, drift and meta.deletable.
func mailLayoutsAndPartials(t *testing.T, env *mailEnv, rootToken string) {
editor := mailEditor(t, env)
def, _ := editor.Catalog().Layout("postcard::mail.layouts.default")
var customID uint
t.Run("layouts", func(t *testing.T) {
created := env.expect(t, http.StatusCreated, http.MethodPost, mailLayoutsPath, rootToken, map[string]any{
"name": "Promo", "code": "promo-2026", "content_html": def.HTML, "content_text": def.Text, "content_css": ".promo { color: #d66829; }",
})
customID = uint(dataOf(created)["id"].(float64))
var custom cabana.MailLayout
if err := env.gdb.First(&custom, customID).Error; err != nil {
t.Fatal(err)
}
if !custom.IsCustom || custom.Source != nil || custom.Code != "promo-2026" {
t.Fatalf("custom layout = %+v", custom)
}
env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPost, mailLayoutsPath, rootToken, map[string]any{
"name": "Bad", "code": "Promo 2026", "content_html": def.HTML, "content_text": def.Text,
}, "code", "Use lowercase letters, digits and dashes only.", false)
env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPost, mailLayoutsPath, rootToken, map[string]any{
"name": "Again", "code": "promo-2026", "content_html": def.HTML, "content_text": def.Text,
}, "code", "already used by another layout", false)
list := env.expect(t, http.StatusOK, http.MethodGet, mailLayoutsPath, rootToken, nil)
codes := listCodes(list)
if len(codes) == 0 || codes[0] != "postcard::mail.layouts.default" {
t.Fatalf("layouts order = %v", codes)
}
for _, want := range []string{"postcard::mail.layouts.system", "postcard::mail.layouts.minimal", blogLayout, "promo-2026"} {
if !strings.Contains(strings.Join(codes, ","), want) {
t.Fatalf("layouts %v miss %s", codes, want)
}
}
if rows := listRows(t, list); rows["promo-2026"]["source"] != "Custom" || rows[blogLayout]["source"] != "acme.blog" {
t.Fatalf("layout sources = %v / %v", rows["promo-2026"], rows[blogLayout])
}
blogID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
blogPath := fmt.Sprintf("%s/%d", mailLayoutsPath, blogID)
blogFile, _ := editor.Catalog().Layout(blogLayout)
env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPut, blogPath, rootToken, map[string]any{
"name": "Blog", "content_html": "<div>no content</div>", "content_text": blogFile.Text, "content_css": "",
}, "content_html", "Put {{ .Content }} where the message goes.", false)
env.expect(t, http.StatusOK, http.MethodPut, blogPath, rootToken, map[string]any{
"name": "Blog", "content_html": `<div class="blog-mail customized-layout">{{ .Content }}</div>`, "content_text": blogFile.Text, "content_css": "",
})
var blog cabana.MailLayout
if err := env.gdb.First(&blog, blogID).Error; err != nil || !blog.IsCustom || blog.BaseHash == nil {
t.Fatalf("customized file layout = %+v err=%v", blog, err)
}
if err := env.mailer.Send(context.Background(), postcard.Message{Template: blogWelcomeEn, To: []string{"reader@example.test"}, Vars: map[string]any{"name": "Grace"}}); err != nil {
t.Fatal(err)
}
if msgs := env.driver.messages(); !strings.Contains(msgs[len(msgs)-1].HTML, "customized-layout") {
t.Fatalf("send did not use the customized layout: %s", msgs[len(msgs)-1].HTML)
}
})
t.Run("partials", func(t *testing.T) {
list := env.expect(t, http.StatusOK, http.MethodGet, mailPartialsPath, rootToken, nil)
codes := strings.Join(listCodes(list), ",")
for _, want := range []string{"postcard::mail.partials.button", "postcard::mail.partials.panel", "postcard::mail.partials.table", "postcard::mail.partials.subcopy", blogCard} {
if !strings.Contains(codes, want) {
t.Fatalf("partials %s miss %s", codes, want)
}
}
cardID := env.mailRowID(t, postcard.PartialsTable, blogCard)
cardPath := fmt.Sprintf("%s/%d", mailPartialsPath, cardID)
env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPut, cardPath, rootToken, map[string]any{
"content_html": `<div class="card">{{ .title </div>`, "content_text": "{{ .title }}",
}, "content_html", "This cannot be read as a template", false)
env.expect(t, http.StatusOK, http.MethodPut, cardPath, rootToken, map[string]any{
"content_html": `<div class="card card--custom">{{ .title }}</div>`, "content_text": "{{ .title }}",
})
info := partialText(t, env, mailPartialsPath, "info", rootToken, cardID)
if !strings.Contains(info, `{{ partial \"acme.blog::mail.partials.card\" \"title\" .title }}`) {
t.Fatalf("partial usage line = %s", info)
}
buttonInfo := partialText(t, env, mailPartialsPath, "info", rootToken, env.mailRowID(t, postcard.PartialsTable, "postcard::mail.partials.button"))
if !strings.Contains(buttonInfo, `{{ partial \"button\"`) {
t.Fatalf("built-in partial usage line = %s", buttonInfo)
}
})
t.Run("reset", func(t *testing.T) {
id := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
path := fmt.Sprintf("%s/%d", mailTemplatesPath, id)
if names := recordActionNames(env.expect(t, http.StatusOK, http.MethodGet, path, rootToken, nil)); strings.Join(names, ",") != "reset" {
t.Fatalf("customized template actions = %v", names)
}
result := env.expect(t, http.StatusOK, http.MethodPost, path+"/actions/reset", rootToken, map[string]any{})
if dataOf(result)["message"] != "Reset to the file version." {
t.Fatalf("reset result = %v", result)
}
file, _ := editor.Catalog().Template(blogWelcome)
var row cabana.MailTemplate
if err := env.gdb.First(&row, id).Error; err != nil {
t.Fatal(err)
}
if row.IsCustom || row.Subject != file.Subject || row.Body != file.Body || row.BaseHash != nil {
t.Fatalf("reset row = %+v", row)
}
if names := recordActionNames(env.expect(t, http.StatusOK, http.MethodGet, path, rootToken, nil)); len(names) != 0 {
t.Fatalf("reset template still offers %v", names)
}
if names := recordActionNames(env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", mailLayoutsPath, customID), rootToken, nil)); len(names) != 0 {
t.Fatalf("custom layout offers %v", names)
}
})
t.Run("delete", func(t *testing.T) {
id := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
path := fmt.Sprintf("%s/%d", mailTemplatesPath, id)
env.expect(t, http.StatusOK, http.MethodPut, path, rootToken, templateBody("Promo for {{ .name }}", "Hi **{{ .name }}**.", customID))
layoutPath := fmt.Sprintf("%s/%d", mailLayoutsPath, customID)
env.expectRefusal(t, http.StatusForbidden, http.MethodDelete, layoutPath, rootToken, nil, "The layout “Promo” is used by 1 customized template.")
env.expect(t, http.StatusOK, http.MethodPost, path+"/actions/reset", rootToken, map[string]any{})
if rec := env.call(t, http.MethodDelete, layoutPath, rootToken, nil); rec.Code/100 != 2 {
t.Fatalf("delete unused custom layout status=%d body=%s", rec.Code, rec.Body.String())
}
for _, target := range []string{
fmt.Sprintf("%s/%d", mailLayoutsPath, env.mailRowID(t, postcard.LayoutsTable, blogLayout)),
path,
fmt.Sprintf("%s/%d", mailPartialsPath, env.mailRowID(t, postcard.PartialsTable, blogCard)),
} {
if rec := env.call(t, http.MethodDelete, target, rootToken, nil); rec.Code != http.StatusForbidden {
t.Fatalf("delete %s status=%d body=%s", target, rec.Code, rec.Body.String())
}
}
})
t.Run("deletable", func(t *testing.T) {
created := env.expect(t, http.StatusCreated, http.MethodPost, mailLayoutsPath, rootToken, map[string]any{
"name": "Keep", "code": "keep-me", "content_html": def.HTML, "content_text": def.Text,
})
keepID := uint(dataOf(created)["id"].(float64))
for _, tc := range []struct {
path string
want string
}{
{fmt.Sprintf("%s/%d", mailLayoutsPath, keepID), "true"},
{fmt.Sprintf("%s/%d", mailLayoutsPath, env.mailRowID(t, postcard.LayoutsTable, blogLayout)), "false"},
{fmt.Sprintf("%s/%d", mailTemplatesPath, env.mailRowID(t, postcard.TemplatesTable, blogWelcome)), "false"},
{fmt.Sprintf("%s/%d", mailPartialsPath, env.mailRowID(t, postcard.PartialsTable, blogCard)), "false"},
} {
meta, _ := env.expect(t, http.StatusOK, http.MethodGet, tc.path, rootToken, nil)["meta"].(map[string]any)
if fmt.Sprint(meta["deletable"]) != tc.want {
t.Fatalf("%s meta.deletable = %v want %s", tc.path, meta["deletable"], tc.want)
}
}
root, _ := env.admin(t, "mail-deletable", true, "")
meta, _ := env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", usersPath, root.ID), rootToken, nil)["meta"].(map[string]any)
if _, has := meta["deletable"]; has {
t.Fatalf("users meta carries deletable: %v", meta)
}
})
t.Run("drift", func(t *testing.T) {
id := env.mailRowID(t, postcard.TemplatesTable, blogWelcomeEn)
path := fmt.Sprintf("%s/%d", mailTemplatesPath, id)
blogID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
env.expect(t, http.StatusOK, http.MethodPut, path, rootToken, templateBody("Welcome aboard, {{ .name }}", "Hi **{{ .name }}**, glad you joined.", blogID))
// A second process boots with a changed file and syncs the index.
files := mailBlogFiles()
files["views/mail/welcome-en.htm"] = &fstest.MapFile{Data: []byte(`subject = "Welcome, {{ .name }}"
description = "Sent after registration (English)"
layout = "blog"
sample.name = "Ada"
==
Hi **{{ .name }}**, thanks for joining the Acme blog.
`)}
next := newMailScreensEnvWith(t, mailEnvOptions{files: files, keep: true})
list := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, rootToken, nil)
if got := fmt.Sprint(rowStates(list, id)); got != "[customized outdated]" {
t.Fatalf("drifted row states = %s", got)
}
filtered := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[status]=outdated", rootToken, nil)
if codes := listCodes(filtered); strings.Join(codes, ",") != blogWelcomeEn {
t.Fatalf("outdated filter = %v", codes)
}
customized := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[status]=customized", rootToken, nil)
if codes := listCodes(customized); strings.Join(codes, ",") != blogWelcomeEn {
t.Fatalf("customized filter = %v", codes)
}
info := partialText(t, next, mailTemplatesPath, "info", rootToken, id)
if !strings.Contains(info, "The file changed after this was customized") {
t.Fatalf("info partial = %s", info)
}
version := partialText(t, next, mailTemplatesPath, "file_version", rootToken, id)
if !strings.Contains(version, "summer-diff__add") || !strings.Contains(version, "summer-diff__del") || !strings.Contains(version, "thanks for joining the Acme blog") {
t.Fatalf("file version partial = %s", version)
}
localeFilter := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[locale]=en", rootToken, nil)
if codes := listCodes(localeFilter); strings.Join(codes, ",") != blogWelcomeEn {
t.Fatalf("locale filter = %v", codes)
}
next.expect(t, http.StatusOK, http.MethodPut, path, rootToken, templateBody("Welcome aboard, {{ .name }}", "Hi **{{ .name }}**, glad you joined.", blogID))
if got := fmt.Sprint(rowStates(next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, rootToken, nil), id)); got != "[customized]" {
t.Fatalf("reviewed row states = %s", got)
}
})
t.Run("diff", func(t *testing.T) {
got := cabana.LineDiffForTest([]string{"a", "b", "c", "d", "e", "f", "g", "h"}, []string{"a", "b", "c", "d", "X", "f", "g", "h"}, 3)
if got != " b| c| d|- e|+ X| f| g| h" {
t.Fatalf("lineDiff = %s", got)
}
long := make([]string, 2001)
for i := range long {
long[i] = fmt.Sprint(i)
}
if got := cabana.LineDiffForTest(long, []string{"x"}, 3); got != "" {
t.Fatalf("lineDiff above the cap = %q", got)
}
})
}
// mailFileHash is the catalog hash and source of a template file.

View File

@@ -40,6 +40,10 @@ type listMessageKeys struct {
RowStateDeleted string `yaml:"rowStateDeleted"`
RowStateNegative string `yaml:"rowStateNegative"`
RowStateDisabled string `yaml:"rowStateDisabled"`
// customized and outdated mark an override of a file and an override
// whose file changed since (the mail screens).
RowStateCustomized string `yaml:"rowStateCustomized"`
RowStateOutdated string `yaml:"rowStateOutdated"`
}
// ListMessages is a list schema's copy, every key resolved (same field order
@@ -59,6 +63,9 @@ type ListMessages struct {
RowStateDeleted MessageForms `json:"rowStateDeleted"`
RowStateNegative MessageForms `json:"rowStateNegative"`
RowStateDisabled MessageForms `json:"rowStateDisabled"`
// The customized and outdated row-state labels.
RowStateCustomized MessageForms `json:"rowStateCustomized"`
RowStateOutdated MessageForms `json:"rowStateOutdated"`
}
// formMessageKeys is the config_form.yaml messages block: phrase keys.
@@ -161,6 +168,9 @@ var (
RowStateDeleted: "backend::lang.messages.list.row_state_deleted",
RowStateNegative: "backend::lang.messages.list.row_state_negative",
RowStateDisabled: "backend::lang.messages.list.row_state_disabled",
RowStateCustomized: "backend::lang.messages.list.row_state_customized",
RowStateOutdated: "backend::lang.messages.list.row_state_outdated",
}
formMessageDefaults = formMessageKeys{
Create: "backend::lang.messages.form.create",

View File

@@ -179,7 +179,7 @@ func ExecuteList(ctx context.Context, db *gorm.DB, cc *CompiledController, in Li
}
// rowStateOrder is the fixed set of row states and the order they are sent in.
var rowStateOrder = []pact.RowState{pact.RowStateDeleted, pact.RowStateNegative, pact.RowStateDisabled}
var rowStateOrder = []pact.RowState{pact.RowStateDeleted, pact.RowStateNegative, pact.RowStateDisabled, pact.RowStateCustomized, pact.RowStateOutdated}
// listRowStates asks a controller implementing pact.ListRowStates for the
// states of one page of records, in one call (D-12). Each row keeps only the

View File

@@ -114,6 +114,11 @@ type RecordMeta struct {
// and save responses carry it; it is omitted when no record lock applies
// and is never part of the form schema.
PermissionLocks map[string][]PermissionRecordLock `json:"permissionLocks,omitempty"`
// Deletable tells the admin whether the record's form offers Delete. Only
// the show response of a controller that decides it per record (the mail
// screens: a custom layout can be deleted, a file-backed row cannot)
// carries it; it is omitted otherwise, and Delete then shows as before.
Deletable *bool `json:"deletable,omitempty"`
}
// FieldNotice is one save notice: the field it is about, the content locale

View File

@@ -230,6 +230,8 @@ messages:
row_state_deleted: Deleted
row_state_negative: Blocked
row_state_disabled: Inactive
row_state_customized: Customized
row_state_outdated: File changed
form:
create: New record
update: Edit record
@@ -604,6 +606,34 @@ mail:
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."
name_field: "Name"
source: "Source"
source_custom: "Custom"
filter_status: "Status"
filter_customized: "Customized"
filter_not_customized: "Not customized"
filter_outdated: "File changed"
state_customized: "Customized"
state_outdated: "File changed"
tab_file_version: "File version"
info_description: "Description: :text"
info_file: "File: :path in :plugin"
info_not_customized: "Not customized. The form shows the file version; saving creates your version."
info_customized: "Customized. Your version is sent instead of the file."
info_custom_layout: "Custom layout. It exists only in the database and can be deleted."
info_variables: "Variables with sample values:"
info_no_samples: "This file declares no sample values. Variables show as [name] in the preview."
info_partial_usage: "Use it in a template or layout with:"
drift_title: "The file changed after this was customized"
drift_text: "A plugin update changed the file. Your version is still sent. Compare both on the File version tab, then save your version again to mark the change as reviewed, or reset to the file version."
file_changes: "Changes from the file"
file_legend: "Lines starting with + are only in your version. Lines starting with − are only in the file."
file_content: "File version"
file_identical: "Your version matches the file."
file_not_customized: "Not customized: the form already shows this version."
reset: "Reset to file version"
reset_done: "Reset to the file version."
reset_unavailable: "There is no customized version to reset."
template:
name: "Mail template"
list_title: "Mail templates"
@@ -621,3 +651,42 @@ mail:
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."
reset_confirm: "Reset this template to the file version? Your subject, message and layout choice are deleted, and unsaved edits on this page are discarded. This cannot be undone."
layout:
name: "Mail layout"
new: "New layout"
list_title: "Mail layouts"
list_empty: "No layouts in this view. Clear the search, or create a layout."
menu_label: "Mail layouts"
menu_description: "Edit the layouts that wrap every message, or create your own."
tab_html: "HTML"
tab_text: "Plain text"
tab_css: "CSS"
code_comment: "Templates refer to the layout by this code. It cannot be changed later."
html: "HTML layout"
html_comment: "Wraps the HTML message. Put {{ .Content }} where the message goes."
text: "Plain-text layout"
text_comment: "Wraps the plain-text message. Put {{ .Content }} where the message goes."
css: "CSS"
css_comment: "Styles for this layout. They are inlined into the HTML message after the branding styles."
delete_confirm: "Delete this layout? This cannot be undone. A layout that customized templates still use cannot be deleted."
reset_confirm: "Reset this layout to the file version? Your HTML, plain-text and CSS changes are deleted, and unsaved edits on this page are discarded. This cannot be undone."
delete_in_use:
one: "The layout “:name” is used by :count customized template. Choose another layout for it first."
other: "The layout “:name” is used by :count customized templates. Choose another layout for them first."
code_taken: "This code is already used by another layout."
code_format: "Use lowercase letters, digits and dashes only."
partial:
name: "Mail partial"
list_title: "Mail partials"
list_empty: "No partials in this view. Clear the search."
menu_label: "Mail partials"
menu_description: "Edit the reusable blocks used in mail, such as buttons and panels."
no_create: "Mail partials come from plugin files and cannot be created here."
tab_html: "HTML"
tab_text: "Plain text"
html: "HTML"
html_comment: "Used in the HTML part of messages."
text: "Plain text"
text_comment: "Used in the plain-text part of messages."
reset_confirm: "Reset this partial to the file version? Your HTML and plain-text changes are deleted, and unsaved edits on this page are discarded. This cannot be undone."

View File

@@ -246,6 +246,8 @@ messages:
row_state_deleted: Usunięty
row_state_negative: Zablokowany
row_state_disabled: Nieaktywny
row_state_customized: Dostosowany
row_state_outdated: Plik zmieniony
form:
create: Nowy rekord
update: Edycja rekordu
@@ -640,6 +642,34 @@ mail:
invalid_layout: "Wybierz układ z listy."
invalid_partial: "Fragment „:name” nie istnieje."
invalid_no_content: "Wstaw {{ .Content }} w miejscu treści."
name_field: "Nazwa"
source: "Źródło"
source_custom: "Własny"
filter_status: "Status"
filter_customized: "Dostosowane"
filter_not_customized: "Niedostosowane"
filter_outdated: "Plik zmieniony"
state_customized: "Dostosowany"
state_outdated: "Plik zmieniony"
tab_file_version: "Wersja z pliku"
info_description: "Opis: :text"
info_file: "Plik: :path we wtyczce :plugin"
info_not_customized: "Nie dostosowano. Formularz pokazuje wersję z pliku; zapisanie utworzy Twoją wersję."
info_customized: "Dostosowano. Zamiast pliku wysyłana jest Twoja wersja."
info_custom_layout: "Układ własny. Istnieje tylko w bazie danych i można go usunąć."
info_variables: "Zmienne z przykładowymi wartościami:"
info_no_samples: "Ten plik nie deklaruje przykładowych wartości. W podglądzie zmienne są pokazane jako [nazwa]."
info_partial_usage: "Użyj go w szablonie lub układzie tak:"
drift_title: "Plik zmienił się po dostosowaniu"
drift_text: "Aktualizacja wtyczki zmieniła plik. Nadal wysyłana jest Twoja wersja. Porównaj obie w zakładce Wersja z pliku, a potem zapisz swoją wersję ponownie, aby oznaczyć zmianę jako sprawdzoną, albo przywróć wersję z pliku."
file_changes: "Zmiany względem pliku"
file_legend: "Wiersze zaczynające się od + są tylko w Twojej wersji. Wiersze zaczynające się od − są tylko w pliku."
file_content: "Wersja z pliku"
file_identical: "Twoja wersja jest zgodna z plikiem."
file_not_customized: "Nie dostosowano: formularz pokazuje już tę wersję."
reset: "Przywróć wersję z pliku"
reset_done: "Przywrócono wersję z pliku."
reset_unavailable: "Nie ma dostosowanej wersji do przywrócenia."
template:
name: "Szablon wiadomości"
list_title: "Szablony wiadomości"
@@ -657,3 +687,44 @@ mail:
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."
reset_confirm: "Przywrócić wersję szablonu z pliku? Twój temat, treść i wybór układu zostaną usunięte, a niezapisane zmiany na tej stronie odrzucone. Tej operacji nie można cofnąć."
layout:
name: "Układ wiadomości"
new: "Nowy układ"
list_title: "Układy wiadomości"
list_empty: "Brak układów w tym widoku. Wyczyść wyszukiwanie lub utwórz układ."
menu_label: "Układy wiadomości"
menu_description: "Edytuj układy otaczające każdą wiadomość lub utwórz własne."
tab_html: "HTML"
tab_text: "Zwykły tekst"
tab_css: "CSS"
code_comment: "Szablony odwołują się do układu przez ten kod. Później nie można go zmienić."
html: "Układ HTML"
html_comment: "Otacza wiadomość HTML. Wstaw {{ .Content }} w miejscu treści."
text: "Układ tekstowy"
text_comment: "Otacza wiadomość tekstową. Wstaw {{ .Content }} w miejscu treści."
css: "CSS"
css_comment: "Style tego układu. Są wstawiane do wiadomości HTML po stylach wyglądu."
delete_confirm: "Usunąć ten układ? Tej operacji nie można cofnąć. Nie można usunąć układu, którego używają dostosowane szablony."
reset_confirm: "Przywrócić wersję układu z pliku? Twoje zmiany HTML, tekstu i CSS zostaną usunięte, a niezapisane zmiany na tej stronie odrzucone. Tej operacji nie można cofnąć."
delete_in_use:
one: "Układ „:name” jest używany przez :count dostosowany szablon. Najpierw wybierz dla niego inny układ."
few: "Układ „:name” jest używany przez :count dostosowane szablony. Najpierw wybierz dla nich inny układ."
many: "Układ „:name” jest używany przez :count dostosowanych szablonów. Najpierw wybierz dla nich inny układ."
other: "Układ „:name” jest używany przez :count dostosowanego szablonu. Najpierw wybierz dla nich inny układ."
code_taken: "Ten kod jest już używany przez inny układ."
code_format: "Używaj tylko małych liter, cyfr i myślników."
partial:
name: "Fragment wiadomości"
list_title: "Fragmenty wiadomości"
list_empty: "Brak fragmentów w tym widoku. Wyczyść wyszukiwanie."
menu_label: "Fragmenty wiadomości"
menu_description: "Edytuj bloki wielokrotnego użytku w wiadomościach, np. przyciski i panele."
no_create: "Fragmenty wiadomości pochodzą z plików wtyczek i nie można ich tu tworzyć."
tab_html: "HTML"
tab_text: "Zwykły tekst"
html: "HTML"
html_comment: "Używany w części HTML wiadomości."
text: "Zwykły tekst"
text_comment: "Używany w części tekstowej wiadomości."
reset_confirm: "Przywrócić wersję fragmentu z pliku? Twoje zmiany HTML i tekstu zostaną usunięte, a niezapisane zmiany na tej stronie odrzucone. Tej operacji nie można cofnąć."