Files
ipal-kit/docs/agent/skills/ipal-form/resources/seed-form.template.ts
T
radoslaw.smolinskiandClaude Opus 5.5 81e864bde9 Docs for 1.9.2: import instead of code; docs↔code consistency test; audit accepts one-line routes
- AGENT.md: §7 full capability catalog (need → import), §0b/§3/§6 on RenderForm, SiteProviders,
  createPageRoute, re-exported routes, plugin section fields, resolveLink/resolveNav
- PROGRAMISTA §2.4, §2.7–2.8 rewritten; §6 items 28–33 (28: FormRenderer leaked the Emails tab)
- forms, links, blocks, pages, consent, turnstile, notifications, seo, mcp, i18n, deployment docs
- ipal-form: RenderForm block, formClasses, CustomForm example (FormRenderer template removed),
  seed template handles steps and option labels per language
- ipal-nav, ipal-block, ipal-setup, ipal-upgrade, ipal-seo-check, ipal-consent-check, vibe.md
- ipal-audit: re-export routes and SiteProviders satisfy the mandatory set; flags form-engine copies,
  project section fields / navigation, server entries in client components
- test/docsConsistency: docs imports exist in code; every public export is documented
- CHANGELOG 1.9.2

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 11:52:29 +02:00

204 lines
9.2 KiB
TypeScript

/**
* Seed of ONE form in the database — fields, confirmation, and the two e-mails
* every site needs: a notification to the company and a confirmation to the
* person who sent it. Copy to scripts/seed-form-<name>.ts, fill FORM from the
* brief (every language), run:
*
* pnpm payload run scripts/seed-form-contact.ts # creates the form if missing
* SEED_UPDATE=1 pnpm payload run scripts/seed-form-contact.ts # also overwrites an existing one
*
* Nothing about the company lives in this file. The notification address comes
* from the panel — NOTIFY.global / NOTIFY.field below (the project's company
* global) — or SEED_NOTIFY_EMAIL for a first run. Without an address the script
* stops: a form whose submissions reach nobody is a bug, not a default.
*
* Safe to send to {{email}}: submitForm accepts exactly one address in an
* `email` field (no extra recipients, no header injection).
*/
import config from '@payload-config'
import { getPayload } from 'payload'
// ─── fill from the brief ────────────────────────────────────────────────────
const FORM = {
/** Unique, not shown to visitors — the seed finds the form by it. */
title: 'Contact form',
fields: [
{ blockType: 'text', name: 'name', required: true, width: 50, label: { pl: 'Imię i nazwisko', en: 'Full name' } },
{ blockType: 'email', name: 'email', required: true, width: 50, label: { pl: 'E-mail', en: 'E-mail' } },
{ blockType: 'text', name: 'phone', required: false, width: 50, label: { pl: 'Telefon', en: 'Phone' } },
{ blockType: 'textarea', name: 'message', required: true, width: 100, label: { pl: 'Wiadomość', en: 'Message' } },
// Step-by-step form: a `step` block starts a new screen (title/description per language).
// { blockType: 'step', title: { pl: 'Projekt', en: 'Project' } },
// Choice lists (option labels per language, values stay the same):
// { blockType: 'radio', name: 'budget', required: true, label: { pl: 'Budżet', en: 'Budget' },
// options: [{ value: 's', label: { pl: 'do 10 tys.', en: 'up to 10k' } }, …] },
// { blockType: 'checkboxGroup', name: 'services', maxSelected: 3, label: {…}, options: [ …same shape… ] },
// { blockType: 'date', name: 'deadline', label: { pl: 'Termin', en: 'Deadline' } },
// GDPR consent — name MUST stay `consent`; never pre-ticked (the plugin enforces it server-side).
{
blockType: 'checkbox',
name: 'consent',
required: true,
width: 100,
label: {
pl: 'Zgadzam się na przetwarzanie moich danych w celu odpowiedzi na wiadomość.',
en: 'I agree to the processing of my data to answer this message.',
},
},
],
submitButtonLabel: { pl: 'Wyślij', en: 'Send' },
confirmation: {
pl: 'Dziękujemy! Odpowiemy najszybciej, jak to możliwe.',
en: 'Thank you! We will get back to you as soon as possible.',
},
/** E-mail to the company. {{*:table}} = every field as a table. */
notification: {
subject: { pl: 'Nowa wiadomość ze strony od {{name}}', en: 'New website message from {{name}}' },
message: { pl: 'Nowe zgłoszenie z formularza:\n\n{{*:table}}', en: 'New form submission:\n\n{{*:table}}' },
},
/** E-mail to the sender. */
confirmationEmail: {
subject: { pl: 'Otrzymaliśmy Twoją wiadomość', en: 'We received your message' },
message: {
pl: 'Dzień dobry {{name}},\n\ndziękujemy za wiadomość — odpowiemy wkrótce.\n\nTwoje zgłoszenie:\n{{*:table}}',
en: 'Hello {{name}},\n\nthank you for your message — we will reply shortly.\n\nYour submission:\n{{*:table}}',
},
},
} as const
/** Where the company's address lives in the panel (project global + field). */
const NOTIFY = { global: 'company', field: 'email' }
// ────────────────────────────────────────────────────────────────────────────
type Localized = Readonly<Record<string, string>>
/** Plain text (with blank-line paragraphs) → Lexical rich text, as form-builder messages expect. */
function richText(text: string) {
return {
root: {
children: text.split(/\n{2,}/).map((para) => ({
children: para.split('\n').flatMap((line, i) => [
...(i ? [{ type: 'linebreak', version: 1 }] : []),
{ detail: 0, format: 0, mode: 'normal', style: '', text: line, type: 'text', version: 1 },
]),
direction: 'ltr',
format: '',
indent: 0,
type: 'paragraph',
version: 1,
})),
direction: 'ltr',
format: '',
indent: 0,
type: 'root',
version: 1,
},
}
}
const payload = await getPayload({ config })
const locales = (payload.config.localization ? payload.config.localization.localeCodes : ['pl']) as string[]
const defaultLocale = (payload.config.localization ? payload.config.localization.defaultLocale : locales[0]) as string
const pick = (value: Localized, locale: string) => value[locale] ?? value[defaultLocale] ?? Object.values(value)[0]
// Notification address — from the panel, never from this file.
let notifyTo = process.env.SEED_NOTIFY_EMAIL?.trim() ?? ''
if (!notifyTo) {
try {
const g = (await payload.findGlobal({ slug: NOTIFY.global as never, depth: 0 })) as Record<string, unknown>
notifyTo = typeof g[NOTIFY.field] === 'string' ? (g[NOTIFY.field] as string).trim() : ''
} catch {
// no such global — handled below
}
}
if (!/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(notifyTo)) {
console.error(
`[seed-form] No notification address. Fill ${NOTIFY.global} → ${NOTIFY.field} in the panel ` +
'(or run with SEED_NOTIFY_EMAIL=…). Ask the client which inbox gets the submissions — do not guess.',
)
process.exit(1)
}
/** A field with every per-language text ({ pl, en }) resolved: label, step title/description, option labels. */
function localizeField(field: Record<string, unknown>, locale: string): Record<string, unknown> {
const text = (v: unknown) => (v && typeof v === 'object' ? pick(v as Localized, locale) : v)
return {
...field,
...('label' in field ? { label: text(field.label) } : {}),
...('title' in field ? { title: text(field.title) } : {}),
...('description' in field ? { description: text(field.description) } : {}),
...(Array.isArray(field.options)
? { options: (field.options as Record<string, unknown>[]).map((o) => ({ ...o, label: text(o.label) })) }
: {}),
}
}
/** Form data in one locale (localized fields resolved for it). */
function dataFor(locale: string) {
return {
confirmationMessage: richText(pick(FORM.confirmation, locale)),
confirmationType: 'message',
emails: [
{
emailTo: notifyTo,
replyTo: '{{email}}',
message: richText(pick(FORM.notification.message, locale)),
subject: pick(FORM.notification.subject, locale),
},
{
emailTo: '{{email}}',
replyTo: notifyTo,
message: richText(pick(FORM.confirmationEmail.message, locale)),
subject: pick(FORM.confirmationEmail.subject, locale),
},
],
fields: FORM.fields.map((field) => localizeField(field as Record<string, unknown>, locale)),
submitButtonLabel: pick(FORM.submitButtonLabel, locale),
title: FORM.title,
}
}
const existing = await payload.find({ collection: 'forms' as never, limit: 1, where: { title: { equals: FORM.title } } })
let id = existing.docs[0]?.id as number | string | undefined
if (id && process.env.SEED_UPDATE !== '1') {
console.log(`[seed-form] "${FORM.title}" exists (id ${id}) — unchanged. SEED_UPDATE=1 overwrites it.`)
process.exit(0)
}
if (!id) {
const created = await payload.create({ collection: 'forms' as never, data: dataFor(defaultLocale) as never, locale: defaultLocale as never })
id = created.id
} else {
await payload.update({ collection: 'forms' as never, data: dataFor(defaultLocale) as never, id, locale: defaultLocale as never })
}
// Other languages: same rows (ids kept), localized texts per locale.
for (const locale of locales.filter((l) => l !== defaultLocale)) {
const doc = (await payload.findByID({ collection: 'forms' as never, depth: 0, id, locale: locale as never })) as {
emails?: { id?: string }[]
fields?: { id?: string; options?: { id?: string }[] }[]
}
const d = dataFor(locale)
await payload.update({
collection: 'forms' as never,
data: {
...d,
emails: d.emails.map((e, i) => ({ ...e, id: doc.emails?.[i]?.id })),
// Keep row ids (fields and their options) — new ids would wipe the other languages' texts.
fields: d.fields.map((f, i) => ({
...f,
id: doc.fields?.[i]?.id,
...(Array.isArray(f.options)
? { options: (f.options as Record<string, unknown>[]).map((o, j) => ({ ...o, id: doc.fields?.[i]?.options?.[j]?.id })) }
: {}),
})),
} as never,
id,
locale: locale as never,
})
}
console.log(`[seed-form] "${FORM.title}" ready (id ${id}) in ${locales.join(', ')} — notifications to ${notifyTo}, confirmation to the sender.`)
console.log('Next: place the form in a Form block on the contact page, then Site Integrations → Send test.')
process.exit(0)