Compare commits

...
4 Commits
Author SHA1 Message Date
radoslaw.smolinski 0f6a43ad12 1.9.9
CI / check (push) Canceled after 0s
2026-10-17 01:29:01 +02:00
radoslaw.smolinskiandClaude Opus 5.5 14d71bcc3a Readable form emails (forms.emailLayout)
{{*:table}} renders a readable submission summary (questions, option labels,
grouped by step, empty fields skipped) inside an email template with logo,
accent colour and footer from Site Settings → Emails. submitForm stores the
submission in the page language, so emails follow the visitor's locale.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 01:29:00 +02:00
radoslaw.smolinski 78e4e0f8e6 1.9.8
CI / check (push) Canceled after 0s
2026-10-16 22:15:57 +02:00
radoslaw.smolinskiandClaude Opus 5.5 8f8b79d003 Under construction mode (developer tool)
Site Settings -> Under construction: a switch, 'Pages still available' and
notice texts. When on, only the homepage and the chosen pages open (every
language); other addresses redirect to the homepage with the notice
(createPageRoute redirect option), and <ConstructionNotice> cancels clicks
on links to blocked pages and shows the notice. getConstructionMode(locale).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:15:57 +02:00
23 changed files with 726 additions and 4 deletions
+28
View File
@@ -8,6 +8,34 @@ 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
- **Strona w budowie** (narzędzie deweloperskie): Site Settings → Under construction — przełącznik, lista
„Pages still available” i teksty popupu. Gdy włączone, otwiera się tylko strona główna i wybrane strony
(w każdym języku); inne adresy → strona główna z popupem, kliknięcie linku do zablokowanej strony →
popup zamiast przejścia. `createPageRoute(…, { redirect })`, `getConstructionMode(locale)`,
`<ConstructionNotice>` (`/client`). Opis: construction.md.
### Wymaga zmian w projekcie
- Nowe pola w Site Settings → migracja (`pnpm payload migrate:create`, z kompletem `R2_*`, jeśli projekt ich używa).
Bez `redirect` w `createPageRoute` i bez `<ConstructionNotice>` tryb nie działa (nic się nie zmienia).
## 1.9.7
### Nowe
+1
View File
@@ -16,6 +16,7 @@ Szczegóły API — jeden plik na moduł:
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
| Zgoda cookies, baner | [consent.md](./consent.md) |
| Strona w budowie — blokada podstron z popupem (narzędzie deweloperskie) | [construction.md](./construction.md) |
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) |
| Email SMTP / Graph | [email.md](./email.md) |
| Walidacja env | [env.md](./env.md) |
+50
View File
@@ -0,0 +1,50 @@
# Strona w budowie (narzędzie deweloperskie)
Tryb dla strony, która nie jest jeszcze gotowa: odwiedzający widzą tylko stronę główną i wybrane
podstrony (np. brief), a cała reszta jest zablokowana — bez zmian w kodzie, jednym przełącznikiem w panelu.
## Panel
**Site Settings → Under construction** (zakładka jest, gdy włączony moduł `pages`):
| Pole | Znaczenie |
|---|---|
| Site under construction | włącza tryb |
| Pages still available | strony, które dalej się otwierają; **strona główna jest dostępna zawsze** |
| Notice title / text / Close button label | treść popupu (per język) |
Lista stron i teksty pokazują się dopiero po zaznaczeniu przełącznika. Wyłączenie trybu przywraca
normalne działanie strony.
## Jak działa
- **Adres spoza listy** (także nieistniejący) → przekierowanie na stronę główną w tym języku z
`?notice=construction` (`createPageRoute` z opcją `redirect`). Strony dozwolone liczone są w
**każdym języku** (`/pl/brief` i `/en/project-brief`), więc przełącznik języka działa.
- **Kliknięcie linku** do strony spoza listy → `<ConstructionNotice>` anuluje przejście (przed
`next/link`) i pokazuje popup. Linki zewnętrzne, kotwice na tej samej stronie, `target="_blank"`
i kliknięcia z modyfikatorem (Ctrl/⌘) działają normalnie.
- Po przekierowaniu popup otwiera się raz, a parametr znika z paska adresu.
- **Jedna reguła dla wszystkich odwiedzających** — strony zostają statyczne (ISR), bez sprawdzania
sesji. Po zmianie ustawień strony odświeżają się po rewalidacji (jak inne zmiany w Site Settings).
## Wpięcie w projekcie
```tsx
// app/(frontend)/[locale]/[[...slug]]/page.tsx — redirect włącza blokadę adresów
import { notFound, permanentRedirect, redirect } from 'next/navigation'
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect, redirect })
// app/(frontend)/[locale]/layout.tsx — popup + przechwytywanie linków (bez stylów, classNames)
import { ConstructionNotice } from '@intecion/ipal-kit/client'
<ConstructionNotice
mode={await getConstructionMode(locale)} // z lib/content (createContentHelpers)
classNames={{ overlay: '…', dialog: '…', title: '…', message: '…', button: '…' }}
/>
```
`getConstructionMode(locale)` zwraca `{ enabled, allowedPaths, homePath, texts }` (typ
`ConstructionMode`). Czysta logika: `isPathAllowed(pathname, allowedPaths)`,
`constructionNoticeHref(homePath)`, stała `CONSTRUCTION_NOTICE_PARAM` (`@intecion/ipal-kit`).
Nowe pola w Site Settings = migracja w projekcie (`payload migrate:create`).
+18 -1
View File
@@ -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
+1
View File
@@ -80,6 +80,7 @@ Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `Local
Strona catch-all z tymi samymi helperami: `createPageRoute(content, { blocks, notFound, permanentRedirect,
blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny widok dla archiwum lub wpisu
(`route.type`: `page | home | archive | entry`), reszta zostaje domyślna.
Opcja `redirect` (z `next/navigation`) włącza tryb „strona w budowie” — [construction.md](./construction.md).
Ręcznie (pełny plik — gdy potrzebujesz czegoś, czego `createNotFoundPage` nie ma):
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.9.7",
"version": "1.9.9",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
+3
View File
@@ -24,6 +24,9 @@ export {
useConsentContext,
} from '../modules/consent/client.js'
export type { CookieBannerClassNames } from '../modules/consent/client.js'
export { ConstructionNotice } from '../modules/construction/ConstructionNotice.js'
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
export type { ConstructionMode } from '../modules/construction/types.js'
export { BuilderForm } from '../modules/forms/BuilderForm.js'
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
+8
View File
@@ -6,6 +6,10 @@ import { themeFields } from './fields/theme.js'
type BuildSiteSettingsArgs = {
/** Extra fields injected by the client project */
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
@@ -30,6 +34,8 @@ type BuildSiteSettingsArgs = {
*/
export function buildSiteSettings({
additionalFields,
constructionFields,
emailFields,
systemPageFields,
}: BuildSiteSettingsArgs = {}): GlobalConfig {
return {
@@ -55,6 +61,8 @@ 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' }] : []),
],
},
+3
View File
@@ -42,6 +42,9 @@ export {
updateConsent,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
export { constructionNoticeHref, isPathAllowed } from './modules/construction/logic.js'
export type { ConstructionMode } from './modules/construction/types.js'
export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js'
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
export {
archiveFieldName,
@@ -0,0 +1,85 @@
'use client'
import { useCallback, useEffect, useId, useRef, useState } from 'react'
import type { ConstructionMode } from './types.js'
import { isPathAllowed } from './logic.js'
import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js'
export type ConstructionNoticeClassNames = {
button?: string
dialog?: string
message?: string
overlay?: string
title?: string
}
/**
* The "site under construction" notice (Site Settings → Under construction).
* Opens after a redirect from a blocked address (?notice=construction, then
* removed from the URL) and when a visitor clicks a link to a page that isn't
* available — the click is cancelled. Closes with its button or Escape.
* Renders nothing while the mode is off.
*
* Unstyled (classNames, like CookieBanner); texts come from the panel.
*
* // [locale]/layout.tsx
* <ConstructionNotice mode={await getConstructionMode(locale)} classNames={{ overlay: '…', dialog: '…' }} />
*/
export function ConstructionNotice({ classNames: cn = {}, mode }: { classNames?: ConstructionNoticeClassNames; mode: ConstructionMode }) {
const [open, setOpen] = useState(false)
const buttonRef = useRef<HTMLButtonElement>(null)
const titleId = useId()
const close = useCallback(() => setOpen(false), [])
const { allowedPaths, enabled } = mode
useEffect(() => {
if (!enabled) {return}
// After a redirect: show the notice once and clean the address bar
const url = new URL(window.location.href)
if (url.searchParams.get(CONSTRUCTION_NOTICE_PARAM) === CONSTRUCTION_NOTICE_VALUE) {
setOpen(true)
url.searchParams.delete(CONSTRUCTION_NOTICE_PARAM)
window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`)
}
// Capture phase, before Next's <Link> — a cancelled click doesn't navigate
const onClick = (event: MouseEvent) => {
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {return}
const anchor = event.target instanceof Element ? event.target.closest('a[href]') : null
if (!(anchor instanceof HTMLAnchorElement) || anchor.hasAttribute('download')) {return}
if (anchor.target && anchor.target !== '_self') {return}
const target = new URL(anchor.href, window.location.href)
if (target.origin !== window.location.origin || isPathAllowed(target.pathname, allowedPaths)) {return}
event.preventDefault()
event.stopPropagation()
setOpen(true)
}
document.addEventListener('click', onClick, true)
return () => document.removeEventListener('click', onClick, true)
}, [enabled, allowedPaths])
useEffect(() => {
if (!open) {return}
buttonRef.current?.focus()
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') {close()}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [open, close])
if (!enabled || !open) {return null}
return (
<div className={cn.overlay} data-ipal="construction-notice">
<div aria-labelledby={mode.texts.title ? titleId : undefined} aria-modal="true" className={cn.dialog} role="dialog">
{mode.texts.title ? <p className={cn.title} id={titleId}>{mode.texts.title}</p> : null}
{mode.texts.message ? <p className={cn.message}>{mode.texts.message}</p> : null}
<button className={cn.button} onClick={close} ref={buttonRef} type="button">
{mode.texts.button ?? '×'}
</button>
</div>
</div>
)
}
+44
View File
@@ -0,0 +1,44 @@
import type { Field } from 'payload'
const whenEnabled = (_: unknown, siblingData: { enabled?: boolean } | undefined) => Boolean(siblingData?.enabled)
/**
* Site Settings → "Under construction" tab: a developer tool for a site that
* isn't finished. When enabled, only the homepage and the chosen pages are
* reachable — any other address redirects to the homepage with a notice, and a
* link to another page shows the notice instead of navigating. One rule for
* every visitor (pages stay static, there is no per-user check).
*/
export function buildConstructionFields(pagesSlug: string): Field[] {
return [
{
name: 'construction',
type: 'group',
admin: { hideGutter: true },
fields: [
{
name: 'enabled',
type: 'checkbox',
admin: {
description:
'Only the homepage and the pages below can be opened. Other addresses redirect to the homepage with the notice; links to other pages show it instead of navigating.',
},
defaultValue: false,
label: 'Site under construction',
},
{
name: 'allowedPages',
type: 'relationship',
admin: { condition: whenEnabled, description: 'The homepage is always available.' },
hasMany: true,
label: 'Pages still available',
relationTo: pagesSlug as never,
},
{ name: 'title', type: 'text', admin: { condition: whenEnabled }, label: 'Notice title', localized: true },
{ name: 'message', type: 'textarea', admin: { condition: whenEnabled }, label: 'Notice text', localized: true },
{ name: 'buttonLabel', type: 'text', admin: { condition: whenEnabled }, label: 'Close button label', localized: true },
],
label: false,
},
]
}
+17
View File
@@ -0,0 +1,17 @@
import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js'
/** `/pl/` → `/pl`, `` → `/` — paths compare without a trailing slash. */
export const normalizePath = (path: string): string => {
const trimmed = path.replace(/\/+$/, '')
return trimmed === '' ? '/' : trimmed
}
/** Is this pathname one of the allowed ones? Exact match, trailing slash ignored. */
export function isPathAllowed(pathname: string, allowedPaths: readonly string[]): boolean {
const path = normalizePath(pathname)
return allowedPaths.some((allowed) => normalizePath(allowed) === path)
}
/** Where a blocked address goes: the homepage with the notice parameter. */
export const constructionNoticeHref = (homePath: string): string =>
`${homePath}?${CONSTRUCTION_NOTICE_PARAM}=${CONSTRUCTION_NOTICE_VALUE}`
+17
View File
@@ -0,0 +1,17 @@
/**
* "Site under construction" (Site Settings → Under construction) as the
* frontend needs it: getConstructionMode(locale) in createContentHelpers.
*/
export type ConstructionMode = {
/** Paths a visitor may open, in every language: the homepage and "Pages still available". */
allowedPaths: string[]
enabled: boolean
/** Homepage in the current language — blocked addresses redirect here (with the notice). */
homePath: string
/** Notice texts from the panel, in the current language. Empty = not set. */
texts: { button?: string; message?: string; title?: string }
}
/** Query parameter that opens the notice after a redirect: /pl?notice=construction */
export const CONSTRUCTION_NOTICE_PARAM = 'notice'
export const CONSTRUCTION_NOTICE_VALUE = 'construction'
+1
View File
@@ -75,6 +75,7 @@ export function createSubmitAction({
data: fields,
formId: String(formId),
ip,
locale,
maxPerMinute,
payload,
turnstileOnConfigError,
+188
View File
@@ -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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;')
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
? `<tr><td colspan="2" class="ipal-group" style="padding:22px 0 8px;font-family:${FONT};font-size:13px;font-weight:700;letter-spacing:0.06em;text-transform:uppercase;color:${accent};border-bottom:2px solid ${accent};">${escapeHtml(group.title)}</td></tr>`
: ''
const items = group.rows
.map(
(row) =>
`<tr class="ipal-row"><td valign="top" class="ipal-label" style="padding:10px 16px 10px 0;width:42%;font-family:${FONT};font-size:13px;line-height:1.5;color:#6b7280;border-bottom:1px solid #eceef1;">${escapeHtml(row.label)}</td>` +
`<td valign="top" class="ipal-value" style="padding:10px 0;font-family:${FONT};font-size:14px;line-height:1.5;color:#111827;border-bottom:1px solid #eceef1;white-space:pre-line;">${escapeHtml(row.value)}</td></tr>`,
)
.join('')
return title + items
})
.join('')
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin:8px 0 4px;">${rows}</table>`
}
/** form-builder's `{{*:table}}` output (optionally inside a paragraph) → the readable summary. */
export const replaceSubmissionTable = (html: string, summaryHtml: string): string =>
html.replace(/(<p[^>]*>\s*)?<table>[\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
? `<img src="${escapeHtml(logoUrl)}" alt="${name}" height="36" style="display:block;height:36px;width:auto;border:0;">`
: `<span style="font-family:${FONT};font-size:20px;font-weight:700;color:#111827;">${name}</span>`
const linkedBrand = siteUrl ? `<a href="${escapeHtml(siteUrl)}" style="text-decoration:none;">${brand}</a>` : brand
const footerLines = [footer ? escapeHtml(footer).replace(/\n/g, '<br>') : '', siteUrl ? `<a href="${escapeHtml(siteUrl)}" style="color:#6b7280;">${escapeHtml(siteUrl.replace(/^https?:\/\//, ''))}</a>` : '']
.filter(Boolean)
.join('<br>')
return `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light">
<style>@media (max-width:520px){.ipal-pad{padding-left:20px!important;padding-right:20px!important}.ipal-row td{display:block!important;width:auto!important}.ipal-label{padding:12px 0 2px!important;border-bottom:0!important}.ipal-value{padding:0 0 12px!important}}</style></head>
<body style="margin:0;padding:0;background:#f3f4f6;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#f3f4f6;"><tr><td align="center" style="padding:32px 12px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;background:#ffffff;border-radius:12px;overflow:hidden;border-top:4px solid ${accent};">
<tr><td class="ipal-pad" style="padding:28px 36px 20px;border-bottom:1px solid #eceef1;">${linkedBrand}</td></tr>
<tr><td class="ipal-pad" style="padding:28px 36px 32px;font-family:${FONT};font-size:15px;line-height:1.65;color:#1f2937;">${content}</td></tr>
${footerLines ? `<tr><td class="ipal-pad" style="padding:20px 36px 28px;background:#f9fafb;font-family:${FONT};font-size:12px;line-height:1.6;color:#6b7280;">${footerLines}</td></tr>` : ''}
</table></td></tr></table></body></html>`
}
/** 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<FormattedEmail[]> => {
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
}
}
}
+11
View File
@@ -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.<type>: false.
+4
View File
@@ -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]) => ({
+12
View File
@@ -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
@@ -5,6 +5,7 @@ import { cache } from 'react'
import type { AnalyticsConfig } from '../analytics/types.js'
import type { ConsentTexts } from '../consent/texts.js'
import type { ConstructionMode } from '../construction/types.js'
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js'
@@ -604,6 +605,40 @@ export function createContentHelpers({
segments,
})
/**
* Site Settings → Under construction, for this locale: whether it's on, the
* paths still reachable (homepage + chosen pages, in every language), the
* homepage to redirect to and the notice texts. createPageRoute (with
* `redirect`) and <ConstructionNotice> (/client) use it.
*/
const getConstructionMode = cache(async (locale: string): Promise<ConstructionMode> => {
const settings = (await getSettings(locale)) as null | Record<string, unknown>
const options = await getLinkOptions(locale)
const rootOf = (code: string) => (options.config.locales.length > 1 ? `/${code}` : '/')
const homePath = resolveLinkRaw({ type: 'internal', page: settings?.homepage }, options)?.href ?? rootOf(locale)
const construction = (settings?.construction ?? {}) as { buttonLabel?: unknown; enabled?: unknown; message?: unknown; title?: unknown }
if (construction.enabled !== true) {return { allowedPaths: [], enabled: false, homePath, texts: {} }}
const configured = await getConfiguredLocales()
const paths = await Promise.all(
(configured.length ? configured : [locale]).map(async (code) => {
const localized = (await getSettings(code)) as null | Record<string, unknown>
const linkOptions = await getLinkOptions(code)
const allowed = (localized?.construction as { allowedPages?: unknown } | undefined)?.allowedPages
const pages = [localized?.homepage, ...(Array.isArray(allowed) ? allowed : [])]
return [rootOf(code), ...pages.map((page) => resolveLinkRaw({ type: 'internal', page }, linkOptions)?.href)]
}),
)
const text = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim() : undefined)
const texts = { button: text(construction.buttonLabel), message: text(construction.message), title: text(construction.title) }
return {
allowedPaths: [...new Set(paths.flat().filter((path): path is string => typeof path === 'string'))],
enabled: true,
homePath,
texts: Object.fromEntries(Object.entries(texts).filter(([, value]) => value)),
}
})
// ── Layout ────────────────────────────────────────────────────────────────
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
@@ -682,6 +717,7 @@ export function createContentHelpers({
generateStaticParams,
getCachedPayload,
getConfiguredLocales,
getConstructionMode,
getEntries,
getFormTexts,
getHomeSlug,
+15 -2
View File
@@ -5,10 +5,11 @@ import type { ResolvedRoute } from '../content/index.js'
import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js'
import { RenderBlocks } from '../blocks/RenderBlocks.js'
import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js'
import { LocaleView } from '../pages/LocaleView.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
type Helpers = Pick<
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode'>> & Pick<
ContentHelpers,
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
>
@@ -28,6 +29,11 @@ export type PageRouteOptions = {
notFound: () => never
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
permanentRedirect: (url: string) => never
/**
* `redirect` from 'next/navigation' — enables Site Settings → Under construction:
* pages that aren't available (and unknown addresses) go to the homepage with the notice.
*/
redirect?: (url: string) => never
/**
* Render a route yourself — an archive listing, a blog entry template.
* Return undefined to keep the default (the document's blocks).
@@ -57,7 +63,7 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
*/
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, render } = options
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, redirect, render } = options
const localeOf = (locale: string | undefined) => {
const l = locale ?? helpers.i18n?.defaultLocale
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
@@ -73,6 +79,13 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
const { slug, locale: param } = await params
const locale = localeOf(param)
const segments = slug ?? []
// Under construction: anything but the homepage and the chosen pages → homepage + notice
if (redirect && helpers.getConstructionMode) {
const construction = await helpers.getConstructionMode(locale)
const multilingual = (helpers.i18n?.locales.length ?? 0) > 1
const path = `/${[...(multilingual ? [locale] : []), ...segments].join('/')}`
if (construction.enabled && !isPathAllowed(path, construction.allowedPaths)) {return redirect(constructionNoticeHref(construction.homePath))}
}
const route = await helpers.resolveRoute(locale, segments, 1)
if (!route) {
const target = await helpers.resolvePageRedirect(locale, segments)
+4
View File
@@ -8,8 +8,10 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { injectRoles } from './modules/access/index.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
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'
@@ -212,6 +214,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
...(config.globals ?? []),
buildSiteSettings({
additionalFields: options.siteSettingsFields,
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}),
systemPageFields,
}),
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
+90
View File
@@ -0,0 +1,90 @@
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'node:os'
import path from 'node:path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { constructionNoticeHref, isPathAllowed, normalizePath } from '../src/modules/construction/logic.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
describe('under construction — path logic', () => {
test('paths compare without a trailing slash; the notice link carries the parameter', () => {
expect(normalizePath('/pl/')).toBe('/pl')
expect(normalizePath('')).toBe('/')
expect(isPathAllowed('/pl/brief/', ['/pl', '/pl/brief'])).toBe(true)
expect(isPathAllowed('/pl/o-nas', ['/pl', '/pl/brief'])).toBe(false)
expect(constructionNoticeHref('/pl')).toBe('/pl?notice=construction')
})
})
describe('under construction — Site Settings → createPageRoute', () => {
let payload: Payload
let configPromise: Parameters<typeof getPayload>[0]['config']
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } as const
beforeAll(async () => {
configPromise = buildConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', index: true, localized: true }] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-construction') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'construction-test-secret',
telemetry: false,
})
payload = await getPayload({ config: configPromise })
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
const redirectError = (url: string): never => {
throw new Error(`REDIRECT ${url}`)
}
const route = () =>
createPageRoute(createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }), {
blocks: {},
notFound: () => {
throw new Error('NEXT_NOT_FOUND')
},
permanentRedirect: vi.fn() as unknown as (url: string) => never,
redirect: redirectError,
})
const open = (locale: string, slug?: string[]) => route().Page({ params: Promise.resolve({ slug, locale }) })
test('off: pages open normally; on: only the homepage and the chosen pages, everything else → homepage + notice', async () => {
const home = await payload.create({ collection: 'pages' as never, data: { slug: 'home', title: 'Start' } as never, locale: 'pl' as never })
const brief = await payload.create({ collection: 'pages' as never, data: { slug: 'brief', title: 'Brief' } as never, locale: 'pl' as never })
await payload.create({ collection: 'pages' as never, data: { slug: 'o-nas', title: 'O nas' } as never, locale: 'pl' as never })
await payload.update({ id: brief.id, collection: 'pages' as never, data: { slug: 'project-brief' } as never, locale: 'en' as never })
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never })
await expect(open('pl', ['o-nas'])).resolves.toBeTruthy()
await payload.updateGlobal({
slug: 'site-settings' as never,
data: { construction: { allowedPages: [brief.id], enabled: true, message: 'Strona w budowie', title: 'Pracujemy nad stroną' } } as never,
locale: 'pl' as never,
})
const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
const mode = await helpers.getConstructionMode('pl')
expect(mode).toMatchObject({ enabled: true, homePath: '/pl', texts: { message: 'Strona w budowie', title: 'Pracujemy nad stroną' } })
expect(mode.allowedPaths).toEqual(expect.arrayContaining(['/pl', '/pl/brief', '/en', '/en/project-brief']))
await expect(open('pl')).resolves.toBeTruthy()
await expect(open('pl', ['brief'])).resolves.toBeTruthy()
await expect(open('pl', ['o-nas'])).rejects.toThrow('REDIRECT /pl?notice=construction')
await expect(open('pl', ['nie-ma'])).rejects.toThrow('REDIRECT /pl?notice=construction')
})
})
+89
View File
@@ -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 <script>' },
{ field: 'website', value: '' },
{ field: 'areas', value: 'web, it' },
{ field: 'size', value: '1-9' },
{ field: 'consent', value: 'true' },
{ field: 'formSubmissionID', value: '42' },
]
describe('e-mail layout', () => {
test('summary: questions + option labels, grouped by step, blanks and empty steps left out', () => {
expect(buildSubmissionSummary(fields, stored)).toEqual([
{
rows: [
{ label: 'Nazwa firmy', value: 'Acme <script>' },
{ label: 'Obszary', value: 'Strony internetowe, IT' },
{ label: 'Wielkość', value: 'Do 10' },
{ label: 'Zgoda RODO', value: '✓' },
],
title: 'O firmie',
},
])
})
test('summary HTML is escaped; the form-builder table (also inside <p>) is replaced', () => {
const html = renderSummaryHtml(buildSubmissionSummary(fields, stored), { accent: '#017BD0' })
expect(html).toContain('Acme &lt;script&gt;')
expect(html).not.toContain('<script>')
expect(replaceSubmissionTable('<p>Nowe:</p><p><table><tr><td>company</td><td>x</td></tr></table></p>', '[S]')).toBe('<p>Nowe:</p>[S]')
})
test('layout: logo or site name, accent colour, footer', () => {
const withLogo = wrapEmailHtml({ accent: '#017BD0', content: '<p>Hi</p>', footer: 'Acme sp. z o.o.\nWrocław', logoUrl: 'https://cdn.acme.pl/logo.png', siteName: 'Acme', siteUrl: 'https://acme.pl' })
expect(withLogo).toContain('src="https://cdn.acme.pl/logo.png"')
expect(withLogo).toContain('border-top:4px solid #017BD0')
expect(withLogo).toContain('Acme sp. z o.o.<br>Wrocław')
expect(wrapEmailHtml({ accent: '#111827', content: '', siteName: 'Acme' })).toContain('>Acme</span>')
})
test('hook: summary + layout from Site Settings → Emails; on an error the original e-mails go out', async () => {
const payload = {
config: { serverURL: 'https://acme.pl/' },
findByID: vi.fn(async () => ({ fields })),
findGlobal: vi.fn(async () => ({ email: { accentColor: '#017BD0', footer: 'Acme', logo: { url: '/api/media/file/logo.png' } }, siteName: 'Acme' })),
logger: { error: vi.fn() },
}
const hook = buildEmailLayoutHook()
const email = { from: '[email protected]', html: '<div><p><table><tr><td>company</td><td>Acme</td></tr></table></p></div>', replyTo: '[email protected]', subject: 'Nowy brief', to: '[email protected]' }
const req = { locale: 'en', payload } as unknown as PayloadRequest
const [out] = await hook([email], { data: { form: 5, submissionData: stored }, req })
expect(payload.findByID).toHaveBeenCalledWith(expect.objectContaining({ id: 5, locale: 'en' }))
expect(out.html).toContain('Strony internetowe, IT')
expect(out.html).toContain('src="https://acme.pl/api/media/file/logo.png"')
expect(out.html).not.toContain('<td>company</td>')
payload.findByID.mockRejectedValueOnce(new Error('db down'))
expect(await hook([email], { data: { form: 5, submissionData: stored }, req })).toEqual([email])
expect(payload.logger.error).toHaveBeenCalled()
})
test('submitForm stores the submission in the page language (e-mail texts per language)', async () => {
const { create, payload } = fakePayload({ forms: { f: { fields: [{ name: 'company', blockType: 'text' }] } } })
await submitForm({ data: { company: 'Acme' }, formId: 'f', locale: 'en', maxPerMinute: 0, payload })
expect(create).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en' }))
})
})