feat(cms): MongoDB → PostgreSQL content transfer; fix two schema issues it found (MITHOME-136)

- scripts/transfer-content.ts: export (shared config + MongoDB adapter,
  locale 'all', drafts, upload files) and import (PostgreSQL, one transaction,
  refuses a non-empty target); pure helpers in src/lib/content-transfer.ts
- LegalPages: the section anchor is its own field; as the array row id it was
  a table-wide primary key in PostgreSQL and the two pages collided
- Products.status: own enumName; the default name equalled the drafts
  _status enum, so only draft/published were accepted
- baseline migration regenerated

Verified on a staging copy (disposable MongoDB + PostgreSQL on llmdev): counts
match, all 14 public pages (hu/en) render identical text, partner logo loads,
second import writes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Do Siki
2026-09-29 22:27:11 +02:00
co-authored by Claude Opus 5.5
parent e3ec6a9ac3
commit a68fb94b61
14 changed files with 500 additions and 50 deletions
+7 -2
View File
@@ -142,6 +142,11 @@ type LegalPageJson = {
sections: { id: string; title: string; content: string }[]
}
/** MITHOME-136: the JSON section `id` is the section anchor. */
function toLegalData({ sections, ...rest }: LegalPageJson) {
return { ...rest, sections: sections.map(({ id, ...section }) => ({ anchor: id, ...section })) }
}
/** Collections have no per-document "known slug" API like Globals do —
* find-by-slug, then update or create. Idempotent across re-runs. */
async function upsertLegalPage(payload: Payload, slug: string, json: LegalPageJson) {
@@ -155,12 +160,12 @@ async function upsertLegalPage(payload: Payload, slug: string, json: LegalPageJs
await payload.update({
collection: 'legal-pages',
id: existing.docs[0].id,
data: { slug, ...json, _status: 'published' },
data: { slug, ...toLegalData(json), _status: 'published' },
})
} else {
await payload.create({
collection: 'legal-pages',
data: { slug, ...json, _status: 'published' },
data: { slug, ...toLegalData(json), _status: 'published' },
})
}
}
+198
View File
@@ -0,0 +1,198 @@
/**
* MITHOME-136: one-off content transfer MongoDB → PostgreSQL, in two steps
* so that only one Payload instance runs per process and the bundle can be
* reviewed (and reused to seed a fresh database).
*
* export — reads through the shared config with the MongoDB adapter:
* MONGODB_URI=… PAYLOAD_SECRET=… node --import tsx scripts/transfer-content.ts export <bundle.json> [--no-submissions] [--media-dir media]
* import — writes through the site's config (PostgreSQL); refuses a non-empty target:
* DATABASE_URI=… PAYLOAD_SECRET=… node --import tsx scripts/transfer-content.ts import <bundle.json>
*
* The bundle holds every global and collection except users (the admin is
* re-created by deploy.sh), the published state in both locales, open drafts,
* and the upload files. It contains personal data (contact submissions) unless
* exported with --no-submissions: keep it out of git, chmod 600.
*/
import fs from 'fs'
import path from 'path'
import {
buildConfig,
commitTransaction,
createLocalReq,
getPayload,
initTransaction,
killTransaction,
type CollectionConfig,
type Payload,
type PayloadRequest,
} from 'payload'
import { mongooseAdapter } from '@payloadcms/db-mongodb'
import { sharedConfig } from '../src/payload.shared'
import { bundleCounts, localeData, upgradeDoc, type BundleDoc, type IdMap, type TransferBundle } from '../src/lib/content-transfer'
type Data = Record<string, unknown>
type Slug = Parameters<Payload['find']>[0]['collection']
type GlobalSlug = Parameters<Payload['findGlobal']>[0]['slug']
const [mode, bundlePath, ...flags] = process.argv.slice(2)
const flag = (name: string) => flags.includes(name)
const option = (name: string, fallback: string) => {
const i = flags.indexOf(name)
return i >= 0 && flags[i + 1] ? flags[i + 1] : fallback
}
const collections = (sharedConfig.collections ?? []).filter((c) => c.slug !== 'users')
const globals = sharedConfig.globals ?? []
const hasDrafts = (c: { versions?: unknown }) => typeof c.versions === 'object' && c.versions !== null && 'drafts' in c.versions && Boolean((c.versions as { drafts?: unknown }).drafts)
const LOCALES = ['hu', 'en'] as const
async function exportBundle(file: string) {
const config = buildConfig({ ...sharedConfig, db: mongooseAdapter({ url: process.env.MONGODB_URI || '' }) })
const payload = await getPayload({ config })
const mediaDir = path.resolve(option('--media-dir', 'media'))
const bundle: TransferBundle = { exportedAt: new Date().toISOString(), source: 'mongodb', globals: {}, collections: {}, files: {} }
for (const g of globals) {
const slug = g.slug as GlobalSlug
const published = (await payload.findGlobal({ slug, locale: 'all', depth: 0 })) as unknown as Data
const latest = (await payload.findGlobal({ slug, locale: 'all', depth: 0, draft: true })) as unknown as Data
bundle.globals[slug] = { published, ...(hasDrafts(g) && latest._status === 'draft' ? { draft: latest } : {}) }
}
for (const c of collections) {
if (c.slug === 'contact-submissions' && flag('--no-submissions')) continue
const slug = c.slug as Slug
const published = (await payload.find({ collection: slug, locale: 'all', depth: 0, pagination: false })).docs as unknown as Data[]
const latest = hasDrafts(c)
? ((await payload.find({ collection: slug, locale: 'all', depth: 0, pagination: false, draft: true })).docs as unknown as Data[])
: []
const byId = new Map<string, BundleDoc>(published.map((doc) => [String(doc.id), { published: doc }]))
for (const doc of latest) {
const entry = byId.get(String(doc.id))
if (doc._status !== 'draft') continue
if (entry) entry.draft = doc
else byId.set(String(doc.id), { published: { ...doc }, draft: doc }) // never published
}
bundle.collections[slug] = [...byId.values()]
if (c.upload) {
for (const { published: doc } of bundle.collections[slug]) {
const name = String(doc.filename)
bundle.files[name] = { mimeType: String(doc.mimeType), base64: fs.readFileSync(path.join(mediaDir, name)).toString('base64') }
}
}
}
fs.writeFileSync(file, JSON.stringify(bundle, null, 2), { mode: 0o600 })
payload.logger.info(`MITHOME-136 export: ${JSON.stringify(bundleCounts(bundle))} → ${file}`)
}
async function assertEmptyTarget(payload: Payload) {
for (const c of collections) {
const { totalDocs } = await payload.count({ collection: c.slug as Slug })
if (totalDocs > 0) throw new Error(`Target is not empty: ${c.slug} has ${totalDocs} document(s). Nothing was written.`)
}
}
async function importCollection(payload: Payload, req: PayloadRequest, c: CollectionConfig, docs: BundleDoc[], bundle: TransferBundle, ids: IdMap) {
const slug = c.slug as Slug
const drafts = hasDrafts(c)
for (const raw of docs) {
const entry: BundleDoc = { published: upgradeDoc(c.slug, raw.published), ...(raw.draft ? { draft: upgradeDoc(c.slug, raw.draft) } : {}) }
const oldId = String(entry.published.id)
const neverPublished = entry.published._status === 'draft'
const status = drafts ? { _status: neverPublished ? 'draft' : 'published' } : {}
const file = c.upload
? (() => {
const name = String(entry.published.filename)
const stored = bundle.files[name]
const data = Buffer.from(stored.base64, 'base64')
return { data, mimetype: stored.mimeType, name, size: data.length }
})()
: undefined
const created = await payload.create({
req,
collection: slug,
locale: 'hu',
data: { ...localeData(c.fields, entry.published, 'hu', ids), ...status } as never,
...(file ? { file, overwriteExistingFiles: true } : {}),
draft: neverPublished,
})
ids.set(oldId, String(created.id))
await payload.update({
req,
collection: slug,
id: created.id,
locale: 'en',
data: { ...localeData(c.fields, entry.published, 'en', ids), ...status } as never,
draft: neverPublished,
})
if (entry.draft && !neverPublished) {
for (const locale of LOCALES) {
await payload.update({ req, collection: slug, id: created.id, locale, draft: true, data: localeData(c.fields, entry.draft, locale, ids) as never })
}
}
}
}
async function importBundle(file: string) {
const bundle = JSON.parse(fs.readFileSync(file, 'utf8')) as TransferBundle
const { default: config } = await import('../src/payload.config')
const payload = await getPayload({ config })
await assertEmptyTarget(payload)
// One transaction: a failure leaves the target untouched ("change nothing").
const req = await createLocalReq({}, payload)
await initTransaction(req)
try {
const ids: IdMap = new Map()
// Uploads first, so relationships can be mapped to the new ids.
const ordered = [...collections].sort((a, b) => Number(Boolean(b.upload)) - Number(Boolean(a.upload)))
for (const c of ordered) {
await importCollection(payload, req, c, bundle.collections[c.slug] ?? [], bundle, ids)
}
for (const g of globals) {
const entry = bundle.globals[g.slug]
if (!entry) continue
const slug = g.slug as GlobalSlug
const status = hasDrafts(g) ? { _status: 'published' } : {}
for (const locale of LOCALES) {
await payload.updateGlobal({ req, slug, locale, data: { ...localeData(g.fields, entry.published, locale, ids), ...status } as never })
}
if (entry.draft) {
for (const locale of LOCALES) {
await payload.updateGlobal({ req, slug, locale, draft: true, data: localeData(g.fields, entry.draft, locale, ids) as never })
}
}
}
await commitTransaction(req)
} catch (error) {
await killTransaction(req)
throw error
}
const counts: Record<string, number> = {}
for (const c of collections) counts[c.slug] = (await payload.count({ collection: c.slug as Slug })).totalDocs
payload.logger.info(`MITHOME-136 import: expected ${JSON.stringify(bundleCounts(bundle))}, got ${JSON.stringify(counts)}`)
}
async function main() {
if (!bundlePath || (mode !== 'export' && mode !== 'import')) {
console.error('Usage: transfer-content.ts export|import <bundle.json> [--no-submissions] [--media-dir DIR]')
process.exit(2)
}
if (mode === 'export') await exportBundle(bundlePath)
else await importBundle(bundlePath)
process.exit(0)
}
main().catch((error) => {
// Payload validation errors carry the failing fields in data.errors.
const details = (error as { data?: { collection?: string; errors?: unknown } })?.data
console.error('MITHOME-136 transfer failed:', error instanceof Error ? error.message : error)
if (details) console.error(JSON.stringify(details, null, 2))
process.exit(1)
})