feat(cabana): code editor, colour and mail image fields, mail branding and the image library
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -59,7 +59,7 @@ Use cases:
|
||||
- Form fields on another plugin's controller: a `pact.AdminActionExtension` with `Form` set to a `pact.AdminFormExtension` places fields and tabs in any admin controller's form by its ID. Its fields document is the `fields.yaml` format plus `before:`/`after:` anchors, `zone:` (only the tab zone for now) and a `tabs:` list, compiled at boot with every `fields.yaml` check; extensions apply in plugin activation order and the form is sent in the compiled order, so the SPA adds no ordering. `Hide` removes owner fields, `Permissions` and `Visible` decide per request who sees the fields (schema, show and save alike), widget fields run the extension's `Actions` and partial fields render from its `Dir` through `PartialData`. Extension values leave the save body before any owner path reads them; `Save` runs in the record's save transaction after the owner row is written (`pact.AdminFormErrors` answers 422, its notices join `meta.notices`) and `Load` serves the values on show. A form no extension lays out compiles unchanged. Unknown anchors, duplicate names, anchor cycles, anchors outside `Requires()`, other zones, `fileupload` fields and clashing widget action or partial names stop the boot naming the plugin, the controller and the name.
|
||||
- Plugins screen: Settings → System → Plugins opens the admin SPA route `/system/plugins` (the settings entry carries `path` instead of a controller) for administrators holding `cabana.PermissionViewPlugins` (`backend.view_plugins`, granted to no role in code; superusers always pass). GET `/plugins` lists the plugins the application was built with from the `party.Installed` metadata `summer build` bakes (name, description, version, source, module and package), or only the IDs of `party.Activated` for an application built before that metadata existed, with the framework version and the state of the plugin registry (`plugins.registry_url`, read through `kiosk.RegistryURL`). With the registry configured, cabana (never the SPA) looks up each versioned plugin's releases through `kiosk.Client` and marks an update when `kiosk.NewestCompatible` finds a release newer than the installed version by `kiosk.Newer` (a `git describe` string or a pseudo-version compares by the tag it builds on), with the `summer plugin:update <id>` command; GET `/plugins/marketplace` searches the registry and adds installed and compatibility markers (compatible when `summer plugin:install` can install some release with the built framework, looking up the releases of a plugin whose newest one needs a newer framework; always compatible when the built framework version is not a release) and the `summer plugin:install <id>` command. Registry calls have a 4 second timeout, at most four run at once, and answers are cached in process (searches 5 minutes, at most 256 distinct searches with expired and then the oldest dropped first, releases 15 minutes, failures 1 minute); a failing registry gives `status` unavailable and never a non-200 answer.
|
||||
- Administrators screen: when some plugin registers admin controllers, `cabana.Activate` also compiles the admin's own screens, an internal plugin with ID `summercms.cabana`. Settings → System → Administrators (controller `cabana.AdministratorsControllerID`, permission `cabana.PermissionManageUsers`) lists backend administrators with their role and last sign-in, opens a preview of each, where record actions (the admin's own and contributed ones) are offered, and creates and edits administrators: login, email, names, a password (hashed at `admin.password.bcrypt_cost`, at least 4 characters and at most 72 bytes), the role and per-administrator permission overrides. The server enforces the privilege rules in the save transaction: only a superuser sees superusers or sends the superuser switch, an administrator can neither grant permissions or roles above their own grants nor change an administrator who holds more than they do, their own role, superuser flag, permissions and password are not changed here, and the last active superuser cannot be demoted. A password set for another administrator ends their sessions (personal API tokens stay valid, as with `admin:reset-password`). Administrators are activated, deactivated and restored by record and bulk actions and deleted softly through `deleted_at` (never hard-deleted); the list shows deleted and deactivated rows with their row states and filters deleted ones, and the preview shows a status hint. Deactivating or deleting an administrator ends their sessions and stops their personal API tokens; the last active superuser cannot be demoted, deactivated or deleted on any of these paths (a transaction-scoped advisory lock serializes the check). The permission codes `cabana.PermissionManageUsers` and `cabana.PermissionManageRoles` are registered with no role grant, so after an upgrade only superusers see the screens until an administrator grants them. An application without admin controllers still activates no admin.
|
||||
- Mail screens (Settings → Mail): when the application publishes postcard's Mailer (`postcard.EditorFrom` succeeds; `party.Activate` runs `postcard.Activate`), the internal plugin also registers the mail screens over postcard's tables, the permission codes `cabana.PermissionManageMailTemplates` (`system.manage_mail_templates`) and `cabana.PermissionManageMailLayouts` (`system.manage_mail_layouts`), both granted to no role in code, and their Settings entries in category `backend::lang.settings.category_mail`. Mail templates (controller `cabana.MailTemplatesControllerID`, model `cabana.MailTemplate`) lists the templates of this process's catalog (rows of uninstalled plugins are hidden) with code, subject, description, locale (Default for a name without a locale suffix) and layout, and edits the subject, the Markdown body and the layout (a `relation` over `cabana.MailLayout` rows: every database-only layout and the catalog's file layouts). There is no create and no delete. A save marks the row customized, stamps `base_hash` with the file's current hash and `customized_at`, and validates the result through `postcard.Editor.Validate` inside the save's transaction; a `postcard.DraftError` is a 422 on its field with `backend::lang.mail.invalid_<rule>` (`:message`, `:name`). The index rows are written by `postcard.SyncIndex` through `lagoon.OnDatabase` at activation; a failed sync is logged and retried on the first mail list request of the process. Mail 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_<rule>` (`:message`, `:name`). The index rows are written by `postcard.SyncIndex` through `lagoon.OnDatabase` at activation; a failed sync is logged and retried on the first mail list request of the process. Mail layouts (`cabana.MailLayoutsControllerID`, model `cabana.MailLayout`) lists postcard's default layout first, then the file layouts and the custom (database-only, `source` NULL, shown as Custom) layouts by name; it creates custom layouts (code `^[a-z0-9-]+$`, free, create-only) and deletes them, refusing one that template rows still reference with a `cabana.ForbiddenError` whose message names the layout and the count (CLDR plural). Mail partials (`cabana.MailPartialsControllerID`, model `cabana.MailPartial`) edits the partials' HTML and text sections. Both need `cabana.PermissionManageMailLayouts`; saves are stamped and validated as templates are. On all three, the record action `reset` (danger, offered on a customized file-backed row) calls `postcard.ResetOverride` in the action's transaction; rows from files are never deleted. The list row states are `customized` (an override) and `outdated` (an override whose `base_hash` differs from the file's `file_hash`), the lists have a status filter (customized, not customized, outdated) and templates a locale filter, and the forms carry the `info` and `file_version` partials: the file, the status, the sample variables or the partial's call, the drift callout, and a 3-line-context LCS line diff of the serialized override (`postcard.FormatTemplate`, `FormatLayout`, `FormatPartial`) against the file, skipped above 2000 lines per side. The mail controllers declare `recordActions` without a preview block: the admin offers them in the update form's footer, a boot rule only these internal controllers are exempt from. 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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
name: backend::lang.mail.images.menu_label
|
||||
modelClass: System\Models\MailImageLibrary
|
||||
form: models/mailimagelibrary/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"
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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"},
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
66
modules/cabana/field_mail.go
Normal file
66
modules/cabana/field_mail.go
Normal file
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
293
modules/cabana/mail_routes.go
Normal file
293
modules/cabana/mail_routes.go
Normal file
@@ -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)
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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"},
|
||||
|
||||
@@ -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] {
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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."
|
||||
|
||||
@@ -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."
|
||||
|
||||
Reference in New Issue
Block a user