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
@@ -44,17 +44,28 @@
- **Seed-konstansok:** a referenciák és a tárhelycsomagok szövegei a `src/content/seeds/` alá költöztek. - **Seed-konstansok:** a referenciák és a tárhelycsomagok szövegei a `src/content/seeds/` alá költöztek.
- A Mongo-adatmigrációk (8 fájl) és a segédfüggvényeik törlődnek. Az általuk elért állapot a stagingadatban van, és azt a D3 hozza át. - A Mongo-adatmigrációk (8 fájl) és a segédfüggvényeik törlődnek. Az általuk elért állapot a stagingadatban van, és azt a D3 hozza át.
### D3: Egyszeri adatmigráció (`proto/scripts/migrate-mongo-to-postgres.ts`) ### D3: Egyszeri adatátvitel (`proto/scripts/transfer-content.ts`)
- **Forrás:** a Mongo-dokumentumok közvetlenül, a `mongodb` driverrel, csak olvasva. A lokalizált mezők `{ hu, en }` alakban vannak. A publikált állapot a fő dokumentum; a nyitott vázlat a legutolsó verzió, ha `_status: draft`. Két lépés, lépésenként egy Payload-példánnyal, a Payload saját interfészén. Nem nyers Mongo-dokumentumokkal dolgozik:
- **Cél:** a Payload Local API, PostgreSQL-configgal. Először `locale: 'hu'` létrehozás, utána `locale: 'en'` frissítés, mindkét esetben `_status` megtartásával. A vázlat publikálás után külön vázlatmentésként kerül be.
- **Média:** új Media dokumentum ugyanarra a fájlra (`filePath` a `media/` könyvtárból). Egy azonosítótérkép (régi ObjectId → új UUID) oldja fel a hivatkozásokat (Partners.logo). - **`export`:** a `sharedConfig` + MongoDB-illesztő olvas mindent `locale: 'all'`-lal (a lokalizált mező `{ hu, en }`), a nyitott vázlatokkal és a médiafájlokkal együtt, egy önálló JSON-csomagba (600-as jogosultság; kapcsolatfelvételi üzenetekkel személyes adatot tartalmaz, `--no-submissions` nélkül nem kerülhet Gitbe). A felhasználókat nem visszük át; az admint a `deploy.sh` seedelése hozza létre.
- **Felhasználók:** nem visszük át, mert a jelszó-hash nem írható a Local API-n. Az admint a `deploy.sh` meglévő `ADMIN_EMAIL`/`ADMIN_PASSWORD` seedelése hozza létre. - **`import`:** a webhely configja (PostgreSQL) **egy tranzakcióban** ír. Hibánál semmi nem marad bent; nem üres célnál el sem indul.
- **Idempotencia:** ha a cél már tartalmaz dokumentumot, a script leáll, és nem ír. - Nyelvenként ír: `hu` létrehozás, `en` frissítés, a config mezőleírása alapján (`src/lib/content-transfer.ts`, tiszta, tesztelt függvények).
- **Ellenőrzés:** - A tömbsorok azonosítója megmarad, hogy az angol frissítés ugyanazokat a sorokat találja meg.
- dokumentumszámok gyűjteményenként; - Az upload-hivatkozások az új azonosítókra képződnek le. A média `overwriteExistingFiles`-szal íródik, így a fájlnév változatlan marad.
- a publikus oldalak szövegének összevetése hu/en nyelven a migráció előtti pillanatképpel (MITHOME-111 módszer); - **Futtatás:** 2026-09-29-én egy staging-másolaton, eldobható MongoDB-vel és PostgreSQL-lel az llmdev-en.
- a média- és partnerhivatkozások. - A számok egyeznek.
- Mind a 14 publikus oldal szövege (hu és en) betűre egyezik a MongoDB-s staginggel.
- A partnerlogó betölt, a partnervázlat átjött, a második futás semmit sem ír.
**A próba során talált két adatmodell-hiba** (MongoDB-ben rejtve maradtak):
1. **A jogi szakasz `id`-ja tartalmi horgony volt** (`bevezetes`), és egyben a tömbsor azonosítója. PostgreSQL-ben a tömbsor azonosítója táblaszinten egyedi kulcs, így a két jogi oldal ütközött. Javítás:
- új `anchor` mező, a sorazonosítót a Payload adja;
- az átvitel az `id`-t `anchor`-ra képezi, a sorazonosító `<slug>-<horgony>` lesz (`upgradeDoc`).
2. **A `Products.status` enumja ugyanazt a nevet kapta**, mint a vázlatrendszer `_status`-a (`enum_products_status`). Emiatt csak a `draft` és a `published` érték volt menthető, az `active` nem. Javítás: saját `enumName` (`enum_products_lifecycle_status`), regressziós teszttel.
**Ismert korlát:** a Home `about.usps` és `services.items` sorai szintén saját, szerkeszthető `id`-t használnak. Egyetlen Global-dokumentum van, ezért nem ütközik, de egy duplikált azonosító mentési hibát adna. Külön ticket (átnevezés `key`-re).
### D4: Infrastruktúra ### D4: Infrastruktúra
@@ -8,8 +8,8 @@
## 2. Adatmigráció ## 2. Adatmigráció
- [ ] 2.1 `scripts/migrate-mongo-to-postgres.ts`: tiszta transzformációs függvények unit tesztekkel (lokalizált alak, vázlat kiválasztása, azonosítótérkép) (D3). - [x] 2.1 `scripts/transfer-content.ts` (export/import) és `src/lib/content-transfer.ts` tiszta, tesztelt függvényekkel (nyelvi bontás, sorazonosítók, azonosítótérkép, `upgradeDoc`) (D3).
- [ ] 2.2 Futtatás egy staging-másolaton (eldobható Mongo és PostgreSQL az llmdev-en). Ellenőrzés: dokumentumszámok, a publikus hu/en oldalak szöveg-összevetése a pillanatképpel, partnerlogók, idempotens második futás. - [x] 2.2 Futtatás egy staging-másolaton (eldobható Mongo és PostgreSQL az llmdev-en). Ellenőrzés: dokumentumszámok, a publikus hu/en oldalak szöveg-összevetése a pillanatképpel, partnerlogók, idempotens második futás.
## 3. Infrastruktúra ## 3. Infrastruktúra
+7 -2
View File
@@ -142,6 +142,11 @@ type LegalPageJson = {
sections: { id: string; title: string; content: string }[] 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 — /** Collections have no per-document "known slug" API like Globals do —
* find-by-slug, then update or create. Idempotent across re-runs. */ * find-by-slug, then update or create. Idempotent across re-runs. */
async function upsertLegalPage(payload: Payload, slug: string, json: LegalPageJson) { 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({ await payload.update({
collection: 'legal-pages', collection: 'legal-pages',
id: existing.docs[0].id, id: existing.docs[0].id,
data: { slug, ...json, _status: 'published' }, data: { slug, ...toLegalData(json), _status: 'published' },
}) })
} else { } else {
await payload.create({ await payload.create({
collection: 'legal-pages', 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)
})
+6 -4
View File
@@ -17,9 +17,8 @@ import { legalValidationGroup } from './fields/legalValidation'
* nem vezetünk be külön szerializációt egy még nem létező render-rétegért. * nem vezetünk be külön szerializációt egy még nem létező render-rétegért.
* *
* MITHOME-112 lokalizáció: a cím, a dátumszöveg és a szakaszok címe/tartalma * MITHOME-112 lokalizáció: a cím, a dátumszöveg és a szakaszok címe/tartalma
* lokalizált; a `slug` (URL-azonosító) és a szakasz-`id` közös, a `sections` * lokalizált; a `slug` (URL-azonosító) és a szakasz-`anchor` közös, a `sections`
* tömb maga is közös (sorrend nyelvenként azonos). A meglévő adatot a * tömb maga is közös (sorrend nyelvenként azonos).
* src/migrations/20260929_localize_legal_pages.ts alakítja át.
*/ */
export const LegalPages: CollectionConfig = { export const LegalPages: CollectionConfig = {
slug: 'legal-pages', slug: 'legal-pages',
@@ -53,7 +52,10 @@ export const LegalPages: CollectionConfig = {
type: 'array', type: 'array',
required: true, required: true,
fields: [ fields: [
{ name: 'id', type: 'text', required: true }, // MITHOME-136: the section anchor is its own field. It used to be the
// array row `id`, which PostgreSQL stores as a table-wide primary key,
// so two pages with the same anchor ("bevezetes") collided.
{ name: 'anchor', type: 'text', required: true, admin: { description: 'A szakasz horgonya (pl. bevezetes), minden nyelven azonos.' } },
{ name: 'title', type: 'text', required: true, localized: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'content', type: 'textarea', required: true, localized: true }, { name: 'content', type: 'textarea', required: true, localized: true },
], ],
+4
View File
@@ -62,6 +62,10 @@ export const Products: CollectionConfig = {
name: 'status', name: 'status',
label: 'Életciklus-állapot', label: 'Életciklus-állapot',
type: 'select', type: 'select',
// MITHOME-136: own PostgreSQL enum name. The default "enum_products_status"
// is also Payload's name for the drafts `_status` enum, so the two
// collided and only draft/published were accepted.
enumName: 'enum_products_lifecycle_status',
required: true, required: true,
defaultValue: 'draft', defaultValue: 'draft',
options: PRODUCT_STATUSES.map((value) => ({ label: PRODUCT_STATUS_LABELS[value], value })), options: PRODUCT_STATUSES.map((value) => ({ label: PRODUCT_STATUS_LABELS[value], value })),
+95
View File
@@ -0,0 +1,95 @@
import type { Field } from 'payload'
import { bundleCounts, localeData, upgradeDoc } from './content-transfer'
const FIELDS: Field[] = [
{ name: 'name', type: 'text' },
{ name: 'title', type: 'text', localized: true },
{
name: 'hero',
type: 'group',
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'icon', type: 'text' },
],
},
{
name: 'items',
type: 'array',
fields: [
{ name: 'label', type: 'text', localized: true },
{ name: 'order', type: 'number' },
],
},
{ name: 'paragraphs', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] },
{ type: 'row', fields: [{ name: 'result', type: 'text' }] },
{ name: 'logo', type: 'upload', relationTo: 'media' },
]
const DOC = {
id: 'old-doc',
_id: 'old-doc',
__v: 0,
_status: 'published',
updatedAt: '2026-09-29T10:00:00.000Z',
createdAt: '2026-09-01T08:00:00.000Z',
name: 'mIT Start',
title: { hu: 'Cím', en: 'Title' },
hero: { title: { hu: 'Hős', en: 'Hero' }, icon: '🔥' },
items: [{ id: 'row1', label: { hu: 'Egy', en: 'One' }, order: 1 }],
paragraphs: { hu: [{ id: 'p1', value: 'Első' }, { id: 'p2', value: 'Második' }], en: [{ id: 'p3', value: 'First' }] },
result: 'ok',
logo: { id: 'old-media', filename: 'logo.png' },
}
describe('content transfer (MITHOME-136)', () => {
it('should split a locale-all document into Hungarian data', () => {
expect(localeData(FIELDS, DOC, 'hu')).toEqual({
name: 'mIT Start',
title: 'Cím',
hero: { title: 'Hős', icon: '🔥' },
items: [{ id: 'row1', label: 'Egy', order: 1 }],
paragraphs: [{ id: 'p1', value: 'Első' }, { id: 'p2', value: 'Második' }],
result: 'ok',
logo: 'old-media',
createdAt: '2026-09-01T08:00:00.000Z',
})
})
it('should keep array row ids so the English update hits the same rows', () => {
const en = localeData(FIELDS, DOC, 'en')
expect(en.items).toEqual([{ id: 'row1', label: 'One', order: 1 }])
expect(en.paragraphs).toEqual([{ id: 'p3', value: 'First' }])
expect(en.title).toBe('Title')
})
it('should map upload ids to the new documents', () => {
const ids = new Map([['old-media', 'new-media']])
expect(localeData(FIELDS, DOC, 'hu', ids).logo).toBe('new-media')
})
it('should drop system fields and leave missing fields out', () => {
const data = localeData(FIELDS, { name: 'x', _status: 'draft', globalType: 'home' }, 'hu')
expect(data).toEqual({ name: 'x' })
})
it('should count the documents of a bundle', () => {
expect(
bundleCounts({
exportedAt: '',
source: '',
globals: { home: { published: {} } },
collections: { partners: [{ published: {} }, { published: {} }] },
files: {},
}),
).toEqual({ partners: 2, 'global:home': 1 })
})
it('should move the legal section anchor out of the row id, unique per page', () => {
const doc = { slug: 'adatvedelem', sections: [{ id: 'bevezetes', title: { hu: 'Bevezetés' } }] }
expect(upgradeDoc('legal-pages', doc).sections).toEqual([
{ id: 'adatvedelem-bevezetes', anchor: 'bevezetes', title: { hu: 'Bevezetés' } },
])
expect(upgradeDoc('legal-pages', upgradeDoc('legal-pages', doc))).toEqual(upgradeDoc('legal-pages', doc))
expect(upgradeDoc('partners', doc)).toBe(doc)
})
})
+100
View File
@@ -0,0 +1,100 @@
/**
* MITHOME-136: pure helpers of the one-off MongoDB → PostgreSQL content
* transfer (scripts/transfer-content.ts).
*
* The export reads every document with `locale: 'all'`, so each localized
* field arrives as `{ hu, en }`. Payload writes one locale at a time, so the
* import splits a document into per-locale data using the field config:
* localized fields take the locale's value, groups/unnamed rows recurse,
* array rows keep their ids (the English update must hit the same rows), and
* upload/relationship ids are mapped from the old to the new id.
*/
import type { Field } from 'payload'
export type Locale = 'hu' | 'en'
type Data = Record<string, unknown>
export type IdMap = Map<string, string>
const SYSTEM_KEYS = new Set(['id', '_id', '__v', 'globalType', 'updatedAt', '_status'])
const isObject = (value: unknown): value is Data =>
typeof value === 'object' && value !== null && !Array.isArray(value)
function mapId(value: unknown, ids: IdMap): unknown {
if (value === null || value === undefined) return value
const id = isObject(value) ? value.id : value
return typeof id === 'string' ? (ids.get(id) ?? id) : id
}
function splitFields(fields: readonly Field[], source: Data, locale: Locale, ids: IdMap, out: Data): Data {
for (const field of fields) {
if (!('name' in field) || !field.name) {
// row / collapsible: unnamed wrappers keep their fields on the same level
if ('fields' in field) splitFields(field.fields, source, locale, ids, out)
continue
}
if (!(field.name in source)) continue
const raw = source[field.name]
const value = 'localized' in field && field.localized && isObject(raw) ? raw[locale] : raw
if (field.type === 'group' && isObject(value)) {
out[field.name] = splitFields(field.fields, value, locale, ids, {})
} else if (field.type === 'array' && Array.isArray(value)) {
out[field.name] = value.map((row) =>
isObject(row) ? { ...(row.id ? { id: row.id } : {}), ...splitFields(field.fields, row, locale, ids, {}) } : row,
)
} else if (field.type === 'upload' || field.type === 'relationship') {
out[field.name] = Array.isArray(value) ? value.map((v) => mapId(v, ids)) : mapId(value, ids)
} else {
out[field.name] = value
}
}
return out
}
/**
* Shape changes between the MongoDB schema and the current one, applied to an
* exported document before it is split by locale.
* - legal-pages: the section anchor was the array row `id`; it is now the
* `anchor` field, and the row id must be unique across all pages (it is a
* table-wide primary key in PostgreSQL), so it becomes `<slug>-<anchor>`.
*/
export function upgradeDoc(collection: string, doc: Data): Data {
if (collection !== 'legal-pages' || !Array.isArray(doc.sections)) return doc
return {
...doc,
sections: doc.sections.map((section) =>
isObject(section) && typeof section.id === 'string' && !('anchor' in section)
? { ...section, id: `${doc.slug}-${section.id}`, anchor: section.id }
: section,
),
}
}
/** The data of one locale, ready for `create`/`update` with that `locale`. */
export function localeData(fields: readonly Field[], doc: Data, locale: Locale, ids: IdMap = new Map()): Data {
const out = splitFields(fields, doc, locale, ids, {})
for (const key of SYSTEM_KEYS) delete out[key]
// Keep the original creation time (contact submission retention).
if (typeof doc.createdAt === 'string') out.createdAt = doc.createdAt
return out
}
/** Count documents per collection/global in an export bundle. */
export function bundleCounts(bundle: TransferBundle): Record<string, number> {
const counts: Record<string, number> = {}
for (const [slug, docs] of Object.entries(bundle.collections)) counts[slug] = docs.length
for (const slug of Object.keys(bundle.globals)) counts[`global:${slug}`] = 1
return counts
}
export type BundleDoc = { published: Data; draft?: Data }
export type TransferBundle = {
exportedAt: string
source: string
globals: Record<string, BundleDoc>
collections: Record<string, BundleDoc[]>
/** Upload files by filename, base64 — the bundle is self-contained. */
files: Record<string, { mimeType: string; base64: string }>
}
@@ -4,14 +4,14 @@ const hu = {
title: 'Adatvédelmi Tájékoztató', title: 'Adatvédelmi Tájékoztató',
lastUpdated: '2026. augusztus 22.', lastUpdated: '2026. augusztus 22.',
sections: [ sections: [
{ id: 'bevezetes', title: '1. Bevezetés', content: 'A mozdIT Bt. mint adatkezelő…' }, { id: 'r1', anchor: 'bevezetes', title: '1. Bevezetés', content: 'A mozdIT Bt. mint adatkezelő…' },
{ id: 'jogok', title: '5. Az érintettek jogai', content: 'Az érintettek bármikor…' }, { id: 'r2', anchor: 'jogok', title: '5. Az érintettek jogai', content: 'Az érintettek bármikor…' },
], ],
} }
const en = { const en = {
title: 'Privacy Notice', title: 'Privacy Notice',
lastUpdated: '22 August 2026', lastUpdated: '22 August 2026',
sections: [{ id: 'bevezetes', title: '1. Introduction', content: 'mozdIT Bt., as controller…' }], sections: [{ id: 'r1', anchor: 'bevezetes', title: '1. Introduction', content: 'mozdIT Bt., as controller…' }],
} }
describe('buildLegalValidationPrompt (MITHOME-113)', () => { describe('buildLegalValidationPrompt (MITHOME-113)', () => {
@@ -34,7 +34,7 @@ describe('buildLegalValidationPrompt (MITHOME-113)', () => {
}) })
it('should return undefined when there is no English text', () => { it('should return undefined when there is no English text', () => {
expect(buildLegalValidationPrompt(hu, { title: ' ', sections: [{ id: 'bevezetes', title: null, content: '' }] })).toBeUndefined() expect(buildLegalValidationPrompt(hu, { title: ' ', sections: [{ id: 'r1', anchor: 'bevezetes', title: null, content: '' }] })).toBeUndefined()
expect(hasEnglishContent({})).toBe(false) expect(hasEnglishContent({})).toBe(false)
}) })
}) })
+2 -2
View File
@@ -11,7 +11,7 @@
* document texts stay in their original languages. * document texts stay in their original languages.
*/ */
export type LegalSection = { id?: string | null; title?: string | null; content?: string | null } export type LegalSection = { id?: string | null; anchor?: string | null; title?: string | null; content?: string | null }
export type LegalText = { title?: string | null; lastUpdated?: string | null; sections?: LegalSection[] | null } export type LegalText = { title?: string | null; lastUpdated?: string | null; sections?: LegalSection[] | null }
const MISSING = '(missing — report as high severity)' const MISSING = '(missing — report as high severity)'
@@ -55,7 +55,7 @@ export function buildLegalValidationPrompt(hu: LegalText, en: LegalText): string
const sections = (hu.sections ?? []).map((section, index) => { const sections = (hu.sections ?? []).map((section, index) => {
const english = enById.get(section.id) ?? {} const english = enById.get(section.id) ?? {}
return [ return [
`--- Section ${index + 1}${section.id ? ` (${section.id})` : ''} ---`, `--- Section ${index + 1}${section.anchor ? ` (${section.anchor})` : ''} ---`,
block('HU', section.title, section.content), block('HU', section.title, section.content),
block('EN', english.title, english.content), block('EN', english.title, english.content),
].join('\n') ].join('\n')
@@ -240,6 +240,12 @@
"type": "varchar", "type": "varchar",
"primaryKey": true, "primaryKey": true,
"notNull": true "notNull": true
},
"anchor": {
"name": "anchor",
"type": "varchar",
"primaryKey": false,
"notNull": false
} }
}, },
"indexes": { "indexes": {
@@ -702,6 +708,12 @@
"notNull": true, "notNull": true,
"default": "gen_random_uuid()" "default": "gen_random_uuid()"
}, },
"anchor": {
"name": "anchor",
"type": "varchar",
"primaryKey": false,
"notNull": false
},
"_uuid": { "_uuid": {
"name": "_uuid", "name": "_uuid",
"type": "varchar", "type": "varchar",
@@ -2139,7 +2151,7 @@
}, },
"status": { "status": {
"name": "status", "name": "status",
"type": "enum_products_status", "type": "enum_products_lifecycle_status",
"typeSchema": "public", "typeSchema": "public",
"primaryKey": false, "primaryKey": false,
"notNull": false, "notNull": false,
@@ -2571,7 +2583,7 @@
}, },
"version_status": { "version_status": {
"name": "version_status", "name": "version_status",
"type": "enum__products_v_version_status", "type": "enum_products_lifecycle_status",
"typeSchema": "public", "typeSchema": "public",
"primaryKey": false, "primaryKey": false,
"notNull": false, "notNull": false,
@@ -10696,12 +10708,15 @@
"managed-service" "managed-service"
] ]
}, },
"public.enum_products_status": { "public.enum_products_lifecycle_status": {
"name": "enum_products_status", "name": "enum_products_lifecycle_status",
"schema": "public", "schema": "public",
"values": [ "values": [
"draft", "draft",
"published" "internal",
"publishable",
"active",
"retired"
] ]
}, },
"public.enum_products_pricing_billing_period": { "public.enum_products_pricing_billing_period": {
@@ -10722,6 +10737,14 @@
"approved" "approved"
] ]
}, },
"public.enum_products_status": {
"name": "enum_products_status",
"schema": "public",
"values": [
"draft",
"published"
]
},
"public.enum__products_v_version_product_type": { "public.enum__products_v_version_product_type": {
"name": "enum__products_v_version_product_type", "name": "enum__products_v_version_product_type",
"schema": "public", "schema": "public",
@@ -10730,14 +10753,6 @@
"managed-service" "managed-service"
] ]
}, },
"public.enum__products_v_version_status": {
"name": "enum__products_v_version_status",
"schema": "public",
"values": [
"draft",
"published"
]
},
"public.enum__products_v_version_pricing_billing_period": { "public.enum__products_v_version_pricing_billing_period": {
"name": "enum__products_v_version_pricing_billing_period", "name": "enum__products_v_version_pricing_billing_period",
"schema": "public", "schema": "public",
@@ -10756,6 +10771,14 @@
"approved" "approved"
] ]
}, },
"public.enum__products_v_version_status": {
"name": "enum__products_v_version_status",
"schema": "public",
"values": [
"draft",
"published"
]
},
"public.enum__products_v_published_locale": { "public.enum__products_v_published_locale": {
"name": "enum__products_v_published_locale", "name": "enum__products_v_published_locale",
"schema": "public", "schema": "public",
@@ -11111,6 +11134,6 @@
"tables": {}, "tables": {},
"columns": {} "columns": {}
}, },
"id": "2ad18472-919a-4a92-9c5b-ca65521af234", "id": "4793a461-cb83-4303-aa78-0a07b81a2cdb",
"prevId": "00000000-0000-0000-0000-000000000000" "prevId": "00000000-0000-0000-0000-000000000000"
} }
@@ -19,13 +19,14 @@ export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
CREATE TYPE "public"."enum__partners_v_published_locale" AS ENUM('hu', 'en'); CREATE TYPE "public"."enum__partners_v_published_locale" AS ENUM('hu', 'en');
CREATE TYPE "public"."enum_contact_submissions_status" AS ENUM('new', 'read', 'replied', 'archived'); CREATE TYPE "public"."enum_contact_submissions_status" AS ENUM('new', 'read', 'replied', 'archived');
CREATE TYPE "public"."enum_products_product_type" AS ENUM('hosting', 'managed-service'); CREATE TYPE "public"."enum_products_product_type" AS ENUM('hosting', 'managed-service');
CREATE TYPE "public"."enum_products_status" AS ENUM('draft', 'published'); CREATE TYPE "public"."enum_products_lifecycle_status" AS ENUM('draft', 'internal', 'publishable', 'active', 'retired');
CREATE TYPE "public"."enum_products_pricing_billing_period" AS ENUM('yearly', 'monthly', 'one-time'); CREATE TYPE "public"."enum_products_pricing_billing_period" AS ENUM('yearly', 'monthly', 'one-time');
CREATE TYPE "public"."enum_products_en_translation_status" AS ENUM('none', 'ai-draft', 'approved'); CREATE TYPE "public"."enum_products_en_translation_status" AS ENUM('none', 'ai-draft', 'approved');
CREATE TYPE "public"."enum_products_status" AS ENUM('draft', 'published');
CREATE TYPE "public"."enum__products_v_version_product_type" AS ENUM('hosting', 'managed-service'); CREATE TYPE "public"."enum__products_v_version_product_type" AS ENUM('hosting', 'managed-service');
CREATE TYPE "public"."enum__products_v_version_status" AS ENUM('draft', 'published');
CREATE TYPE "public"."enum__products_v_version_pricing_billing_period" AS ENUM('yearly', 'monthly', 'one-time'); CREATE TYPE "public"."enum__products_v_version_pricing_billing_period" AS ENUM('yearly', 'monthly', 'one-time');
CREATE TYPE "public"."enum__products_v_version_en_translation_status" AS ENUM('none', 'ai-draft', 'approved'); CREATE TYPE "public"."enum__products_v_version_en_translation_status" AS ENUM('none', 'ai-draft', 'approved');
CREATE TYPE "public"."enum__products_v_version_status" AS ENUM('draft', 'published');
CREATE TYPE "public"."enum__products_v_published_locale" AS ENUM('hu', 'en'); CREATE TYPE "public"."enum__products_v_published_locale" AS ENUM('hu', 'en');
CREATE TYPE "public"."enum_home_hero_cta_primary_link_type" AS ENUM('page', 'url'); CREATE TYPE "public"."enum_home_hero_cta_primary_link_type" AS ENUM('page', 'url');
CREATE TYPE "public"."enum_home_hero_cta_primary_page" AS ENUM('home', 'about', 'services', 'hostingPlans', 'contact', 'privacy', 'terms'); CREATE TYPE "public"."enum_home_hero_cta_primary_page" AS ENUM('home', 'about', 'services', 'hostingPlans', 'contact', 'privacy', 'terms');
@@ -90,7 +91,8 @@ export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
CREATE TABLE "legal_pages_sections" ( CREATE TABLE "legal_pages_sections" (
"_order" integer NOT NULL, "_order" integer NOT NULL,
"_parent_id" uuid NOT NULL, "_parent_id" uuid NOT NULL,
"id" varchar PRIMARY KEY NOT NULL "id" varchar PRIMARY KEY NOT NULL,
"anchor" varchar
); );
CREATE TABLE "legal_pages_sections_locales" ( CREATE TABLE "legal_pages_sections_locales" (
@@ -133,6 +135,7 @@ export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
"_order" integer NOT NULL, "_order" integer NOT NULL,
"_parent_id" uuid NOT NULL, "_parent_id" uuid NOT NULL,
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"anchor" varchar,
"_uuid" varchar "_uuid" varchar
); );
@@ -254,7 +257,7 @@ export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
"name" varchar, "name" varchar,
"slug" varchar, "slug" varchar,
"product_type" "enum_products_product_type" DEFAULT 'hosting', "product_type" "enum_products_product_type" DEFAULT 'hosting',
"status" "enum_products_status" DEFAULT 'draft', "status" "enum_products_lifecycle_status" DEFAULT 'draft',
"sort_order" numeric DEFAULT 0, "sort_order" numeric DEFAULT 0,
"highlighted" boolean DEFAULT false, "highlighted" boolean DEFAULT false,
"pricing_net_amount" numeric, "pricing_net_amount" numeric,
@@ -299,7 +302,7 @@ export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
"version_name" varchar, "version_name" varchar,
"version_slug" varchar, "version_slug" varchar,
"version_product_type" "enum__products_v_version_product_type" DEFAULT 'hosting', "version_product_type" "enum__products_v_version_product_type" DEFAULT 'hosting',
"version_status" "enum__products_v_version_status" DEFAULT 'draft', "version_status" "enum_products_lifecycle_status" DEFAULT 'draft',
"version_sort_order" numeric DEFAULT 0, "version_sort_order" numeric DEFAULT 0,
"version_highlighted" boolean DEFAULT false, "version_highlighted" boolean DEFAULT false,
"version_pricing_net_amount" numeric, "version_pricing_net_amount" numeric,
@@ -1499,13 +1502,14 @@ export async function down({ db, payload, req }: MigrateDownArgs): Promise<void>
DROP TYPE "public"."enum__partners_v_published_locale"; DROP TYPE "public"."enum__partners_v_published_locale";
DROP TYPE "public"."enum_contact_submissions_status"; DROP TYPE "public"."enum_contact_submissions_status";
DROP TYPE "public"."enum_products_product_type"; DROP TYPE "public"."enum_products_product_type";
DROP TYPE "public"."enum_products_status"; DROP TYPE "public"."enum_products_lifecycle_status";
DROP TYPE "public"."enum_products_pricing_billing_period"; DROP TYPE "public"."enum_products_pricing_billing_period";
DROP TYPE "public"."enum_products_en_translation_status"; DROP TYPE "public"."enum_products_en_translation_status";
DROP TYPE "public"."enum_products_status";
DROP TYPE "public"."enum__products_v_version_product_type"; DROP TYPE "public"."enum__products_v_version_product_type";
DROP TYPE "public"."enum__products_v_version_status";
DROP TYPE "public"."enum__products_v_version_pricing_billing_period"; DROP TYPE "public"."enum__products_v_version_pricing_billing_period";
DROP TYPE "public"."enum__products_v_version_en_translation_status"; DROP TYPE "public"."enum__products_v_version_en_translation_status";
DROP TYPE "public"."enum__products_v_version_status";
DROP TYPE "public"."enum__products_v_published_locale"; DROP TYPE "public"."enum__products_v_published_locale";
DROP TYPE "public"."enum_home_hero_cta_primary_link_type"; DROP TYPE "public"."enum_home_hero_cta_primary_link_type";
DROP TYPE "public"."enum_home_hero_cta_primary_page"; DROP TYPE "public"."enum_home_hero_cta_primary_page";
+4 -4
View File
@@ -1,9 +1,9 @@
import * as migration_20260929_200306_initial from './20260929_200306_initial'; import * as migration_20260929_202255_initial from './20260929_202255_initial';
export const migrations = [ export const migrations = [
{ {
up: migration_20260929_200306_initial.up, up: migration_20260929_202255_initial.up,
down: migration_20260929_200306_initial.down, down: migration_20260929_202255_initial.down,
name: '20260929_200306_initial' name: '20260929_202255_initial'
}, },
]; ];
+9 -1
View File
@@ -158,7 +158,8 @@ describe('Payload globals', () => {
// MITHOME-112: `slug` is the shared URL identifier of LegalPages. // MITHOME-112: `slug` is the shared URL identifier of LegalPages.
// MITHOME-113: `result`/`notes` are legal-validation metadata, not copy. // MITHOME-113: `result`/`notes` are legal-validation metadata, not copy.
// MITHOME-130: a product `name` is a brand, the same in every language. // MITHOME-130: a product `name` is a brand, the same in every language.
const SHARED_TEXT_FIELDS = new Set(['icon', 'id', 'address', 'slug', 'result', 'notes', 'name']) // MITHOME-136: the legal section `anchor` (formerly its row `id`) is shared too.
const SHARED_TEXT_FIELDS = new Set(['icon', 'id', 'anchor', 'address', 'slug', 'result', 'notes', 'name'])
type Node = FieldLike & { localized?: boolean; fields?: Node[] } type Node = FieldLike & { localized?: boolean; fields?: Node[] }
type Finding = { path: string; type?: string; localized: boolean } type Finding = { path: string; type?: string; localized: boolean }
@@ -285,6 +286,13 @@ describe('MITHOME-130 hosting plans', () => {
expect(slug).toMatchObject({ required: true, unique: true }) expect(slug).toMatchObject({ required: true, unique: true })
}) })
it('should give the lifecycle status its own PostgreSQL enum (MITHOME-136)', () => {
// Regression: the default enum name equals the drafts `_status` enum, and
// PostgreSQL then only accepted draft/published.
const status = findField(Products.fields, 'status') as unknown as { enumName?: string }
expect(status.enumName).toBe('enum_products_lifecycle_status')
})
it('should require a whole, non-negative net price and default to yearly billing', () => { it('should require a whole, non-negative net price and default to yearly billing', () => {
const net = findField(group('pricing'), 'netAmount') as unknown as FieldLike & { validate: Validate } const net = findField(group('pricing'), 'netAmount') as unknown as FieldLike & { validate: Validate }
expect(net.required).toBe(true) expect(net.required).toBe(true)