- Translate to English every doc the code branches did not touch: AGENT.md, developer guide, vibe, CHANGELOG, docs index, module pages, all skills except ipal-seo-check (14 pages follow after the security/SEO merge). Placeholder marker is now [TO FILL: …]; skill resources renamed to section-code.md / nav-code.md. AGENT.md and the ipal-skills pointer block say the docs are in English. - docs/seeding.md: create-only, natural keys, never delete, no users or secrets, empty-field globals, fallbackLocale: false, dry run, backup and restore, production update guard, seeds vs migrations, Coolify Terminal. Seed templates gain --dry-run, the SEED_UPDATE production guard (IPAL_SEED_ALLOW_PROD_UPDATE), skip of edited records and a summary. "Seeding on production" rule block in AGENT.md. - Coolify is the single deployment path (deployment, env, developer guide, ipal-setup): build vs runtime env, migrations on container start (prodMigrations), health check and rolling updates, rollback, backups and restore, DNS/Let's Encrypt/CAA. R2: custom domain needs a Cloudflare zone; default is media served by the app (R2_PUBLIC_URL empty). - docsConsistency: no Polish prose outside code/quoted data (pending pages listed); IPAL_* names may also be read by shipped skill templates. Co-Authored-By: Claude Opus 5.5 <[email protected]>
345 lines
17 KiB
TypeScript
345 lines
17 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 (rules: docs/seeding.md):
|
|
*
|
|
* SEED_DRY_RUN=1 pnpm payload run scripts/seed-form-contact.ts # no writes: prints create / skip / update
|
|
* pnpm payload run scripts/seed-form-contact.ts # creates the form if missing, never overwrites
|
|
* SEED_UPDATE=1 pnpm payload run scripts/seed-form-contact.ts # also updates it if nobody edited it since seeding
|
|
* (`--dry-run` after the script path works too.)
|
|
*
|
|
* Safety: the form is matched by its title; nothing is ever deleted. SEED_UPDATE=1 is
|
|
* refused when NODE_ENV=production or the database is not local, unless
|
|
* IPAL_SEED_ALLOW_PROD_UPDATE=1 is also set — back up the database first. A form an
|
|
* editor changed is skipped and reported ("skip (edited)"); see SAFETY below.
|
|
*
|
|
* 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).
|
|
*
|
|
* GOTCHA (Payload, localization.fallback: true): a read or update in locale X without
|
|
* `fallbackLocale: false` merges the FALLBACK values into X — the default-locale
|
|
* text gets saved as the X translation. Every non-default read and write below sets it.
|
|
*/
|
|
import { createHash } from 'node:crypto'
|
|
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' }
|
|
// ────────────────────────────────────────────────────────────────────────────
|
|
|
|
// ─── SAFETY — defaults the project may change here or through env (docs/seeding.md) ───
|
|
/** Env var that holds the database URL (ipal-kit projects: DATABASE_URI). */
|
|
const DB_URL_ENV = process.env.SEED_DB_URL_ENV || 'DATABASE_URI'
|
|
/** Hosts that count as a local database. Add more with SEED_LOCAL_HOSTS=db,postgres. */
|
|
const LOCAL_HOSTS = ['localhost', '127.0.0.1', '::1', ...(process.env.SEED_LOCAL_HOSTS ?? '').split(',').map((h) => h.trim()).filter(Boolean)]
|
|
/**
|
|
* "Untouched since seeding", primary method: updatedAt is at most this many seconds
|
|
* after createdAt. After one seeded update the form counts as edited — add a hidden
|
|
* SEED_HASH_FIELD (formOverrides) for repeated updates.
|
|
*/
|
|
const UNTOUCHED_SECONDS = Number(process.env.SEED_UNTOUCHED_SECONDS ?? 120)
|
|
/** Optional: hidden text field with a hash of the seeded values; used only if the forms collection has it. */
|
|
const HASH_FIELD = process.env.SEED_HASH_FIELD ?? 'seedHash'
|
|
/** SEED_FORCE=1 also overwrites an edited form — refused outside a local database. */
|
|
const FORCE_ONLY_LOCAL = true
|
|
// ────────────────────────────────────────────────────────────────────────────
|
|
|
|
const DRY = process.argv.includes('--dry-run') || process.env.SEED_DRY_RUN === '1'
|
|
const UPDATE = process.env.SEED_UPDATE === '1'
|
|
const FORCE = UPDATE && process.env.SEED_FORCE === '1'
|
|
|
|
function dbIsLocal(): boolean {
|
|
const url = (process.env[DB_URL_ENV] ?? '').trim()
|
|
if (!url) return false
|
|
if (/^file:/i.test(url) || /\.(db|sqlite3?)$/i.test(url)) return true // SQLite file
|
|
try {
|
|
const u = new URL(url)
|
|
if (u.protocol === 'mongodb+srv:') return false
|
|
if (u.searchParams.get('host')?.startsWith('/')) return true // ?host=/var/run/postgresql
|
|
const host = decodeURIComponent(u.hostname).replace(/^\[|\]$/g, '')
|
|
if (!host || host.startsWith('/')) return true // postgres:///db = unix socket
|
|
return LOCAL_HOSTS.includes(host)
|
|
} catch {
|
|
return false // unparsable (e.g. several Mongo hosts) = not local
|
|
}
|
|
}
|
|
|
|
const local = dbIsLocal()
|
|
const prodLike = process.env.NODE_ENV === 'production' || !local
|
|
if (UPDATE && prodLike && process.env.IPAL_SEED_ALLOW_PROD_UPDATE !== '1') {
|
|
console.error(
|
|
`[seed-form] SEED_UPDATE=1 refused: ${process.env.NODE_ENV === 'production' ? 'NODE_ENV=production' : `${DB_URL_ENV} is not a local database`}.\n` +
|
|
' 1. Back up the database (Coolify → database → Backups → Backup now, or pg_dump -Fc "$DATABASE_URI" > before-seed.dump).\n' +
|
|
' 2. Run with SEED_DRY_RUN=1 and read the plan.\n' +
|
|
' 3. Run again with IPAL_SEED_ALLOW_PROD_UPDATE=1. An edited form is still skipped.',
|
|
)
|
|
process.exit(1)
|
|
}
|
|
if (FORCE && FORCE_ONLY_LOCAL && prodLike) {
|
|
console.error('[seed-form] SEED_FORCE=1 refused: it overwrites editors\' changes and works only on a local database.')
|
|
process.exit(1)
|
|
}
|
|
if (UPDATE && prodLike) console.warn('[seed-form] Updating a production-like database (IPAL_SEED_ALLOW_PROD_UPDATE=1). Did you back it up?')
|
|
|
|
// disableRevalidate + ipalSkipIndexNow: the plugin's hooks skip revalidation and IndexNow. ipalSeed: for project hooks.
|
|
const CTX = { ipalSeed: true, disableRevalidate: true, ipalSkipIndexNow: true }
|
|
|
|
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,
|
|
}
|
|
}
|
|
|
|
/** JSON with sorted keys, no row ids, null = missing — so equal content gives an equal hash. */
|
|
const stable = (v: unknown): string =>
|
|
Array.isArray(v) ? `[${v.map(stable).join(',')}]`
|
|
: v && typeof v === 'object'
|
|
? `{${Object.keys(v).filter((k) => k !== 'id' && (v as Record<string, unknown>)[k] != null).sort()
|
|
.map((k) => `${JSON.stringify(k)}:${stable((v as Record<string, unknown>)[k])}`).join(',')}}`
|
|
: JSON.stringify(v ?? null)
|
|
const hashOf = (v: unknown) => createHash('sha256').update(stable(v)).digest('hex').slice(0, 32)
|
|
/** The current values at the keys the seed writes (everything else in the form is ignored). */
|
|
function project(seed: unknown, cur: unknown): unknown {
|
|
if (Array.isArray(seed)) return Array.isArray(cur) && cur.length === seed.length ? seed.map((x, i) => project(x, cur[i])) : cur
|
|
if (seed && typeof seed === 'object') {
|
|
if (!cur || typeof cur !== 'object' || Array.isArray(cur)) return cur
|
|
return Object.fromEntries(Object.keys(seed).map((k) => [k, project((seed as Record<string, unknown>)[k], (cur as Record<string, unknown>)[k])]))
|
|
}
|
|
return cur
|
|
}
|
|
const seedHash = () => hashOf(Object.fromEntries(locales.map((l) => [l, dataFor(l)])))
|
|
const hasHashField = !!HASH_FIELD && !!(payload.collections['forms' as never]?.config.fields as { name?: string }[] | undefined)?.some((f) => f.name === HASH_FIELD)
|
|
|
|
type FormDoc = Record<string, unknown> & { emails?: { id?: string }[]; fields?: { id?: string; options?: { id?: string }[] }[] }
|
|
const readForm = async (formId: number | string, locale: string) =>
|
|
(await payload.findByID({ collection: 'forms' as never, depth: 0, id: formId, locale: locale as never, fallbackLocale: false as never })) as FormDoc
|
|
|
|
/** null = untouched since seeding; a string = why it counts as edited. */
|
|
async function editedReason(formId: number | string): Promise<string | null> {
|
|
const doc = await readForm(formId, defaultLocale)
|
|
const stored = hasHashField ? doc[HASH_FIELD] : undefined
|
|
if (typeof stored === 'string' && stored) {
|
|
const current: Record<string, unknown> = {}
|
|
for (const l of locales) current[l] = project(dataFor(l), l === defaultLocale ? doc : await readForm(formId, l))
|
|
return hashOf(current) === stored ? null : `${HASH_FIELD} differs`
|
|
}
|
|
const c = Date.parse(String(doc.createdAt)), u = Date.parse(String(doc.updatedAt))
|
|
if (!Number.isFinite(c) || !Number.isFinite(u)) return 'no createdAt/updatedAt'
|
|
const sec = Math.round((u - c) / 1000)
|
|
return sec <= UNTOUCHED_SECONDS ? null : `updated ${sec}s after creation`
|
|
}
|
|
|
|
/** Locale data onto the existing row ids (fields, their options, e-mails) — new ids would wipe the other languages' texts. */
|
|
function withRowIds(d: ReturnType<typeof dataFor>, doc: FormDoc | undefined) {
|
|
if (!doc) return d
|
|
return {
|
|
...d,
|
|
emails: d.emails.map((e, i) => ({ ...e, id: doc.emails?.[i]?.id })),
|
|
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 })) }
|
|
: {}),
|
|
})),
|
|
}
|
|
}
|
|
|
|
const summary = (status: string, errors = 0) => {
|
|
console.log(`\n[seed-form] summary${DRY ? ' (dry run — nothing written)' : ''}`)
|
|
console.table({
|
|
created: status === 'create' ? 1 : 0,
|
|
skipped: status === 'skip (exists)' ? 1 : 0,
|
|
updated: status === 'update' ? 1 : 0,
|
|
'skipped-edited': status === 'skip (edited)' ? 1 : 0,
|
|
errors,
|
|
})
|
|
}
|
|
|
|
console.log(`[seed-form] ${DRY ? 'DRY RUN — nothing is written' : 'writing'} · ${UPDATE ? `updates on${FORCE ? ' (FORCE)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'}`)
|
|
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
|
|
let status: 'create' | 'skip (exists)' | 'update' | 'skip (edited)' = id ? 'update' : 'create'
|
|
let note = ''
|
|
if (id && !UPDATE) { status = 'skip (exists)'; note = 'SEED_UPDATE=1 updates it if nobody edited it' }
|
|
if (id && UPDATE) {
|
|
const why = await editedReason(id)
|
|
if (why && !FORCE) { status = 'skip (edited)'; note = why }
|
|
}
|
|
if (DRY || status === 'skip (exists)' || status === 'skip (edited)') {
|
|
console.log(`${status.padEnd(14)} form "${FORM.title}"${id ? ` (id ${id})` : ''}${note ? ` — ${note}` : ''}`)
|
|
summary(status)
|
|
process.exit(0)
|
|
}
|
|
|
|
try {
|
|
const hash = hasHashField ? { [HASH_FIELD]: seedHash() } : {}
|
|
if (!id) {
|
|
const created = await payload.create({ collection: 'forms' as never, data: { ...dataFor(defaultLocale), ...hash } as never, locale: defaultLocale as never, context: CTX })
|
|
id = created.id
|
|
} else {
|
|
const doc = await readForm(id, defaultLocale)
|
|
await payload.update({ collection: 'forms' as never, data: { ...withRowIds(dataFor(defaultLocale), doc), ...hash } as never, id, locale: defaultLocale as never, context: CTX })
|
|
}
|
|
const formId = id
|
|
|
|
// Other languages: same rows (ids kept), localized texts per locale.
|
|
for (const locale of locales.filter((l) => l !== defaultLocale)) {
|
|
const doc = await readForm(formId, locale)
|
|
await payload.update({
|
|
collection: 'forms' as never,
|
|
data: withRowIds(dataFor(locale), doc) as never,
|
|
id: formId,
|
|
locale: locale as never,
|
|
fallbackLocale: false as never,
|
|
context: CTX,
|
|
})
|
|
}
|
|
} catch (e) {
|
|
console.error(`error form "${FORM.title}" — ${(e as Error).message}`)
|
|
summary('', 1)
|
|
process.exit(1)
|
|
}
|
|
|
|
console.log(`${status.padEnd(14)} form "${FORM.title}" (id ${id}) in ${locales.join(', ')} — notifications to ${notifyTo}, confirmation to the sender.`)
|
|
summary(status)
|
|
console.log('Next: place the form in a Form block on the contact page, then Site Integrations → Send test.')
|
|
process.exit(0)
|