diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 9ee9b98..8606292 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,21 @@ wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” o wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy dopiero powyżej 20. +## 1.9.9 + +### Nowe +- **Ładne maile z formularzy** (`forms: { emailLayout: true }`): `{{*:table}}` → czytelne podsumowanie (pytania, + etykiety odpowiedzi, grupy według kroków, bez pustych pól) + szablon maila (logo, kolor akcentu, stopka z + Site Settings → Emails; tabele + inline CSS). Przepustka `forms.beforeEmail`. Opis: forms.md → „Ładne maile”. + +### Poprawki +- `submitForm` zapisuje zgłoszenie w języku strony — maile (temat, treść, potwierdzenie) wychodziły zawsze w + języku domyślnym, także dla odwiedzających wersję angielską. + +### Wymaga zmian w projekcie +- `emailLayout: true` dodaje pola w Site Settings → migracja (`pnpm payload migrate:create`, z kompletem `R2_*`). + Ustaw `serverURL` w `buildConfig` (absolutny adres logo i link w mailu). + ## 1.9.8 ### Nowe diff --git a/docs/forms.md b/docs/forms.md index 21c9e69..b62657a 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -208,7 +208,24 @@ email: mailAdapter(), // z '@intecion/ipal-kit' — SMTP albo Graph wg panelu Wtedy idą transportem wybranym w Site Integrations (SMTP albo Graph). Edytor ustawia odbiorców, temat i treść (placeholdery: `{{pole}}`, `{{*}}`, `{{*:table}}`) bez dotykania kodu. -`submitForm` odpowiada tylko za weryfikację Turnstile i zapis. +`submitForm` odpowiada tylko za weryfikację Turnstile i zapis. Zgłoszenie zapisuje w języku strony +(`locale` z `createSubmitAction`), więc form-builder bierze teksty maili i etykiety w tym języku. + +### Ładne maile (`emailLayout`) + +```ts +forms: { emailLayout: true } // opcjonalnie: beforeEmail: (emails, args) => emails (po layoucie) +``` + +- `{{*:table}}` zamienia się w **czytelne podsumowanie**: treść pytania zamiast nazwy pola, etykiety opcji + zamiast wartości (także Checkbox group), zaznaczony checkbox = ✓, puste odpowiedzi pominięte, grupy według + kroków (tytuły Step). Tylko pola, które odwiedzający widział (ukrytych warunkiem serwer nie zapisuje). +- Każdy mail dostaje **szablon** (tabele + inline CSS — Gmail, Outlook, Apple Mail): nagłówek z logo, + treść z panelu, stopka. Ustawienia: **Site Settings → Emails** — logo (**PNG/JPG**, SVG nie działa w + Gmailu/Outlooku; puste = nazwa strony), kolor akcentu (hex), stopka (per język). Link do strony i + absolutny adres logo z `serverURL` w `buildConfig` (ustaw go z `NEXT_PUBLIC_SERVER_URL`). +- Błąd przy składaniu szablonu nigdy nie blokuje wysyłki — idzie oryginalny mail, błąd w logu. +- Nowa zakładka = migracja w projekcie (`payload migrate:create`). ## Własne pola w kolekcji formularzy diff --git a/src/globals/SiteSettings/index.ts b/src/globals/SiteSettings/index.ts index ffb85b3..c373ce9 100644 --- a/src/globals/SiteSettings/index.ts +++ b/src/globals/SiteSettings/index.ts @@ -8,6 +8,8 @@ type BuildSiteSettingsArgs = { additionalFields?: Field[] /** "Under construction" tab (developer tool) — given when the pages module is on. */ constructionFields?: Field[] + /** "Emails" tab — given with `forms: { emailLayout: true }`. */ + emailFields?: Field[] /** * Fields for the "System Pages" tab — page assignments by role (homepage, * privacy policy, collection archives). Assembled by the caller, which is the @@ -33,6 +35,7 @@ type BuildSiteSettingsArgs = { export function buildSiteSettings({ additionalFields, constructionFields, + emailFields, systemPageFields, }: BuildSiteSettingsArgs = {}): GlobalConfig { return { @@ -58,6 +61,7 @@ export function buildSiteSettings({ ...(systemPageFields?.length ? [{ fields: systemPageFields, label: 'System Pages' }] : []), + ...(emailFields?.length ? [{ fields: emailFields, label: 'Emails' }] : []), ...(constructionFields?.length ? [{ fields: constructionFields, label: 'Under construction' }] : []), ...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []), ], diff --git a/src/modules/forms/createSubmitAction.ts b/src/modules/forms/createSubmitAction.ts index aae80ba..f216801 100644 --- a/src/modules/forms/createSubmitAction.ts +++ b/src/modules/forms/createSubmitAction.ts @@ -75,6 +75,7 @@ export function createSubmitAction({ data: fields, formId: String(formId), ip, + locale, maxPerMinute, payload, turnstileOnConfigError, diff --git a/src/modules/forms/emailLayout.ts b/src/modules/forms/emailLayout.ts new file mode 100644 index 0000000..c77c70e --- /dev/null +++ b/src/modules/forms/emailLayout.ts @@ -0,0 +1,188 @@ +import type { FormattedEmail } from '@payloadcms/plugin-form-builder/types' +import type { Field, PayloadRequest } from 'payload' + +import type { BuilderField } from './builderTypes.js' + +/** + * Branded e-mails for panel forms (`forms: { emailLayout: true }`). + * + * The form-builder sends what the editor wrote in Forms → Emails, with + * `{{*:table}}` rendered as a bare `field : value` table — technical names + * (`web_type`) and raw option values (`redesign_site`). This module swaps that + * table for a readable summary (the question as the visitor saw it, option + * labels, grouped by step, blanks left out) and wraps the message in an + * e-mail-safe layout (tables + inline CSS) with the logo, accent colour and + * footer from Site Settings → Emails. Pure functions + one beforeEmail hook. + */ + +export type SummaryRow = { label: string; value: string } +export type SummaryGroup = { rows: SummaryRow[]; title?: string } +type SubmissionValue = { field?: null | string; value?: unknown } + +const NON_INPUT = new Set(['message', 'step']) + +const escapeHtml = (text: string): string => + text.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''') + +const asText = (value: unknown): string => + value == null ? '' : typeof value === 'string' ? value : typeof value === 'number' || typeof value === 'boolean' ? String(value) : JSON.stringify(value) + +/** + * The stored submission as readable rows: one group per Step (titled), the + * field label as the question, option labels instead of values (a checkbox + * group's "a, b" too), a ticked checkbox as ✓. Empty answers are skipped. + */ +export function buildSubmissionSummary(fields: BuilderField[] | null | undefined, submissionData: readonly SubmissionValue[]): SummaryGroup[] { + const stored = new Map(submissionData.filter((d) => d.field).map((d) => [d.field as string, asText(d.value).trim()])) + const groups: SummaryGroup[] = [{ rows: [] }] + for (const field of fields ?? []) { + if (field.blockType === 'step') { + groups.push({ rows: [], ...(field.title ? { title: field.title } : {}) }) + continue + } + if (!field.name || NON_INPUT.has(field.blockType)) {continue} + const raw = stored.get(field.name) + if (!raw || raw === 'false') {continue} + const optionLabel = (value: string) => field.options?.find((o) => o.value === value)?.label || value + const value = + field.blockType === 'checkbox' ? '✓' + : field.blockType === 'checkboxGroup' ? raw.split(', ').map(optionLabel).join(', ') + : field.options?.length ? optionLabel(raw) + : raw + groups[groups.length - 1].rows.push({ label: field.label || field.name, value }) + } + return groups.filter((g) => g.rows.length > 0) +} + +const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif" + +/** The summary as an e-mail-safe table (inline CSS only). */ +export function renderSummaryHtml(groups: SummaryGroup[], { accent }: { accent: string }): string { + const rows = groups + .map((group) => { + const title = group.title + ? `${escapeHtml(group.title)}` + : '' + const items = group.rows + .map( + (row) => + `${escapeHtml(row.label)}` + + `${escapeHtml(row.value)}`, + ) + .join('') + return title + items + }) + .join('') + return `${rows}
` +} + +/** form-builder's `{{*:table}}` output (optionally inside a paragraph) → the readable summary. */ +export const replaceSubmissionTable = (html: string, summaryHtml: string): string => + html.replace(/(]*>\s*)?[\s\S]*?<\/table>(\s*<\/p>)?/g, summaryHtml) + +export type EmailLayoutArgs = { + /** Accent colour (hex), Site Settings → Emails. */ + accent: string + /** The message body (HTML from the panel, summary already in). */ + content: string + /** Footer line, Site Settings → Emails. */ + footer?: string + /** Absolute URL of a PNG/JPG logo — without it the site name is shown. */ + logoUrl?: string + siteName?: string + siteUrl?: string +} + +/** A complete HTML e-mail: header (logo or name), the message, footer. Tables + inline CSS. */ +export function wrapEmailHtml({ accent, content, footer, logoUrl, siteName, siteUrl }: EmailLayoutArgs): string { + const name = siteName ? escapeHtml(siteName) : '' + const brand = logoUrl + ? `${name}` + : `${name}` + const linkedBrand = siteUrl ? `${brand}` : brand + const footerLines = [footer ? escapeHtml(footer).replace(/\n/g, '
') : '', siteUrl ? `${escapeHtml(siteUrl.replace(/^https?:\/\//, ''))}` : ''] + .filter(Boolean) + .join('
') + return ` + + +
+ + + +${footerLines ? `` : ''} +
${linkedBrand}
${content}
${footerLines}
` +} + +/** Site Settings → "Emails" tab (shown with `forms: { emailLayout: true }`). */ +export const emailSettingsFields: Field[] = [ + { + name: 'email', + type: 'group', + admin: { hideGutter: true }, + fields: [ + { + name: 'logo', + type: 'upload', + admin: { description: 'PNG or JPG for a light background — Gmail and Outlook do not show SVG. Empty = the site name.' }, + label: 'E-mail logo', + relationTo: 'media', + }, + { + name: 'accentColor', + type: 'text', + admin: { description: 'Hex, e.g. #017BD0 — top bar and section titles.' }, + label: 'Accent colour', + validate: (value: unknown) => !value || /^#(?:[0-9a-f]{3}){1,2}$/i.test(String(value)) || 'Use a hex colour, e.g. #017BD0.', + }, + { name: 'footer', type: 'textarea', admin: { description: 'E.g. company name and address.' }, label: 'Footer', localized: true }, + ], + label: false, + }, +] + +/** Neutral accent when the panel has none (plugin default, not a brand colour). */ +const DEFAULT_ACCENT = '#111827' + +type HookArgs = { data?: { form?: unknown; submissionData?: SubmissionValue[] }; req: PayloadRequest } + +const mediaUrl = (media: unknown): string | undefined => + media && typeof media === 'object' && 'url' in media && typeof media.url === 'string' ? media.url : undefined + +/** + * form-builder `beforeEmail`: summary instead of the raw table + the layout. + * Never blocks sending — on any error the original e-mails go out (logged). + */ +export function buildEmailLayoutHook({ formsSlug = 'forms' }: { formsSlug?: string } = {}) { + return async (emails: FormattedEmail[], { data, req }: HookArgs): Promise => { + const { locale, payload } = req + try { + const formRef = data?.form + const formId = formRef && typeof formRef === 'object' && 'id' in formRef ? formRef.id : formRef + const [form, settings] = await Promise.all([ + payload.findByID({ id: formId as number | string, collection: formsSlug as never, depth: 0, locale: locale as never, overrideAccess: true, req }), + payload.findGlobal({ slug: 'site-settings' as never, depth: 1, locale: locale as never, req }), + ]) + const s = settings as { email?: { accentColor?: string; footer?: string; logo?: unknown }; siteName?: string } + const accent = s.email?.accentColor || DEFAULT_ACCENT + const summary = renderSummaryHtml(buildSubmissionSummary((form as { fields?: BuilderField[] }).fields, data?.submissionData ?? []), { accent }) + const serverURL = payload.config.serverURL?.replace(/\/$/, '') + const logo = mediaUrl(s.email?.logo) + const logoUrl = logo && /^https?:\/\//.test(logo) ? logo : logo && serverURL ? `${serverURL}${logo}` : undefined + return emails.map((email) => ({ + ...email, + html: wrapEmailHtml({ + accent, + content: replaceSubmissionTable(email.html ?? '', summary), + ...(s.email?.footer ? { footer: s.email.footer } : {}), + ...(logoUrl ? { logoUrl } : {}), + ...(s.siteName ? { siteName: s.siteName } : {}), + ...(serverURL ? { siteUrl: serverURL } : {}), + }), + })) + } catch (err) { + payload.logger.error(`[ipal] E-mail layout skipped: ${(err as Error).message}`) + return emails + } + } +} diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index cec8ef7..9c18abb 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -1,3 +1,4 @@ +import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types' import type { Block, Field, Plugin } from 'payload' import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-form-builder' @@ -6,6 +7,7 @@ import type { FormsOption } from './types.js' import { hasMinimumRole, isAdmin } from '../access/predicates.js' import { checkboxGroupBlock, stepBlock, withShowWhen } from './builderBlocks.js' +import { buildEmailLayoutHook } from './emailLayout.js' type AccessArgs = { req: { user?: unknown } } @@ -56,7 +58,16 @@ function hideEmails(fields: Field[]): Field[] { export function buildFormsPlugin(forms: FormsOption): Plugin { const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup const group = adminGroup ? { group: adminGroup } : {} + const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug: forms.formOverrides?.slug ?? 'forms' }) : undefined + const beforeEmail: BeforeEmail | undefined = + layout || forms.beforeEmail + ? async (emails, args) => { + const laidOut = layout ? await layout(emails, args) : emails + return forms.beforeEmail ? forms.beforeEmail(laidOut, args) : laidOut + } + : undefined return formBuilderPlugin({ + ...(beforeEmail ? { beforeEmail } : {}), // Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are // panel choices only — a form uses what the editor adds, nothing changes on // existing forms. Switch any off with forms.fields.: false. diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index 74ce533..e9bcca3 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -19,6 +19,8 @@ export type SubmitFormArgs = { formId: string /** Client IP — used for Turnstile and rate limiting. */ ip?: string + /** Page language — the form-builder reads the form (e-mail texts, labels) in it. */ + locale?: string /** * Rate limit: max submissions per IP per minute. Defaults to 5. * Set to 0 to disable (e.g. when a real limiter sits in front). @@ -96,6 +98,7 @@ export async function submitForm({ data, formId, ip, + locale, maxPerMinute = 5, payload, turnstileOnConfigError = 'allow', @@ -143,6 +146,7 @@ export async function submitForm({ try { const submission = await payload.create({ collection: 'form-submissions', + ...(locale ? { locale: locale as never } : {}), data: { form: formId, submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({ diff --git a/src/modules/forms/types.ts b/src/modules/forms/types.ts index 983cfbb..7aeee12 100644 --- a/src/modules/forms/types.ts +++ b/src/modules/forms/types.ts @@ -1,3 +1,4 @@ +import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types' import type { CollectionConfig, Field } from 'payload' /** @@ -25,12 +26,23 @@ export type FormsOption = { * formOverrides / formSubmissionOverrides still wins. */ adminGroup?: false | string + /** + * form-builder `beforeEmail` — change the e-mails before they go out. Runs after + * the ipal layout when `emailLayout` is on. + */ + beforeEmail?: BeforeEmail /** * Name of the checkbox field treated as a GDPR consent gate. A form field * with this name must be checked for submission to succeed — enforced * server-side in submitForm. Defaults to 'consent'. */ consentFieldName?: string + /** + * Branded e-mails (emailLayout.ts): `{{*:table}}` becomes a readable summary + * (questions, option labels, grouped by step) and every e-mail gets a layout + * with the logo, accent colour and footer from Site Settings → Emails. Default false. + */ + emailLayout?: boolean /** Field types available in the form builder. Sensible defaults applied. */ fields?: { checkbox?: boolean diff --git a/src/plugin.ts b/src/plugin.ts index 90c3dcb..8a35612 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -11,6 +11,7 @@ import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/co import { buildConstructionFields } from './modules/construction/fields.js' import { buildArchiveFields } from './modules/content/index.js' import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js' +import { emailSettingsFields } from './modules/forms/emailLayout.js' import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js' import { buildSystemPagesFields } from './modules/pages/index.js' @@ -214,6 +215,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { buildSiteSettings({ additionalFields: options.siteSettingsFields, ...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}), + ...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}), systemPageFields, }), buildSiteIntegrations({ additionalFields: options.integrationsFields }), diff --git a/test/emailLayout.test.ts b/test/emailLayout.test.ts new file mode 100644 index 0000000..37c3d88 --- /dev/null +++ b/test/emailLayout.test.ts @@ -0,0 +1,89 @@ +import type { PayloadRequest } from 'payload' + +import { describe, expect, test, vi } from 'vitest' + +import type { BuilderField } from '../src/modules/forms/builderTypes.js' + +import { buildEmailLayoutHook, buildSubmissionSummary, renderSummaryHtml, replaceSubmissionTable, wrapEmailHtml } from '../src/modules/forms/emailLayout.js' +import { submitForm } from '../src/modules/forms/submitForm.js' +import { fakePayload } from './helpers.js' + +vi.mock('server-only', () => ({})) + +const fields: BuilderField[] = [ + { blockType: 'step', title: 'O firmie' }, + { blockType: 'message' }, + { name: 'company', blockType: 'text', label: 'Nazwa firmy' }, + { name: 'website', blockType: 'text', label: 'Strona' }, + { name: 'areas', blockType: 'checkboxGroup', label: 'Obszary', options: [{ label: 'Strony internetowe', value: 'web' }, { label: 'IT', value: 'it' }] }, + { name: 'size', blockType: 'radio', label: 'Wielkość', options: [{ label: 'Do 10', value: '1-9' }] }, + { name: 'consent', blockType: 'checkbox', label: 'Zgoda RODO' }, + { blockType: 'step', title: 'IT' }, + { name: 'it_scope', blockType: 'textarea', label: 'Zakres' }, +] +const stored = [ + { field: 'company', value: 'Acme