From 83f76cc3f7ccc04ceb9c58d28386233adfabeafa Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Fri, 13 Nov 2026 12:33:20 +0100 Subject: [PATCH] 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 --- docs/backend/lists-and-filters.md | 4 +- docs/services/mail.md | 9 + modules/cabana/README.md | 9 +- .../controllers/maillayouts/_file_version.htm | 11 + .../controllers/maillayouts/_info.htm | 10 + .../maillayouts/config_filter.yaml | 6 + .../controllers/maillayouts/config_form.yaml | 21 + .../controllers/maillayouts/config_list.yaml | 22 + .../mailpartials/_file_version.htm | 11 + .../controllers/mailpartials/_info.htm | 10 + .../mailpartials/config_filter.yaml | 6 + .../controllers/mailpartials/config_form.yaml | 14 + .../controllers/mailpartials/config_list.yaml | 21 + .../mailtemplates/_file_version.htm | 11 + .../controllers/mailtemplates/_info.htm | 10 + .../mailtemplates/config_filter.yaml | 11 + .../mailtemplates/config_form.yaml | 2 + .../mailtemplates/config_list.yaml | 3 + .../models/maillayout/columns.yaml | 17 + .../models/maillayout/fields.yaml | 51 + .../models/mailpartial/columns.yaml | 13 + .../models/mailpartial/fields.yaml | 26 + .../models/mailtemplate/fields.yaml | 11 + modules/cabana/crud.go | 4 + modules/cabana/export_test.go | 22 + modules/cabana/extension.go | 5 +- modules/cabana/list_schema_test.go | 2 +- modules/cabana/mail_admin.go | 980 +++++++++++++++++- modules/cabana/mail_diff.go | 124 +++ modules/cabana/mail_screens_smoke_test.go | 283 ++++- modules/cabana/messages.go | 10 + modules/cabana/query.go | 2 +- modules/cabana/relation_field.go | 5 + modules/phrasebook/backend/lang/en/lang.yaml | 69 ++ modules/phrasebook/backend/lang/pl/lang.yaml | 71 ++ 35 files changed, 1868 insertions(+), 18 deletions(-) create mode 100644 modules/cabana/backendscreens/controllers/maillayouts/_file_version.htm create mode 100644 modules/cabana/backendscreens/controllers/maillayouts/_info.htm create mode 100644 modules/cabana/backendscreens/controllers/maillayouts/config_filter.yaml create mode 100644 modules/cabana/backendscreens/controllers/maillayouts/config_form.yaml create mode 100644 modules/cabana/backendscreens/controllers/maillayouts/config_list.yaml create mode 100644 modules/cabana/backendscreens/controllers/mailpartials/_file_version.htm create mode 100644 modules/cabana/backendscreens/controllers/mailpartials/_info.htm create mode 100644 modules/cabana/backendscreens/controllers/mailpartials/config_filter.yaml create mode 100644 modules/cabana/backendscreens/controllers/mailpartials/config_form.yaml create mode 100644 modules/cabana/backendscreens/controllers/mailpartials/config_list.yaml create mode 100644 modules/cabana/backendscreens/controllers/mailtemplates/_file_version.htm create mode 100644 modules/cabana/backendscreens/controllers/mailtemplates/_info.htm create mode 100644 modules/cabana/backendscreens/controllers/mailtemplates/config_filter.yaml create mode 100644 modules/cabana/backendscreens/models/maillayout/columns.yaml create mode 100644 modules/cabana/backendscreens/models/maillayout/fields.yaml create mode 100644 modules/cabana/backendscreens/models/mailpartial/columns.yaml create mode 100644 modules/cabana/backendscreens/models/mailpartial/fields.yaml create mode 100644 modules/cabana/mail_diff.go diff --git a/docs/backend/lists-and-filters.md b/docs/backend/lists-and-filters.md index eda909ae..f0e5f159 100644 --- a/docs/backend/lists-and-filters.md +++ b/docs/backend/lists-and-filters.md @@ -236,7 +236,7 @@ func (PeopleController) ListRowStates(_ context.Context, _ *gorm.DB, records []a cabana calls the hook once per list page, with that page's records and the list's database handle, never once per row. A list does not run in a transaction, so `cabana.TxFromContext` reports none in this hook; use the handle it is given. -The set of states is fixed: `pact.RowStateDeleted`, `pact.RowStateNegative` and `pact.RowStateDisabled`. A row may carry several. The list response sends them in `meta.row_states`, keyed by row id, always in that order and each at most once; a value outside the set is dropped and logged, and a controller without the hook sends no `row_states` key. The admin shows each state as a text badge after the row's first cell and with a text style (a deleted row is struck through and muted, a negative one is red, a disabled one is muted), so the state is never carried by colour alone. +The set of states is fixed: `pact.RowStateDeleted`, `pact.RowStateNegative`, `pact.RowStateDisabled`, `pact.RowStateCustomized` and `pact.RowStateOutdated`. The last two mark a record whose shipped content an administrator replaced (a mail template with an override, for example) and such a record whose shipped content changed since. A row may carry several. The list response sends them in `meta.row_states`, keyed by row id, always in that order and each at most once; a value outside the set is dropped and logged, and a controller without the hook sends no `row_states` key. The admin shows each state as a text badge after the row's first cell, and the first three also with a text style (a deleted row is struck through and muted, a negative one is red, a disabled one is muted), so the state is never carried by colour alone. A customized or outdated row keeps the normal text style. The badge texts are list messages. Override them per list in the `messages` block of `config_list.yaml`: @@ -245,6 +245,8 @@ The badge texts are list messages. Override them per list in the `messages` bloc | `rowStateDeleted` | Deleted | | `rowStateNegative` | Blocked | | `rowStateDisabled` | Inactive | +| `rowStateCustomized` | Customized | +| `rowStateOutdated` | File changed | A list that shows soft-deleted records includes them in its scope, as `withTrashed()` does in WinterCMS: return `db.Unscoped()` (narrowed as needed) from `pact.ListExtendQuery` and `pact.FormExtendQuery`. Such a record can then be shown, updated and targeted by bulk and record actions, and it stays soft-deleted through an update. Code that writes to it, such as an action's `Run`, must use an unscoped handle too (`tx.Unscoped()`), or GORM adds its `deleted_at IS NULL` condition and the write matches nothing. Deleting it through the admin soft-deletes again, which changes nothing; a controller that wants the delete to be permanent removes the row in `pact.FormAfterDelete`. diff --git a/docs/services/mail.md b/docs/services/mail.md index aaf9e99d..6ab0df9e 100644 --- a/docs/services/mail.md +++ b/docs/services/mail.md @@ -177,6 +177,15 @@ The rows exist before anyone edits a template: when the admin starts, it writes Saving a template stores your subject, message and layout in its row and marks it customized, together with the hash of the file the change was based on. From then on your version is sent instead of the file, until the template is reset to the file version. A save is checked the way a send would render it (`postcard.Editor.Validate`): a message that does not parse, does not render with the sample values or fails the safety checks is refused with a line under the field, and nothing is stored. +- **Mail layouts** lists postcard's default layout first, then every other file layout and every custom layout by name; the source column is the plugin, or Custom for a layout that exists only in the database. The form has HTML, Plain text and CSS tabs. A file layout's name stays the file's. **New layout** creates a custom layout: its code (lowercase letters, digits and dashes, and not used by another layout) is what template overrides store, so it cannot be changed later. A custom layout can be deleted, unless customized templates still use it: the refusal names the layout and how many templates use it. +- **Mail partials** lists every partial, postcard's built-in ones included. The form edits the HTML and plain-text sections and shows how to call the partial, for example `{{ partial "button" "body" .body "type" .type "url" .url }}`. + +Layouts and partials need `system.manage_mail_layouts`. + +On a customized template, file layout or partial, **Reset to file version** returns the row to its file: your subject, message and layout choice (or the wrappers, CSS or sections) are discarded, and the file version is sent again. Rows that come from files are never deleted, and a custom layout has no file version to reset to. + +When a plugin update changes a file you customized, your version is still sent, but the list marks the row Customized and File changed, the status filter's File changed choice finds it, and the form shows a notice. The File version tab shows the lines your version changed against the current file (lines starting with + are only in your version, lines starting with − only in the file) and the file itself. Saving your version again marks the change as reviewed; resetting takes the new file. + ## Drivers `mail.driver` selects the driver: diff --git a/modules/cabana/README.md b/modules/cabana/README.md index 13510c58..b450de05 100644 --- a/modules/cabana/README.md +++ b/modules/cabana/README.md @@ -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: ` 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 ` 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 ` 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_` (`: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_` (`: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. diff --git a/modules/cabana/backendscreens/controllers/maillayouts/_file_version.htm b/modules/cabana/backendscreens/controllers/maillayouts/_file_version.htm new file mode 100644 index 00000000..b2d20eb4 --- /dev/null +++ b/modules/cabana/backendscreens/controllers/maillayouts/_file_version.htm @@ -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 }}

{{ trans "backend::lang.mail.info_custom_layout" }}

{{ end -}} +{{- if .Show -}} +{{- if .Customized -}} +{{- if .Identical }}

{{ trans "backend::lang.mail.file_identical" }}

+{{- else if .Diff }}

{{ trans "backend::lang.mail.file_changes" }}

{{ trans "backend::lang.mail.file_legend" }}

{{ range .Diff }}{{ .Text }}{{ end }}
{{ end -}} +{{- else }}

{{ trans "backend::lang.mail.file_not_customized" }}

{{ end -}} +

{{ trans "backend::lang.mail.file_content" }}

{{ range .Content }}{{ . }}{{ end }}
+{{- end -}} +{{- end -}} diff --git a/modules/cabana/backendscreens/controllers/maillayouts/_info.htm b/modules/cabana/backendscreens/controllers/maillayouts/_info.htm new file mode 100644 index 00000000..6dadb3af --- /dev/null +++ b/modules/cabana/backendscreens/controllers/maillayouts/_info.htm @@ -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 }}

{{ .Description }}

{{ end -}} +{{- if .File }}

{{ range .File }}{{ if .Code }}{{ .Text }}{{ else }}{{ .Text }}{{ end }}{{ end }}

{{ end -}} +{{- if .CustomCode }}

{{ trans "backend::lang.mail.info_custom_layout" }} {{ .CustomCode }}

{{ end -}} +{{- if .Status }}

{{ trans .Status }}

{{ end -}} +{{- if .Template }}{{ if .Variables }}

{{ trans "backend::lang.mail.info_variables" }} {{ range $i, $name := .Variables }}{{ if $i }}, {{ end }}{{ $name }}{{ end }}

{{ else }}

{{ trans "backend::lang.mail.info_no_samples" }}

{{ end }}{{ end -}} +{{- if .Usage }}

{{ trans "backend::lang.mail.info_partial_usage" }} {{ .Usage }}

{{ end -}} +{{- if .Outdated }}

{{ trans "backend::lang.mail.drift_title" }}

{{ trans "backend::lang.mail.drift_text" }}

{{ end -}} +{{- end -}} diff --git a/modules/cabana/backendscreens/controllers/maillayouts/config_filter.yaml b/modules/cabana/backendscreens/controllers/maillayouts/config_filter.yaml new file mode 100644 index 00000000..a5745403 --- /dev/null +++ b/modules/cabana/backendscreens/controllers/maillayouts/config_filter.yaml @@ -0,0 +1,6 @@ +scopes: + status: + label: backend::lang.mail.filter_status + modelClass: System\Models\MailLayout + nameFrom: code + scope: filterStatus diff --git a/modules/cabana/backendscreens/controllers/maillayouts/config_form.yaml b/modules/cabana/backendscreens/controllers/maillayouts/config_form.yaml new file mode 100644 index 00000000..4ca62ee6 --- /dev/null +++ b/modules/cabana/backendscreens/controllers/maillayouts/config_form.yaml @@ -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 diff --git a/modules/cabana/backendscreens/controllers/maillayouts/config_list.yaml b/modules/cabana/backendscreens/controllers/maillayouts/config_list.yaml new file mode 100644 index 00000000..fbeba10b --- /dev/null +++ b/modules/cabana/backendscreens/controllers/maillayouts/config_list.yaml @@ -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 diff --git a/modules/cabana/backendscreens/controllers/mailpartials/_file_version.htm b/modules/cabana/backendscreens/controllers/mailpartials/_file_version.htm new file mode 100644 index 00000000..b2d20eb4 --- /dev/null +++ b/modules/cabana/backendscreens/controllers/mailpartials/_file_version.htm @@ -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 }}

{{ trans "backend::lang.mail.info_custom_layout" }}

{{ end -}} +{{- if .Show -}} +{{- if .Customized -}} +{{- if .Identical }}

{{ trans "backend::lang.mail.file_identical" }}

+{{- else if .Diff }}

{{ trans "backend::lang.mail.file_changes" }}

{{ trans "backend::lang.mail.file_legend" }}

{{ range .Diff }}{{ .Text }}{{ end }}
{{ end -}} +{{- else }}

{{ trans "backend::lang.mail.file_not_customized" }}

{{ end -}} +

{{ trans "backend::lang.mail.file_content" }}

{{ range .Content }}{{ . }}{{ end }}
+{{- end -}} +{{- end -}} diff --git a/modules/cabana/backendscreens/controllers/mailpartials/_info.htm b/modules/cabana/backendscreens/controllers/mailpartials/_info.htm new file mode 100644 index 00000000..6dadb3af --- /dev/null +++ b/modules/cabana/backendscreens/controllers/mailpartials/_info.htm @@ -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 }}

{{ .Description }}

{{ end -}} +{{- if .File }}

{{ range .File }}{{ if .Code }}{{ .Text }}{{ else }}{{ .Text }}{{ end }}{{ end }}

{{ end -}} +{{- if .CustomCode }}

{{ trans "backend::lang.mail.info_custom_layout" }} {{ .CustomCode }}

{{ end -}} +{{- if .Status }}

{{ trans .Status }}

{{ end -}} +{{- if .Template }}{{ if .Variables }}

{{ trans "backend::lang.mail.info_variables" }} {{ range $i, $name := .Variables }}{{ if $i }}, {{ end }}{{ $name }}{{ end }}

{{ else }}

{{ trans "backend::lang.mail.info_no_samples" }}

{{ end }}{{ end -}} +{{- if .Usage }}

{{ trans "backend::lang.mail.info_partial_usage" }} {{ .Usage }}

{{ end -}} +{{- if .Outdated }}

{{ trans "backend::lang.mail.drift_title" }}

{{ trans "backend::lang.mail.drift_text" }}

{{ end -}} +{{- end -}} diff --git a/modules/cabana/backendscreens/controllers/mailpartials/config_filter.yaml b/modules/cabana/backendscreens/controllers/mailpartials/config_filter.yaml new file mode 100644 index 00000000..eb044255 --- /dev/null +++ b/modules/cabana/backendscreens/controllers/mailpartials/config_filter.yaml @@ -0,0 +1,6 @@ +scopes: + status: + label: backend::lang.mail.filter_status + modelClass: System\Models\MailPartial + nameFrom: code + scope: filterStatus diff --git a/modules/cabana/backendscreens/controllers/mailpartials/config_form.yaml b/modules/cabana/backendscreens/controllers/mailpartials/config_form.yaml new file mode 100644 index 00000000..af833693 --- /dev/null +++ b/modules/cabana/backendscreens/controllers/mailpartials/config_form.yaml @@ -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 diff --git a/modules/cabana/backendscreens/controllers/mailpartials/config_list.yaml b/modules/cabana/backendscreens/controllers/mailpartials/config_list.yaml new file mode 100644 index 00000000..e4e2da19 --- /dev/null +++ b/modules/cabana/backendscreens/controllers/mailpartials/config_list.yaml @@ -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 diff --git a/modules/cabana/backendscreens/controllers/mailtemplates/_file_version.htm b/modules/cabana/backendscreens/controllers/mailtemplates/_file_version.htm new file mode 100644 index 00000000..b2d20eb4 --- /dev/null +++ b/modules/cabana/backendscreens/controllers/mailtemplates/_file_version.htm @@ -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 }}

{{ trans "backend::lang.mail.info_custom_layout" }}

{{ end -}} +{{- if .Show -}} +{{- if .Customized -}} +{{- if .Identical }}

{{ trans "backend::lang.mail.file_identical" }}

+{{- else if .Diff }}

{{ trans "backend::lang.mail.file_changes" }}

{{ trans "backend::lang.mail.file_legend" }}

{{ range .Diff }}{{ .Text }}{{ end }}
{{ end -}} +{{- else }}

{{ trans "backend::lang.mail.file_not_customized" }}

{{ end -}} +

{{ trans "backend::lang.mail.file_content" }}

{{ range .Content }}{{ . }}{{ end }}
+{{- end -}} +{{- end -}} diff --git a/modules/cabana/backendscreens/controllers/mailtemplates/_info.htm b/modules/cabana/backendscreens/controllers/mailtemplates/_info.htm new file mode 100644 index 00000000..6dadb3af --- /dev/null +++ b/modules/cabana/backendscreens/controllers/mailtemplates/_info.htm @@ -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 }}

{{ .Description }}

{{ end -}} +{{- if .File }}

{{ range .File }}{{ if .Code }}{{ .Text }}{{ else }}{{ .Text }}{{ end }}{{ end }}

{{ end -}} +{{- if .CustomCode }}

{{ trans "backend::lang.mail.info_custom_layout" }} {{ .CustomCode }}

{{ end -}} +{{- if .Status }}

{{ trans .Status }}

{{ end -}} +{{- if .Template }}{{ if .Variables }}

{{ trans "backend::lang.mail.info_variables" }} {{ range $i, $name := .Variables }}{{ if $i }}, {{ end }}{{ $name }}{{ end }}

{{ else }}

{{ trans "backend::lang.mail.info_no_samples" }}

{{ end }}{{ end -}} +{{- if .Usage }}

{{ trans "backend::lang.mail.info_partial_usage" }} {{ .Usage }}

{{ end -}} +{{- if .Outdated }}

{{ trans "backend::lang.mail.drift_title" }}

{{ trans "backend::lang.mail.drift_text" }}

{{ end -}} +{{- end -}} diff --git a/modules/cabana/backendscreens/controllers/mailtemplates/config_filter.yaml b/modules/cabana/backendscreens/controllers/mailtemplates/config_filter.yaml new file mode 100644 index 00000000..8ae0d0cf --- /dev/null +++ b/modules/cabana/backendscreens/controllers/mailtemplates/config_filter.yaml @@ -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 diff --git a/modules/cabana/backendscreens/controllers/mailtemplates/config_form.yaml b/modules/cabana/backendscreens/controllers/mailtemplates/config_form.yaml index 03598078..c73c2b1f 100644 --- a/modules/cabana/backendscreens/controllers/mailtemplates/config_form.yaml +++ b/modules/cabana/backendscreens/controllers/mailtemplates/config_form.yaml @@ -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 diff --git a/modules/cabana/backendscreens/controllers/mailtemplates/config_list.yaml b/modules/cabana/backendscreens/controllers/mailtemplates/config_list.yaml index da8fc58b..4254cbbe 100644 --- a/modules/cabana/backendscreens/controllers/mailtemplates/config_list.yaml +++ b/modules/cabana/backendscreens/controllers/mailtemplates/config_list.yaml @@ -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 diff --git a/modules/cabana/backendscreens/models/maillayout/columns.yaml b/modules/cabana/backendscreens/models/maillayout/columns.yaml new file mode 100644 index 00000000..0b874517 --- /dev/null +++ b/modules/cabana/backendscreens/models/maillayout/columns.yaml @@ -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 diff --git a/modules/cabana/backendscreens/models/maillayout/fields.yaml b/modules/cabana/backendscreens/models/maillayout/fields.yaml new file mode 100644 index 00000000..1b1167b3 --- /dev/null +++ b/modules/cabana/backendscreens/models/maillayout/fields.yaml @@ -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 diff --git a/modules/cabana/backendscreens/models/mailpartial/columns.yaml b/modules/cabana/backendscreens/models/mailpartial/columns.yaml new file mode 100644 index 00000000..40ca4e52 --- /dev/null +++ b/modules/cabana/backendscreens/models/mailpartial/columns.yaml @@ -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 diff --git a/modules/cabana/backendscreens/models/mailpartial/fields.yaml b/modules/cabana/backendscreens/models/mailpartial/fields.yaml new file mode 100644 index 00000000..3b1bdc77 --- /dev/null +++ b/modules/cabana/backendscreens/models/mailpartial/fields.yaml @@ -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 diff --git a/modules/cabana/backendscreens/models/mailtemplate/fields.yaml b/modules/cabana/backendscreens/models/mailtemplate/fields.yaml index 8ff32cc5..9ea07a71 100644 --- a/modules/cabana/backendscreens/models/mailtemplate/fields.yaml +++ b/modules/cabana/backendscreens/models/mailtemplate/fields.yaml @@ -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 diff --git a/modules/cabana/crud.go b/modules/cabana/crud.go index 8387f649..aaf6a25b 100644 --- a/modules/cabana/crud.go +++ b/modules/cabana/crud.go @@ -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 }) diff --git a/modules/cabana/export_test.go b/modules/cabana/export_test.go index 8ab8214d..ae15cefb 100644 --- a/modules/cabana/export_test.go +++ b/modules/cabana/export_test.go @@ -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, "|") +} diff --git a/modules/cabana/extension.go b/modules/cabana/extension.go index 22adb86c..07a23a6c 100644 --- a/modules/cabana/extension.go +++ b/modules/cabana/extension.go @@ -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 { diff --git a/modules/cabana/list_schema_test.go b/modules/cabana/list_schema_test.go index 55f04e4f..e4c2e917 100644 --- a/modules/cabana/list_schema_test.go +++ b/modules/cabana/list_schema_test.go @@ -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") diff --git a/modules/cabana/mail_admin.go b/modules/cabana/mail_admin.go index 08fb9c96..f3287fc6 100644 --- a/modules/cabana/mail_admin.go +++ b/modules/cabana/mail_admin.go @@ -4,6 +4,9 @@ import ( "context" "errors" "fmt" + "regexp" + "sort" + "strconv" "strings" "sync" "sync/atomic" @@ -15,6 +18,7 @@ import ( "git.golem15.com/golem15/summercms/modules/postcard" "git.golem15.com/golem15/summercms/modules/towel" "gorm.io/gorm" + "gorm.io/gorm/clause" ) // mailLang prefixes the phrase keys of the mail screens. @@ -40,7 +44,7 @@ func mailPermissions() []pact.Permission { } func (m *mailScreens) controllers() []pact.AdminController { - return []pact.AdminController{mailTemplatesAdmin{mail: m}} + return []pact.AdminController{mailTemplatesAdmin{mail: m}, mailLayoutsAdmin{mail: m}, mailPartialsAdmin{mail: m}} } // settings are the Settings → Mail entries. @@ -56,6 +60,26 @@ func (m *mailScreens) settings() []pact.SettingsItem { Permissions: []string{PermissionManageMailTemplates}, Controller: MailTemplatesControllerID, }, + { + Code: "mail_layouts", + Label: mailLang + "layout.menu_label", + Description: mailLang + "layout.menu_description", + Category: mailCategory, + Icon: "layout-grid", + Order: 210, + Permissions: []string{PermissionManageMailLayouts}, + Controller: MailLayoutsControllerID, + }, + { + Code: "mail_partials", + Label: mailLang + "partial.menu_label", + Description: mailLang + "partial.menu_description", + Category: mailCategory, + Icon: "puzzle", + Order: 220, + Permissions: []string{PermissionManageMailLayouts}, + Controller: MailPartialsControllerID, + }, } } @@ -248,6 +272,25 @@ type MailTemplate struct { func (MailTemplate) TableName() string { return postcard.TemplatesTable } +// FilterScopes lists the scopes of the templates list filters. +func (MailTemplate) FilterScopes() []string { return []string{mailFilterLocale, mailFilterStatus} } + +// FilterScope narrows the templates list: filterLocale keeps one locale +// (default: no locale suffix), filterStatus one status. +func (MailTemplate) FilterScope(name string, db *gorm.DB, value any) *gorm.DB { + if db == nil { + return db + } + text := strings.TrimSpace(fmt.Sprint(value)) + if name == mailFilterLocale { + if text == mailLocaleDefault { + return db.Where(postcard.TemplatesTable + ".locale IS NULL") + } + return db.Where(postcard.TemplatesTable+".locale = ?", text) + } + return mailStatusScope(db, name, postcard.TemplatesTable, text) +} + // Fillable lists the override columns a form writes: subject and body. The // layout is written through the layout relation field. func (MailTemplate) Fillable() []string { return []string{"subject", "body"} } @@ -300,6 +343,12 @@ var ( _ pact.FormBeforeUpdate = mailTemplatesAdmin{} _ pact.FormAfterUpdate = mailTemplatesAdmin{} _ pact.FormBeforeDelete = mailTemplatesAdmin{} + _ pact.ListRowStates = mailTemplatesAdmin{} + _ pact.FilterOptions = mailTemplatesAdmin{} + _ pact.HasAdminRecordActions = mailTemplatesAdmin{} + _ pact.AdminPartialData = mailTemplatesAdmin{} + _ recordDeletable = mailTemplatesAdmin{} + _ formFooterActions = mailTemplatesAdmin{} ) func (mailTemplatesAdmin) ID() string { return MailTemplatesControllerID } @@ -405,6 +454,92 @@ func (mailTemplatesAdmin) FormBeforeDelete(context.Context, any) error { return &ForbiddenError{Message: mailLang + "file_delete"} } +func (mailTemplatesAdmin) recordDeletable(any) bool { return false } + +func (mailTemplatesAdmin) formFooterActions() {} + +// ListRowStates marks a customized template, and one whose file changed +// since, outdated (D-07). +func (mailTemplatesAdmin) ListRowStates(_ context.Context, _ *gorm.DB, records []any) ([][]pact.RowState, error) { + out := make([][]pact.RowState, len(records)) + for i, record := range records { + t, err := asMailTemplate(record) + if err != nil { + return nil, err + } + out[i] = mailRowStates(true, t.IsCustom, t.BaseHash, t.FileHash) + } + return out, nil +} + +// FilterOptions serves the locale filter (Default plus every locale a +// catalog template carries) and the status filter. +func (c mailTemplatesAdmin) FilterOptions(scope string) []pact.Option { + switch scope { + case mailFilterStatus: + return mailStatusOptions() + case mailFilterLocale: + out := []pact.Option{{Value: mailLocaleDefault, Label: mailLang + "template.locale_default"}} + seen := map[string]bool{} + locales := c.mail.locales() + for _, f := range c.mail.catalog().Templates() { + if locale := postcard.TemplateLocale(f.Name, locales); locale != "" && !seen[locale] { + seen[locale] = true + out = append(out, pact.Option{Value: locale, Label: locale}) + } + } + return out + } + return nil +} + +// AdminRecordActions is Reset to file version on a customized template. +func (c mailTemplatesAdmin) AdminRecordActions() []pact.AdminRecordAction { + return []pact.AdminRecordAction{c.mail.resetAction(postcard.KindTemplate, PermissionManageMailTemplates, mailLang+"template.reset_confirm", + func(record any) (string, bool, error) { + t, err := asMailTemplate(record) + if err != nil { + return "", false, err + } + return t.Code, t.IsCustom, nil + })} +} + +// PartialData serves the form's info and file_version partials. +func (c mailTemplatesAdmin) PartialData(ctx context.Context, name string, record any) (any, error) { + t, _ := record.(*MailTemplate) + if t == nil || t.ID == 0 { + return mailEmptyView(name) + } + file, ok := c.mail.catalog().Template(t.Code) + switch name { + case mailPartialInfo: + view := mailInfoView{Template: true, Customized: t.IsCustom, Outdated: mailOutdated(t.IsCustom, t.BaseHash, t.FileHash)} + view.Status = mailStatusKey(t.IsCustom) + if ok { + view.Description = c.mail.message(ctx, mailLang+"info_description", map[string]string{"text": file.Description}) + view.File = c.mail.fileLine(ctx, t.Code, file.PluginID) + for key := range file.Samples { + view.Variables = append(view.Variables, key) + } + sort.Strings(view.Variables) + } + return view, nil + case mailPartialFileVersion: + if !ok { + return mailFileVersionView{}, nil + } + layout, err := c.mail.layoutCodeRead(ctx, t.LayoutID) + if err != nil { + return nil, err + } + return mailFileVersion(t.IsCustom, + postcard.FormatTemplate(file.Subject, file.Layout, file.Body), + postcard.FormatTemplate(t.Subject, layout, t.Body), file.Source), nil + } + return nil, fmt.Errorf("cabana: mail templates: unknown partial %q", name) +} + // FormBeforeUpdate marks the row customized and stamps it with the hash of // the file it is based on, which is what later shows a changed file (D-07). func (c mailTemplatesAdmin) FormBeforeUpdate(_ context.Context, model any) error { @@ -464,12 +599,845 @@ func (m *mailScreens) layoutCode(ctx context.Context, id *uint) (string, error) 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, "::") +// layoutCodeRead is layoutCode for display: "" when the row is gone. +func (m *mailScreens) layoutCodeRead(ctx context.Context, id *uint) (string, error) { + code, err := m.layoutCode(ctx, id) + var invalid *ValidationError + if errors.As(err, &invalid) { + return "", nil + } + return code, err +} + +// recordDeletable is implemented by the mail controllers, which decide per +// record whether the form offers Delete; the show response then carries +// meta.deletable. Other controllers do not implement it and send no key. +type recordDeletable interface { + recordDeletable(record any) bool +} + +// formFooterActions marks a controller whose config_form.yaml declares +// recordActions without a preview block: the admin offers them in the +// update form's footer instead. Only the mail controllers implement it. +type formFooterActions interface { + formFooterActions() +} + +// The mail list filter scopes and values. +const ( + mailFilterLocale = "filterLocale" + mailFilterStatus = "filterStatus" + mailLocaleDefault = "default" + + mailStatusCustomized = "customized" + mailStatusNotCustomized = "not_customized" + mailStatusOutdated = "outdated" +) + +// mailStatusOptions are the status filter's choices. +func mailStatusOptions() []pact.Option { + return []pact.Option{ + {Value: mailStatusCustomized, Label: mailLang + "filter_customized"}, + {Value: mailStatusNotCustomized, Label: mailLang + "filter_not_customized"}, + {Value: mailStatusOutdated, Label: mailLang + "filter_outdated"}, + } +} + +// mailStatusScope narrows a mail list on table to one status: customized +// (a file-backed row with an override), not customized, or outdated (an +// override whose file changed since). Any other scope matches nothing. +func mailStatusScope(db *gorm.DB, name, table, value string) *gorm.DB { + if name != mailFilterStatus { + return db.Where("1 = 0") + } + switch value { + case mailStatusCustomized: + return db.Where(table + ".is_custom AND " + table + ".source IS NOT NULL") + case mailStatusNotCustomized: + return db.Where("NOT " + table + ".is_custom") + case mailStatusOutdated: + return db.Where(table + ".is_custom AND " + table + ".source IS NOT NULL AND " + table + ".base_hash IS DISTINCT FROM " + table + ".file_hash") + } + return db +} + +// mailOutdated reports an override whose file changed after it was saved. +func mailOutdated(custom bool, base, file *string) bool { + if !custom { + return false + } + if base == nil || file == nil { + return base != file + } + return *base != *file +} + +// mailRowStates are a file-backed row's states: customized while it holds +// an override, and outdated as well when its file changed since. +func mailRowStates(fileBacked, custom bool, base, file *string) []pact.RowState { + if !fileBacked || !custom { + return nil + } + if mailOutdated(custom, base, file) { + return []pact.RowState{pact.RowStateCustomized, pact.RowStateOutdated} + } + return []pact.RowState{pact.RowStateCustomized} +} + +// mailStatusKey is the info partial's status line. +func mailStatusKey(custom bool) string { + if custom { + return mailLang + "info_customized" + } + return mailLang + "info_not_customized" +} + +// resetAction is Reset to file version for kind: offered on a file-backed +// row that holds an override (row reports the code and whether it applies), +// it returns the row to its file through postcard.ResetOverride inside the +// action's transaction. +func (m *mailScreens) resetAction(kind postcard.Kind, permission, confirm string, row func(record any) (string, bool, error)) pact.AdminRecordAction { + return pact.AdminRecordAction{ + Name: "reset", + Label: mailLang + "reset", + Confirm: confirm, + Permissions: []string{permission}, + Danger: true, + Applies: func(_ context.Context, record any) (bool, error) { + _, applies, err := row(record) + return applies, err + }, + Run: func(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) { + code, applies, err := row(in.Record) + if err != nil { + return pact.AdminRecordActionResult{}, err + } + if !applies { + return pact.AdminRecordActionResult{}, &ForbiddenError{Message: mailLang + "reset_unavailable"} + } + tx, ok := TxFromContext(ctx) + if !ok { + return pact.AdminRecordActionResult{}, errors.New("cabana: mail: a reset needs its transaction") + } + if err := postcard.ResetOverride(ctx, tx.Session(&gorm.Session{NewDB: true}), m.catalog(), kind, code); err != nil { + return pact.AdminRecordActionResult{}, err + } + return pact.AdminRecordActionResult{Message: mailLang + "reset_done"}, nil + }, + } +} + +// stamp marks a file-backed row customized against the file hash. +func stamp(custom *bool, base, file **string, at **time.Time, hash string) { + now := time.Now().UTC() + *custom = true + value := hash + *base = &value + current := hash + *file = ¤t + *at = &now +} + +// MailLayout methods: the layouts screen's form, rules and filter. + +// Fillable lists the columns the layout form writes. code is written only +// when a custom layout is created (its field's context is create). +func (MailLayout) Fillable() []string { + return []string{"name", "code", "content_html", "content_text", "content_css"} +} + +// Rules require a name and a code. +func (MailLayout) Rules() map[string]string { + return map[string]string{"name": "required|max:255", "code": "required|max:255"} +} + +// FilterScopes lists the layouts list filter scope. +func (MailLayout) FilterScopes() []string { return []string{mailFilterStatus} } + +// FilterScope narrows the layouts list to one status. +func (MailLayout) FilterScope(name string, db *gorm.DB, value any) *gorm.DB { + if db == nil { + return db + } + return mailStatusScope(db, name, postcard.LayoutsTable, strings.TrimSpace(fmt.Sprint(value))) +} + +// mailLayoutsAdmin is the Mail layouts screen (summercms.cabana.maillayouts): +// every file layout, which can be customized and reset, and the custom +// layouts that exist only in the database, which can be created and +// deleted. Every route needs system.manage_mail_layouts. +type mailLayoutsAdmin struct { + mail *mailScreens +} + +var ( + _ pact.AdminController = mailLayoutsAdmin{} + _ pact.AdminPermissioned = mailLayoutsAdmin{} + _ pact.AdminRecordSource = mailLayoutsAdmin{} + _ pact.FormRecordTitle = mailLayoutsAdmin{} + _ pact.ListExtendQuery = mailLayoutsAdmin{} + _ pact.ListExtendRecords = mailLayoutsAdmin{} + _ pact.FormExtendQuery = mailLayoutsAdmin{} + _ pact.FormBeforeCreate = mailLayoutsAdmin{} + _ pact.FormAfterCreate = mailLayoutsAdmin{} + _ pact.FormBeforeUpdate = mailLayoutsAdmin{} + _ pact.FormAfterUpdate = mailLayoutsAdmin{} + _ pact.FormBeforeDelete = mailLayoutsAdmin{} + _ pact.ListRowStates = mailLayoutsAdmin{} + _ pact.FilterOptions = mailLayoutsAdmin{} + _ pact.HasAdminRecordActions = mailLayoutsAdmin{} + _ pact.AdminPartialData = mailLayoutsAdmin{} + _ recordDeletable = mailLayoutsAdmin{} + _ formFooterActions = mailLayoutsAdmin{} +) + +func (mailLayoutsAdmin) ID() string { return MailLayoutsControllerID } + +func (mailLayoutsAdmin) ModelName() string { return `System\Models\MailLayout` } + +func (mailLayoutsAdmin) ConfigDir() string { return "controllers/maillayouts" } + +func (mailLayoutsAdmin) RequiredPermissions() []string { + return []string{PermissionManageMailLayouts} +} + +func (mailLayoutsAdmin) NewRecord() any { return &MailLayout{} } + +func (mailLayoutsAdmin) formFooterActions() {} + +func asMailLayout(model any) (*MailLayout, error) { + l, ok := model.(*MailLayout) + if !ok || l == nil { + return nil, errors.New("cabana: mail layouts: record is not a mail layout") + } + return l, nil +} + +// recordDeletable: only a custom layout can be deleted. +func (mailLayoutsAdmin) recordDeletable(record any) bool { + l, err := asMailLayout(record) + return err == nil && l.Source == nil +} + +// FormRecordTitle names a layout by its name. +func (mailLayoutsAdmin) FormRecordTitle(_ context.Context, _ *gorm.DB, record any) (string, error) { + l, err := asMailLayout(record) + if err != nil { + return "", err + } + return l.Name, nil +} + +// mailDefaultLayout is postcard's built-in default layout, listed first. +const mailDefaultLayout = "postcard::mail.layouts.default" + +// ListExtendQuery retries the index sync, lists the layouts this process can +// send and puts postcard's default layout first. +func (c mailLayoutsAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB { + c.mail.ensureSynced(ctx) + // A raw column: an OrderBy expression would be dropped when the list's + // own sort is merged into the clause. The SQL is a constant. + return c.mail.scopeLayouts(db).Order(clause.OrderByColumn{Column: clause.Column{ + Name: "CASE WHEN " + postcard.LayoutsTable + ".code = '" + mailDefaultLayout + "' THEN 0 ELSE 1 END", Raw: true, + }}) +} + +// FormExtendQuery applies the catalog scope to every record lookup. +func (c mailLayoutsAdmin) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB { + return c.mail.scopeLayouts(db) +} + +// ListExtendRecords shows a custom layout's source as Custom. +func (c mailLayoutsAdmin) ListExtendRecords(ctx context.Context, _ *gorm.DB, records []any) error { + label := c.mail.message(ctx, mailLang+"source_custom", nil) + for _, record := range records { + l, err := asMailLayout(record) + if err != nil { + return err + } + if l.Source == nil { + value := label + l.Source = &value + } + } + return nil +} + +// ListRowStates marks customized file layouts (and outdated ones); custom +// layouts carry no state. +func (mailLayoutsAdmin) ListRowStates(_ context.Context, _ *gorm.DB, records []any) ([][]pact.RowState, error) { + out := make([][]pact.RowState, len(records)) + for i, record := range records { + l, err := asMailLayout(record) + if err != nil { + return nil, err + } + out[i] = mailRowStates(l.Source != nil, l.IsCustom, l.BaseHash, l.FileHash) + } + return out, nil +} + +// FilterOptions serves the status filter. +func (mailLayoutsAdmin) FilterOptions(scope string) []pact.Option { + if scope == mailFilterStatus { + return mailStatusOptions() + } + return nil +} + +// mailLayoutCode is the format of a custom layout's code. +var mailLayoutCode = regexp.MustCompile(`^[a-z0-9-]+$`) + +// FormBeforeCreate creates a custom layout: the code must be lowercase +// letters, digits and dashes and free, and the row has no source. +func (c mailLayoutsAdmin) FormBeforeCreate(ctx context.Context, model any) error { + l, err := asMailLayout(model) + if err != nil { + return err + } + l.Code = strings.TrimSpace(l.Code) + if !mailLayoutCode.MatchString(l.Code) { + return &ValidationError{Details: map[string]any{"code": []string{c.mail.message(ctx, mailLang+"layout.code_format", nil)}}} + } + db := c.mail.requestDB(ctx) + if db == nil { + return errors.New("cabana: mail layouts: database handle is missing") + } + var taken int64 + if err := db.Table(postcard.LayoutsTable).Where("code = ?", l.Code).Count(&taken).Error; err != nil { + return err + } + if taken > 0 { + return &ValidationError{Details: map[string]any{"code": []string{c.mail.message(ctx, mailLang+"layout.code_taken", nil)}}} + } + now := time.Now().UTC() + l.Source = nil + l.IsCustom = true + l.FileHash, l.BaseHash = nil, nil + l.CustomizedAt = &now + return nil +} + +// FormAfterCreate validates the new layout through postcard. +func (c mailLayoutsAdmin) FormAfterCreate(ctx context.Context, model any) error { + return c.validate(ctx, model) +} + +// FormBeforeUpdate stamps a file layout customized against its file (its +// name stays the file's: the index sync owns it); a custom layout records +// when it was saved. +func (c mailLayoutsAdmin) FormBeforeUpdate(_ context.Context, model any) error { + l, err := asMailLayout(model) + if err != nil { + return err + } + if l.Source == nil { + now := time.Now().UTC() + l.IsCustom = true + l.CustomizedAt = &now + return nil + } + file, ok := c.mail.catalog().Layout(l.Code) if !ok { - return code, "" + return &ForbiddenError{Message: mailLang + "file_missing"} + } + l.Name = mailRowName(file.Title, file.Name) + stamp(&l.IsCustom, &l.BaseHash, &l.FileHash, &l.CustomizedAt, file.Hash) + return nil +} + +// FormAfterUpdate validates the saved layout through postcard (D-13). +func (c mailLayoutsAdmin) FormAfterUpdate(ctx context.Context, model any) error { + return c.validate(ctx, model) +} + +func (c mailLayoutsAdmin) validate(ctx context.Context, model any) error { + l, err := asMailLayout(model) + if err != nil { + return err + } + draft := postcard.Draft{Kind: postcard.KindLayout, Name: l.Code, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS} + if de := c.mail.editor.Validate(ctx, draft); de != nil { + return c.mail.draftFailure(ctx, de) + } + return nil +} + +// FormBeforeDelete refuses a file layout and a custom layout that templates +// still use, naming the layout and how many (D-08). The foreign key's ON +// DELETE RESTRICT stays the backstop. +func (c mailLayoutsAdmin) FormBeforeDelete(ctx context.Context, model any) error { + l, err := asMailLayout(model) + if err != nil { + return err + } + if l.Source != nil { + return &ForbiddenError{Message: mailLang + "file_delete"} + } + db := c.mail.requestDB(ctx) + if db == nil { + return errors.New("cabana: mail layouts: database handle is missing") + } + var users int64 + if err := db.Table(postcard.TemplatesTable).Where("layout_id = ?", l.ID).Count(&users).Error; err != nil { + return err + } + if users == 0 { + return nil + } + return &ForbiddenError{Message: c.mail.choice(ctx, mailLang+"layout.delete_in_use", users, map[string]string{"name": l.Name, "count": strconv.FormatInt(users, 10)})} +} + +// AdminRecordActions is Reset to file version on a customized file layout. +func (c mailLayoutsAdmin) AdminRecordActions() []pact.AdminRecordAction { + return []pact.AdminRecordAction{c.mail.resetAction(postcard.KindLayout, PermissionManageMailLayouts, mailLang+"layout.reset_confirm", + func(record any) (string, bool, error) { + l, err := asMailLayout(record) + if err != nil { + return "", false, err + } + return l.Code, l.Source != nil && l.IsCustom, nil + })} +} + +// PartialData serves the form's info and file_version partials. +func (c mailLayoutsAdmin) PartialData(ctx context.Context, name string, record any) (any, error) { + l, _ := record.(*MailLayout) + if l == nil || l.ID == 0 { + return mailEmptyView(name) + } + if l.Source == nil { + switch name { + case mailPartialInfo: + return mailInfoView{CustomCode: l.Code}, nil + case mailPartialFileVersion: + return mailFileVersionView{CustomLayout: true}, nil + } + return nil, fmt.Errorf("cabana: mail layouts: unknown partial %q", name) + } + file, ok := c.mail.catalog().Layout(l.Code) + switch name { + case mailPartialInfo: + view := mailInfoView{Customized: l.IsCustom, Status: mailStatusKey(l.IsCustom), Outdated: mailOutdated(l.IsCustom, l.BaseHash, l.FileHash)} + if ok { + view.File = c.mail.fileLine(ctx, l.Code, file.PluginID) + } + return view, nil + case mailPartialFileVersion: + if !ok { + return mailFileVersionView{}, nil + } + return mailFileVersion(l.IsCustom, + postcard.FormatLayout(mailRowName(file.Title, file.Name), file.Text, file.HTML, ""), + postcard.FormatLayout(l.Name, l.ContentText, l.ContentHTML, l.ContentCSS), file.Source), nil + } + return nil, fmt.Errorf("cabana: mail layouts: unknown partial %q", name) +} + +// mailRowName is the name of a file layout's or partial's row: the file +// header's name, else the full name (as postcard.SyncIndex writes it). +func mailRowName(title, full string) string { + if title != "" { + return title + } + return full +} + +// MailPartial is a row of postcard's partials table: one per file partial, +// its content columns holding the override while it is customized. +type MailPartial struct { + ID uint `gorm:"column:id;primaryKey"` + Code string `gorm:"column:code"` + Source string `gorm:"column:source"` + Name string `gorm:"column:name"` + ContentHTML string `gorm:"column:content_html"` + ContentText string `gorm:"column:content_text"` + IsCustom bool `gorm:"column:is_custom"` + FileHash *string `gorm:"column:file_hash"` + BaseHash *string `gorm:"column:base_hash"` + CustomizedAt *time.Time `gorm:"column:customized_at"` + CreatedAt time.Time `gorm:"column:created_at"` + UpdatedAt time.Time `gorm:"column:updated_at"` +} + +func (MailPartial) TableName() string { return postcard.PartialsTable } + +// Fillable lists the columns the partial form writes. +func (MailPartial) Fillable() []string { return []string{"content_html", "content_text"} } + +// Rules has no base rule: postcard's draft check validates a partial. +func (MailPartial) Rules() map[string]string { return map[string]string{} } + +// FilterScopes lists the partials list filter scope. +func (MailPartial) FilterScopes() []string { return []string{mailFilterStatus} } + +// FilterScope narrows the partials list to one status. +func (MailPartial) FilterScope(name string, db *gorm.DB, value any) *gorm.DB { + if db == nil { + return db + } + return mailStatusScope(db, name, postcard.PartialsTable, strings.TrimSpace(fmt.Sprint(value))) +} + +// mailPartialsAdmin is the Mail partials screen +// (summercms.cabana.mailpartials): every file partial, customized and reset +// here, never created or deleted. Every route needs +// system.manage_mail_layouts. +type mailPartialsAdmin struct { + mail *mailScreens +} + +var ( + _ pact.AdminController = mailPartialsAdmin{} + _ pact.AdminPermissioned = mailPartialsAdmin{} + _ pact.AdminRecordSource = mailPartialsAdmin{} + _ pact.FormRecordTitle = mailPartialsAdmin{} + _ pact.ListExtendQuery = mailPartialsAdmin{} + _ pact.FormExtendQuery = mailPartialsAdmin{} + _ pact.FormBeforeCreate = mailPartialsAdmin{} + _ pact.FormBeforeUpdate = mailPartialsAdmin{} + _ pact.FormAfterUpdate = mailPartialsAdmin{} + _ pact.FormBeforeDelete = mailPartialsAdmin{} + _ pact.ListRowStates = mailPartialsAdmin{} + _ pact.FilterOptions = mailPartialsAdmin{} + _ pact.HasAdminRecordActions = mailPartialsAdmin{} + _ pact.AdminPartialData = mailPartialsAdmin{} + _ recordDeletable = mailPartialsAdmin{} + _ formFooterActions = mailPartialsAdmin{} +) + +func (mailPartialsAdmin) ID() string { return MailPartialsControllerID } + +func (mailPartialsAdmin) ModelName() string { return `System\Models\MailPartial` } + +func (mailPartialsAdmin) ConfigDir() string { return "controllers/mailpartials" } + +func (mailPartialsAdmin) RequiredPermissions() []string { + return []string{PermissionManageMailLayouts} +} + +func (mailPartialsAdmin) NewRecord() any { return &MailPartial{} } + +func (mailPartialsAdmin) recordDeletable(any) bool { return false } + +func (mailPartialsAdmin) formFooterActions() {} + +func asMailPartial(model any) (*MailPartial, error) { + p, ok := model.(*MailPartial) + if !ok || p == nil { + return nil, errors.New("cabana: mail partials: record is not a mail partial") + } + return p, nil +} + +// FormRecordTitle names a partial by its code. +func (mailPartialsAdmin) FormRecordTitle(_ context.Context, _ *gorm.DB, record any) (string, error) { + p, err := asMailPartial(record) + if err != nil { + return "", err + } + return p.Code, nil +} + +// scopePartials hides the rows of partials this process's catalog does not +// hold. +func (c mailPartialsAdmin) scopePartials(db *gorm.DB) *gorm.DB { + if db == nil { + return db + } + files := c.mail.catalog().Partials() + codes := make([]string, 0, len(files)) + for _, f := range files { + codes = append(codes, f.Name) + } + return db.Where(postcard.PartialsTable+".code IN ?", nonEmpty(codes)) +} + +// ListExtendQuery retries the index sync and lists the catalog's partials. +func (c mailPartialsAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB { + c.mail.ensureSynced(ctx) + return c.scopePartials(db) +} + +// FormExtendQuery applies the catalog scope to every record lookup. +func (c mailPartialsAdmin) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB { + return c.scopePartials(db) +} + +// ListRowStates marks customized partials (and outdated ones). +func (mailPartialsAdmin) ListRowStates(_ context.Context, _ *gorm.DB, records []any) ([][]pact.RowState, error) { + out := make([][]pact.RowState, len(records)) + for i, record := range records { + p, err := asMailPartial(record) + if err != nil { + return nil, err + } + out[i] = mailRowStates(true, p.IsCustom, p.BaseHash, p.FileHash) + } + return out, nil +} + +// FilterOptions serves the status filter. +func (mailPartialsAdmin) FilterOptions(scope string) []pact.Option { + if scope == mailFilterStatus { + return mailStatusOptions() + } + return nil +} + +// FormBeforeCreate refuses: partials come from files. +func (mailPartialsAdmin) FormBeforeCreate(context.Context, any) error { + return &ForbiddenError{Message: mailLang + "partial.no_create"} +} + +// FormBeforeDelete refuses: a partial's row belongs to its file. +func (mailPartialsAdmin) FormBeforeDelete(context.Context, any) error { + return &ForbiddenError{Message: mailLang + "file_delete"} +} + +// FormBeforeUpdate stamps the partial customized against its file. +func (c mailPartialsAdmin) FormBeforeUpdate(_ context.Context, model any) error { + p, err := asMailPartial(model) + if err != nil { + return err + } + file, ok := c.mail.catalog().Partial(p.Code) + if !ok { + return &ForbiddenError{Message: mailLang + "file_missing"} + } + stamp(&p.IsCustom, &p.BaseHash, &p.FileHash, &p.CustomizedAt, file.Hash) + return nil +} + +// FormAfterUpdate validates the saved partial through postcard (D-13). +func (c mailPartialsAdmin) FormAfterUpdate(ctx context.Context, model any) error { + p, err := asMailPartial(model) + if err != nil { + return err + } + draft := postcard.Draft{Kind: postcard.KindPartial, Name: p.Code, HTML: p.ContentHTML, Text: p.ContentText} + if de := c.mail.editor.Validate(ctx, draft); de != nil { + return c.mail.draftFailure(ctx, de) + } + return nil +} + +// AdminRecordActions is Reset to file version on a customized partial. +func (c mailPartialsAdmin) AdminRecordActions() []pact.AdminRecordAction { + return []pact.AdminRecordAction{c.mail.resetAction(postcard.KindPartial, PermissionManageMailLayouts, mailLang+"partial.reset_confirm", + func(record any) (string, bool, error) { + p, err := asMailPartial(record) + if err != nil { + return "", false, err + } + return p.Code, p.IsCustom, nil + })} +} + +// PartialData serves the form's info and file_version partials. +func (c mailPartialsAdmin) PartialData(ctx context.Context, name string, record any) (any, error) { + p, _ := record.(*MailPartial) + if p == nil || p.ID == 0 { + return mailEmptyView(name) + } + file, ok := c.mail.catalog().Partial(p.Code) + switch name { + case mailPartialInfo: + view := mailInfoView{Customized: p.IsCustom, Status: mailStatusKey(p.IsCustom), Outdated: mailOutdated(p.IsCustom, p.BaseHash, p.FileHash)} + if ok { + view.File = c.mail.fileLine(ctx, p.Code, file.PluginID) + view.Usage = partialUsage(p.Code, file.HTML+"\n"+file.Text) + } + return view, nil + case mailPartialFileVersion: + if !ok { + return mailFileVersionView{}, nil + } + return mailFileVersion(p.IsCustom, + postcard.FormatPartial(mailRowName(file.Title, file.Name), file.Text, file.HTML), + postcard.FormatPartial(p.Name, p.ContentText, p.ContentHTML), file.Source), nil + } + return nil, fmt.Errorf("cabana: mail partials: unknown partial %q", name) +} + +// The form partials of the mail screens (controllers/mail*/_info.htm and +// _file_version.htm). +const ( + mailPartialInfo = "info" + mailPartialFileVersion = "file_version" +) + +// mailInfoView is the view model of _info.htm, the lines at the top of a +// mail form: the template's description, the file it comes from (or a +// custom layout's code), the status, the template's sample variables, a +// partial's call, and the drift callout. +type mailInfoView struct { + Template bool + Description string + File []mailTextPart + CustomCode string + Customized bool + Status string + Variables []string + Usage string + Outdated bool +} + +// mailTextPart is a piece of a translated line; Code pieces are shown as +// code. +type mailTextPart struct { + Text string + Code bool +} + +// mailFileVersionView is the view model of _file_version.htm: the line diff +// of the override against the file and the file's own text. A custom layout +// has no file. +type mailFileVersionView struct { + Show bool + CustomLayout bool + Customized bool + Identical bool + Diff []mailDiffRow + Content []string +} + +// mailDiffRow is one rendered diff line: its class and its prefixed text. +type mailDiffRow struct { + Class string + Text string +} + +// mailEmptyView is the view of a partial without a record (a create form). +func mailEmptyView(name string) (any, error) { + switch name { + case mailPartialInfo: + return mailInfoView{}, nil + case mailPartialFileVersion: + return mailFileVersionView{}, nil + } + return nil, fmt.Errorf("cabana: mail: unknown partial %q", name) +} + +// diffContext is the number of unchanged lines kept around each change. +const diffContext = 3 + +// mailFileVersion compares the serialized override (mine) with the +// serialized file (theirs); source is the file's own text. +func mailFileVersion(custom bool, theirs, mine, source string) mailFileVersionView { + view := mailFileVersionView{Show: true, Customized: custom, Content: splitLines(source)} + if !custom { + return view + } + if theirs == mine { + view.Identical = true + return view + } + for _, line := range lineDiff(splitLines(theirs), splitLines(mine), diffContext) { + switch line.Kind { + case diffAdd: + view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__add", Text: "+ " + line.Text}) + case diffDel: + view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__del", Text: "− " + line.Text}) + case diffGap: + view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__ctx", Text: " …"}) + default: + view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__ctx", Text: " " + line.Text}) + } + } + return view +} + +// splitLines splits text into lines; a trailing newline adds no empty line, +// and an empty line is a space so that it keeps its height. +func splitLines(text string) []string { + text = strings.TrimSuffix(strings.ReplaceAll(text, "\r\n", "\n"), "\n") + if text == "" { + return nil + } + lines := strings.Split(text, "\n") + for i, line := range lines { + if line == "" { + lines[i] = " " + } + } + return lines +} + +// fileLine is the translated "File: :path in :plugin" line, with the path +// and the plugin as code pieces. +func (m *mailScreens) fileLine(ctx context.Context, code, plugin string) []mailTextPart { + const pathMark, pluginMark = "\x00path\x00", "\x00plugin\x00" + text := m.message(ctx, mailLang+"info_file", map[string]string{"path": pathMark, "plugin": pluginMark}) + path := mailFilePath(code) + var out []mailTextPart + for text != "" { + i := strings.IndexByte(text, 0) + if i < 0 { + out = append(out, mailTextPart{Text: text}) + break + } + if i > 0 { + out = append(out, mailTextPart{Text: text[:i]}) + } + rest := text[i:] + switch { + case strings.HasPrefix(rest, pathMark): + out = append(out, mailTextPart{Text: path, Code: true}) + text = rest[len(pathMark):] + case strings.HasPrefix(rest, pluginMark): + out = append(out, mailTextPart{Text: plugin, Code: true}) + text = rest[len(pluginMark):] + default: + out = append(out, mailTextPart{Text: rest[1:]}) + text = "" + } + } + return out +} + +// mailFilePath is the file of a mail name inside its plugin: +// acme.blog::mail.layouts.blog is views/mail/layouts/blog.htm. +func mailFilePath(code string) string { + _, rest, ok := strings.Cut(code, "::") + if !ok { + return code } rest = strings.TrimPrefix(rest, "mail.") - return fmt.Sprintf("views/mail/%s.htm", strings.ReplaceAll(rest, ".", "/")), plugin + return "views/mail/" + strings.ReplaceAll(rest, ".", "/") + ".htm" +} + +// builtinPartialPrefix is the name prefix of postcard's own partials, which +// a call names by their bare name. +const builtinPartialPrefix = "postcard::mail.partials." + +// partialArg matches a top-level variable (.name) inside a template action. +var ( + partialAction = regexp.MustCompile(`\{\{-?(.*?)-?\}\}`) + partialArg = regexp.MustCompile(`(?:^|[\s(|])\.([A-Za-z_][A-Za-z0-9_]*)`) +) + +// partialUsage is the call of a partial in a body or a layout: its bare +// name for a built-in, else its full name, then a key and a value for every +// variable its sections read. +func partialUsage(code, sections string) string { + name := strings.TrimPrefix(code, builtinPartialPrefix) + seen := map[string]bool{} + var keys []string + for _, action := range partialAction.FindAllStringSubmatch(sections, -1) { + for _, arg := range partialArg.FindAllStringSubmatch(action[1], -1) { + if !seen[arg[1]] { + seen[arg[1]] = true + keys = append(keys, arg[1]) + } + } + } + sort.Strings(keys) + var b strings.Builder + b.WriteString(`{{ partial "` + name + `"`) + for _, key := range keys { + b.WriteString(` "` + key + `" .` + key) + } + b.WriteString(" }}") + return b.String() } diff --git a/modules/cabana/mail_diff.go b/modules/cabana/mail_diff.go new file mode 100644 index 00000000..cd45b78a --- /dev/null +++ b/modules/cabana/mail_diff.go @@ -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 +} diff --git a/modules/cabana/mail_screens_smoke_test.go b/modules/cabana/mail_screens_smoke_test.go index 243f4b47..9e8f64c8 100644 --- a/modules/cabana/mail_screens_smoke_test.go +++ b/modules/cabana/mail_screens_smoke_test.go @@ -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": "
no content
", "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": `
{{ .Content }}
`, "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": `
{{ .title
`, "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": `
{{ .title }}
`, "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. diff --git a/modules/cabana/messages.go b/modules/cabana/messages.go index 1021e7ec..bb3f74dd 100644 --- a/modules/cabana/messages.go +++ b/modules/cabana/messages.go @@ -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", diff --git a/modules/cabana/query.go b/modules/cabana/query.go index 01119c71..5e123bd1 100644 --- a/modules/cabana/query.go +++ b/modules/cabana/query.go @@ -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 diff --git a/modules/cabana/relation_field.go b/modules/cabana/relation_field.go index feb71be1..c0142a90 100644 --- a/modules/cabana/relation_field.go +++ b/modules/cabana/relation_field.go @@ -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 diff --git a/modules/phrasebook/backend/lang/en/lang.yaml b/modules/phrasebook/backend/lang/en/lang.yaml index 9b45723c..61985709 100644 --- a/modules/phrasebook/backend/lang/en/lang.yaml +++ b/modules/phrasebook/backend/lang/en/lang.yaml @@ -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." diff --git a/modules/phrasebook/backend/lang/pl/lang.yaml b/modules/phrasebook/backend/lang/pl/lang.yaml index 9bd386b0..6ce3a672 100644 --- a/modules/phrasebook/backend/lang/pl/lang.yaml +++ b/modules/phrasebook/backend/lang/pl/lang.yaml @@ -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ąć."