{{*: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]>
121 lines
5.5 KiB
TypeScript
121 lines
5.5 KiB
TypeScript
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'
|
|
|
|
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 } }
|
|
|
|
/** A built-in form-builder block with "Show only when" added (full block — form-builder merges arrays by replacing). */
|
|
const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'radio' | 'select' | 'text' | 'textarea') =>
|
|
withShowWhen(builtinBlocks[key] as Block)
|
|
|
|
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
|
|
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
|
|
/**
|
|
* Submissions are visitors' personal data: editors and admins only. The
|
|
* form-builder default lets ANY account of the admin collection read them —
|
|
* including a plain 'user' from an open sign-up.
|
|
*/
|
|
const submissionsReadAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor')
|
|
const submissionsDeleteAccess = ({ req }: AccessArgs) => isAdmin(req.user as never)
|
|
|
|
/**
|
|
* Forms stay publicly readable (their fields render the form), but the Emails
|
|
* tab — recipient addresses, templates — is for logged-in staff only, so
|
|
* GET /api/forms doesn't hand out the company's inboxes to spammers.
|
|
*/
|
|
function hideEmails(fields: Field[]): Field[] {
|
|
return fields.map((field) =>
|
|
'name' in field && field.name === 'emails'
|
|
? ({
|
|
...field,
|
|
access: { ...(field as { access?: object }).access, read: ({ req }: AccessArgs) => Boolean(req.user) },
|
|
} as Field)
|
|
: field,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.
|
|
*
|
|
* Provides the forms / form-submissions collections and field types. E-mails
|
|
* after a submission are the form-builder's own (Forms → Emails), sent through
|
|
* the project's email adapter (mailAdapter()).
|
|
*
|
|
* SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.
|
|
* anyone can POST /api/form-submissions and skip everything submitForm enforces
|
|
* (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL
|
|
* creation is limited to logged-in users; the site submits through submitForm
|
|
* (server action → Local API, which bypasses access by design). A project that
|
|
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
|
|
*/
|
|
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.
|
|
fields: {
|
|
// every block carries "Show only when" (showWhen) — conditional fields and steps
|
|
checkbox: builtin('checkbox'),
|
|
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
|
|
date: builtin('date'),
|
|
email: builtin('email'),
|
|
message: builtin('message'),
|
|
number: builtin('number'),
|
|
payment: false,
|
|
radio: builtin('radio'),
|
|
select: builtin('select'),
|
|
step: forms.fields?.step === false ? false : stepBlock,
|
|
text: builtin('text'),
|
|
textarea: builtin('textarea'),
|
|
...Object.fromEntries(
|
|
// `true` keeps ipal's block (with "Show only when"); false / an object override it
|
|
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && v !== true),
|
|
),
|
|
},
|
|
...(forms.redirectRelationships
|
|
? { redirectRelationships: forms.redirectRelationships }
|
|
: {}),
|
|
// Client-supplied collection overrides (e.g. a per-form notification
|
|
// address). The plugin provides the hook, not the opinion about which
|
|
// extra fields a form should carry.
|
|
// Tidy panel by default: both collections under one sidebar group with plain
|
|
// labels — no per-project overrides needed just to sort the sidebar.
|
|
formOverrides: {
|
|
labels: { plural: 'Forms', singular: 'Form' },
|
|
...forms.formOverrides,
|
|
admin: { ...group, ...forms.formOverrides?.admin },
|
|
fields: ({ defaultFields }) =>
|
|
hideEmails(forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields }) : defaultFields),
|
|
},
|
|
formSubmissionOverrides: {
|
|
labels: { plural: 'Submissions', singular: 'Submission' },
|
|
...forms.formSubmissionOverrides,
|
|
access: {
|
|
create: submissionsCreateAccess,
|
|
delete: submissionsDeleteAccess,
|
|
read: submissionsReadAccess,
|
|
...forms.formSubmissionOverrides?.access,
|
|
},
|
|
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
|
|
},
|
|
})
|
|
}
|