diff --git a/admin/openapi/admin.json b/admin/openapi/admin.json index 1aafa031..c58aac21 100644 --- a/admin/openapi/admin.json +++ b/admin/openapi/admin.json @@ -403,6 +403,73 @@ ], "type": "object" }, + "cabana.AdminMailImage": { + "properties": { + "fileName": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "thumbUrl": { + "type": "string" + }, + "title": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": [ + "fileName", + "id", + "title", + "url" + ], + "type": "object" + }, + "cabana.AdminMailImagesMeta": { + "properties": { + "canUpload": { + "type": "boolean" + }, + "page": { + "type": "integer" + }, + "perPage": { + "type": "integer" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "canUpload", + "page", + "perPage", + "total" + ], + "type": "object" + }, + "cabana.AdminMailImagesResponse": { + "properties": { + "data": { + "items": { + "$ref": "#/components/schemas/cabana.AdminMailImage" + }, + "type": "array" + }, + "meta": { + "$ref": "#/components/schemas/cabana.AdminMailImagesMeta" + } + }, + "required": [ + "data", + "meta" + ], + "type": "object" + }, "cabana.AdminMarkdownPreviewRequest": { "properties": { "markdown": { @@ -981,6 +1048,21 @@ ], "type": "object" }, + "cabana.Envelope-cabana_AdminMailImage": { + "properties": { + "data": { + "$ref": "#/components/schemas/cabana.AdminMailImage" + }, + "meta": { + "$ref": "#/components/schemas/cabana.SuccessMeta" + } + }, + "required": [ + "data", + "meta" + ], + "type": "object" + }, "cabana.Envelope-cabana_AdminMarkdownPreviewResult": { "properties": { "data": { @@ -1570,6 +1652,14 @@ "label": { "type": "string" }, + "language": { + "description": "Language is the codeeditor language: html, css or text.", + "type": "string" + }, + "mailImages": { + "description": "MailImages, when true, shows the mail image insert control on a\nmarkdown or codeeditor field.", + "type": "boolean" + }, "max": { "description": "Max is a money field's column ceiling as a decimal string; a value\nabove it in absolute magnitude is a 422 money.too_large.", "type": "string" @@ -1604,7 +1694,7 @@ "type": "integer" }, "mode": { - "description": "Mode is the fileupload mode (image or file, default file), the\ndatepicker mode (date, datetime or time, default datetime), the\npermissioneditor mode (radio or checkbox) or the taglist mode (string,\nthe default, or array).", + "description": "Mode is the fileupload mode (image or file, default file), the\ndatepicker mode (date, datetime or time, default datetime), the\npermissioneditor mode (radio or checkbox), the taglist mode (string,\nthe default, or array), or the mailpreview mode (template, layout,\npartial or branding).", "type": "string" }, "multiple": { @@ -2154,6 +2244,14 @@ "recordCount": { "$ref": "#/components/schemas/cabana.MessageForms" }, + "rowStateCustomized": { + "allOf": [ + { + "$ref": "#/components/schemas/cabana.MessageForms" + } + ], + "description": "The customized and outdated row-state labels." + }, "rowStateDeleted": { "allOf": [ { @@ -2168,6 +2266,9 @@ "rowStateNegative": { "$ref": "#/components/schemas/cabana.MessageForms" }, + "rowStateOutdated": { + "$ref": "#/components/schemas/cabana.MessageForms" + }, "searchPrompt": { "$ref": "#/components/schemas/cabana.MessageForms" }, @@ -2184,9 +2285,11 @@ "emptySearch", "emptySearchHint", "recordCount", + "rowStateCustomized", "rowStateDeleted", "rowStateDisabled", "rowStateNegative", + "rowStateOutdated", "searchPrompt", "selected" ], @@ -2710,6 +2813,10 @@ }, "type": "array" }, + "deletable": { + "description": "Deletable tells the admin whether the record's form offers Delete. Only\nthe show response of a controller that decides it per record (the mail\nscreens: a custom layout can be deleted, a file-backed row cannot)\ncarries it; it is omitted otherwise, and Delete then shows as before.", + "type": "boolean" + }, "labels": { "additionalProperties": { "items": { @@ -4230,6 +4337,251 @@ ] } }, + "/mail/images": { + "get": { + "description": "Lists public mail library images with absolute URLs. Holders of either mail permission may list; meta.canUpload is true only for system.manage_mail_layouts. Without storage.uploads.public_url or app.url the route answers 409 with mail.images.no_public_url.", + "parameters": [ + { + "description": "Filename or title match", + "in": "query", + "name": "q", + "schema": { + "type": "string" + } + }, + { + "description": "Page (1-based)", + "in": "query", + "name": "page", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.AdminMailImagesResponse" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Conflict" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "List mail library images", + "tags": [ + "admin" + ] + }, + "post": { + "description": "Stores a multipart file part as a public library image and answers it with absolute URLs. Needs system.manage_mail_layouts. Without an absolute public URL base the route answers 409.", + "requestBody": { + "content": { + "multipart/form-data": { + "schema": { + "properties": { + "file": { + "description": "Image file", + "format": "binary", + "type": "string" + } + }, + "required": [ + "file" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMailImage" + } + } + }, + "description": "Created" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Upload a mail library image", + "tags": [ + "admin" + ] + } + }, + "/mail/images/{id}": { + "get": { + "description": "One library image by id with absolute URLs. An image outside the library is 404.", + "parameters": [ + { + "description": "Image id", + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMailImage" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Conflict" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Show one mail library image", + "tags": [ + "admin" + ] + } + }, "/markdown/preview": { "post": { "description": "Renders the markdown source through cabana.RenderMarkdown (goldmark without unsafe HTML) and answers the sanitized HTML. Output the renderer's gate refuses is a 422 on markdown. Any backend session may call it.", diff --git a/admin/src/api/schema.d.ts b/admin/src/api/schema.d.ts index 5a193141..2c4f16d1 100644 --- a/admin/src/api/schema.d.ts +++ b/admin/src/api/schema.d.ts @@ -1065,6 +1065,233 @@ export interface paths { patch?: never; trace?: never; }; + "/mail/images": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List mail library images + * @description Lists public mail library images with absolute URLs. Holders of either mail permission may list; meta.canUpload is true only for system.manage_mail_layouts. Without storage.uploads.public_url or app.url the route answers 409 with mail.images.no_public_url. + */ + get: { + parameters: { + query?: { + /** @description Filename or title match */ + q?: string; + /** @description Page (1-based) */ + page?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.AdminMailImagesResponse"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Conflict */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + put?: never; + /** + * Upload a mail library image + * @description Stores a multipart file part as a public library image and answers it with absolute URLs. Needs system.manage_mail_layouts. Without an absolute public URL base the route answers 409. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "multipart/form-data": { + /** + * Format: binary + * @description Image file + */ + file: string; + }; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMailImage"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Conflict */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Request Entity Too Large */ + 413: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/mail/images/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Show one mail library image + * @description One library image by id with absolute URLs. An image outside the library is 404. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Image id */ + id: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMailImage"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Conflict */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/markdown/preview": { parameters: { query?: never; @@ -5765,6 +5992,23 @@ export interface components { "cabana.AdminLogoutData": { status: string; }; + "cabana.AdminMailImage": { + fileName: string; + id: number; + thumbUrl?: string; + title: string; + url: string; + }; + "cabana.AdminMailImagesMeta": { + canUpload: boolean; + page: number; + perPage: number; + total: number; + }; + "cabana.AdminMailImagesResponse": { + data: components["schemas"]["cabana.AdminMailImage"][]; + meta: components["schemas"]["cabana.AdminMailImagesMeta"]; + }; "cabana.AdminMarkdownPreviewRequest": { markdown: string; }; @@ -5928,6 +6172,10 @@ export interface components { data: components["schemas"]["cabana.AdminLogoutData"]; meta: components["schemas"]["cabana.SuccessMeta"]; }; + "cabana.Envelope-cabana_AdminMailImage": { + data: components["schemas"]["cabana.AdminMailImage"]; + meta: components["schemas"]["cabana.SuccessMeta"]; + }; "cabana.Envelope-cabana_AdminMarkdownPreviewResult": { data: components["schemas"]["cabana.AdminMarkdownPreviewResult"]; meta: components["schemas"]["cabana.SuccessMeta"]; @@ -6125,6 +6373,13 @@ export interface components { /** @description ImageWidth and ImageHeight are the preview size of an image upload. */ imageWidth?: number; label?: string; + /** @description Language is the codeeditor language: html, css or text. */ + language?: string; + /** + * @description MailImages, when true, shows the mail image insert control on a + * markdown or codeeditor field. + */ + mailImages?: boolean; /** * @description Max is a money field's column ceiling as a decimal string; a value * above it in absolute magnitude is a 422 money.too_large. @@ -6151,8 +6406,9 @@ export interface components { /** * @description Mode is the fileupload mode (image or file, default file), the * datepicker mode (date, datetime or time, default datetime), the - * permissioneditor mode (radio or checkbox) or the taglist mode (string, - * the default, or array). + * permissioneditor mode (radio or checkbox), the taglist mode (string, + * the default, or array), or the mailpreview mode (template, layout, + * partial or branding). */ mode?: string; multiple?: boolean; @@ -6374,10 +6630,13 @@ export interface components { emptySearch: components["schemas"]["cabana.MessageForms"]; emptySearchHint: components["schemas"]["cabana.MessageForms"]; recordCount: components["schemas"]["cabana.MessageForms"]; + /** @description The customized and outdated row-state labels. */ + rowStateCustomized: components["schemas"]["cabana.MessageForms"]; /** @description The row-state badge labels (D-12). */ rowStateDeleted: components["schemas"]["cabana.MessageForms"]; rowStateDisabled: components["schemas"]["cabana.MessageForms"]; rowStateNegative: components["schemas"]["cabana.MessageForms"]; + rowStateOutdated: components["schemas"]["cabana.MessageForms"]; searchPrompt: components["schemas"]["cabana.MessageForms"]; selected: components["schemas"]["cabana.MessageForms"]; }; @@ -6540,6 +6799,13 @@ export interface components { }; "cabana.RecordMeta": { actions?: components["schemas"]["cabana.RecordAction"][]; + /** + * @description 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?: boolean; labels: { [key: string]: components["schemas"]["cabana.RelationOption"][]; }; diff --git a/docs/backend/forms.md b/docs/backend/forms.md index 522ea152..04d4b6d5 100644 --- a/docs/backend/forms.md +++ b/docs/backend/forms.md @@ -107,12 +107,16 @@ for _, f := range form.Fields { | `repeater` | A list of rows, each with its own small form, stored as JSON in one column; see [Repeater](#repeater). | | `money` | An exact decimal amount with a currency suffix, never a float and never rounded; see [Money](#money). | | `taglist` | A list of tags edited as chips, stored as a JSON array or as one separator-joined string; see [Taglist](#taglist). | +| `codeeditor` | A source editor for HTML, CSS or plain text (`language` required: `html`, `css` or `text`); optional `size` and `mailImages: true` for the mail image insert control. | +| `colorpicker` | A `#rrggbb` colour (or empty); Winter's `availableColors` is not supported. Invalid colours are a 422 with `backend::lang.colorpicker.invalid`. | +| `mailimage` | A single image chosen from the mail image library (stores a file id). Missing library images are a 422 with `backend::lang.mailimage.missing`. | +| `mailpreview` | A valueless live preview control (`mode` required: `template`, `layout`, `partial` or `branding`); never bound or accepted in a save body. | The WinterCMS widgets that are not in this list (the code editor, the color picker, the media finder and the others) are not provided. A field with one of those types stops the start-up, unless a plugin registers that alias as its own field type: plugins add field types with a custom element and Go code that decides what is stored; see [Plugin field types](field-types.md). ### Field options -A field takes `label`, `comment`, `type`, `required`, `default`, `tab`, `span` (`left`, `right`, `full`, `auto`, `row`), `size` (`tiny`, `small`, `large`, `huge`, `giant`), `context`, `attributes` (scalar HTML attributes for the input), `options` and `emptyOption`, plus `nameFrom` and `relation` on relation fields, `preset` on text and mltext fields, `dependsOn` on dropdowns (see [Dependent dropdowns](#dependent-dropdowns)), `currency`, `currencyFrom`, `scale` and `max` on money fields (see [Money](#money)), `mode`, `separator` and `customTags` on taglist fields (see [Taglist](#taglist)), and `trigger` (see [Triggers](#triggers)). WinterCMS keys outside this set, such as `readOnly` or `disabled`, are refused. +A field takes `label`, `comment`, `type`, `required`, `default`, `tab`, `span` (`left`, `right`, `full`, `auto`, `row`), `size` (`tiny`, `small`, `large`, `huge`, `giant`), `context`, `attributes` (scalar HTML attributes for the input), `options` and `emptyOption`, plus `nameFrom` and `relation` on relation fields, `preset` on text and mltext fields, `dependsOn` on dropdowns (see [Dependent dropdowns](#dependent-dropdowns)), `currency`, `currencyFrom`, `scale` and `max` on money fields (see [Money](#money)), `mode`, `separator` and `customTags` on taglist fields (see [Taglist](#taglist)), `language` and `mailImages` on `codeeditor` (and `mailImages` on `markdown`), `mode` on `mailpreview`, and `trigger` (see [Triggers](#triggers)). WinterCMS keys outside this set, such as `readOnly` or `disabled`, are refused. `context: update` shows a field only on the update form, and `context: create` only on the create form; a list of contexts is also accepted, and `context: preview` shows a field only on the [preview screen](#preview-screen). The context is enforced on the server too: a field that is hidden on a form is never written by that form's save, whatever the request body holds. diff --git a/docs/backend/settings.md b/docs/backend/settings.md index 4498e68f..ed4920c1 100644 --- a/docs/backend/settings.md +++ b/docs/backend/settings.md @@ -137,6 +137,8 @@ cabana only checks whether the key resolves to a non-empty value (`env` state); `type: richeditor` is accepted on a settings form. The settings save runs every submitted value through the same seaglass sanitizer as a controller save (see [Rich text](forms.md#rich-text)): clean HTML is stored byte for byte, otherwise the clean value is stored and the answer lists what was removed in `meta.notices`, which the admin shows under the field. A value that is not a string or `null` is a 422 on the field. `repeater` and `dependsOn` are still refused on settings forms, as they are on relation forms. +`type: colorpicker`, `type: mailimage` and `type: mailpreview` are also accepted on settings forms (they are built-in cabana types). `mailpreview` is valueless and never written. The Mail section entries `mail_templates`, `mail_layouts`, `mail_partials`, `mail_brand` and `mail_images` (category `backend::lang.settings.category_mail`) come from cabana's internal plugin when postcard's Mailer is published: Branding (`mail_brand`) is a settings form on `system_mail_brand_settings`; until that row exists mail uses `mail.brandCss`, and the first save switches to the compiled colours. + ## Tabs Settings fields take `tab` like record form fields. When any field declares one, the admin renders the tab strip in the page header, with the fields that have no `tab` on the default tab first; the form card sits inside the active tab's panel. After a 422 the first tab with an error is activated and shows its error count. Without any `tab` the page is unchanged. diff --git a/modules/cabana/README.md b/modules/cabana/README.md index b450de05..9ad5e831 100644 --- a/modules/cabana/README.md +++ b/modules/cabana/README.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 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. +- 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. Layout and partial content fields use the built-in `codeeditor` type (`language: html|css|text`, optional `mailImages`); Branding is the settings form `mail_brand` on `cabana.MailBrandSetting` (postcard's brand row, 13 `colorpicker` colours and a `mailimage` logo; the first save switches mail from `mail.brandCss` to the compiled colours). Mail images is the singleton controller `cabana.MailImagesControllerID` (`cabana.MailImageLibrary`) with a public attachMany `images` fileupload; GET/POST `/mail/images` and GET `/mail/images/{id}` return absolute public URLs (`attach.AbsolutePublicURL`) and refuse with `mail.images.no_public_url` when neither `storage.uploads.public_url` nor `app.url` is set. Listing answers either mail permission; upload and the singleton form need `system.manage_mail_layouts`. - 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. diff --git a/modules/cabana/admin_openapi.go b/modules/cabana/admin_openapi.go index 9bb9375a..0eb22a61 100644 --- a/modules/cabana/admin_openapi.go +++ b/modules/cabana/admin_openapi.go @@ -573,6 +573,56 @@ func AdminSettingsPut() {} // @Router /markdown/preview [post] func AdminMarkdownPreview() {} +// AdminMailImagesList documents GET /mail/images. +// +// @Summary List mail library images +// @Description Lists public mail library images with absolute URLs. Holders of either mail permission may list; meta.canUpload is true only for system.manage_mail_layouts. Without storage.uploads.public_url or app.url the route answers 409 with mail.images.no_public_url. +// @Tags admin +// @Produce json +// @Security BackendBearer +// @Param q query string false "Filename or title match" +// @Param page query int false "Page (1-based)" +// @Success 200 {object} AdminMailImagesResponse +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 409 {object} ErrorEnvelope +// @Router /mail/images [get] +func AdminMailImagesList() {} + +// AdminMailImagesShow documents GET /mail/images/{id}. +// +// @Summary Show one mail library image +// @Description One library image by id with absolute URLs. An image outside the library is 404. +// @Tags admin +// @Produce json +// @Security BackendBearer +// @Param id path int true "Image id" +// @Success 200 {object} Envelope[AdminMailImage] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Failure 409 {object} ErrorEnvelope +// @Router /mail/images/{id} [get] +func AdminMailImagesShow() {} + +// AdminMailImagesUpload documents POST /mail/images. +// +// @Summary Upload a mail library image +// @Description Stores a multipart file part as a public library image and answers it with absolute URLs. Needs system.manage_mail_layouts. Without an absolute public URL base the route answers 409. +// @Tags admin +// @Accept multipart/form-data +// @Produce json +// @Security BackendBearer +// @Param file formData file true "Image file" +// @Success 201 {object} Envelope[AdminMailImage] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 409 {object} ErrorEnvelope +// @Failure 413 {object} ErrorEnvelope +// @Failure 422 {object} ErrorEnvelope +// @Router /mail/images [post] +func AdminMailImagesUpload() {} + // AdminListSchema documents the list schema route. // // @Summary Admin list schema diff --git a/modules/cabana/backendscreens/controllers/mailimages/config_form.yaml b/modules/cabana/backendscreens/controllers/mailimages/config_form.yaml new file mode 100644 index 00000000..547fdae2 --- /dev/null +++ b/modules/cabana/backendscreens/controllers/mailimages/config_form.yaml @@ -0,0 +1,3 @@ +name: backend::lang.mail.images.menu_label +modelClass: System\Models\MailImageLibrary +form: models/mailimagelibrary/fields.yaml diff --git a/modules/cabana/backendscreens/models/mailbrandsetting/fields.yaml b/modules/cabana/backendscreens/models/mailbrandsetting/fields.yaml new file mode 100644 index 00000000..68118801 --- /dev/null +++ b/modules/cabana/backendscreens/models/mailbrandsetting/fields.yaml @@ -0,0 +1,71 @@ +fields: + logo_file_id: + label: backend::lang.mail.brand.logo + comment: backend::lang.mail.brand.logo_comment + type: mailimage + span: full + body_bg: + label: backend::lang.mail.brand.body_bg + type: colorpicker + span: left + default: "#f5f8fa" + content_bg: + label: backend::lang.mail.brand.content_bg + type: colorpicker + span: right + default: "#ffffff" + header_color: + label: backend::lang.mail.brand.header_color + type: colorpicker + span: left + default: "#bbbfc3" + footer_color: + label: backend::lang.mail.brand.footer_color + type: colorpicker + span: right + default: "#aeaeae" + heading_color: + label: backend::lang.mail.brand.heading_color + type: colorpicker + span: left + default: "#2f3133" + text_color: + label: backend::lang.mail.brand.text_color + type: colorpicker + span: right + default: "#74787e" + link_color: + label: backend::lang.mail.brand.link_color + type: colorpicker + span: left + default: "#2da7c7" + button_text_color: + label: backend::lang.mail.brand.button_text_color + type: colorpicker + span: right + default: "#ffffff" + button_primary_bg: + label: backend::lang.mail.brand.button_primary_bg + type: colorpicker + span: left + default: "#d66829" + button_positive_bg: + label: backend::lang.mail.brand.button_positive_bg + type: colorpicker + span: right + default: "#52a838" + button_negative_bg: + label: backend::lang.mail.brand.button_negative_bg + type: colorpicker + span: left + default: "#e01346" + panel_bg: + label: backend::lang.mail.brand.panel_bg + type: colorpicker + span: right + default: "#edeff2" + table_border_color: + label: backend::lang.mail.brand.table_border_color + type: colorpicker + span: left + default: "#edeff2" diff --git a/modules/cabana/backendscreens/models/mailimagelibrary/fields.yaml b/modules/cabana/backendscreens/models/mailimagelibrary/fields.yaml new file mode 100644 index 00000000..39daedbc --- /dev/null +++ b/modules/cabana/backendscreens/models/mailimagelibrary/fields.yaml @@ -0,0 +1,10 @@ +fields: + images: + label: backend::lang.mail.images.field + comment: backend::lang.mail.images.field_comment + type: fileupload + mode: image + useCaption: true + fileTypes: jpg,jpeg,png,gif,webp + maxFilesize: 5 + span: full diff --git a/modules/cabana/backendscreens/models/maillayout/fields.yaml b/modules/cabana/backendscreens/models/maillayout/fields.yaml index 1b1167b3..eabe6fd8 100644 --- a/modules/cabana/backendscreens/models/maillayout/fields.yaml +++ b/modules/cabana/backendscreens/models/maillayout/fields.yaml @@ -25,22 +25,27 @@ fields: content_html: label: backend::lang.mail.layout.html comment: backend::lang.mail.layout.html_comment - type: textarea + type: codeeditor + language: html size: giant + mailImages: true 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 + type: codeeditor + language: text 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 + type: codeeditor + language: css size: huge + mailImages: true span: full tab: backend::lang.mail.layout.tab_css _file_version: diff --git a/modules/cabana/backendscreens/models/mailpartial/fields.yaml b/modules/cabana/backendscreens/models/mailpartial/fields.yaml index 3b1bdc77..34a6b5c0 100644 --- a/modules/cabana/backendscreens/models/mailpartial/fields.yaml +++ b/modules/cabana/backendscreens/models/mailpartial/fields.yaml @@ -7,14 +7,17 @@ fields: content_html: label: backend::lang.mail.partial.html comment: backend::lang.mail.partial.html_comment - type: textarea + type: codeeditor + language: html size: huge + mailImages: true 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 + type: codeeditor + language: text size: large span: full tab: backend::lang.mail.partial.tab_text diff --git a/modules/cabana/backendscreens/models/mailtemplate/fields.yaml b/modules/cabana/backendscreens/models/mailtemplate/fields.yaml index 9ea07a71..3d996497 100644 --- a/modules/cabana/backendscreens/models/mailtemplate/fields.yaml +++ b/modules/cabana/backendscreens/models/mailtemplate/fields.yaml @@ -24,6 +24,7 @@ fields: comment: backend::lang.mail.template.body_comment type: markdown size: giant + mailImages: true span: full tab: backend::lang.mail.template.tab_template _file_version: diff --git a/modules/cabana/crud.go b/modules/cabana/crud.go index aaf6a25b..a40a11fa 100644 --- a/modules/cabana/crud.go +++ b/modules/cabana/crud.go @@ -1522,7 +1522,8 @@ func modelColumns(model any) map[string]struct{} { func scalarFormField(typ string) bool { switch typ { case "text", "textarea", "number", "checkbox", "switch", "dropdown", "datepicker", - "markdown", "mltext", "mltextarea", "mlmarkdown", "richeditor", moneyType: + "markdown", "mltext", "mltextarea", "mlmarkdown", "richeditor", moneyType, + codeEditorType, colorPickerType, mailImageType: return true default: return false diff --git a/modules/cabana/datepicker_smoke_test.go b/modules/cabana/datepicker_smoke_test.go index cf4b216c..b50950eb 100644 --- a/modules/cabana/datepicker_smoke_test.go +++ b/modules/cabana/datepicker_smoke_test.go @@ -93,7 +93,7 @@ func TestDatepickerSmokeCompile(t *testing.T) { "minDate on time": {" day:\n type: datepicker\n mode: time\n minDate: 2026-01-01\n", "minDate is not valid with mode: time"}, "min after max": {" starts_at:\n type: datepicker\n minDate: 2026-02-01\n maxDate: 2026-01-01\n", "is after maxDate"}, "key on another type": {" title:\n type: text\n firstDay: 1\n", "firstDay is only valid on type: datepicker"}, - "mode on another type": {" title:\n type: text\n mode: date\n", "mode is only valid on type: fileupload, datepicker, permissioneditor or taglist"}, + "mode on another type": {" title:\n type: text\n mode: date\n", "mode is only valid on type: fileupload, datepicker, permissioneditor, taglist or mailpreview"}, } { t.Run(name, func(t *testing.T) { err := activateFields(t, datepickerFields(tc.field)) diff --git a/modules/cabana/datepicker_test.go b/modules/cabana/datepicker_test.go index 44ee7500..590b9e23 100644 --- a/modules/cabana/datepicker_test.go +++ b/modules/cabana/datepicker_test.go @@ -65,7 +65,7 @@ func TestDatepickerCompile(t *testing.T) { "ignoreTimezone not bool": {field("starts_at", " ignoreTimezone: maybe\n"), "ignoreTimezone:"}, "ignoreTimezone on date": {field("released_on", " mode: date\n ignoreTimezone: true\n"), "ignoreTimezone is only valid with mode: datetime"}, "key on another type": {" name2:\n type: text\n firstDay: 1\n", "firstDay is only valid on type: datepicker"}, - "mode on another type": {" name2:\n type: text\n mode: date\n", "mode is only valid on type: fileupload, datepicker, permissioneditor or taglist"}, + "mode on another type": {" name2:\n type: text\n mode: date\n", "mode is only valid on type: fileupload, datepicker, permissioneditor, taglist or mailpreview"}, "date on a datetime": {field("starts_at", " mode: date\n"), "field starts_at: datepicker mode date needs a lagoon.Date or *lagoon.Date column, found *time.Time"}, "datetime on a date": {field("released_on", " mode: datetime\n"), "datepicker mode datetime needs a time.Time or *time.Time column, found lagoon.Date"}, "time on a date": {field("released_on", " mode: time\n"), "datepicker mode time needs a lagoon.TimeOfDay or *lagoon.TimeOfDay column, found lagoon.Date"}, diff --git a/modules/cabana/field_file.go b/modules/cabana/field_file.go index 195d911f..5e2417f2 100644 --- a/modules/cabana/field_file.go +++ b/modules/cabana/field_file.go @@ -75,8 +75,8 @@ func compileFileuploadKeys(typ string, values map[string]ast.Node, field *FormFi return fmt.Errorf("%s is only valid on type: fileupload", key) } } - if _, ok := values["mode"]; ok && typ != "datepicker" && typ != permissionFieldType && typ != taglistType { - return fmt.Errorf("mode is only valid on type: fileupload, datepicker, permissioneditor or taglist") + if _, ok := values["mode"]; ok && typ != "datepicker" && typ != permissionFieldType && typ != taglistType && typ != mailPreviewType { + return fmt.Errorf("mode is only valid on type: fileupload, datepicker, permissioneditor, taglist or mailpreview") } return nil } diff --git a/modules/cabana/field_mail.go b/modules/cabana/field_mail.go new file mode 100644 index 00000000..2d03e503 --- /dev/null +++ b/modules/cabana/field_mail.go @@ -0,0 +1,66 @@ +package cabana + +import ( + "fmt" + + "github.com/goccy/go-yaml/ast" +) + +const ( + codeEditorType = "codeeditor" + colorPickerType = "colorpicker" + mailImageType = "mailimage" + mailPreviewType = "mailpreview" +) + +var codeEditorLanguages = map[string]struct{}{ + "html": {}, "css": {}, "text": {}, +} + +var mailPreviewModes = map[string]struct{}{ + "template": {}, "layout": {}, "partial": {}, "branding": {}, +} + +// compileMailFieldKeys decodes the mail field keys: language on codeeditor, +// mailImages on markdown and codeeditor, and mode on mailpreview. They are +// refused on every other type; a missing required value is a boot error. +func compileMailFieldKeys(typ string, values map[string]ast.Node, field *FormField) error { + if node, ok := values["language"]; ok { + if typ != codeEditorType { + return fmt.Errorf("language is only valid on type: codeeditor") + } + lang, err := nodeString(node) + if err != nil || lang == "" { + return fmt.Errorf("language is required on type: codeeditor") + } + if _, ok := codeEditorLanguages[lang]; !ok { + return fmt.Errorf("language %q must be html, css or text", lang) + } + field.Language = lang + } else if typ == codeEditorType { + return fmt.Errorf("language is required on type: codeeditor") + } + + if node, ok := values["mailImages"]; ok { + if typ != codeEditorType && typ != "markdown" { + return fmt.Errorf("mailImages is only valid on type: markdown or codeeditor") + } + on, err := nodeBool(node) + if err != nil { + return fmt.Errorf("mailImages: %w", err) + } + field.MailImages = &on + } + + if typ == mailPreviewType { + mode, err := nodeString(values["mode"]) + if err != nil || mode == "" { + return fmt.Errorf("mode is required on type: mailpreview") + } + if _, ok := mailPreviewModes[mode]; !ok { + return fmt.Errorf("mode %q must be template, layout, partial or branding", mode) + } + field.Mode = mode + } + return nil +} diff --git a/modules/cabana/form_schema.go b/modules/cabana/form_schema.go index 4e5cce8b..dc01a9b5 100644 --- a/modules/cabana/form_schema.go +++ b/modules/cabana/form_schema.go @@ -28,6 +28,7 @@ var ( "password": {}, "permissioneditor": {}, "markdown": {}, "mltext": {}, "mltextarea": {}, "mlmarkdown": {}, "richeditor": {}, "repeater": {}, "money": {}, "taglist": {}, + "codeeditor": {}, "colorpicker": {}, "mailimage": {}, "mailpreview": {}, } formSpans = map[string]struct{}{ "left": {}, "right": {}, "full": {}, "auto": {}, "row": {}, @@ -50,6 +51,7 @@ var ( "groups": {}, "style": {}, "currency": {}, "currencyFrom": {}, "scale": {}, "max": {}, "separator": {}, "customTags": {}, + "language": {}, "mailImages": {}, } // widgetKeys are valid only on `type: widget` (D-06). widgetKeys = []string{"widget", "action", "fill"} @@ -647,6 +649,9 @@ func compileFieldNode(name string, node ast.Node, types *fieldTypeRegistry) (For if err := compileMoneyKeys(typ, values, &field); err != nil { return FormField{}, err } + if err := compileMailFieldKeys(typ, values, &field); err != nil { + return FormField{}, err + } if err := compilePresetKey(typ, values, &field); err != nil { return FormField{}, err } diff --git a/modules/cabana/http.go b/modules/cabana/http.go index e5c3d916..2b504710 100644 --- a/modules/cabana/http.go +++ b/modules/cabana/http.go @@ -168,6 +168,7 @@ func Activate(app *backpack.App, plugins []party.Plugin) (*Routes, error) { // soon as the database is there. The hook never fails the boot; until a // sync succeeded, the first mail list request retries it. if mail := screens.mail; mail != nil { + injectLayoutCreateDefaults(reg, mail.editor) if err := lagoon.OnDatabase(app, func(_ *sql.DB, gdb *gorm.DB) error { mail.syncOnDatabase(gdb) return nil @@ -353,6 +354,11 @@ func (s *service) mount(r pact.Router) { g.Get("/field-types", s.fieldTypesList) // Form previews render through RenderMarkdown; nothing is stored. g.Post("/markdown/preview", requireAjax(s.markdownPreview)) + // Mail image library (absolute public URLs); preview and test-send + // join these in plan 35-02 Task 4. + g.Get("/mail/images", s.mailImagesList) + g.Get("/mail/images/{id}", s.mailImagesShow) + g.Post("/mail/images", requireAjax(s.mailImagesUpload)) g.Get("/settings", s.settingsList) // The read-only Plugins screen (backend.view_plugins). g.Get("/plugins", s.pluginsInstalled) diff --git a/modules/cabana/mail_admin.go b/modules/cabana/mail_admin.go index f3287fc6..02a980d8 100644 --- a/modules/cabana/mail_admin.go +++ b/modules/cabana/mail_admin.go @@ -2,6 +2,7 @@ package cabana import ( "context" + "encoding/json" "errors" "fmt" "regexp" @@ -13,6 +14,7 @@ import ( "time" "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/lagoon/attach" "git.golem15.com/golem15/summercms/modules/pact" "git.golem15.com/golem15/summercms/modules/phrasebook" "git.golem15.com/golem15/summercms/modules/postcard" @@ -44,7 +46,12 @@ func mailPermissions() []pact.Permission { } func (m *mailScreens) controllers() []pact.AdminController { - return []pact.AdminController{mailTemplatesAdmin{mail: m}, mailLayoutsAdmin{mail: m}, mailPartialsAdmin{mail: m}} + return []pact.AdminController{ + mailTemplatesAdmin{mail: m}, + mailLayoutsAdmin{mail: m}, + mailPartialsAdmin{mail: m}, + mailImagesAdmin{mail: m}, + } } // settings are the Settings → Mail entries. @@ -80,6 +87,27 @@ func (m *mailScreens) settings() []pact.SettingsItem { Permissions: []string{PermissionManageMailLayouts}, Controller: MailPartialsControllerID, }, + { + Code: "mail_brand", + Label: mailLang + "brand.menu_label", + Description: mailLang + "brand.menu_description", + Category: mailCategory, + Icon: "palette", + Order: 230, + Permissions: []string{PermissionManageMailLayouts}, + Form: "models/mailbrandsetting/fields.yaml", + NewModel: func() any { return &MailBrandSetting{} }, + }, + { + Code: "mail_images", + Label: mailLang + "images.menu_label", + Description: mailLang + "images.menu_description", + Category: mailCategory, + Icon: "image", + Order: 240, + Permissions: []string{PermissionManageMailLayouts}, + Controller: MailImagesControllerID, + }, } } @@ -1441,3 +1469,199 @@ func partialUsage(code, sections string) string { b.WriteString(" }}") return b.String() } + +// MailBrandSetting is the settings form over postcard's branding row (id 1). +// Saving it switches mail from mail.brandCss to the compiled colours. +type MailBrandSetting struct { + ID uint `gorm:"column:id;primaryKey"` + LogoFileID *uint `gorm:"column:logo_file_id"` + BodyBg string `gorm:"column:body_bg"` + ContentBg string `gorm:"column:content_bg"` + HeaderColor string `gorm:"column:header_color"` + FooterColor string `gorm:"column:footer_color"` + HeadingColor string `gorm:"column:heading_color"` + TextColor string `gorm:"column:text_color"` + LinkColor string `gorm:"column:link_color"` + ButtonTextColor string `gorm:"column:button_text_color"` + ButtonPrimaryBg string `gorm:"column:button_primary_bg"` + ButtonPositiveBg string `gorm:"column:button_positive_bg"` + ButtonNegativeBg string `gorm:"column:button_negative_bg"` + PanelBg string `gorm:"column:panel_bg"` + TableBorderColor string `gorm:"column:table_border_color"` + CreatedAt time.Time `gorm:"column:created_at"` + UpdatedAt time.Time `gorm:"column:updated_at"` +} + +func (MailBrandSetting) TableName() string { return postcard.BrandTable } + +func (MailBrandSetting) Fillable() []string { + return []string{ + "logo_file_id", "body_bg", "content_bg", "header_color", "footer_color", + "heading_color", "text_color", "link_color", "button_text_color", + "button_primary_bg", "button_positive_bg", "button_negative_bg", + "panel_bg", "table_border_color", + } +} + +func (MailBrandSetting) Rules() map[string]string { + return map[string]string{ + "logo_file_id": "nullable", + "body_bg": "nullable", + "content_bg": "nullable", + "header_color": "nullable", + "footer_color": "nullable", + "heading_color": "nullable", + "text_color": "nullable", + "link_color": "nullable", + "button_text_color": "nullable", + "button_primary_bg": "nullable", + "button_positive_bg": "nullable", + "button_negative_bg": "nullable", + "panel_bg": "nullable", + "table_border_color": "nullable", + } +} + +var brandColourPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`) + +// BeforeValidate lower-cases colours, refuses anything but #rrggbb or empty, +// and checks logo_file_id is null or a library image. +func (b *MailBrandSetting) BeforeValidate(tx *gorm.DB) error { + details := map[string]any{} + for _, col := range []struct { + name string + value *string + }{ + {"body_bg", &b.BodyBg}, + {"content_bg", &b.ContentBg}, + {"header_color", &b.HeaderColor}, + {"footer_color", &b.FooterColor}, + {"heading_color", &b.HeadingColor}, + {"text_color", &b.TextColor}, + {"link_color", &b.LinkColor}, + {"button_text_color", &b.ButtonTextColor}, + {"button_primary_bg", &b.ButtonPrimaryBg}, + {"button_positive_bg", &b.ButtonPositiveBg}, + {"button_negative_bg", &b.ButtonNegativeBg}, + {"panel_bg", &b.PanelBg}, + {"table_border_color", &b.TableBorderColor}, + } { + colour := strings.ToLower(strings.TrimSpace(*col.value)) + *col.value = colour + if colour == "" { + continue + } + if !brandColourPattern.MatchString(colour) { + details[col.name] = []string{"backend::lang.colorpicker.invalid"} + } + } + if b.LogoFileID != nil { + var n int64 + if err := tx.Session(&gorm.Session{NewDB: true}). + Table("system_files"). + Where("id = ? AND attachment_type = ? AND field = ?", *b.LogoFileID, mailImageLibraryMorph, "images"). + Count(&n).Error; err != nil { + return err + } + if n == 0 { + details["logo_file_id"] = []string{"backend::lang.mailimage.missing"} + } + } + if len(details) > 0 { + return &ValidationError{Details: details} + } + return nil +} + +// mailImageLibraryMorph is the attachment_type of the mail image library host. +const mailImageLibraryMorph = `System\Models\MailImageLibrary` + +// MailImageLibrary is the one-row host of the mail image library's attachMany +// images relation. +type MailImageLibrary struct { + ID uint `gorm:"column:id;primaryKey"` + CreatedAt time.Time `gorm:"column:created_at"` + UpdatedAt time.Time `gorm:"column:updated_at"` +} + +func (MailImageLibrary) TableName() string { return postcard.ImageLibraryTable } + +func (MailImageLibrary) MorphName() string { return mailImageLibraryMorph } + +func (MailImageLibrary) AttachRelations() []attach.Relation { + return []attach.Relation{{Name: "images", Many: true, Public: true}} +} + +func (MailImageLibrary) Fillable() []string { return nil } + +func (MailImageLibrary) Rules() map[string]string { return nil } + +// mailImagesAdmin is the Mail images singleton screen. +type mailImagesAdmin struct { + mail *mailScreens +} + +var ( + _ pact.AdminController = mailImagesAdmin{} + _ pact.AdminPermissioned = mailImagesAdmin{} + _ pact.AdminSingleton = mailImagesAdmin{} +) + +func (mailImagesAdmin) ID() string { return MailImagesControllerID } + +func (mailImagesAdmin) ModelName() string { return `System\Models\MailImageLibrary` } + +func (mailImagesAdmin) ConfigDir() string { return "controllers/mailimages" } + +func (mailImagesAdmin) RequiredPermissions() []string { + return []string{PermissionManageMailLayouts} +} + +func (mailImagesAdmin) NewRecord() any { return &MailImageLibrary{} } + +// SingletonRecord returns the library host row, creating it when absent. +func (mailImagesAdmin) SingletonRecord(ctx context.Context, db *gorm.DB) (any, error) { + var row MailImageLibrary + err := db.WithContext(ctx).Order("id").Limit(1).Take(&row).Error + if err == nil { + return &row, nil + } + if !errors.Is(err, gorm.ErrRecordNotFound) { + return nil, err + } + row = MailImageLibrary{} + if err := db.WithContext(ctx).Create(&row).Error; err != nil { + return nil, err + } + return &row, nil +} + +// injectLayoutCreateDefaults copies postcard's default layout into the create +// form defaults of the layouts controller, so the YAML carries no copy of it. +func injectLayoutCreateDefaults(reg *Registry, editor *postcard.Editor) { + if reg == nil || editor == nil { + return + } + cc, ok := reg.Get(MailLayoutsControllerID) + if !ok || cc == nil || cc.Form == nil { + return + } + file, ok := editor.Catalog().Layout(mailDefaultLayout) + if !ok { + return + } + set := map[string]string{ + "content_html": file.HTML, + "content_text": file.Text, + "content_css": "", + } + for i := range cc.Form.Fields { + if raw, ok := set[cc.Form.Fields[i].Name]; ok { + encoded, err := json.Marshal(raw) + if err != nil { + continue + } + cc.Form.Fields[i].Default = &jsonScalar{raw: encoded} + } + } +} diff --git a/modules/cabana/mail_routes.go b/modules/cabana/mail_routes.go new file mode 100644 index 00000000..afb2581a --- /dev/null +++ b/modules/cabana/mail_routes.go @@ -0,0 +1,293 @@ +package cabana + +import ( + "context" + "errors" + "io" + "net/http" + "strconv" + "strings" + + "git.golem15.com/golem15/summercms/modules/bouncer" + "git.golem15.com/golem15/summercms/modules/lagoon" + "git.golem15.com/golem15/summercms/modules/lagoon/attach" + "gorm.io/gorm" +) + +// AdminMailImage is one library image with absolute public URLs. +type AdminMailImage struct { + ID uint `json:"id"` + FileName string `json:"fileName"` + Title string `json:"title"` + URL string `json:"url"` + ThumbURL string `json:"thumbUrl,omitempty"` +} + +// AdminMailImagesMeta is the meta of GET /mail/images. +type AdminMailImagesMeta struct { + CanUpload bool `json:"canUpload"` + Total int64 `json:"total"` + Page int `json:"page"` + PerPage int `json:"perPage"` +} + +// AdminMailImagesResponse is the GET /mail/images answer (custom meta). +type AdminMailImagesResponse struct { + Data []AdminMailImage `json:"data"` + Meta AdminMailImagesMeta `json:"meta"` +} + +const ( + mailImagesPerPage = 40 + mailImageMaxBytes = 5 << 20 +) + +var mailImageLimits = attach.Limits{ + MaxBytes: mailImageMaxBytes, + Extensions: attach.DefaultImageExtensions, + Image: true, +} + +// mailImagesList serves GET /mail/images: library images with absolute URLs, +// for holders of either mail permission. canUpload is true only for layouts. +func (s *service) mailImagesList(w http.ResponseWriter, r *http.Request) { + principal, ok := bouncer.User(r.Context()) + if !ok || principal == nil || !principal.Backend { + WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated) + return + } + if !tokenRouteGate(principal, w) { + return + } + if !Allows(principal, []string{PermissionManageMailTemplates, PermissionManageMailLayouts}) { + WriteError(w, http.StatusForbidden, "forbidden", msgForbidden) + return + } + cfg := s.config() + if _, err := attach.AbsolutePublicURL(cfg, "probe"); errors.Is(err, attach.ErrNoAbsoluteURL) { + WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url")) + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + q := strings.TrimSpace(r.URL.Query().Get("q")) + page := 1 + if raw := r.URL.Query().Get("page"); raw != "" { + if n, err := strconv.Atoi(raw); err == nil && n > 0 { + page = n + } + } + query := db.WithContext(r.Context()).Model(&attach.File{}). + Where("attachment_type = ? AND field = ?", mailImageLibraryMorph, "images") + if q != "" { + like := "%" + q + "%" + query = query.Where("file_name ILIKE ? OR title ILIKE ?", like, like) + } + var total int64 + if err := query.Count(&total).Error; err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + var files []attach.File + if err := query.Order("id DESC").Offset((page - 1) * mailImagesPerPage).Limit(mailImagesPerPage).Find(&files).Error; err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + items := make([]AdminMailImage, 0, len(files)) + for i := range files { + item, err := s.mailImageItem(r.Context(), &files[i]) + if err != nil { + if errors.Is(err, attach.ErrNoAbsoluteURL) { + WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url")) + return + } + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + items = append(items, item) + } + WriteData(w, http.StatusOK, items, AdminMailImagesMeta{ + CanUpload: Allows(principal, []string{PermissionManageMailLayouts}), + Total: total, + Page: page, + PerPage: mailImagesPerPage, + }) +} + +// mailImagesShow serves GET /mail/images/{id}: one library image, or 404. +func (s *service) mailImagesShow(w http.ResponseWriter, r *http.Request) { + principal, ok := bouncer.User(r.Context()) + if !ok || principal == nil || !principal.Backend { + WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated) + return + } + if !tokenRouteGate(principal, w) { + return + } + if !Allows(principal, []string{PermissionManageMailTemplates, PermissionManageMailLayouts}) { + WriteError(w, http.StatusForbidden, "forbidden", msgForbidden) + return + } + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil || id == 0 { + writeNotFound(w, r) + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + var f attach.File + err = db.WithContext(r.Context()). + Where("id = ? AND attachment_type = ? AND field = ?", id, mailImageLibraryMorph, "images"). + Take(&f).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + writeNotFound(w, r) + return + } + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + item, err := s.mailImageItem(r.Context(), &f) + if err != nil { + if errors.Is(err, attach.ErrNoAbsoluteURL) { + WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url")) + return + } + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + WriteData(w, http.StatusOK, item, nil) +} + +// mailImagesUpload serves POST /mail/images: layouts holders only, multipart +// "file", attached to the library host with an absolute public URL. +func (s *service) mailImagesUpload(w http.ResponseWriter, r *http.Request) { + principal, ok := bouncer.User(r.Context()) + if !ok || principal == nil || !principal.Backend { + WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated) + return + } + if !tokenRouteGate(principal, w) { + return + } + if !Allows(principal, []string{PermissionManageMailLayouts}) { + WriteError(w, http.StatusForbidden, "forbidden", msgForbidden) + return + } + if _, err := attach.AbsolutePublicURL(s.config(), "probe"); errors.Is(err, attach.ErrNoAbsoluteURL) { + WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url")) + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + bucket := s.bucket() + if bucket == nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + body := &bodyReader{r: http.MaxBytesReader(w, r.Body, s.uploadCap(nil))} + r.Body = io.NopCloser(body) + mr, err := r.MultipartReader() + if err != nil { + writeCRUDError(w, invalidBody()) + return + } + part, err := mr.NextPart() + if err != nil { + writeCRUDError(w, invalidBody()) + return + } + if part.FormName() != "file" || strings.TrimSpace(part.FileName()) == "" { + writeCRUDError(w, invalidBody()) + return + } + var stored *attach.File + var item AdminMailImage + err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error { + host, err := mailImagesAdmin{}.SingletonRecord(ctx, tx) + if err != nil { + return err + } + library, ok := host.(*MailImageLibrary) + if !ok || library == nil || library.ID == 0 { + return errors.New("cabana: mail image library host missing") + } + f, err := attach.Store(ctx, tx, bucket, attach.Upload{FileName: part.FileName(), Body: part, Public: true}, mailImageLimits) + if err != nil { + return err + } + stored = f + if _, err := mr.NextPart(); !errors.Is(err, io.EOF) { + if err == nil { + return invalidBody() + } + return err + } + if err := tx.Session(&gorm.Session{NewDB: true, Context: ctx}).Model(&attach.File{}).Where("id = ?", f.ID).Updates(map[string]any{ + "attachment_id": uitoa(library.ID), + "attachment_type": mailImageLibraryMorph, + "field": "images", + }).Error; err != nil { + return err + } + f.AttachmentID = uitoa(library.ID) + f.AttachmentType = mailImageLibraryMorph + f.Field = "images" + item, err = s.mailImageItem(ctx, f) + return err + }) + if err != nil { + if stored != nil { + _ = attach.DeleteKeys(context.WithoutCancel(r.Context()), bucket, attach.BlobKeys(*stored)) + } + if errors.Is(err, attach.ErrNoAbsoluteURL) { + WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url")) + return + } + if errors.Is(err, attach.ErrNotImage) || errors.Is(err, attach.ErrFileType) || errors.Is(err, attach.ErrMIMEType) || errors.Is(err, attach.ErrTooLarge) { + writeCRUDError(w, &ValidationError{Details: map[string]any{"file": []string{err.Error()}}}) + return + } + writeCRUDError(w, err) + return + } + WriteData(w, http.StatusCreated, item, nil) +} + +func (s *service) mailImageItem(ctx context.Context, f *attach.File) (AdminMailImage, error) { + url, err := attach.AbsolutePublicURL(s.config(), attach.BlobKey(f.DiskName)) + if err != nil { + return AdminMailImage{}, err + } + title := f.FileName + if f.Title != nil && *f.Title != "" { + title = *f.Title + } + item := AdminMailImage{ID: f.ID, FileName: f.FileName, Title: title, URL: url} + if bucket := s.bucket(); bucket != nil { + if key, err := f.ThumbKey(ctx, bucket, defaultThumbEdge, defaultThumbEdge, "auto"); err == nil && key != "" { + if abs, err := attach.AbsolutePublicURL(s.config(), key); err == nil { + item.ThumbURL = abs + } + } + } + return item, nil +} + +// mailMessage translates a mail phrase key in the request locale. +func (s *service) mailMessage(ctx context.Context, key string) string { + tr := s.translator() + if tr == nil { + return key + } + return translateKey(ctx, tr, key) +} diff --git a/modules/cabana/mail_screens_smoke_test.go b/modules/cabana/mail_screens_smoke_test.go index 9e8f64c8..b68c74a2 100644 --- a/modules/cabana/mail_screens_smoke_test.go +++ b/modules/cabana/mail_screens_smoke_test.go @@ -1,11 +1,16 @@ package cabana_test import ( + "bytes" "context" + "encoding/json" "errors" "fmt" + "io" "io/fs" + "mime/multipart" "net/http" + "net/http/httptest" "os" "path/filepath" "strings" @@ -19,10 +24,12 @@ import ( "git.golem15.com/golem15/summercms/modules/cabana" "git.golem15.com/golem15/summercms/modules/compass" "git.golem15.com/golem15/summercms/modules/lagoon" + "git.golem15.com/golem15/summercms/modules/lagoon/attach" "git.golem15.com/golem15/summercms/modules/party" "git.golem15.com/golem15/summercms/modules/phrasebook" "git.golem15.com/golem15/summercms/modules/postcard" "git.golem15.com/golem15/summercms/modules/surf" + "gocloud.dev/blob/memblob" ) // The mail screens' paths under the admin API. @@ -177,6 +184,11 @@ func newMailScreensEnvWith(t *testing.T, opts mailEnvOptions) *mailEnv { if err := lagoon.Publish(app, adminSQL, gdb); err != nil { t.Fatal(err) } + bucket := memblob.OpenBucket(nil) + t.Cleanup(func() { _ = bucket.Close() }) + if err := attach.Publish(app, bucket); err != nil { + t.Fatal(err) + } driver := &mailSpy{} mailer := postcard.NewMailer(nil, driver, postcard.Options{From: "noreply@example.test", Overrides: postcard.NewDBSource(app)}) if err := app.Publish[postcard.Mailer](mailer); err != nil { @@ -586,6 +598,114 @@ Hi **{{ .name }}**, thanks for joining the Acme blog. t.Fatalf("lineDiff above the cap = %q", got) } }) + + t.Run("fields", func(t *testing.T) { + schema := env.expect(t, http.StatusOK, http.MethodGet, mailLayoutsPath+"/schema/form", rootToken, nil) + fields, _ := schema["data"].(map[string]any)["fields"].([]any) + var html map[string]any + for _, raw := range fields { + f, _ := raw.(map[string]any) + if f["name"] == "content_html" { + html = f + break + } + } + if html == nil || html["type"] != "codeeditor" || html["language"] != "html" || html["mailImages"] != true { + t.Fatalf("content_html schema = %#v", html) + } + }) + + t.Run("branding", func(t *testing.T) { + got := env.expect(t, http.StatusOK, http.MethodGet, "/settings/mail_brand", rootToken, nil) + if got["data"].(map[string]any)["exists"] != false { + t.Fatalf("fresh brand exists = %#v", got["data"]) + } + data, _ := got["data"].(map[string]any)["data"].(map[string]any) + if fmt.Sprint(data["button_primary_bg"]) != "#d66829" { + t.Fatalf("default button_primary_bg = %#v", data["button_primary_bg"]) + } + env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"button_primary_bg": "red"}) + saved := env.expect(t, http.StatusOK, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"button_primary_bg": "#D66829"}) + if saved["data"].(map[string]any)["exists"] != true { + t.Fatalf("saved brand exists = %#v", saved["data"]) + } + row := saved["data"].(map[string]any)["data"].(map[string]any) + if fmt.Sprint(row["button_primary_bg"]) != "#d66829" { + t.Fatalf("stored colour = %#v", row["button_primary_bg"]) + } + env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"logo_file_id": 999999}) + }) + + t.Run("images", func(t *testing.T) { + listed := env.expect(t, http.StatusOK, http.MethodGet, "/mail/images", rootToken, nil) + meta, _ := listed["meta"].(map[string]any) + if meta["canUpload"] != true { + t.Fatalf("root canUpload = %#v", meta) + } + rec := mailUpload(t, env.h, rootToken, conformPNG(t), "badge.png") + if rec.Code != http.StatusCreated { + t.Fatalf("upload status=%d body=%s", rec.Code, rec.Body.String()) + } + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + item, _ := body["data"].(map[string]any) + if !strings.HasPrefix(fmt.Sprint(item["url"]), "https://mail.example.test/") { + t.Fatalf("url = %#v", item["url"]) + } + id := fmt.Sprint(item["id"]) + env.expect(t, http.StatusOK, http.MethodGet, "/mail/images/"+id, rootToken, nil) + env.expect(t, http.StatusNotFound, http.MethodGet, "/mail/images/999999", rootToken, nil) + noURL := newMailScreensEnv(t, func(cfg *compass.Config) { + _ = cfg.Set("app.url", "") + _ = cfg.Set("storage.uploads.public_url", "") + }) + _, tok := noURL.admin(t, "mail-nourl", true, "") + noURL.expect(t, http.StatusConflict, http.MethodGet, "/mail/images", tok, nil) + }) + + t.Run("images_permissions", func(t *testing.T) { + _, templatesTok := env.admin(t, "mail-tmpl-img", false, `{"system.manage_mail_templates":1}`) + _, layoutsTok := env.admin(t, "mail-lay-img", false, `{"system.manage_mail_layouts":1}`) + listed := env.expect(t, http.StatusOK, http.MethodGet, "/mail/images", templatesTok, nil) + if listed["meta"].(map[string]any)["canUpload"] != false { + t.Fatalf("templates canUpload = %#v", listed["meta"]) + } + if rec := mailUpload(t, env.h, templatesTok, conformPNG(t), "x.png"); rec.Code != http.StatusForbidden { + t.Fatalf("templates upload status=%d", rec.Code) + } + if rec := mailUpload(t, env.h, layoutsTok, conformPNG(t), "ok.png"); rec.Code != http.StatusCreated { + t.Fatalf("layouts upload status=%d body=%s", rec.Code, rec.Body.String()) + } + env.expect(t, http.StatusForbidden, http.MethodGet, "/summercms/cabana/mailimages/singleton", templatesTok, nil) + env.expect(t, http.StatusOK, http.MethodGet, "/summercms/cabana/mailimages/singleton", layoutsTok, nil) + }) +} + +// mailUpload POSTs a multipart file to /mail/images. +func mailUpload(t *testing.T, h http.Handler, token string, data []byte, name string) *httptest.ResponseRecorder { + t.Helper() + var body bytes.Buffer + w := multipart.NewWriter(&body) + part, err := w.CreateFormFile("file", name) + if err != nil { + t.Fatal(err) + } + if _, err := io.Copy(part, bytes.NewReader(data)); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodPost, adminAPI("/mail/images"), &body) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", w.FormDataContentType()) + req.Header.Set("Accept", "application/json") + req.Header.Set("X-Requested-With", "XMLHttpRequest") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec } // mailFileHash is the catalog hash and source of a template file. diff --git a/modules/cabana/openapi_conformance_test.go b/modules/cabana/openapi_conformance_test.go index 3ecf49e4..7a18dc4e 100644 --- a/modules/cabana/openapi_conformance_test.go +++ b/modules/cabana/openapi_conformance_test.go @@ -440,6 +440,36 @@ func conformCases() []conformCase { {"POST /markdown/preview", 200, "cabana.Envelope-cabana_AdminMarkdownPreviewResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/markdown/preview", map[string]string{"markdown": "# Conform"}, true) }, into[cabana.Envelope[cabana.AdminMarkdownPreviewResult]](), nil}, + {"GET /mail/images", 200, "cabana.AdminMailImagesResponse", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodGet, "/mail/images", nil, true) + }, into[cabana.AdminMailImagesResponse](), nil}, + {"POST /mail/images", 201, "cabana.Envelope-cabana_AdminMailImage", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + var buf bytes.Buffer + mw := multipart.NewWriter(&buf) + part, err := mw.CreateFormFile("file", "mail-badge.png") + if err != nil { + t.Fatal(err) + } + if _, err := part.Write(conformPNG(t)); err != nil { + t.Fatal(err) + } + if err := mw.Close(); err != nil { + t.Fatal(err) + } + rec := e.sendWith(t, http.MethodPost, "/mail/images", buf.Bytes(), mw.FormDataContentType(), map[string]string{"X-Requested-With": "XMLHttpRequest"}) + var body cabana.Envelope[cabana.AdminMailImage] + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("mail image upload: %v body=%s", err, rec.Body.String()) + } + e.mailImageID = body.Data.ID + return rec + }, into[cabana.Envelope[cabana.AdminMailImage]](), nil}, + {"GET /mail/images/{id}", 200, "cabana.Envelope-cabana_AdminMailImage", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + if e.mailImageID == 0 { + t.Fatal("mail image id unset; POST /mail/images must run first") + } + return e.send(t, http.MethodGet, fmt.Sprintf("/mail/images/%d", e.mailImageID), nil, true) + }, into[cabana.Envelope[cabana.AdminMailImage]](), nil}, {"GET /{vendor}/{plugin}/{controller}/schema/list", 200, "cabana.Envelope-cabana_ListSchema", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodGet, "/acme/conform/gadgets/schema/list", nil, true) var body cabana.Envelope[cabana.ListSchema] @@ -833,22 +863,23 @@ func conformSpec(t *testing.T) conformSpecDoc { } type conformEnv struct { - h http.Handler - db *gorm.DB - bucket *blob.Bucket - login string - token string - stamp string - sessionKey string - photoID uint - manualID uint - groupID uint - memberID uint - gadgetID uint - partID uint - partFileID uint - childKey string - tokenID uint + h http.Handler + db *gorm.DB + bucket *blob.Bucket + login string + token string + stamp string + sessionKey string + photoID uint + manualID uint + groupID uint + memberID uint + gadgetID uint + partID uint + partFileID uint + childKey string + tokenID uint + mailImageID uint } // sendWith sends a raw body with extra headers through the assembled router. @@ -1039,7 +1070,9 @@ func newConformEnv(t *testing.T) *conformEnv { login := "conform-" + stamp insertAdmin(t, gdb, login, login+"@example.test", adminTestPassword, true, false) // The Plugins screen needs backend.view_plugins, which no role holds. - if err := gdb.Exec(`UPDATE backend_users SET permissions = ? WHERE login = ?`, `{"backend.view_plugins":1}`, login).Error; err != nil { + // Mail image routes need either mail permission (conform is not a superuser). + if err := gdb.Exec(`UPDATE backend_users SET permissions = ? WHERE login = ?`, + `{"backend.view_plugins":1,"system.manage_mail_templates":1,"system.manage_mail_layouts":1}`, login).Error; err != nil { t.Fatal(err) } @@ -1052,7 +1085,12 @@ func newConformEnv(t *testing.T) *conformEnv { t.Fatal(err) } // plugins.registry_url "" keeps GET /plugins from calling a registry. - for key, value := range map[string]any{"http.body_limits.default_bytes": 1048576, "http.body_limits.upload_bytes": 1048576, "plugins.registry_url": ""} { + for key, value := range map[string]any{ + "http.body_limits.default_bytes": 1048576, + "http.body_limits.upload_bytes": 1048576, + "plugins.registry_url": "", + "app.url": "https://conform.example.test", + } { if err := cfg.Set(key, value); err != nil { t.Fatal(err) } @@ -1061,6 +1099,9 @@ func newConformEnv(t *testing.T) *conformEnv { if err := lagoon.Publish(app, adminSQL, gdb); err != nil { t.Fatal(err) } + if err := gdb.AutoMigrate(&cabana.MailImageLibrary{}); err != nil { + t.Fatal(err) + } bucket := memblob.OpenBucket(nil) t.Cleanup(func() { _ = bucket.Close() }) if err := attach.Publish(app, bucket); err != nil { diff --git a/modules/cabana/phase10_coverage_test.go b/modules/cabana/phase10_coverage_test.go index acef9637..703d0632 100644 --- a/modules/cabana/phase10_coverage_test.go +++ b/modules/cabana/phase10_coverage_test.go @@ -99,6 +99,7 @@ func TestPhase10Coverage(t *testing.T) { "POST /auth/login", "POST /auth/logout", "POST /auth/refresh", + "POST /mail/images", "POST /markdown/preview", "POST /{vendor}/{plugin}/{controller}", "POST /{vendor}/{plugin}/{controller}/bulk-delete", diff --git a/modules/cabana/phase10_csrf_test.go b/modules/cabana/phase10_csrf_test.go index 95ee2e38..fd1bb1d8 100644 --- a/modules/cabana/phase10_csrf_test.go +++ b/modules/cabana/phase10_csrf_test.go @@ -72,9 +72,10 @@ func TestPhase10CSRF(t *testing.T) { // delete, record action, link, unlink, file upload, file reorder, file // caption, file remove, relation child create, update and delete, pivot // update, child file upload, reorder, caption and remove, plugin field - // type upload, tree reorder save, account contribution action - if unsafe != 35 { - t.Fatalf("walked %d state-changing routes, want 35: %v", unsafe, router.order) + // type upload, tree reorder save, account contribution action, + // mail image upload + if unsafe != 36 { + t.Fatalf("walked %d state-changing routes, want 36: %v", unsafe, router.order) } loginHandler := router.handlers[login] diff --git a/modules/cabana/phase121_form_test.go b/modules/cabana/phase121_form_test.go index 00cb08c2..5836a79b 100644 --- a/modules/cabana/phase121_form_test.go +++ b/modules/cabana/phase121_form_test.go @@ -544,7 +544,7 @@ func TestPermissionEditorSmoke(t *testing.T) { rosterBootFails(t, map[string]string{rosterFieldsFile: rosterFields(t, " mode: radio\n", " mode: radio\n default: 1\n")}, "default is not valid on type: permissioneditor") rosterBootFails(t, map[string]string{rosterFieldsFile: rosterFields(t, " type: checkbox\n default: true\n", " type: checkbox\n default: true\n mode: radio\n")}, - "mode is only valid on type: fileupload, datepicker, permissioneditor or taglist") + "mode is only valid on type: fileupload, datepicker, permissioneditor, taglist or mailpreview") if err := rosterBoot(t, rosterTree(t, map[string]string{rosterFieldsFile: rosterFields(t, " mode: radio\n", " mode: checkbox\n")})); err != nil { t.Fatalf("mode: checkbox did not boot: %v", err) } diff --git a/modules/cabana/phase121_schema_boot_test.go b/modules/cabana/phase121_schema_boot_test.go index 660c5977..30b75285 100644 --- a/modules/cabana/phase121_schema_boot_test.go +++ b/modules/cabana/phase121_schema_boot_test.go @@ -169,7 +169,7 @@ func TestPhase121BootErrors(t *testing.T) { {name: "permissioneditor with a default", files: map[string]string{rosterFieldsFile: rosterFields(t, " mode: radio\n", " mode: radio\n default: 1\n")}, want: "default is not valid on type: permissioneditor", file: rosterFieldsFile}, {name: "mode on another type", files: map[string]string{rosterFieldsFile: rosterFields(t, " type: checkbox\n default: true\n", " type: checkbox\n default: true\n mode: radio\n")}, - want: "mode is only valid on type: fileupload, datepicker, permissioneditor or taglist", file: rosterFieldsFile}, + want: "mode is only valid on type: fileupload, datepicker, permissioneditor, taglist or mailpreview", file: rosterFieldsFile}, // Relation fields (D-27 G3) and controller filter choices. {name: "WritableForeignKey on belongsToMany", plugin: relations(func(in []cabana.FieldRelationContract) { in[1].WritableForeignKey = true }), want: "field tags: WritableForeignKey is only valid on belongsTo"}, diff --git a/modules/cabana/repeater_test.go b/modules/cabana/repeater_test.go index 3c562380..e251b512 100644 --- a/modules/cabana/repeater_test.go +++ b/modules/cabana/repeater_test.go @@ -245,6 +245,8 @@ func TestRepeaterCompile(t *testing.T) { "permissioneditor": " mode: checkbox\n", "repeater": " form:\n fields:\n a:\n type: text\n", "money": " currency: PLN\n", + "codeeditor": " language: html\n", + "mailpreview": " mode: template\n", } for typ := range formFieldTypes { if repeaterNestedTypes[typ] { diff --git a/modules/cabana/schema_types.go b/modules/cabana/schema_types.go index 582dbe11..3f46f9f4 100644 --- a/modules/cabana/schema_types.go +++ b/modules/cabana/schema_types.go @@ -319,9 +319,15 @@ type FormField struct { Path string `json:"path,omitempty"` // Mode is the fileupload mode (image or file, default file), the // datepicker mode (date, datetime or time, default datetime), the - // permissioneditor mode (radio or checkbox) or the taglist mode (string, - // the default, or array). + // permissioneditor mode (radio or checkbox), the taglist mode (string, + // the default, or array), or the mailpreview mode (template, layout, + // partial or branding). Mode string `json:"mode,omitempty"` + // Language is the codeeditor language: html, css or text. + Language string `json:"language,omitempty"` + // MailImages, when true, shows the mail image insert control on a + // markdown or codeeditor field. + MailImages *bool `json:"mailImages,omitempty"` // Format is a datepicker's WinterCMS (PHP date) display format; // DisplayFormat is the same format in the SPA's moment-style tokens. Format string `json:"format,omitempty"` diff --git a/modules/cabana/security_coverage_test.go b/modules/cabana/security_coverage_test.go index c8fc1459..c78aa286 100644 --- a/modules/cabana/security_coverage_test.go +++ b/modules/cabana/security_coverage_test.go @@ -59,6 +59,9 @@ var phase09Routes = []adminRoute{ {key: "GET /settings/{code}"}, {key: "PUT /settings/{code}"}, {key: "POST /markdown/preview"}, + {key: "GET /mail/images"}, + {key: "GET /mail/images/{id}"}, + {key: "POST /mail/images"}, {key: "GET /{vendor}/{plugin}/{controller}/schema/list"}, {key: "GET /{vendor}/{plugin}/{controller}/schema/form"}, {key: "GET /{vendor}/{plugin}/{controller}/schema/relation/{name}"}, @@ -360,6 +363,9 @@ func phase09ProtectedCalls() []phase09Call { {"settings-schema", (*service).settingsSchema}, {"settings-get", (*service).settingsGet}, {"settings-put", (*service).settingsPut}, + {"mail-images-list", (*service).mailImagesList}, + {"mail-images-show", (*service).mailImagesShow}, + {"mail-images-upload", (*service).mailImagesUpload}, } } diff --git a/modules/cabana/settings.go b/modules/cabana/settings.go index 8bc30378..16578186 100644 --- a/modules/cabana/settings.go +++ b/modules/cabana/settings.go @@ -126,6 +126,10 @@ func compileSettingWithTypes(pluginID string, item pact.SettingsItem, fsys fs.FS // A password field is a write-only secret on a settings form (D-13): // bound like a scalar, checked against lagoon.Encrypted, never served. secret := field.Type == passwordFieldType + // mailpreview is valueless: never bound, never accepted in a save body. + if field.Type == mailPreviewType { + continue + } if (!scalarFormField(field.Type) && !secret && field.Type != taglistType) || protectedFillKey(field.Name) { continue } diff --git a/modules/cabana/token_routes_test.go b/modules/cabana/token_routes_test.go index 952ee1c4..d49a095f 100644 --- a/modules/cabana/token_routes_test.go +++ b/modules/cabana/token_routes_test.go @@ -55,6 +55,9 @@ var tokenRouteClasses = map[string]tokenRouteClass{ "GET /settings/{code}": classAllowsSettings, "PUT /settings/{code}": classAllowsSettings, "POST /markdown/preview": classExplicitGate, + "GET /mail/images": classExplicitGate, + "GET /mail/images/{id}": classExplicitGate, + "POST /mail/images": classExplicitGate, "GET /{vendor}/{plugin}/{controller}/schema/list": classAllowsProtect, "GET /{vendor}/{plugin}/{controller}/schema/form": classAllowsProtect, diff --git a/modules/phrasebook/backend/lang/en/lang.yaml b/modules/phrasebook/backend/lang/en/lang.yaml index 61985709..0dabb331 100644 --- a/modules/phrasebook/backend/lang/en/lang.yaml +++ b/modules/phrasebook/backend/lang/en/lang.yaml @@ -690,3 +690,55 @@ mail: 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." + brand: + menu_label: "Mail branding" + menu_description: "Set the colours and logo used by every message." + logo: "Logo" + logo_comment: "Layouts show the logo where they use {{ .logoUrl }}." + body_bg: "Body background" + content_bg: "Content background" + header_color: "Header colour" + footer_color: "Footer colour" + heading_color: "Headings colour" + text_color: "Text colour" + link_color: "Link colour" + button_text_color: "Button text colour" + button_primary_bg: "Primary button background" + button_positive_bg: "Positive button background" + button_negative_bg: "Negative button background" + panel_bg: "Panel background" + table_border_color: "Table border colour" + preview_comment: "Until this page is saved for the first time, mail uses the brand CSS from the configuration (mail.brandCss). After that, these colours replace it." + images: + menu_label: "Mail images" + menu_description: "Upload images to use in mail templates, layouts and partials." + field: "Images" + field_comment: "Stored on the public disk and linked from mail by their public address. The caption title is the image's alternative text. Removing an image breaks every template, layout or partial that still shows it." + no_public_url: "Mail images need an absolute address. Set storage.uploads.public_url or app.url in the configuration." + preview: + label: "Preview" + test_send: "Send test to myself" + test_sent: "Test sent to :email." + test_failed: "The test could not be sent. Try again later." + rate_limited: "You have sent too many test messages. Try again in a few minutes." + picker: + insert_button: "Insert image" + choose_title: "Choose an image" + insert_title: "Insert an image" + search: "Search images" + empty: "No images yet. Upload one to use it in mail." + upload: "Upload image" + no_upload: "You can choose an image, but uploading needs the mail layouts permission." +codeeditor: + load_failed: "The code editor could not be loaded. You can still edit the text here." + toolbar: "Code editor tools" +colorpicker: + pick: "Pick a colour for “:field”" + not_set: "Not set" + invalid: "Enter a colour as #rrggbb, for example #d66829." +mailimage: + empty: "No image chosen" + choose: "Choose image" + change: "Change image" + remove: "Remove image" + missing: "This image is no longer in the library. Choose another one." diff --git a/modules/phrasebook/backend/lang/pl/lang.yaml b/modules/phrasebook/backend/lang/pl/lang.yaml index 6ce3a672..04fd3284 100644 --- a/modules/phrasebook/backend/lang/pl/lang.yaml +++ b/modules/phrasebook/backend/lang/pl/lang.yaml @@ -728,3 +728,55 @@ mail: 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ąć." + brand: + menu_label: "Wygląd wiadomości" + menu_description: "Ustaw kolory i logo używane we wszystkich wiadomościach." + logo: "Logo" + logo_comment: "Układy pokazują logo tam, gdzie używają {{ .logoUrl }}." + body_bg: "Główne tło" + content_bg: "Tło treści" + header_color: "Kolor górnego nagłówka" + footer_color: "Kolor stopki" + heading_color: "Kolor nagłówków" + text_color: "Kolor tekstu" + link_color: "Kolor linków" + button_text_color: "Kolor tekstu przycisków" + button_primary_bg: "Tło głównego przycisku" + button_positive_bg: "Tło pozytywnego przycisku" + button_negative_bg: "Tło negatywnego przycisku" + panel_bg: "Tło panelu" + table_border_color: "Kolor ramki tabeli" + preview_comment: "Dopóki ta strona nie zostanie zapisana po raz pierwszy, wiadomości używają stylów wyglądu z konfiguracji (mail.brandCss). Potem zastępują je te kolory." + images: + menu_label: "Obrazy w wiadomościach" + menu_description: "Prześlij obrazy do użycia w szablonach, układach i fragmentach wiadomości." + field: "Obrazy" + field_comment: "Przechowywane na dysku publicznym i linkowane z wiadomości przez publiczny adres. Tytuł podpisu to tekst alternatywny obrazu. Usunięcie obrazu psuje każdy szablon, układ lub fragment, który nadal go pokazuje." + no_public_url: "Obrazy w wiadomościach wymagają pełnego adresu. Ustaw storage.uploads.public_url lub app.url w konfiguracji." + preview: + label: "Podgląd" + test_send: "Wyślij test do siebie" + test_sent: "Test wysłano na :email." + test_failed: "Nie udało się wysłać testu. Spróbuj ponownie później." + rate_limited: "Wysłano zbyt wiele wiadomości testowych. Spróbuj ponownie za kilka minut." + picker: + insert_button: "Wstaw obraz" + choose_title: "Wybierz obraz" + insert_title: "Wstaw obraz" + search: "Szukaj obrazów" + empty: "Brak obrazów. Prześlij jeden, aby użyć go w wiadomościach." + upload: "Prześlij obraz" + no_upload: "Możesz wybrać obraz, ale przesyłanie wymaga uprawnienia do układów wiadomości." +codeeditor: + load_failed: "Nie udało się wczytać edytora kodu. Nadal możesz edytować tekst tutaj." + toolbar: "Narzędzia edytora kodu" +colorpicker: + pick: "Wybierz kolor: „:field”" + not_set: "Nie ustawiono" + invalid: "Podaj kolor w formacie #rrggbb, na przykład #d66829." +mailimage: + empty: "Nie wybrano obrazu" + choose: "Wybierz obraz" + change: "Zmień obraz" + remove: "Usuń obraz" + missing: "Tego obrazu nie ma już w bibliotece. Wybierz inny."