/** * Content seed from the brief — skill ipal-site, phase 6. * * pnpm payload run scripts/seed-content.ts # creates what's missing, never overwrites * SEED_UPDATE=1 pnpm payload run scripts/seed-content.ts # also updates existing docs (asks nobody — use before handover only) * * Write content ONCE, all languages side by side: * heading: { pl: 'Nasze usługi', en: 'Our services' } → localized value * heading: 'Nasze usługi' → same in every locale / non-localized field * page: { $page: 'kontakt' } → ID of the page whose DEFAULT-locale slug is 'kontakt' * Missing data: '[DO UZUPEŁNIENIA: NIP]' — never invent company data, prices, reviews, numbers. * * The default locale creates the structure (blocks, array rows); other locales are * written onto the SAME row ids, so nothing is duplicated. Media: leave empty or * reference existing uploads by ID — the editor adds images. * * GOTCHA (Payload, localization.fallback: true): an 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 write below sets it. */ import { getPayload } from 'payload' import config from '@payload-config' type Json = string | number | boolean | null | Json[] | { [k: string]: Json } // ------------------------------------------------------------------ CONTENT -- const PAGES: { [k: string]: Json }[] = [ { title: { pl: 'Strona główna', en: 'Home' }, slug: { pl: 'home', en: 'home' }, layout: [ { blockType: 'hero', heading: { pl: 'Nagłówek z briefu', en: 'Heading from the brief' }, links: [{ link: { type: 'internal', page: { $page: 'kontakt' }, label: { pl: 'Kontakt', en: 'Contact' }, appearance: 'primary' } }], }, ], }, { title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' }, layout: [] }, ] const GLOBALS: { slug: string; data: { [k: string]: Json } }[] = [ // { slug: 'header', data: { links: [{ link: { type: 'internal', page: { $page: 'kontakt' }, label: { pl: 'Kontakt', en: 'Contact' } } }] } }, ] const COLLECTION = 'pages' // ----------------------------------------------------------------- /CONTENT -- const UPDATE = process.env.SEED_UPDATE === '1' const payload = await getPayload({ config }) const loc = payload.config.localization const def = loc ? loc.defaultLocale : undefined const codes = loc ? loc.localeCodes : [] const others = codes.filter((c) => c !== def) const ids = new Map() const isLocalized = (v: Json): boolean => !!v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => codes.includes(k)) /** Value for one locale; arrays keep the ids of rows that already exist. undefined = omit. */ function pick(v: Json, locale: string | undefined, existing: unknown): Json | undefined { if (isLocalized(v)) { const m = v as { [k: string]: Json }; return locale ? m[locale] : m[def as string] } if (Array.isArray(v)) { const ex = Array.isArray(existing) ? existing : [] return v.map((item, i) => { const out = pick(item, locale, ex[i]) const id = (ex[i] as { id?: string } | undefined)?.id return out && typeof out === 'object' && !Array.isArray(out) && id ? { ...out, id } : (out ?? null) }) } if (v && typeof v === 'object') { if (typeof v.$page === 'string') { const id = ids.get(v.$page) if (id === undefined) throw new Error(`$page "${v.$page}" not found — seed that page earlier in PAGES or create it in the panel`) return id } const ex = (existing && typeof existing === 'object' ? existing : {}) as Record const out: { [k: string]: Json } = {} for (const [k, val] of Object.entries(v) as [string, Json][]) { const r = pick(val, locale, ex[k]) if (r !== undefined) out[k] = r } return out } return v } const defSlug = (p: { [k: string]: Json }) => String(isLocalized(p.slug) ? (p.slug as { [k: string]: Json })[def as string] : p.slug) const hasPageRef = (v: Json): boolean => Array.isArray(v) ? v.some(hasPageRef) : !!v && typeof v === 'object' ? typeof v.$page === 'string' || Object.values(v).some(hasPageRef) : false // Existing pages first, so $page works regardless of order. const { docs: existingPages } = await payload.find({ collection: COLLECTION as never, depth: 0, limit: 0, pagination: false, ...(def ? { locale: def as never } : {}) }) for (const d of existingPages as { id: string | number; slug?: string }[]) if (d.slug) ids.set(d.slug, d.id) const hasContent = (v: unknown): boolean => typeof v === 'string' ? v.trim() !== '' : typeof v === 'number' || v === true ? true : Array.isArray(v) ? v.some(hasContent) : !!v && typeof v === 'object' ? Object.entries(v).some(([k, x]) => k !== 'id' && hasContent(x)) : false const log: string[] = [] const writeLocales = async (write: (locale: string | undefined, existing: unknown) => Promise, read: (l: string) => Promise) => { for (const l of others) await write(l, await read(def as string)) } // Pass 1: create missing pages without layout links (targets may not exist yet), pass 2: full content. for (const pass of [1, 2] as const) { for (const p of PAGES) { const slug = defSlug(p) let id = ids.get(slug) if (pass === 1) { if (id !== undefined) continue const data = pick(hasPageRef(p) ? { ...p, layout: [] } : p, def, undefined) as Record const created = await payload.create({ collection: COLLECTION as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: { ipalSeed: true } }) id = (created as { id: string | number }).id ids.set(slug, id) log.push(`created ${COLLECTION}/${String(id)} "${slug}"`) continue } const fresh = log.includes(`created ${COLLECTION}/${String(id)} "${slug}"`) if (!fresh && !UPDATE) { log.push(`skipped "${slug}" (exists — SEED_UPDATE=1 to overwrite)`); continue } const readDoc = (l: string) => payload.findByID({ collection: COLLECTION as never, id: id as never, depth: 0, locale: l as never, fallbackLocale: false as never }) await payload.update({ collection: COLLECTION as never, id: id as never, data: pick(p, def, undefined) as never, depth: 0, ...(def ? { locale: def as never } : {}), context: { ipalSeed: true } }) await writeLocales( (l, ex) => payload.update({ collection: COLLECTION as never, id: id as never, data: pick(p, l, ex) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: { ipalSeed: true } }), readDoc, ) log.push(`${fresh ? 'filled' : 'updated'} "${slug}" [${codes.join(', ') || '-'}]`) } } for (const g of GLOBALS) { const readG = (l: string) => payload.findGlobal({ slug: g.slug as never, depth: 0, locale: l as never, fallbackLocale: false as never }) if (!UPDATE && def) { const cur = (await readG(def)) as Record const filled = Object.keys(g.data).some((k) => hasContent(cur[k])) if (filled) { log.push(`skipped global ${g.slug} (has content — SEED_UPDATE=1 to overwrite)`); continue } } await payload.updateGlobal({ slug: g.slug as never, data: pick(g.data, def, undefined) as never, depth: 0, ...(def ? { locale: def as never } : {}), context: { ipalSeed: true } }) await writeLocales((l, ex) => payload.updateGlobal({ slug: g.slug as never, data: pick(g.data, l, ex) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: { ipalSeed: true } }), readG) log.push(`global ${g.slug} [${codes.join(', ') || '-'}]`) } for (const line of log) console.log(line) const todo = JSON.stringify({ PAGES, GLOBALS }).match(/\[DO UZUPEŁNIENIA:[^\]]*\]/g) ?? [] if (todo.length) console.log(`\n${todo.length} placeholder(s) for the final report:\n ${[...new Set(todo)].join('\n ')}`) process.exit(0)