From 829f5439626fcd2c2c04fbee4c213f44f26c2664 Mon Sep 17 00:00:00 2001 From: Do Siki Date: Tue, 29 Sep 2026 00:52:26 +0200 Subject: [PATCH] feat(cms): localize translatable Globals fields with lossless migration (MITHOME-111) Mark every translatable text/textarea field of the Home, About, Services, Contact and Common globals as localized. Icons, row ids, the external flag and the postal address stay shared; CTA hrefs are localized because internal routes differ per locale. String lists (paragraphs, bullets, features, spec items) are localized at array level so locales can have different item counts; structured rows share order/icons and localize only their inner text. Existing data is not re-seeded (that would overwrite admin edits): a Payload migration wraps legacy values into { hu: value } on the published global and every draft/version record, idempotently, and runs on production startup via prodMigrations. Paths are derived from the Global configs themselves so the migration cannot drift from the schema. OpenSpec change: openspec/changes/localize-globals-mithome-111 Co-Authored-By: Claude Opus 5.5 --- .agent/steering/architecture.md | 9 ++ .../.openspec.yaml | 2 + .../localize-globals-mithome-111/design.md | 79 +++++++++++ .../localize-globals-mithome-111/proposal.md | 36 +++++ .../specs/content-management/spec.md | 61 ++++++++ .../localize-globals-mithome-111/tasks.md | 22 +++ proto/scripts/migrate-content-to-payload.ts | 14 +- .../localize-globals-migration.test.ts | 80 +++++++++++ proto/src/globals/About.ts | 34 ++--- proto/src/globals/Common.ts | 26 ++-- proto/src/globals/Contact.ts | 70 +++++----- proto/src/globals/Home.ts | 48 ++++--- proto/src/globals/Services.ts | 38 ++--- proto/src/globals/fields/stringArray.test.ts | 20 +++ proto/src/globals/fields/stringArray.ts | 16 ++- proto/src/lib/localize-paths.test.ts | 131 ++++++++++++++++++ proto/src/lib/localize-paths.ts | 111 +++++++++++++++ .../migrations/20260929_localize_globals.ts | 82 +++++++++++ proto/src/migrations/index.ts | 13 ++ proto/src/payload-config.test.ts | 51 +++++++ proto/src/payload.config.ts | 7 + 21 files changed, 839 insertions(+), 111 deletions(-) create mode 100644 openspec/changes/localize-globals-mithome-111/.openspec.yaml create mode 100644 openspec/changes/localize-globals-mithome-111/design.md create mode 100644 openspec/changes/localize-globals-mithome-111/proposal.md create mode 100644 openspec/changes/localize-globals-mithome-111/specs/content-management/spec.md create mode 100644 openspec/changes/localize-globals-mithome-111/tasks.md create mode 100644 proto/src/__tests__/localize-globals-migration.test.ts create mode 100644 proto/src/globals/fields/stringArray.test.ts create mode 100644 proto/src/lib/localize-paths.test.ts create mode 100644 proto/src/lib/localize-paths.ts create mode 100644 proto/src/migrations/20260929_localize_globals.ts create mode 100644 proto/src/migrations/index.ts diff --git a/.agent/steering/architecture.md b/.agent/steering/architecture.md index 0045edc..52acb01 100644 --- a/.agent/steering/architecture.md +++ b/.agent/steering/architecture.md @@ -71,6 +71,15 @@ mező felvételekor a megfelelő `proto/src/globals/*.ts` vagy `proto/src/collections/*.ts` fájlt bővítsd, majd generáld újra a típusokat (`payload generate:types`). +Ha egy meglévő mező tárolási alakja változik (pl. utólagos `localized: true`), +a meglévő adatot **Payload migrációval** kell átalakítani +(`proto/src/migrations/`, regisztrálva az `index.ts`-ben). A migráció +productionben induláskor automatikusan fut (`prodMigrations`). A JSON-seed +újrafuttatása tilos erre a célra, mert felülírná az admin-szerkesztéseket +(MITHOME-111). Lokalizációs retrofithez a `proto/src/lib/localize-paths.ts` +helperek használhatók. A `src/migrations/` mappába csak migrációs fájl +kerüljön, mert a Payload CLI minden `.ts` fájlt migrációnak tekint. + ## Dependency szabályok - Új NPM package bevezetéséhez **jóváhagyás szükséges** diff --git a/openspec/changes/localize-globals-mithome-111/.openspec.yaml b/openspec/changes/localize-globals-mithome-111/.openspec.yaml new file mode 100644 index 0000000..ee7c544 --- /dev/null +++ b/openspec/changes/localize-globals-mithome-111/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-28 diff --git a/openspec/changes/localize-globals-mithome-111/design.md b/openspec/changes/localize-globals-mithome-111/design.md new file mode 100644 index 0000000..06c368c --- /dev/null +++ b/openspec/changes/localize-globals-mithome-111/design.md @@ -0,0 +1,79 @@ +# Design + +## Context + +- A Payload 3.88 `mongooseAdapter`-rel tárolja a Globalokat. A publikált, illetve aktuális dokumentum a `globals` collectionben van (`globalType: ''`). Mivel a `versions.drafts` be van kapcsolva (MITHOME-92), a draftok és a verziótörténet a globalonkénti `__versions` collectionben élnek, `version.` alatt. +- Egy lokalizált mező MongoDB-alakja `{ hu: …, en: … }`. Egy lokalizált tömb alakja `{ hu: [...], en: [...] }`. Egy nem lokalizált tömbön belüli lokalizált mező alakja `[{ id, title: { hu, en }, icon }]`. A korábban tárolt, nem lokalizált érték (`"szöveg"` vagy `[...]`) a lokalizált mezőn üresnek olvasódik (ezt a MITHOME-110 bizonyította). +- A `Common.buttons.*` már lokalizált és migrált. Ezeket a migrációnak érintetlenül kell hagynia. +- A staging és a production konténerben `NODE_ENV=production` van, a dev compose-ban `development`. A fejlesztői Macen nincs Docker daemon. Konténert (pl. eldobható MongoDB-t) csak az llmdev szerveren lehet futtatni (`docker --context llmdev`). +- A `payload-content.ts` adapter és a view komponensek locale szerint kérdeznek (`findGlobal({ slug, locale })`), a visszakapott alak nem változik. A frontenden ezért nincs teendő. + +## Goals / Non-Goals + +**Goals:** +- A lokalizált mezőkészletnek egyetlen forrása legyen, a Global config (`localized: true`). A migráció ebből vezesse le az útvonalakat, ne egy kézzel karbantartott listából. +- A migráció adatvesztés nélküli, idempotens legyen, és lefedje a `globals` és a `__versions` rekordokat. + +**Non-Goals:** +- Angol tartalom előállítása (MITHOME-113), LegalPages (MITHOME-112). +- A lokalizáció visszafordítása (down-migráció) automatikus adatmentés nélkül. Lásd a Migration Plan szakaszt. + +## Decisions + +### D1: Mezőválasztás — a „mi fordítható?” szabály + +Minden `text`/`textarea` mező lokalizált, kivéve ezeket: +- `icon`: ikonkulcs, a render logika része. +- Objektum-sorok `id` mezője (`home.about.usps[].id`, `home.services.items[].id`): anchor/kulcs. +- `external` (checkbox). +- `common.footer.address`: postai cím, nyelvfüggetlen adat. Nem szövegmásolat. + +A `hero.cta.*.href` lokalizált, mert a belső útvonal nyelvenként eltér (`PAGE_SLUGS`). *Alternatíva:* a href-et PageKey-re cseréljük, és `localePath()`-szal számoljuk. Ez tisztább, de sémaváltással és a view-k módosításával járna, ezért külön feladat. + +### D2: Tömbök — vegyes stratégia (felhasználói döntés) + +- A `stringArrayField` új, opcionális `localized` paramétert kap, és az **egész array mezőt** jelöli lokalizáltnak. Ennek oka, hogy a bekezdésszám nyelvenként eltérhet. +- Az objektum-tömböknél (usps, items, values, services, channels, faq.items) a tömb maga közös, csak a belső szövegmezők lokalizáltak. Így az ikon és a sorrend egy helyen szerkeszthető. +- Kivétel: a `home.services.items[].features` és a `services.details.services[].specs.items` string-lista egy nem lokalizált sorban van, de maga a lista lokalizált. Ezt a Payload támogatja (tárolási alak: `features: { hu: [...] }`). + +### D3: Migráció Payload migrációként, `prodMigrations`-szel indítva + +- Új fájl: `src/migrations/20260929_localize_globals.ts`, `up({ payload })`. A migráció regisztrálva van a `src/migrations/index.ts`-ben, és a `mongooseAdapter({ prodMigrations })` kapja meg. A Payload production induláskor lefuttatja a még nem futott migrációkat, és a `payload-migrations` collectionben nyilvántartja őket. +- *Alternatíva 1:* a JSON-seed újrafuttatása. Elvetve, mert felülírja az admin-szerkesztéseket (felhasználói döntés). +- *Alternatíva 2:* külön `tsx` script, amelyet a `deploy.sh` futtat. Elvetve, mert a production image-ben nincs `tsx`/forrás, ezért a deploy scriptben új, törékeny lépést igényelne. A `prodMigrations` a Payload natív mechanizmusa, és a már bundle-ölt configgal fut. +- Dev környezetben a futtatás `npx payload migrate` paranccsal, vagy a `NODE_ENV=production` induláskor. + +### D4: Transzformáció — config-vezérelt, tiszta függvény + +- `src/lib/localize-paths.ts`: a `GlobalConfig.fields` bejárásával előállítja a lokalizált mezők relatív útvonalait (group → `a.b`, array → `a[]`, lokalizált mező → levél). Ebben a körben csak a `group`, `array`, `text`, `textarea` és `checkbox` típust kell kezelni, ismeretlen mezőtípusnál hibát dob (fail-fast). +- `wrapLocalized(doc, paths, locale = 'hu')`: tiszta függvény. + - `string`, illetve tömb értéket `{ hu: érték }` alakba csomagol. + - Ha az érték már plain object (`{ hu?, en? }`), érintetlenül hagyja. Ez adja az idempotenciát. + - `null` és `undefined` értékhez nem nyúl. +- A migráció a `globals` dokumentumra a gyökérből, a `__versions` dokumentumokra a `version` alól alkalmazza a transzformációt. Közvetlenül a mongoose `collection.updateOne`-nal ír, nem a Local API-val. Így nem keletkezik új verzió, nem futnak hookok, és a `updatedAt` sem változik. +- *Alternatíva:* kézzel írt útvonallista. Elvetve, mert elcsúszhat a configtól. A config-vezérelt bejárás a Global configok változásával automatikusan együtt mozog. + +### D5: Tesztek + +- A `localize-paths` és a `wrapLocalized` unit tesztekkel fedett (>90%). Esetek: string, tömb, beágyazott sor, már migrált érték, `null`, már lokalizált `Common.buttons`, dupla futtatás. +- `payload-config.test.ts`: táblázatos teszt arra, hogy a D1 kivételei nem lokalizáltak, minden más `text`/`textarea` lokalizált, és a stringArray mezők a tömb szintjén lokalizáltak. +- Élő ellenőrzés: eldobható MongoDB az llmdev szerveren, staging-dump visszaállításával (részletek a tasks.md-ben). + +## Risks / Trade-offs + +- [A migráció félúton elhasal (kapcsolatszakadás)] → A transzformáció dokumentumonként idempotens, ezért az újraindítás befejezi. A `payload-migrations` rekord csak siker után íródik. +- [Az Payload belső tárolási alakja eltér a feltételezettől (pl. versions collection neve)] → Élő ellenőrzés staging-dumppal deploy előtt. A migráció a `payload.db.globals` és a `payload.db.versions[slug]` modellekből veszi a collectiont, nem beégetett névből. +- [Egy lokalizált string-lista angol változata üres tömbként mentődik, és nem esik vissza a magyarra] → A Payload fallback csak `undefined`/`null` esetén lép életbe. Ezt az élő ellenőrzés során megnézzük, és ha kell, a MITHOME-113 seed kezeli. +- [Az admin required-validáció az `en` locale mentésekor minden kötelező mezőt kér] → Elfogadott: az angol változat teljes kitöltése a MITHOME-113 feladata. +- [Rollback] → A down-migráció fordított transzformáció, amely csak a `hu` értéket tartja meg, az `en` elveszik. Ezért a deploy előtti `mongodump` kötelező. + +## Migration Plan + +1. Deploy előtt `mongodump` a staging, majd a production adatbázisról. +2. Deploy (a meglévő `deploy.sh`). A konténer indulásakor a `prodMigrations` lefut, a log jelzi a sikert. +3. Ellenőrzés: `/hu/...` oldalak változatlanok, `/en/...` oldalakon magyar fallback, admin `en` locale üres/fallback, egy régi verzió megnyitása hu értékkel. +4. Rollback: az előző image visszaállítása és a dump `mongorestore`-ja. + +## Open Questions + +- A `hero.cta.primary.href` jelenlegi `/kapcsolat` értéke prefix nélküli (lásd proposal). Az adat javítása adminból történik, a szabályt nem érinti. diff --git a/openspec/changes/localize-globals-mithome-111/proposal.md b/openspec/changes/localize-globals-mithome-111/proposal.md new file mode 100644 index 0000000..21e4b9c --- /dev/null +++ b/openspec/changes/localize-globals-mithome-111/proposal.md @@ -0,0 +1,36 @@ +# Proposal + +## Why + +A MITHOME-110 bekapcsolta a Payload hu/en lokalizációt, és a MITHOME-114 óta a `/en/...` útvonalak is élnek. Az 5 Global (Home, About, Services, Contact, Common) mezői azonban a `Common.buttons.*` kivételével nem lokalizáltak, ezért az angol oldalak minden szövege magyar, és az adminban nincs hova angol változatot írni. A MITHOME-111 ezt pótolja. Erre a lépésre épül a LegalPages retrofit (MITHOME-112), az AI-draft angol tartalom (MITHOME-113) és a nyelvválasztó (MITHOME-115). + +A Plane-ticket szerint a meglévő magyar tartalom „migrálás nélkül, automatikusan” a `hu` locale alá kerül. A MITHOME-110 tapasztalata ezt cáfolja. Ha egy mezőt utólag `localized: true`-ra állítunk, a tárolási alak `"érték"`-ről `{ hu: "érték" }`-re változik, a régi érték pedig üresnek látszik. A MITHOME-110-nél ezt a JSON-seed újrafuttatásával oldottuk meg, ez azonban felülírná az ügyfél adminban végzett szerkesztéseit, ezért itt nem használható. + +## What Changes + +- Az 5 Global szöveges (`text`/`textarea`) mezői `localized: true` jelölést kapnak. A strukturális mezők közösek maradnak a nyelvek között: `icon`, a sorok `id` mezője, `external` és a postai cím (`footer.address`). +- A tömbökre vegyes stratégia vonatkozik: + - Az objektum-tömbökben (`about.usps`, `services.items`, `mission.values`, `details.services`, `support.channels`, `faq.items`) a sorok **belső szövegmezői** lokalizáltak, a sorok száma, sorrendje és ikonja közös. + - A string-listák (`stringArrayField`: `paragraphs`, `trustBullets`, `features`, `specs.items`) **egészükben** lokalizáltak, így nyelvenként eltérő számú elemük lehet. +- A `hero.cta.*.href` lokalizált lesz, mert a belső linkek nyelvenként eltérő útvonalra mutatnak (`/hu/kapcsolat` vs `/en/contact`). +- **BREAKING (tárolási alak)**: az érintett mezők MongoDB-alakja megváltozik. Egy idempotens Payload-migráció a meglévő értékeket `{ hu: <érték> }` alakba csomagolja. Ez a publikált dokumentumra, valamint a draft- és verziórekordokra is vonatkozik, az admin-szerkesztések megmaradnak. A migráció productionben a Payload `prodMigrations` mechanizmusán keresztül, induláskor automatikusan fut le. +- A `migrate-content-to-payload.ts` seed-script dokumentációja frissül: az újrafuttatás már nem része a lokalizációs átállásnak. +- Az angol tartalom feltöltése nem része ennek a változásnak (MITHOME-113). Addig a fallback miatt a magyar érték jelenik meg angolul is. + +## Capabilities + +### New Capabilities + +- Nincs. + +### Modified Capabilities + +- `content-management`: a „Hungarian and English locale support” követelmény kiegészül azzal, hogy a Global oldaltartalom fordítható szövegmezői lokalizáltak (a strukturális mezők közösek), és a meglévő tartalom adatvesztés nélkül a `hu` locale alá kerül át. + +## Impact + +- Érintett kód: `proto/src/globals/{Home,About,Services,Contact,Common}.ts`, `proto/src/globals/fields/stringArray.ts`, `proto/src/payload.config.ts` (`prodMigrations`), új `proto/src/migrations/` (lokalizációs migráció és a hozzá tartozó mezőútvonal-segéd), `proto/src/payload-types.ts` (újragenerálva), `proto/src/payload-config.test.ts` és a migráció új unit tesztjei. +- Nem változik: `proto/src/lib/payload-content.ts` és a page komponensek. A Local API a kért locale értékét adja vissza, a visszaadott alak ugyanaz marad. +- Adat: a staging és a production `globals` collection, valamint a `__versions` rekordok egyszeri átalakítása. Deploy előtt MongoDB-mentés szükséges (`scripts/` vagy `mongodump`). +- Kívül esik a scope-on: LegalPages (MITHOME-112), angol tartalom (MITHOME-113), nyelvválasztó UI (MITHOME-115), admin UI fordítás (MITHOME-122). +- Mellékmegfigyelés: a Home `hero.cta.primary.href` jelenlegi értéke `/kapcsolat`, locale-prefix nélkül. Middleware/redirect nélkül ez valószínűleg 404-re vezet. Ezt adatszinten, a migráció után az adminban kell javítani (`/hu/kapcsolat`), vagy külön ticketben kell kezelni. diff --git a/openspec/changes/localize-globals-mithome-111/specs/content-management/spec.md b/openspec/changes/localize-globals-mithome-111/specs/content-management/spec.md new file mode 100644 index 0000000..f1c4305 --- /dev/null +++ b/openspec/changes/localize-globals-mithome-111/specs/content-management/spec.md @@ -0,0 +1,61 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: Localized page globals + +The Home, About, Services, Contact, and Common globals SHALL store every translatable +text value (titles, subtitles, descriptions, body paragraphs, labels, button texts, +form messages, FAQ entries, metadata, and locale-dependent link targets) separately per +locale. Structural values (icons, row identifiers, the external-link flag, and the +postal address) SHALL be shared across locales. List items that consist of a single +text value (paragraph lists, bullet lists, feature lists, specification item lists) +SHALL be editable per locale, including a different number of items per locale. For +lists of structured rows, the row count, order, and structural values SHALL be shared +across locales, and only the text values within each row SHALL be localized. + +#### Scenario: An administrator saves an English value + +- **WHEN** an administrator edits a translatable global field in the `en` locale and + publishes it +- **THEN** the English public page SHALL render the English value and the Hungarian + public page SHALL continue to render the unchanged Hungarian value + +#### Scenario: An administrator changes a shared structural value + +- **WHEN** an administrator changes a structural value such as an icon in either locale +- **THEN** both locales SHALL render the changed value + +#### Scenario: A paragraph list differs between locales + +- **WHEN** the Hungarian version of a paragraph list has three items and the English + version has two +- **THEN** each locale's public page SHALL render exactly its own items + +### Requirement: Lossless locale migration of existing content + +When a previously non-localized global field becomes localized, its existing value +SHALL be preserved as the Hungarian value, including values edited by administrators +after the initial content import. The migration SHALL cover published content, saved +drafts, and version history, SHALL NOT overwrite existing content with seed data, and +SHALL be safe to run more than once. Deployed environments SHALL apply the migration +without a manual step. + +#### Scenario: Deploy onto a database with administrator edits + +- **WHEN** the localized configuration is deployed onto a database whose globals were + edited in the admin after the initial import +- **THEN** after startup the Hungarian public pages SHALL render the edited values + unchanged, and the English public pages SHALL render the same values through fallback + +#### Scenario: Restore an older version after migration + +- **WHEN** an administrator opens or restores a global version saved before the + migration +- **THEN** the version SHALL show its original text as the Hungarian value rather than + empty fields + +#### Scenario: Migration runs a second time + +- **WHEN** the migration is executed on already migrated data +- **THEN** stored values SHALL remain unchanged diff --git a/openspec/changes/localize-globals-mithome-111/tasks.md b/openspec/changes/localize-globals-mithome-111/tasks.md new file mode 100644 index 0000000..ae26fe4 --- /dev/null +++ b/openspec/changes/localize-globals-mithome-111/tasks.md @@ -0,0 +1,22 @@ +# Tasks + +## 1. Lokalizált Global configok + +- [x] 1.1 A `stringArrayField` bővítése opcionális `localized` paraméterrel (az array szinten jelöl), unit teszttel. Ellenőrzés: `cd proto && npm test -- stringArray`. +- [x] 1.2 A Home, About, Services, Contact és Common Global mezőinek `localized: true` jelölése a design D1/D2 szabálya szerint. Kivételek: `icon`, sor-`id`, `external`, `footer.address`. A `hero.cta.*.href` lokalizált. A fejléc-kommentek frissítése (MITHOME-111). Ellenőrzés: a `payload-config.test.ts` táblázatos tesztje, amely minden Global összes mezőjét bejárja, és a kivételek kivételével minden `text`/`textarea`-t, valamint a stringArray tömböket lokalizáltnak várja, zöld. +- [x] 1.3 A `payload-types.ts` újragenerálása (a `payload` CLI Node 26 alatt `ERR_REQUIRE_ASYNC_MODULE`-lal elhasal, ezért a `generateTypes` függvényt közvetlenül, ESM-importtal hívtuk; a kimenet változatlan, mert a lokalizált mezők TS-típusa azonos), a `tsc --noEmit` és az `npm run lint` futtatása. Ellenőrzés: nincs típushiba, a `payload-content.ts` változatlanul fordul. + +## 2. Adatmigráció + +- [x] 2.1 A `src/lib/localize-paths.ts` elkészítése (nem a `src/migrations/` alatt, mert a Payload CLI ott minden `.ts`-t migrációnak vesz): a config-vezérelt útvonalgyűjtés és a `wrapLocalized` tiszta függvény (D4). Unit tesztek fedik le a string, a tömb, a sorban lévő mező, a sorban lévő lokalizált lista, a már migrált érték, a `null` és a dupla futtatás esetét. Ellenőrzés: `npm test -- localize-paths` (100% sor-, 88% ág-lefedettség), lefedettség >90%. +- [x] 2.2 A `src/migrations/20260929_localize_globals.ts` (`up`/`down`) és a `src/migrations/index.ts` elkészítése, `prodMigrations` regisztrációval a `payload.config.ts`-ben. A migráció a `globals` és a `__versions` rekordokat alakítja át, és hookok, illetve új verzió nélkül ír. Unit teszt mockolt collectionnel (`src/__tests__/localize-globals-migration.test.ts`): a helyes dokumentumokat és útvonalakat frissíti. Ellenőrzés: `npm test`. +- [x] 2.3 A `migrate-content-to-payload.ts` fejkommentjének frissítése: a lokalizációs átállás a migrációval történik, nem a seed újrafuttatásával. A `.agent/steering/architecture.md` kiegészítése a migrációs szabállyal. Ellenőrzés: nincs elavult utasítás a scriptben és a `docs/`-ban (`grep -rn "újra kell futtatni" proto/scripts docs`). + +## 3. Élő ellenőrzés és deploy-előkészítés + +- [ ] 3.1 Eldobható MongoDB indítása az llmdev szerveren (`docker --context llmdev`, a Docker-háttér spec szerint, csak `127.0.0.1`-re kötve, SSH-tunnellel). Ide kerül a staging adatbázis dumpja. Erre fut a `npx payload migrate`, kétszer. Ellenőrzés: a második futás 0 módosítást jelez; a `npm run test:payload` a hu értékeket adja; a `/hu/*` HTML egyezik a migráció előtti snapshottal (`scripts/export-content-snapshot.ts`); a `/en/*` magyar fallbacket mutat; az adminban egy régi verzió hu értékkel nyílik meg; egy `en` mentés csak az angol oldalt változtatja meg. +- [ ] 3.2 A `docs/` deploy-dokumentáció kiegészítése a kötelező deploy előtti `mongodump` lépéssel és a rollback menetével. Utána az eldobható konténer leállítása és eltávolítása. Ellenőrzés: a dokumentált parancsok egyeznek a 3.1-ben ténylegesen futtatottakkal. + +## 4. Lezárás + +- [ ] 4.1 `cd proto && npm test && npm run lint && npm run build` zöld. Utána a MITHOME-111 Plane-státusz és a `TODO.md` szinkronizálása, Plane-komment a „migrálás nélkül” téves állítás helyesbítésével és a `/kapcsolat` href mellékmegfigyeléssel. Ellenőrzés: a Plane és a `TODO.md` egyezik, a commitok Conventional Commits formátumúak. diff --git a/proto/scripts/migrate-content-to-payload.ts b/proto/scripts/migrate-content-to-payload.ts index 33d83e9..d1f4b59 100644 --- a/proto/scripts/migrate-content-to-payload.ts +++ b/proto/scripts/migrate-content-to-payload.ts @@ -21,12 +21,14 @@ * script eredménye mindig publikált tartalom legyen, sosem draft. * * MITHOME-110 tapasztalat: ha egy mezőt utólag `localized: true`-ra - * állítasz (MITHOME-111/112 retrofit), a korábban beírt érték a régi, - * nem-lokalizált tárolási alakban marad, és `locale: defaultLocale`-lal - * nem olvasható vissza (üresnek látszik) — ilyenkor ezt a scriptet újra - * kell futtatni, hogy a defaultLocale (hu) alá újra beírja az értéket a - * lokalizált alakban. Explicit `locale` paramétert egyik updateGlobal/ - * update hívás sem ad meg itt, ezért mindig a `defaultLocale` (hu) alá ír. + * állítasz, a korábban beírt érték a régi, nem-lokalizált tárolási alakban + * marad, és `locale: defaultLocale`-lal nem olvasható vissza (üresnek + * látszik). MITHOME-111 óta ezt NEM ennek a scriptnek az újrafuttatásával + * kezeljük (az felülírná az admin-szerkesztéseket), hanem Payload + * migrációval (src/migrations/, prodMigrations) — egy újabb retrofitnál + * (pl. MITHOME-112) is új migráció kell, a src/lib/localize-paths.ts + * helperekkel. Explicit `locale` paramétert egyik updateGlobal/update hívás + * sem ad meg itt, ezért mindig a `defaultLocale` (hu) alá ír. */ import path from 'path' import { fileURLToPath } from 'url' diff --git a/proto/src/__tests__/localize-globals-migration.test.ts b/proto/src/__tests__/localize-globals-migration.test.ts new file mode 100644 index 0000000..456e660 --- /dev/null +++ b/proto/src/__tests__/localize-globals-migration.test.ts @@ -0,0 +1,80 @@ +import { down, up } from '../migrations/20260929_localize_globals' + +type Doc = Record + +function fakeCollection(docs: Doc[]) { + return { + findOne: jest.fn(async (filter: { globalType: string }) => docs.find((d) => d.globalType === filter.globalType) ?? null), + find: jest.fn(() => ({ + async *[Symbol.asyncIterator]() { + yield* docs + }, + })), + updateOne: jest.fn(async (_filter: Doc, _update: { $set: Doc }, _options?: unknown) => ({})), + } +} + +function setup() { + const globals = fakeCollection([ + { _id: 'g-home', globalType: 'home', hero: { title: 'Cím', trustBullets: [{ value: 'Egy' }] }, cta: { title: 'CTA' } }, + { _id: 'g-common', globalType: 'common', buttons: { contact: { hu: 'Kapcsolat', en: 'Contact' } } }, + ]) + const homeVersions = fakeCollection([ + { _id: 'v1', version: { hero: { title: 'Régi cím' } } }, + { _id: 'v2', version: { hero: { title: { hu: 'Már migrált' } } } }, + ]) + const payload = { + db: { globals: { collection: globals }, versions: { home: { collection: homeVersions } } }, + logger: { info: jest.fn() }, + } + const args = { payload, session: undefined, req: {} } as never + return { args, globals, homeVersions, payload } +} + +describe('20260929_localize_globals migration', () => { + it('should wrap legacy values of the published global under hu and $set only touched keys', async () => { + const { args, globals } = setup() + await up(args) + + const homeCall = globals.updateOne.mock.calls.find(([filter]) => filter._id === 'g-home') + expect(homeCall).toBeDefined() + const [, update] = homeCall! + expect(update.$set.hero).toEqual({ title: { hu: 'Cím' }, trustBullets: { hu: [{ value: 'Egy' }] } }) + expect(update.$set.cta).toEqual({ title: { hu: 'CTA' } }) + expect(update.$set).not.toHaveProperty('_id') + expect(update.$set).not.toHaveProperty('globalType') + }) + + it('should not rewrite a global whose values are already localized', async () => { + const { args, globals } = setup() + await up(args) + const ids = globals.updateOne.mock.calls.map(([filter]) => filter._id) + expect(ids).not.toContain('g-common') + }) + + it('should migrate legacy version records and skip migrated ones', async () => { + const { args, homeVersions } = setup() + await up(args) + + expect(homeVersions.updateOne).toHaveBeenCalledTimes(1) + expect(homeVersions.updateOne).toHaveBeenCalledWith( + { _id: 'v1' }, + { $set: { version: { hero: { title: { hu: 'Régi cím' } } } } }, + { session: undefined }, + ) + }) + + it('should log a per-global summary', async () => { + const { args, payload } = setup() + await up(args) + expect(payload.logger.info).toHaveBeenCalledWith('MITHOME-111 locale migration: home — 4 value(s) rewritten') + }) + + it('should restore the hu value on down', async () => { + const { args, globals } = setup() + await down(args) + const commonCall = globals.updateOne.mock.calls.find(([filter]) => filter._id === 'g-common') + const [, update] = commonCall! + expect(update.$set.buttons).toEqual({ contact: 'Kapcsolat' }) + }) +}) diff --git a/proto/src/globals/About.ts b/proto/src/globals/About.ts index 66303a8..7fd5094 100644 --- a/proto/src/globals/About.ts +++ b/proto/src/globals/About.ts @@ -15,39 +15,39 @@ export const About: GlobalConfig = { name: 'meta', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'description', type: 'textarea', required: true }, - { name: 'ogDescription', type: 'textarea', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'description', type: 'textarea', required: true, localized: true }, + { name: 'ogDescription', type: 'textarea', required: true, localized: true }, ], }, { name: 'hero', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'text', required: true, localized: true }, ], }, { name: 'story', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - stringArrayField('paragraphs', 'Paragraphs'), + { name: 'title', type: 'text', required: true, localized: true }, + stringArrayField('paragraphs', 'Paragraphs', { localized: true }), ], }, { name: 'mission', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'text', required: true, localized: true }, { name: 'values', type: 'array', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'description', type: 'textarea', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'description', type: 'textarea', required: true, localized: true }, { name: 'icon', type: 'text', required: true }, ], }, @@ -57,18 +57,18 @@ export const About: GlobalConfig = { name: 'team', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'text', required: true }, - stringArrayField('paragraphs', 'Paragraphs'), + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'text', required: true, localized: true }, + stringArrayField('paragraphs', 'Paragraphs', { localized: true }), ], }, { name: 'cta', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'textarea', required: true }, - { name: 'button', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'textarea', required: true, localized: true }, + { name: 'button', type: 'text', required: true, localized: true }, ], }, ], diff --git a/proto/src/globals/Common.ts b/proto/src/globals/Common.ts index 63758b9..e040b34 100644 --- a/proto/src/globals/Common.ts +++ b/proto/src/globals/Common.ts @@ -5,11 +5,11 @@ import { globalVersions } from '../lib/payload-versions' /** * Mirrors CommonContent (proto/src/content/types.ts) — MITHOME-87. * - * `buttons.*` localized: true (MITHOME-110) — ez a lokalizáció-mechanizmus - * bizonyítéka (admin nyelvváltó + Local/REST API locale param), és egyben - * előremutató, helyes darabja a MITHOME-111 teljes retrofitnak: ezek - * ténylegesen fordítandó UI-feliratok. A többi mező itt még nem lokalizált, - * azt a MITHOME-111 teljes körűen elvégzi. + * `buttons.*` localized: true (MITHOME-110) volt a lokalizáció-mechanizmus + * első bizonyítéka; a MITHOME-111 minden fordítható szöveget lokalizált. + * + * DECISION: `footer.address` szándékosan NEM lokalizált — postai cím, + * nyelvfüggetlen adat, nem szövegmásolat (MITHOME-111 design D1). */ export const Common: GlobalConfig = { slug: 'common', @@ -32,20 +32,21 @@ export const Common: GlobalConfig = { name: 'labels', type: 'group', fields: [ - { name: 'required', type: 'text', required: true }, - { name: 'features', type: 'text', required: true }, + { name: 'required', type: 'text', required: true, localized: true }, + { name: 'features', type: 'text', required: true, localized: true }, ], }, { name: 'validation', type: 'group', fields: [ - { name: 'required', type: 'text', required: true }, - { name: 'invalidEmail', type: 'text', required: true }, + { name: 'required', type: 'text', required: true, localized: true }, + { name: 'invalidEmail', type: 'text', required: true, localized: true }, { name: 'minLength', type: 'text', required: true, + localized: true, admin: { description: 'A {min} placeholder futásidőben cserélődik ki.', }, @@ -55,7 +56,7 @@ export const Common: GlobalConfig = { { name: 'staging', type: 'group', - fields: [{ name: 'banner', type: 'text', required: true }], + fields: [{ name: 'banner', type: 'text', required: true, localized: true }], }, { name: 'footer', @@ -65,6 +66,7 @@ export const Common: GlobalConfig = { name: 'copyright', type: 'text', required: true, + localized: true, admin: { description: 'A {year} placeholder futásidőben cserélődik ki.', }, @@ -76,8 +78,8 @@ export const Common: GlobalConfig = { name: 'a11y', type: 'group', fields: [ - { name: 'openMenu', type: 'text', required: true }, - { name: 'closeMenu', type: 'text', required: true }, + { name: 'openMenu', type: 'text', required: true, localized: true }, + { name: 'closeMenu', type: 'text', required: true, localized: true }, ], }, ], diff --git a/proto/src/globals/Contact.ts b/proto/src/globals/Contact.ts index fbfa54c..683a7cc 100644 --- a/proto/src/globals/Contact.ts +++ b/proto/src/globals/Contact.ts @@ -22,25 +22,25 @@ export const Contact: GlobalConfig = { name: 'meta', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'description', type: 'textarea', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'description', type: 'textarea', required: true, localized: true }, ], }, { name: 'hero', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'text', required: true, localized: true }, ], }, { name: 'form', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'successMessage', type: 'text', required: true }, - { name: 'errorMessage', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'successMessage', type: 'text', required: true, localized: true }, + { name: 'errorMessage', type: 'text', required: true, localized: true }, { name: 'fields', type: 'group', @@ -49,79 +49,79 @@ export const Contact: GlobalConfig = { name: 'name', type: 'group', fields: [ - { name: 'label', type: 'text', required: true }, - { name: 'placeholder', type: 'text', required: true }, - { name: 'error', type: 'text', required: true }, + { name: 'label', type: 'text', required: true, localized: true }, + { name: 'placeholder', type: 'text', required: true, localized: true }, + { name: 'error', type: 'text', required: true, localized: true }, ], }, { name: 'email', type: 'group', fields: [ - { name: 'label', type: 'text', required: true }, - { name: 'placeholder', type: 'text', required: true }, - { name: 'errorRequired', type: 'text', required: true }, - { name: 'errorInvalid', type: 'text', required: true }, + { name: 'label', type: 'text', required: true, localized: true }, + { name: 'placeholder', type: 'text', required: true, localized: true }, + { name: 'errorRequired', type: 'text', required: true, localized: true }, + { name: 'errorInvalid', type: 'text', required: true, localized: true }, ], }, { name: 'subject', type: 'group', fields: [ - { name: 'label', type: 'text', required: true }, - { name: 'placeholder', type: 'text', required: true }, - { name: 'error', type: 'text', required: true }, + { name: 'label', type: 'text', required: true, localized: true }, + { name: 'placeholder', type: 'text', required: true, localized: true }, + { name: 'error', type: 'text', required: true, localized: true }, ], }, { name: 'message', type: 'group', fields: [ - { name: 'label', type: 'text', required: true }, - { name: 'placeholder', type: 'text', required: true }, - { name: 'errorRequired', type: 'text', required: true }, - { name: 'errorMinLength', type: 'text', required: true }, + { name: 'label', type: 'text', required: true, localized: true }, + { name: 'placeholder', type: 'text', required: true, localized: true }, + { name: 'errorRequired', type: 'text', required: true, localized: true }, + { name: 'errorMinLength', type: 'text', required: true, localized: true }, ], }, { name: 'gdpr', type: 'group', fields: [ - { name: 'label', type: 'textarea', required: true }, - { name: 'error', type: 'text', required: true }, + { name: 'label', type: 'textarea', required: true, localized: true }, + { name: 'error', type: 'text', required: true, localized: true }, ], }, ], }, - { name: 'submitButton', type: 'text', required: true }, - { name: 'submittingButton', type: 'text', required: true }, + { name: 'submitButton', type: 'text', required: true, localized: true }, + { name: 'submittingButton', type: 'text', required: true, localized: true }, ], }, { name: 'info', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, { name: 'email', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'responseTime', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'responseTime', type: 'text', required: true, localized: true }, ], }, { name: 'company', type: 'group', - fields: [{ name: 'title', type: 'text', required: true }], + fields: [{ name: 'title', type: 'text', required: true, localized: true }], }, { name: 'webmail', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'linkText', type: 'text', required: true }, - { name: 'subtitle', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'linkText', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'text', required: true, localized: true }, ], }, ], @@ -130,13 +130,13 @@ export const Contact: GlobalConfig = { name: 'faq', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, { name: 'items', type: 'array', fields: [ - { name: 'question', type: 'text', required: true }, - { name: 'answer', type: 'textarea', required: true }, + { name: 'question', type: 'text', required: true, localized: true }, + { name: 'answer', type: 'textarea', required: true, localized: true }, ], }, ], diff --git a/proto/src/globals/Home.ts b/proto/src/globals/Home.ts index f1a6296..cc2dbee 100644 --- a/proto/src/globals/Home.ts +++ b/proto/src/globals/Home.ts @@ -10,6 +10,12 @@ import { globalVersions } from '../lib/payload-versions' * beágyazott lista, de a Payload oldalon önálló `Partners` collection lesz * (logó = Media upload reference) — lásd MITHOME-89. Itt szándékosan * kihagyjuk, nehogy két, egymásnak ellentmondó forrás legyen. + * + * MITHOME-111 lokalizáció: minden fordítható szöveg `localized: true`; az + * `icon`, a sor-`id` és az `external` közös. WHY a `cta.*.href` is + * lokalizált: a belső útvonal nyelvenként eltér (/hu/kapcsolat vs + * /en/contact, lásd PAGE_SLUGS). A string-listák (trustBullets, features) + * tömb-szinten lokalizáltak — nyelvenként eltérő elemszám lehet. */ export const Home: GlobalConfig = { slug: 'home', @@ -22,10 +28,10 @@ export const Home: GlobalConfig = { name: 'hero', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'text', required: true }, - { name: 'description', type: 'textarea', required: true }, - stringArrayField('trustBullets', 'Trust bullets'), + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'text', required: true, localized: true }, + { name: 'description', type: 'textarea', required: true, localized: true }, + stringArrayField('trustBullets', 'Trust bullets', { localized: true }), { name: 'cta', type: 'group', @@ -34,8 +40,8 @@ export const Home: GlobalConfig = { name: 'primary', type: 'group', fields: [ - { name: 'text', type: 'text', required: true }, - { name: 'href', type: 'text', required: true }, + { name: 'text', type: 'text', required: true, localized: true }, + { name: 'href', type: 'text', required: true, localized: true }, { name: 'external', type: 'checkbox', defaultValue: false }, ], }, @@ -43,8 +49,8 @@ export const Home: GlobalConfig = { name: 'secondary', type: 'group', fields: [ - { name: 'text', type: 'text', required: true }, - { name: 'href', type: 'text', required: true }, + { name: 'text', type: 'text', required: true, localized: true }, + { name: 'href', type: 'text', required: true, localized: true }, { name: 'external', type: 'checkbox', defaultValue: false }, ], }, @@ -56,14 +62,14 @@ export const Home: GlobalConfig = { name: 'about', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, { name: 'usps', type: 'array', fields: [ { name: 'id', type: 'text', required: true }, - { name: 'title', type: 'text', required: true }, - { name: 'description', type: 'textarea', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'description', type: 'textarea', required: true, localized: true }, { name: 'icon', type: 'text', required: true }, ], }, @@ -73,18 +79,18 @@ export const Home: GlobalConfig = { name: 'services', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'text', required: true, localized: true }, { name: 'items', type: 'array', fields: [ { name: 'id', type: 'text', required: true }, - { name: 'title', type: 'text', required: true }, - { name: 'description', type: 'textarea', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'description', type: 'textarea', required: true, localized: true }, { name: 'icon', type: 'text', required: true }, - stringArrayField('features', 'Features'), - { name: 'ctaText', type: 'text', required: true }, + stringArrayField('features', 'Features', { localized: true }), + { name: 'ctaText', type: 'text', required: true, localized: true }, ], }, ], @@ -93,15 +99,15 @@ export const Home: GlobalConfig = { name: 'cta', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'textarea', required: true }, - { name: 'button', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'textarea', required: true, localized: true }, + { name: 'button', type: 'text', required: true, localized: true }, ], }, { name: 'serviceFeatures', type: 'group', - fields: [{ name: 'title', type: 'text', required: true }], + fields: [{ name: 'title', type: 'text', required: true, localized: true }], }, ], } diff --git a/proto/src/globals/Services.ts b/proto/src/globals/Services.ts index a3454c9..533f024 100644 --- a/proto/src/globals/Services.ts +++ b/proto/src/globals/Services.ts @@ -15,38 +15,38 @@ export const Services: GlobalConfig = { name: 'meta', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'description', type: 'textarea', required: true }, - { name: 'ogDescription', type: 'textarea', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'description', type: 'textarea', required: true, localized: true }, + { name: 'ogDescription', type: 'textarea', required: true, localized: true }, ], }, { name: 'hero', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'text', required: true, localized: true }, ], }, { name: 'details', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'text', required: true, localized: true }, { name: 'services', type: 'array', fields: [ { name: 'icon', type: 'text', required: true }, - { name: 'title', type: 'text', required: true }, - { name: 'description', type: 'textarea', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'description', type: 'textarea', required: true, localized: true }, { name: 'specs', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - stringArrayField('items', 'Items'), + { name: 'title', type: 'text', required: true, localized: true }, + stringArrayField('items', 'Items', { localized: true }), ], }, ], @@ -57,15 +57,15 @@ export const Services: GlobalConfig = { name: 'support', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'text', required: true, localized: true }, { name: 'channels', type: 'array', fields: [ { name: 'icon', type: 'text', required: true }, - { name: 'title', type: 'text', required: true }, - { name: 'description', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'description', type: 'text', required: true, localized: true }, ], }, ], @@ -74,10 +74,10 @@ export const Services: GlobalConfig = { name: 'cta', type: 'group', fields: [ - { name: 'title', type: 'text', required: true }, - { name: 'subtitle', type: 'textarea', required: true }, - { name: 'primaryButton', type: 'text', required: true }, - { name: 'secondaryButton', type: 'text', required: true }, + { name: 'title', type: 'text', required: true, localized: true }, + { name: 'subtitle', type: 'textarea', required: true, localized: true }, + { name: 'primaryButton', type: 'text', required: true, localized: true }, + { name: 'secondaryButton', type: 'text', required: true, localized: true }, ], }, ], diff --git a/proto/src/globals/fields/stringArray.test.ts b/proto/src/globals/fields/stringArray.test.ts new file mode 100644 index 0000000..12b2155 --- /dev/null +++ b/proto/src/globals/fields/stringArray.test.ts @@ -0,0 +1,20 @@ +import { stringArrayField } from './stringArray' + +describe('stringArrayField', () => { + it('should build an optional, non-localized array of { value } rows by default', () => { + const field = stringArrayField('paragraphs', 'Paragraphs') + expect(field).toMatchObject({ name: 'paragraphs', type: 'array', label: 'Paragraphs', required: false }) + expect(field).not.toHaveProperty('localized') + expect(field.fields).toEqual([{ name: 'value', type: 'text', required: true }]) + }) + + it('should localize the array itself, not the inner value, when localized is set', () => { + const field = stringArrayField('paragraphs', 'Paragraphs', { localized: true }) + expect(field.localized).toBe(true) + expect(field.fields[0]).not.toHaveProperty('localized') + }) + + it('should pass the required flag through', () => { + expect(stringArrayField('items', undefined, { required: true }).required).toBe(true) + }) +}) diff --git a/proto/src/globals/fields/stringArray.ts b/proto/src/globals/fields/stringArray.ts index a2f57a3..d76f17a 100644 --- a/proto/src/globals/fields/stringArray.ts +++ b/proto/src/globals/fields/stringArray.ts @@ -1,5 +1,14 @@ import type { ArrayField } from 'payload' +type StringArrayOptions = { + required?: boolean + /** + * MITHOME-111: localizes the whole array (not the inner `value`), so each + * locale can have its own number of items (e.g. 3 hu paragraphs, 2 en). + */ + localized?: boolean +} + /** * Payload has no native "array of plain strings" field — the closest * built-in shape is an array of one-field objects. Used for every @@ -7,11 +16,16 @@ import type { ArrayField } from 'payload' * features, spec items, …) so the JSON -> Payload migration script has a * single, consistent shape to transform into. */ -export function stringArrayField(name: string, label?: string, required = false): ArrayField { +export function stringArrayField( + name: string, + label?: string, + { required = false, localized = false }: StringArrayOptions = {}, +): ArrayField { return { name, type: 'array', label, + ...(localized ? { localized: true } : {}), fields: [ { name: 'value', diff --git a/proto/src/lib/localize-paths.test.ts b/proto/src/lib/localize-paths.test.ts new file mode 100644 index 0000000..6e22845 --- /dev/null +++ b/proto/src/lib/localize-paths.test.ts @@ -0,0 +1,131 @@ +import { collectLocalizedPaths, topLevelKeys, unwrapLocalized, wrapLocalized } from './localize-paths' +import { Home } from '../globals/Home' +import { Common } from '../globals/Common' + +type Doc = Record + +const FIELDS = [ + { + name: 'hero', + type: 'group', + fields: [ + { name: 'title', type: 'text', localized: true }, + { name: 'bullets', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] }, + ], + }, + { + name: 'items', + type: 'array', + fields: [ + { name: 'icon', type: 'text' }, + { name: 'title', type: 'text', localized: true }, + { name: 'features', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] }, + ], + }, + { name: 'address', type: 'text' }, + { name: 'external', type: 'checkbox' }, +] + +function legacyDoc(): Doc { + return { + hero: { title: 'Cím', bullets: [{ id: 'b1', value: 'Egy' }] }, + items: [ + { id: 'r1', icon: 'star', title: 'Első', features: [{ id: 'f1', value: 'A' }] }, + { id: 'r2', icon: 'bolt', title: 'Második', features: [] }, + ], + address: 'Budapest', + external: false, + } +} + +describe('collectLocalizedPaths', () => { + it('should collect localized leaves through groups and shared array rows', () => { + expect(collectLocalizedPaths(FIELDS)).toEqual([ + ['hero', 'title'], + ['hero', 'bullets'], + ['items', '[]', 'title'], + ['items', '[]', 'features'], + ]) + }) + + it('should throw on layout fields that could hide localized data', () => { + expect(() => collectLocalizedPaths([{ type: 'tabs' }])).toThrow('unsupported field type "tabs"') + }) + + it('should derive paths from the real Global configs', () => { + const homePaths = collectLocalizedPaths(Home.fields as never) + expect(homePaths).toContainEqual(['hero', 'trustBullets']) + expect(homePaths).toContainEqual(['services', 'items', '[]', 'features']) + expect(homePaths).not.toContainEqual(['about', 'usps', '[]', 'icon']) + expect(collectLocalizedPaths(Common.fields as never)).not.toContainEqual(['footer', 'address']) + }) +}) + +describe('wrapLocalized', () => { + const paths = collectLocalizedPaths(FIELDS) + + it('should wrap strings and arrays under the hu locale and keep shared values', () => { + const doc = legacyDoc() + const changed = wrapLocalized(doc, paths) + + expect(changed).toBe(6) + expect(doc.hero).toEqual({ title: { hu: 'Cím' }, bullets: { hu: [{ id: 'b1', value: 'Egy' }] } }) + expect(doc.items).toEqual([ + { id: 'r1', icon: 'star', title: { hu: 'Első' }, features: { hu: [{ id: 'f1', value: 'A' }] } }, + { id: 'r2', icon: 'bolt', title: { hu: 'Második' }, features: { hu: [] } }, + ]) + expect(doc.address).toBe('Budapest') + expect(doc.external).toBe(false) + }) + + it('should be idempotent on already migrated data', () => { + const doc = legacyDoc() + wrapLocalized(doc, paths) + const snapshot = JSON.stringify(doc) + + expect(wrapLocalized(doc, paths)).toBe(0) + expect(JSON.stringify(doc)).toBe(snapshot) + }) + + it('should leave existing locale maps (e.g. Common.buttons) untouched', () => { + const doc: Doc = { hero: { title: { hu: 'Cím', en: 'Title' } } } + expect(wrapLocalized(doc, paths)).toBe(0) + expect(doc).toEqual({ hero: { title: { hu: 'Cím', en: 'Title' } } }) + }) + + it('should skip missing branches and null values', () => { + const doc: Doc = { hero: { title: null }, items: null } + expect(wrapLocalized(doc, paths)).toBe(0) + expect(doc).toEqual({ hero: { title: null }, items: null }) + }) + + it('should not descend into a row path when the stored value is not an array', () => { + const doc: Doc = { items: { unexpected: true } } + expect(wrapLocalized(doc, paths)).toBe(0) + }) +}) + +describe('unwrapLocalized', () => { + const paths = collectLocalizedPaths(FIELDS) + + it('should restore the legacy shape from the hu value', () => { + const doc = legacyDoc() + wrapLocalized(doc, paths) + ;(doc.hero as Doc).title = { hu: 'Cím', en: 'Title' } + + expect(unwrapLocalized(doc, paths)).toBe(6) + expect(doc).toEqual(legacyDoc()) + }) + + it('should fall back to null when the hu value is missing', () => { + const doc: Doc = { hero: { title: { en: 'Title' } } } + unwrapLocalized(doc, paths) + expect(doc).toEqual({ hero: { title: null } }) + }) +}) + +describe('topLevelKeys', () => { + it('should return unique first segments', () => { + expect(topLevelKeys(collectLocalizedPaths(FIELDS))).toEqual(['hero', 'items']) + }) +}) diff --git a/proto/src/lib/localize-paths.ts b/proto/src/lib/localize-paths.ts new file mode 100644 index 0000000..d4fc48a --- /dev/null +++ b/proto/src/lib/localize-paths.ts @@ -0,0 +1,111 @@ +/** + * MITHOME-111: pure helpers for the "field became `localized: true`" + * data migration (design D4). + * + * WHY config-driven paths: the Global configs are the single source of + * truth for which fields are localized — deriving the migration paths from + * them means the migration can never drift from the schema. + * + * Storage shapes (Payload mongooseAdapter): + * non-localized text -> "szöveg" localized -> { hu: "szöveg" } + * non-localized array -> [{ value }] localized -> { hu: [{ value }] } + * A path segment `[]` means "every row of this (shared) array". + */ + +type FieldNode = { name?: string; type: string; localized?: boolean; fields?: FieldNode[] } + +export type LocalizedPath = readonly string[] + +const ARRAY_ROWS = '[]' + +/** Layout fields that could hide localized children — not traversed here. */ +const UNSUPPORTED_CONTAINERS = new Set(['tabs', 'row', 'collapsible', 'blocks']) + +export function collectLocalizedPaths( + fields: readonly FieldNode[], + prefix: LocalizedPath = [], +): LocalizedPath[] { + const paths: LocalizedPath[] = [] + for (const field of fields) { + if (UNSUPPORTED_CONTAINERS.has(field.type)) { + // DECISION: fail fast rather than silently skip localized data. + throw new Error(`collectLocalizedPaths: unsupported field type "${field.type}"`) + } + if (!field.name) continue + const path = [...prefix, field.name] + if (field.localized) { + paths.push(path) + } else if (field.type === 'group') { + paths.push(...collectLocalizedPaths(field.fields ?? [], path)) + } else if (field.type === 'array') { + paths.push(...collectLocalizedPaths(field.fields ?? [], [...path, ARRAY_ROWS])) + } + } + return paths +} + +type Transform = (value: unknown) => { value: unknown; changed: boolean } + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function applyAtPath(node: unknown, path: LocalizedPath, transform: Transform): number { + if (typeof node !== 'object' || node === null) return 0 + const [head, ...rest] = path + if (head === ARRAY_ROWS) { + if (!Array.isArray(node)) return 0 + return node.reduce((sum, row) => sum + applyAtPath(row, rest, transform), 0) + } + if (!isPlainObject(node)) return 0 + if (rest.length > 0) return applyAtPath(node[head], rest, transform) + + const result = transform(node[head]) + if (result.changed) node[head] = result.value + return result.changed ? 1 : 0 +} + +// WHY in-place mutation instead of structuredClone: raw Mongo documents +// carry BSON class instances (ObjectId) that a structured clone would +// silently turn into plain objects. Callers pass freshly read documents. +function applyAll(doc: Record, paths: readonly LocalizedPath[], transform: Transform) { + return paths.reduce((sum, path) => sum + applyAtPath(doc, path, transform), 0) +} + +/** Top-level document keys touched by `paths` — the `$set` scope of a write. */ +export function topLevelKeys(paths: readonly LocalizedPath[]): string[] { + return [...new Set(paths.map((path) => path[0]))] +} + +/** + * Wraps legacy (non-localized) values into `{ [locale]: value }`, in place. + * Idempotent: values already stored as a locale map are left untouched, + * null/undefined are skipped (nothing to preserve). Returns the number of + * values changed. + */ +export function wrapLocalized( + doc: Record, + paths: readonly LocalizedPath[], + locale = 'hu', +) { + return applyAll(doc, paths, (value) => + typeof value === 'string' || Array.isArray(value) + ? { value: { [locale]: value }, changed: true } + : { value, changed: false }, + ) +} + +/** + * Inverse of wrapLocalized (down migration), in place: keeps only + * `locale`'s value. + * TRADEOFF: every other locale's value is dropped — take a DB dump first. + */ +export function unwrapLocalized( + doc: Record, + paths: readonly LocalizedPath[], + locale = 'hu', +) { + return applyAll(doc, paths, (value) => + isPlainObject(value) ? { value: value[locale] ?? null, changed: true } : { value, changed: false }, + ) +} diff --git a/proto/src/migrations/20260929_localize_globals.ts b/proto/src/migrations/20260929_localize_globals.ts new file mode 100644 index 0000000..424decf --- /dev/null +++ b/proto/src/migrations/20260929_localize_globals.ts @@ -0,0 +1,82 @@ +/** + * MITHOME-111: a Global mezők utólagos `localized: true` jelölése után a + * meglévő (nem lokalizált alakú) értékeket `{ hu: érték }` alakba csomagolja. + * + * WHY nem a JSON-seed újrafuttatása (mint MITHOME-110-nél): az felülírná az + * ügyfél admin-szerkesztéseit. Ez a migráció a tárolt értéket őrzi meg — + * a publikált dokumentumon ÉS a draft/verzió rekordokon is. + * + * DECISION: közvetlen Mongo `updateOne` a Local API helyett — így nem + * keletkezik új verzió, nem futnak hookok, és az `updatedAt` sem változik. + * + * Futás: productionben induláskor automatikusan (`prodMigrations`, + * payload.config.ts); dev-ben `npx payload migrate`. Idempotens. + */ +import type { MigrateDownArgs, MigrateUpArgs, MongooseAdapter } from '@payloadcms/db-mongodb' +import type { GlobalConfig } from 'payload' + +import { Home } from '../globals/Home' +import { About } from '../globals/About' +import { Services } from '../globals/Services' +import { Contact } from '../globals/Contact' +import { Common } from '../globals/Common' +import { + collectLocalizedPaths, + topLevelKeys, + unwrapLocalized, + wrapLocalized, + type LocalizedPath, +} from '../lib/localize-paths' + +const LOCALIZED_GLOBALS: readonly GlobalConfig[] = [Home, About, Services, Contact, Common] + +type Transform = (doc: Record, paths: readonly LocalizedPath[]) => number +type Args = MigrateUpArgs | MigrateDownArgs + +function pick(doc: Record, keys: readonly string[]) { + return Object.fromEntries(keys.filter((key) => key in doc).map((key) => [key, doc[key]])) +} + +async function migrateGlobal(global: GlobalConfig, { payload, session }: Args, transform: Transform) { + const db = payload.db as unknown as MongooseAdapter + const paths = collectLocalizedPaths(global.fields as never) + let changed = 0 + + const main = await db.globals.collection.findOne({ globalType: global.slug }, { session }) + if (main) { + const count = transform(main, paths) + if (count > 0) { + await db.globals.collection.updateOne({ _id: main._id }, { $set: pick(main, topLevelKeys(paths)) }, { session }) + changed += count + } + } + + const versions = db.versions[global.slug] + if (versions) { + const versionPaths = paths.map((path) => ['version', ...path]) + for await (const doc of versions.collection.find({}, { session })) { + const count = transform(doc, versionPaths) + if (count > 0) { + await versions.collection.updateOne({ _id: doc._id }, { $set: { version: doc.version } }, { session }) + changed += count + } + } + } + + payload.logger.info(`MITHOME-111 locale migration: ${global.slug} — ${changed} value(s) rewritten`) +} + +async function migrateAll(args: Args, transform: Transform) { + for (const global of LOCALIZED_GLOBALS) { + await migrateGlobal(global, args, transform) + } +} + +export async function up(args: MigrateUpArgs): Promise { + await migrateAll(args, (doc, paths) => wrapLocalized(doc, paths)) +} + +/** TRADEOFF: drops every non-hu value — restore from a DB dump instead if possible. */ +export async function down(args: MigrateDownArgs): Promise { + await migrateAll(args, (doc, paths) => unwrapLocalized(doc, paths)) +} diff --git a/proto/src/migrations/index.ts b/proto/src/migrations/index.ts new file mode 100644 index 0000000..c24d604 --- /dev/null +++ b/proto/src/migrations/index.ts @@ -0,0 +1,13 @@ +import * as migration_20260929_localize_globals from './20260929_localize_globals' + +/** + * Payload migrations, in order. Passed to `mongooseAdapter({ prodMigrations })` + * so they run automatically on production startup (MITHOME-111). + */ +export const migrations = [ + { + up: migration_20260929_localize_globals.up, + down: migration_20260929_localize_globals.down, + name: '20260929_localize_globals', + }, +] diff --git a/proto/src/payload-config.test.ts b/proto/src/payload-config.test.ts index 824c682..0f30867 100644 --- a/proto/src/payload-config.test.ts +++ b/proto/src/payload-config.test.ts @@ -142,4 +142,55 @@ describe('Payload globals', () => { expect(field.localized).toBe(true) } }) + + describe('MITHOME-111 localization rule', () => { + // DECISION (design D1): structural values shared across locales. + const SHARED_TEXT_FIELDS = new Set(['icon', 'id', 'address']) + + type Node = FieldLike & { localized?: boolean; fields?: Node[] } + type Finding = { path: string; localized: boolean } + + const isStringArray = (f: Node) => + f.type === 'array' && f.fields?.length === 1 && f.fields[0].name === 'value' + + function walk(fields: Node[], prefix: string, out: Finding[]): Finding[] { + for (const f of fields) { + const path = `${prefix}${f.name}` + if (isStringArray(f)) { + out.push({ path: `${path}[]`, localized: f.localized === true }) + } else if (f.type === 'group' || f.type === 'array') { + // Object arrays/groups themselves stay shared; only their leaves localize. + out.push({ path: `${path}(container)`, localized: f.localized === true }) + walk(f.fields ?? [], `${path}.`, out) + } else { + out.push({ path, localized: f.localized === true }) + } + } + return out + } + + function expected(finding: Finding): boolean { + if (finding.path.endsWith('(container)')) return false + if (finding.path.endsWith('[]')) return true + const leaf = finding.path.split('.').pop()! + if (leaf === 'external') return false + return !SHARED_TEXT_FIELDS.has(leaf) + } + + it.each([Home, About, Services, Contact, Common].map((g) => [g.slug, g] as const))( + 'should localize exactly the translatable fields of the %s global', + (_slug, global) => { + const findings = walk(global.fields as Node[], '', []) + const wrong = findings.filter((f) => f.localized !== expected(f)).map((f) => f.path) + expect(wrong).toEqual([]) + }, + ) + + it('should localize the locale-dependent CTA hrefs but share the external flag', () => { + const findings = walk(Home.fields as Node[], '', []) + const byPath = Object.fromEntries(findings.map((f) => [f.path, f.localized])) + expect(byPath['hero.cta.primary.href']).toBe(true) + expect(byPath['hero.cta.primary.external']).toBe(false) + }) + }) }) diff --git a/proto/src/payload.config.ts b/proto/src/payload.config.ts index 459b143..a6a088c 100644 --- a/proto/src/payload.config.ts +++ b/proto/src/payload.config.ts @@ -21,6 +21,8 @@ * nyers, Payload-on kívüli Mongo collection-be (`contact_submissions`, * proto/src/lib/mongodb.ts) írt, amit az ügyfél nem látott sehol az admin * felületen. Mostantól Payload collection, a route.ts a Local API-n ír bele. + * MITHOME-111: a Globals fordítható mezői lokalizáltak; a meglévő adatot a + * src/migrations/20260929_localize_globals.ts alakítja át (prodMigrations). */ import path from 'path' import { fileURLToPath } from 'url' @@ -39,6 +41,7 @@ import { About } from './globals/About' import { Services } from './globals/Services' import { Contact } from './globals/Contact' import { Common } from './globals/Common' +import { migrations } from './migrations' const filename = fileURLToPath(import.meta.url) const dirname = path.dirname(filename) @@ -81,6 +84,10 @@ export default buildConfig({ db: mongooseAdapter({ url: process.env.MONGODB_URI || '', + // MITHOME-111: pending migrations run automatically on production + // startup (NODE_ENV=production — staging + prod containers), so a deploy + // never serves the localized schema on un-migrated data. + prodMigrations: migrations, }), // WHY: Payload sends anonymous usage telemetry to its own servers by