From a68fb94b61b854f89757d83b7a987ac9d7126c66 Mon Sep 17 00:00:00 2001 From: Do Siki Date: Tue, 29 Sep 2026 22:27:11 +0200 Subject: [PATCH] =?UTF-8?q?feat(cms):=20MongoDB=20=E2=86=92=20PostgreSQL?= =?UTF-8?q?=20content=20transfer;=20fix=20two=20schema=20issues=20it=20fou?= =?UTF-8?q?nd=20(MITHOME-136)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .../postgres-migration-mithome-136/design.md | 31 ++- .../postgres-migration-mithome-136/tasks.md | 4 +- proto/scripts/migrate-content-to-payload.ts | 9 +- proto/scripts/transfer-content.ts | 198 ++++++++++++++++++ proto/src/collections/LegalPages.ts | 10 +- proto/src/collections/Products.ts | 4 + proto/src/lib/content-transfer.test.ts | 95 +++++++++ proto/src/lib/content-transfer.ts | 100 +++++++++ proto/src/lib/legal-validation-prompt.test.ts | 8 +- proto/src/lib/legal-validation-prompt.ts | 4 +- ...tial.json => 20260929_202255_initial.json} | 51 +++-- ..._initial.ts => 20260929_202255_initial.ts} | 18 +- proto/src/migrations/index.ts | 8 +- proto/src/payload-config.test.ts | 10 +- 14 files changed, 500 insertions(+), 50 deletions(-) create mode 100644 proto/scripts/transfer-content.ts create mode 100644 proto/src/lib/content-transfer.test.ts create mode 100644 proto/src/lib/content-transfer.ts rename proto/src/migrations/{20260929_200306_initial.json => 20260929_202255_initial.json} (99%) rename proto/src/migrations/{20260929_200306_initial.ts => 20260929_202255_initial.ts} (99%) diff --git a/openspec/changes/postgres-migration-mithome-136/design.md b/openspec/changes/postgres-migration-mithome-136/design.md index 31a89f4..810400a 100644 --- a/openspec/changes/postgres-migration-mithome-136/design.md +++ b/openspec/changes/postgres-migration-mithome-136/design.md @@ -44,17 +44,28 @@ - **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. -### 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`. -- **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). -- **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. -- **Idempotencia:** ha a cél már tartalmaz dokumentumot, a script leáll, és nem ír. -- **Ellenőrzés:** - - dokumentumszámok gyűjteményenként; - - a publikus oldalak szövegének összevetése hu/en nyelven a migráció előtti pillanatképpel (MITHOME-111 módszer); - - a média- és partnerhivatkozások. +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: + +- **`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. +- **`import`:** a webhely configja (PostgreSQL) **egy tranzakcióban** ír. Hibánál semmi nem marad bent; nem üres célnál el sem indul. + - 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). + - A tömbsorok azonosítója megmarad, hogy az angol frissítés ugyanazokat a sorokat találja meg. + - 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. +- **Futtatás:** 2026-09-29-én egy staging-másolaton, eldobható MongoDB-vel és PostgreSQL-lel az llmdev-en. + - 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ó `-` 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 diff --git a/openspec/changes/postgres-migration-mithome-136/tasks.md b/openspec/changes/postgres-migration-mithome-136/tasks.md index ded5cf7..3648587 100644 --- a/openspec/changes/postgres-migration-mithome-136/tasks.md +++ b/openspec/changes/postgres-migration-mithome-136/tasks.md @@ -8,8 +8,8 @@ ## 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). -- [ ] 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.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). +- [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 diff --git a/proto/scripts/migrate-content-to-payload.ts b/proto/scripts/migrate-content-to-payload.ts index a4bea4d..1d55de1 100644 --- a/proto/scripts/migrate-content-to-payload.ts +++ b/proto/scripts/migrate-content-to-payload.ts @@ -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' }, }) } } diff --git a/proto/scripts/transfer-content.ts b/proto/scripts/transfer-content.ts new file mode 100644 index 0000000..4282da1 --- /dev/null +++ b/proto/scripts/transfer-content.ts @@ -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 [--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 + * + * 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 +type Slug = Parameters[0]['collection'] +type GlobalSlug = Parameters[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(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 = {} + 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 [--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) +}) diff --git a/proto/src/collections/LegalPages.ts b/proto/src/collections/LegalPages.ts index 88fb649..07ce820 100644 --- a/proto/src/collections/LegalPages.ts +++ b/proto/src/collections/LegalPages.ts @@ -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. * * 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` - * tömb maga is közös (sorrend nyelvenként azonos). A meglévő adatot a - * src/migrations/20260929_localize_legal_pages.ts alakítja át. + * 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). */ export const LegalPages: CollectionConfig = { slug: 'legal-pages', @@ -53,7 +52,10 @@ export const LegalPages: CollectionConfig = { type: 'array', required: true, 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: 'content', type: 'textarea', required: true, localized: true }, ], diff --git a/proto/src/collections/Products.ts b/proto/src/collections/Products.ts index 412c70a..aadea96 100644 --- a/proto/src/collections/Products.ts +++ b/proto/src/collections/Products.ts @@ -62,6 +62,10 @@ export const Products: CollectionConfig = { name: 'status', label: 'Életciklus-állapot', 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, defaultValue: 'draft', options: PRODUCT_STATUSES.map((value) => ({ label: PRODUCT_STATUS_LABELS[value], value })), diff --git a/proto/src/lib/content-transfer.test.ts b/proto/src/lib/content-transfer.test.ts new file mode 100644 index 0000000..a13d3d2 --- /dev/null +++ b/proto/src/lib/content-transfer.test.ts @@ -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) + }) +}) diff --git a/proto/src/lib/content-transfer.ts b/proto/src/lib/content-transfer.ts new file mode 100644 index 0000000..a3899b0 --- /dev/null +++ b/proto/src/lib/content-transfer.ts @@ -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 +export type IdMap = Map + +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 `-`. + */ +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 { + const counts: Record = {} + 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 + collections: Record + /** Upload files by filename, base64 — the bundle is self-contained. */ + files: Record +} diff --git a/proto/src/lib/legal-validation-prompt.test.ts b/proto/src/lib/legal-validation-prompt.test.ts index 25cee17..8ccce98 100644 --- a/proto/src/lib/legal-validation-prompt.test.ts +++ b/proto/src/lib/legal-validation-prompt.test.ts @@ -4,14 +4,14 @@ const hu = { title: 'Adatvédelmi Tájékoztató', lastUpdated: '2026. augusztus 22.', sections: [ - { id: 'bevezetes', title: '1. Bevezetés', content: 'A mozdIT Bt. mint adatkezelő…' }, - { id: 'jogok', title: '5. Az érintettek jogai', content: 'Az érintettek bármikor…' }, + { id: 'r1', anchor: 'bevezetes', title: '1. Bevezetés', content: 'A mozdIT Bt. mint adatkezelő…' }, + { id: 'r2', anchor: 'jogok', title: '5. Az érintettek jogai', content: 'Az érintettek bármikor…' }, ], } const en = { title: 'Privacy Notice', 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)', () => { @@ -34,7 +34,7 @@ describe('buildLegalValidationPrompt (MITHOME-113)', () => { }) 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) }) }) diff --git a/proto/src/lib/legal-validation-prompt.ts b/proto/src/lib/legal-validation-prompt.ts index 7798cb6..70c71c2 100644 --- a/proto/src/lib/legal-validation-prompt.ts +++ b/proto/src/lib/legal-validation-prompt.ts @@ -11,7 +11,7 @@ * 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 } 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 english = enById.get(section.id) ?? {} return [ - `--- Section ${index + 1}${section.id ? ` (${section.id})` : ''} ---`, + `--- Section ${index + 1}${section.anchor ? ` (${section.anchor})` : ''} ---`, block('HU', section.title, section.content), block('EN', english.title, english.content), ].join('\n') diff --git a/proto/src/migrations/20260929_200306_initial.json b/proto/src/migrations/20260929_202255_initial.json similarity index 99% rename from proto/src/migrations/20260929_200306_initial.json rename to proto/src/migrations/20260929_202255_initial.json index 100486e..b4a3975 100644 --- a/proto/src/migrations/20260929_200306_initial.json +++ b/proto/src/migrations/20260929_202255_initial.json @@ -240,6 +240,12 @@ "type": "varchar", "primaryKey": true, "notNull": true + }, + "anchor": { + "name": "anchor", + "type": "varchar", + "primaryKey": false, + "notNull": false } }, "indexes": { @@ -702,6 +708,12 @@ "notNull": true, "default": "gen_random_uuid()" }, + "anchor": { + "name": "anchor", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, "_uuid": { "name": "_uuid", "type": "varchar", @@ -2139,7 +2151,7 @@ }, "status": { "name": "status", - "type": "enum_products_status", + "type": "enum_products_lifecycle_status", "typeSchema": "public", "primaryKey": false, "notNull": false, @@ -2571,7 +2583,7 @@ }, "version_status": { "name": "version_status", - "type": "enum__products_v_version_status", + "type": "enum_products_lifecycle_status", "typeSchema": "public", "primaryKey": false, "notNull": false, @@ -10696,12 +10708,15 @@ "managed-service" ] }, - "public.enum_products_status": { - "name": "enum_products_status", + "public.enum_products_lifecycle_status": { + "name": "enum_products_lifecycle_status", "schema": "public", "values": [ "draft", - "published" + "internal", + "publishable", + "active", + "retired" ] }, "public.enum_products_pricing_billing_period": { @@ -10722,6 +10737,14 @@ "approved" ] }, + "public.enum_products_status": { + "name": "enum_products_status", + "schema": "public", + "values": [ + "draft", + "published" + ] + }, "public.enum__products_v_version_product_type": { "name": "enum__products_v_version_product_type", "schema": "public", @@ -10730,14 +10753,6 @@ "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": { "name": "enum__products_v_version_pricing_billing_period", "schema": "public", @@ -10756,6 +10771,14 @@ "approved" ] }, + "public.enum__products_v_version_status": { + "name": "enum__products_v_version_status", + "schema": "public", + "values": [ + "draft", + "published" + ] + }, "public.enum__products_v_published_locale": { "name": "enum__products_v_published_locale", "schema": "public", @@ -11111,6 +11134,6 @@ "tables": {}, "columns": {} }, - "id": "2ad18472-919a-4a92-9c5b-ca65521af234", + "id": "4793a461-cb83-4303-aa78-0a07b81a2cdb", "prevId": "00000000-0000-0000-0000-000000000000" } \ No newline at end of file diff --git a/proto/src/migrations/20260929_200306_initial.ts b/proto/src/migrations/20260929_202255_initial.ts similarity index 99% rename from proto/src/migrations/20260929_200306_initial.ts rename to proto/src/migrations/20260929_202255_initial.ts index 262fc1c..f6ea280 100644 --- a/proto/src/migrations/20260929_200306_initial.ts +++ b/proto/src/migrations/20260929_202255_initial.ts @@ -19,13 +19,14 @@ export async function up({ db, payload, req }: MigrateUpArgs): Promise { 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_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_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_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_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_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'); @@ -90,7 +91,8 @@ export async function up({ db, payload, req }: MigrateUpArgs): Promise { CREATE TABLE "legal_pages_sections" ( "_order" integer 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" ( @@ -133,6 +135,7 @@ export async function up({ db, payload, req }: MigrateUpArgs): Promise { "_order" integer NOT NULL, "_parent_id" uuid NOT NULL, "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "anchor" varchar, "_uuid" varchar ); @@ -254,7 +257,7 @@ export async function up({ db, payload, req }: MigrateUpArgs): Promise { "name" varchar, "slug" varchar, "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, "highlighted" boolean DEFAULT false, "pricing_net_amount" numeric, @@ -299,7 +302,7 @@ export async function up({ db, payload, req }: MigrateUpArgs): Promise { "version_name" varchar, "version_slug" varchar, "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_highlighted" boolean DEFAULT false, "version_pricing_net_amount" numeric, @@ -1499,13 +1502,14 @@ export async function down({ db, payload, req }: MigrateDownArgs): Promise DROP TYPE "public"."enum__partners_v_published_locale"; DROP TYPE "public"."enum_contact_submissions_status"; 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_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_status"; 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_status"; 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_page"; diff --git a/proto/src/migrations/index.ts b/proto/src/migrations/index.ts index b6531be..74be478 100644 --- a/proto/src/migrations/index.ts +++ b/proto/src/migrations/index.ts @@ -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 = [ { - up: migration_20260929_200306_initial.up, - down: migration_20260929_200306_initial.down, - name: '20260929_200306_initial' + up: migration_20260929_202255_initial.up, + down: migration_20260929_202255_initial.down, + name: '20260929_202255_initial' }, ]; diff --git a/proto/src/payload-config.test.ts b/proto/src/payload-config.test.ts index 18ffb98..9cf8933 100644 --- a/proto/src/payload-config.test.ts +++ b/proto/src/payload-config.test.ts @@ -158,7 +158,8 @@ describe('Payload globals', () => { // MITHOME-112: `slug` is the shared URL identifier of LegalPages. // MITHOME-113: `result`/`notes` are legal-validation metadata, not copy. // 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 Finding = { path: string; type?: string; localized: boolean } @@ -285,6 +286,13 @@ describe('MITHOME-130 hosting plans', () => { 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', () => { const net = findField(group('pricing'), 'netAmount') as unknown as FieldLike & { validate: Validate } expect(net.required).toBe(true)