Compare commits

...
2 Commits
Author SHA1 Message Date
Do SikiandClaude Opus 5.5 38d34fab4c sync: update Plane issues + TODO [MITHOME-111 globals localization]
CI Pipeline with Test Management / 🧪 Run Tests & Generate Reports (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 🧪 Run Tests & Generate Reports (push) Canceled after 0s
CI Pipeline with Test Management / 🐳 Docker Integration Tests (push) Canceled after 0s
CI Pipeline with Test Management / 🏗️ Build Docker Image (push) Canceled after 0s
CI Pipeline with Test Management / 📊 Generate Test Summary (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 📊 Analyze Test Coverage (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 🔄 Sync with Linear (push) Canceled after 0s
Test Reporting & Gherkin Analysis / ⚡ Performance Monitoring (push) Canceled after 0s
Mark MITHOME-111 done. Document the mandatory pre-deploy mongodump and
the restore-based rollback for releases that carry Payload data
migrations, and record the live verification results in the OpenSpec
tasks (staging DB copy: hu/draft/version content unchanged, en falls
back, second run is a no-op).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 01:11:16 +02:00
Do SikiandClaude Opus 5.5 829f543962 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 <noreply@anthropic.com>
2026-09-29 00:52:26 +02:00
23 changed files with 868 additions and 113 deletions
+9
View File
@@ -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 `proto/src/collections/*.ts` fájlt bővítsd, majd generáld újra a típusokat
(`payload generate:types`). (`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 ## Dependency szabályok
- Új NPM package bevezetéséhez **jóváhagyás szükséges** - Új NPM package bevezetéséhez **jóváhagyás szükséges**
+27 -1
View File
@@ -46,6 +46,20 @@ Bármely lépés hibája azonnal leállítja a folyamatot. Paraméterek környez
3. Healthcheck: max 60s-ig kérdezi a `http://localhost:<port>/api/health`-t (staging: 8081, prod: 8080). Sikertelenség esetén app-logok kiírása + exit 1. 3. Healthcheck: max 60s-ig kérdezi a `http://localhost:<port>/api/health`-t (staging: 8081, prod: 8080). Sikertelenség esetén app-logok kiírása + exit 1.
4. **Payload admin-seedelés** (MITHOME-97): healthcheck után meghívja a Payload beépített `POST /api/users/first-register` endpointját az `.env.<env>`-ben megadott `ADMIN_EMAIL`/`ADMIN_PASSWORD`-del. Ez az endpoint csakis akkor enged létrehozni felhasználót, ha a `users` collection teljesen üres — ezért idempotens: egy vadonatúj adatbázisnál (első deploy, vagy volume-törlés utáni újrakezdés) automatikusan létrehozza az ismert admin fiókot, minden további deployon pedig 403-at kap és ártalmatlanul kihagyja (a jelszót utólag sosem írja felül). Ha az `ADMIN_EMAIL`/`ADMIN_PASSWORD` hiányzik az env fájlból, ezt a lépést egyszerűen kihagyja (figyelmeztetéssel, nem hibával) — ilyenkor az első felhasználót manuálisan kell létrehozni `/admin` alatt. 4. **Payload admin-seedelés** (MITHOME-97): healthcheck után meghívja a Payload beépített `POST /api/users/first-register` endpointját az `.env.<env>`-ben megadott `ADMIN_EMAIL`/`ADMIN_PASSWORD`-del. Ez az endpoint csakis akkor enged létrehozni felhasználót, ha a `users` collection teljesen üres — ezért idempotens: egy vadonatúj adatbázisnál (első deploy, vagy volume-törlés utáni újrakezdés) automatikusan létrehozza az ismert admin fiókot, minden további deployon pedig 403-at kap és ártalmatlanul kihagyja (a jelszót utólag sosem írja felül). Ha az `ADMIN_EMAIL`/`ADMIN_PASSWORD` hiányzik az env fájlból, ezt a lépést egyszerűen kihagyja (figyelmeztetéssel, nem hibával) — ilyenkor az első felhasználót manuálisan kell létrehozni `/admin` alatt.
## Payload adatmigrációk és kötelező DB-mentés (MITHOME-111)
A `proto/src/migrations/` alatti Payload migrációk a `mongooseAdapter({ prodMigrations })` révén **az app konténer indulásakor automatikusan lefutnak** (`NODE_ENV=production`, tehát stagingen és productionben is). A lefutottakat a `payload-migrations` collection tartja nyilván, ezért minden migráció csak egyszer fut. A `deploy.sh`-ban ehhez nincs külön lépés. A lefutást az app-log mutatja (`Migrating: …` / `Migrated: …`).
**Ha a kiadás migrációt tartalmaz, deploy előtt kötelező a mentés** (a szerveren, a projekt mappájából; a hitelesítő adatok a konténeren belül maradnak):
```bash
ENV=staging # vagy production
mkdir -p ~/backups && chmod 700 ~/backups
docker exec mozdit-mongodb-$ENV sh -c 'mongodump --quiet --username "$MONGO_INITDB_ROOT_USERNAME" --password "$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin --db mozdit --archive' \
> ~/backups/mozdit-$ENV-$(date +%Y%m%d-%H%M%S).archive
chmod 600 ~/backups/*.archive
```
## Tartalom publikálása (Payload admin) ## Tartalom publikálása (Payload admin)
A régi Content Editor (`content-editor.js`, git push-alapú publikálás) helyét a Payload admin (`/admin`) draft/publish + verziózás funkciója vette át (MITHOME-92/93) — ez nem jár git commit-tal vagy automatikus deployjal, a tartalom közvetlenül a MongoDB-be íródik. Kódváltozás (Globals/Collections séma, frontend) továbbra is a lenti git-alapú deploy folyamaton megy át. A régi Content Editor (`content-editor.js`, git push-alapú publikálás) helyét a Payload admin (`/admin`) draft/publish + verziózás funkciója vette át (MITHOME-92/93) — ez nem jár git commit-tal vagy automatikus deployjal, a tartalom közvetlenül a MongoDB-be íródik. Kódváltozás (Globals/Collections séma, frontend) továbbra is a lenti git-alapú deploy folyamaton megy át.
@@ -62,7 +76,8 @@ cd <prod-path>
## Post-deploy ellenőrzés ## Post-deploy ellenőrzés
- [ ] Minden oldal betölt (`/`, `/rolunk`, `/szolgaltatasok`, `/kapcsolat`) - [ ] Minden oldal betölt mindkét nyelven (`/hu`, `/hu/rolunk`, `/hu/szolgaltatasok`, `/hu/kapcsolat`, illetve `/en`, `/en/about`, `/en/services`, `/en/contact`)
- [ ] Migrációs kiadásnál: az app-logban szerepel a `Migrated: <név>` sor, és a magyar tartalom változatlan
- [ ] `/api/health` zöld - [ ] `/api/health` zöld
- [ ] Smoke tesztek: `BASE_URL=<url> npm run test:smoke:staging` (proto/) - [ ] Smoke tesztek: `BASE_URL=<url> npm run test:smoke:staging` (proto/)
- [ ] Logok: `docker compose -f docker-compose.<env>.yml logs -f app` - [ ] Logok: `docker compose -f docker-compose.<env>.yml logs -f app`
@@ -74,6 +89,15 @@ git checkout HEAD~1
./deploy.sh <env> ./deploy.sh <env>
``` ```
Ha a visszavont kiadás adatmigrációt tartalmazott, a régi kód a migrált adatot nem feltétlenül tudja olvasni. Ilyenkor a deploy előtti mentést is vissza kell állítani (a `--drop` felülírja a jelenlegi adatbázist):
```bash
docker exec -i mozdit-mongodb-$ENV sh -c 'mongorestore --quiet --drop --username "$MONGO_INITDB_ROOT_USERNAME" --password "$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin --archive' \
< ~/backups/mozdit-$ENV-<időbélyeg>.archive
```
A migrációk `down` függvénye csak végső esetre való: a lokalizációs migráció `down`-ja minden nem magyar értéket eldob.
--- ---
## CI — Gitea Actions (jelenleg szünetel) ## CI — Gitea Actions (jelenleg szünetel)
@@ -82,6 +106,8 @@ A Gitea Actions workflow szünetel, mert nincs dedikált, biztonságosan elkül
## Docker lokális dev stack ## Docker lokális dev stack
> **Megjegyzés (2026-09-28):** a fejlesztői Macen már nincs Docker daemon. A konténerek a közös llmdev szerveren futnak (`docker --context llmdev …`); a konvenciókat és a portregisztert a `~/Projects/maintenance/docker-hatter-specifikacio.md` írja le. Az alábbi parancsok ennek megfelelően csak a távoli contexttel működnek.
```bash ```bash
cd proto cd proto
npm run docker:dev # indítás (docker-compose.dev.yml) npm run docker:dev # indítás (docker-compose.dev.yml)
+2 -1
View File
@@ -134,7 +134,7 @@ Cél: a weboldal magyar (alapértelmezett, prefix nélkül, pl. `/rolunk`) és a
|-------|---------|---------| |-------|---------|---------|
| MITHOME-109 | **EPIC**: Többnyelvűség bevezetése (hu alapértelmezett + en) | 📋 | | MITHOME-109 | **EPIC**: Többnyelvűség bevezetése (hu alapértelmezett + en) | 📋 |
| MITHOME-110 | Payload localization config bekapcsolása | ✅ | | MITHOME-110 | Payload localization config bekapcsolása | ✅ |
| MITHOME-111 | Globals retrofit: localized mezők (Home/About/Services/Contact/Common) | 📋 | | MITHOME-111 | Globals retrofit: localized mezők (Home/About/Services/Contact/Common) | ✅ |
| MITHOME-112 | LegalPages collection retrofit: localized mezők | 📋 | | MITHOME-112 | LegalPages collection retrofit: localized mezők | 📋 |
| MITHOME-113 | AI-draft angol tartalom + migrációs script bővítése (en locale seed) | 📋 | | MITHOME-113 | AI-draft angol tartalom + migrációs script bővítése (en locale seed) | 📋 |
| MITHOME-114 | Next.js /hu/ + /en/ szimmetrikus prefix routing (egy menetben MITHOME-91-gyel) | ✅ | | MITHOME-114 | Next.js /hu/ + /en/ szimmetrikus prefix routing (egy menetben MITHOME-91-gyel) | ✅ |
@@ -208,6 +208,7 @@ docker-compose -f docker-compose.dev.yml down
--- ---
## Frissítési Napló ## Frissítési Napló
- **2026-09-29**: MITHOME-111 (Globals lokalizációs retrofit) kész, OpenSpec change: `openspec/changes/localize-globals-mithome-111`. Az 5 Global minden fordítható szövegmezője lokalizált; közös maradt az `icon`, a sor-`id`, az `external` és a `footer.address`. A `hero.cta.*.href` lokalizált. A string-listák tömb szinten, az objektum-tömbök csak a belső szövegeikben lokalizáltak. A ticket „migrálás nélkül” állítása téves volt: a lokalizált tömbök a régi tárolási alakban üresnek olvasódnak. Megoldás: idempotens Payload-migráció (`src/migrations/20260929_localize_globals.ts`), amely a publikált dokumentumon, a draftokon és a verziótörténeten is `{ hu }` alakba csomagol, és induláskor automatikusan fut (`prodMigrations`). A JSON-seed újrafuttatását elvetettük, mert felülírná az admin-szerkesztéseket. Élesben ellenőrizve a staging-DB másolatán, eldobható konténerben az llmdev-en: 405 érték átírva, a hu/draft/verziók bájtra azonosak a migráció előtti állapottal, az en fallbacket ad, a második futás nem módosít, mind a 8 oldal 200. A deploy-workflow kiegészült a kötelező `mongodump`-pal és a rollback menetével. Mellékeredmény: a főoldal fő CTA `href` értéke `/kapcsolat`, prefix nélkül, és 404-et ad (Plane-kommentben jelezve, új ticketet igényel). A `payload` CLI Node 26 alatt `ERR_REQUIRE_ASYNC_MODULE`-lal elhasal (a típusgenerálást kerülőúton futtattuk).
- **2026-09-28**: MITHOME-17 alkalmazásoldali része kész és stagingen ellenőrizve: Winston JSON stdout/stderr, komponens-metaadat, biztonságos hibamezők; MITHOME-33 lezárva, mert a staging/production app közvetlen Loki-host konfigurációja kivezetve. Az ISPConfig partneroldalak központi gyűjtése külön Hosting-infrastruktúra munka, MITHOME-17 részeként nem telepítettük. - **2026-09-28**: MITHOME-17 alkalmazásoldali része kész és stagingen ellenőrizve: Winston JSON stdout/stderr, komponens-metaadat, biztonságos hibamezők; MITHOME-33 lezárva, mert a staging/production app közvetlen Loki-host konfigurációja kivezetve. Az ISPConfig partneroldalak központi gyűjtése külön Hosting-infrastruktúra munka, MITHOME-17 részeként nem telepítettük.
- **2026-09-27**: OpenSpec 1.13.2 bekötve OpenCode-hoz (`openspec/config.yaml`, `.opencode/` workflow-k, `openspec/` struktúra). Nagyobb változtatások specifikációs folyamata OpenSpecen fut; Plane MITHOME marad a task/státusz authoritative source, a `TODO.md` annak tükre. - **2026-09-27**: OpenSpec 1.13.2 bekötve OpenCode-hoz (`openspec/config.yaml`, `.opencode/` workflow-k, `openspec/` struktúra). Nagyobb változtatások specifikációs folyamata OpenSpecen fut; Plane MITHOME marad a task/státusz authoritative source, a `TODO.md` annak tükre.
- **2026-09-13**: MITHOME-95 (dokumentáció frissítése) kész — `.agent/steering/architecture.md` és `CLAUDE.md` már a Payload Global/Collection + `/admin` + `payload-content.ts` Local API adaptert írja le a régi JSON rendszer helyett (rendszer-áttekintés, Content sor/szabály, kódpélda, projekt-struktúra fa). Emellett javítva több, ugyanebbe a dokumentációs adósságba tartozó, de a ticketben nem nevesített hely is: `.agent/AGENTS.md` projekt-fája, `new-feature.md`/`review.md` workflow-ok, `development-rules.md` TRADEOFF példakódja, és a `README.md` teljes "Tartalomkezelés" szekciója + egy halott link a MITHOME-93-ban törölt CMS-útmutatóra. Tisztán dokumentáció-változtatás. - **2026-09-13**: MITHOME-95 (dokumentáció frissítése) kész — `.agent/steering/architecture.md` és `CLAUDE.md` már a Payload Global/Collection + `/admin` + `payload-content.ts` Local API adaptert írja le a régi JSON rendszer helyett (rendszer-áttekintés, Content sor/szabály, kódpélda, projekt-struktúra fa). Emellett javítva több, ugyanebbe a dokumentációs adósságba tartozó, de a ticketben nem nevesített hely is: `.agent/AGENTS.md` projekt-fája, `new-feature.md`/`review.md` workflow-ok, `development-rules.md` TRADEOFF példakódja, és a `README.md` teljes "Tartalomkezelés" szekciója + egy halott link a MITHOME-93-ban törölt CMS-útmutatóra. Tisztán dokumentáció-változtatás.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-09-28
@@ -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: '<slug>'`). Mivel a `versions.drafts` be van kapcsolva (MITHOME-92), a draftok és a verziótörténet a globalonkénti `_<slug>_versions` collectionben élnek, `version.<mező>` 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 `_<slug>_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 `_<slug>_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.
@@ -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 `_<global>_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.
@@ -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
@@ -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 `_<slug>_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
- [x] 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 migráció kétszer: `NODE_ENV=production` induláskor, a `prodMigrations` útján. 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. **Eredmény (2026-09-29):** a staging-másolaton a migráció 405 értéket írt át. A `hu` publikált tartalom, a draft és a teljes verziótörténet azonos a migráció előtti snapshottal (régi kód, HEAD~1 worktree). Az `en` mindenhol a magyar fallbacket adja. A második indításnál a migráció nem fut újra, a közvetlen `up()` 0 módosítást jelez. Az `en` mentés után a `hu` változatlan, az ikon közös. Mind a 8 oldal 200. A konténer nem kapott hostportot, SSH-tunnellel értük el a belső IP-jét. Mellékeredmény: migráció nélkül csak a lokalizált tömbök tűnnének el. A `/kapcsolat` (prefix nélkül) valóban 404.
- [x] 3.2 A deploy-dokumentáció (`.agent/workflows/deploy.md`) 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
- [x] 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.
+8 -6
View File
@@ -21,12 +21,14 @@
* script eredménye mindig publikált tartalom legyen, sosem draft. * script eredménye mindig publikált tartalom legyen, sosem draft.
* *
* MITHOME-110 tapasztalat: ha egy mezőt utólag `localized: true`-ra * 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, * állítasz, a korábban beírt érték a régi, nem-lokalizált tárolási alakban
* nem-lokalizált tárolási alakban marad, és `locale: defaultLocale`-lal * marad, és `locale: defaultLocale`-lal nem olvasható vissza (üresnek
* nem olvasható vissza (üresnek látszik) — ilyenkor ezt a scriptet újra * látszik). MITHOME-111 óta ezt NEM ennek a scriptnek az újrafuttatásával
* kell futtatni, hogy a defaultLocale (hu) alá újra beírja az értéket a * kezeljük (az felülírná az admin-szerkesztéseket), hanem Payload
* lokalizált alakban. Explicit `locale` paramétert egyik updateGlobal/ * migrációval (src/migrations/, prodMigrations) — egy újabb retrofitnál
* update hívás sem ad meg itt, ezért mindig a `defaultLocale` (hu) alá ír. * (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 path from 'path'
import { fileURLToPath } from 'url' import { fileURLToPath } from 'url'
@@ -0,0 +1,80 @@
import { down, up } from '../migrations/20260929_localize_globals'
type Doc = Record<string, unknown>
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' })
})
})
+17 -17
View File
@@ -15,39 +15,39 @@ export const About: GlobalConfig = {
name: 'meta', name: 'meta',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'description', type: 'textarea', required: true }, { name: 'description', type: 'textarea', required: true, localized: true },
{ name: 'ogDescription', type: 'textarea', required: true }, { name: 'ogDescription', type: 'textarea', required: true, localized: true },
], ],
}, },
{ {
name: 'hero', name: 'hero',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'text', required: true }, { name: 'subtitle', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'story', name: 'story',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
stringArrayField('paragraphs', 'Paragraphs'), stringArrayField('paragraphs', 'Paragraphs', { localized: true }),
], ],
}, },
{ {
name: 'mission', name: 'mission',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'text', required: true }, { name: 'subtitle', type: 'text', required: true, localized: true },
{ {
name: 'values', name: 'values',
type: 'array', type: 'array',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'description', type: 'textarea', required: true }, { name: 'description', type: 'textarea', required: true, localized: true },
{ name: 'icon', type: 'text', required: true }, { name: 'icon', type: 'text', required: true },
], ],
}, },
@@ -57,18 +57,18 @@ export const About: GlobalConfig = {
name: 'team', name: 'team',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'text', required: true }, { name: 'subtitle', type: 'text', required: true, localized: true },
stringArrayField('paragraphs', 'Paragraphs'), stringArrayField('paragraphs', 'Paragraphs', { localized: true }),
], ],
}, },
{ {
name: 'cta', name: 'cta',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'textarea', required: true }, { name: 'subtitle', type: 'textarea', required: true, localized: true },
{ name: 'button', type: 'text', required: true }, { name: 'button', type: 'text', required: true, localized: true },
], ],
}, },
], ],
+14 -12
View File
@@ -5,11 +5,11 @@ import { globalVersions } from '../lib/payload-versions'
/** /**
* Mirrors CommonContent (proto/src/content/types.ts) — MITHOME-87. * Mirrors CommonContent (proto/src/content/types.ts) — MITHOME-87.
* *
* `buttons.*` localized: true (MITHOME-110) — ez a lokalizáció-mechanizmus * `buttons.*` localized: true (MITHOME-110) volt a lokalizáció-mechanizmus
* bizonyítéka (admin nyelvváltó + Local/REST API locale param), és egyben * első bizonyítéka; a MITHOME-111 minden fordítható szöveget lokalizált.
* 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, * DECISION: `footer.address` szándékosan NEM lokalizált — postai cím,
* azt a MITHOME-111 teljes körűen elvégzi. * nyelvfüggetlen adat, nem szövegmásolat (MITHOME-111 design D1).
*/ */
export const Common: GlobalConfig = { export const Common: GlobalConfig = {
slug: 'common', slug: 'common',
@@ -32,20 +32,21 @@ export const Common: GlobalConfig = {
name: 'labels', name: 'labels',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'required', type: 'text', required: true }, { name: 'required', type: 'text', required: true, localized: true },
{ name: 'features', type: 'text', required: true }, { name: 'features', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'validation', name: 'validation',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'required', type: 'text', required: true }, { name: 'required', type: 'text', required: true, localized: true },
{ name: 'invalidEmail', type: 'text', required: true }, { name: 'invalidEmail', type: 'text', required: true, localized: true },
{ {
name: 'minLength', name: 'minLength',
type: 'text', type: 'text',
required: true, required: true,
localized: true,
admin: { admin: {
description: 'A {min} placeholder futásidőben cserélődik ki.', description: 'A {min} placeholder futásidőben cserélődik ki.',
}, },
@@ -55,7 +56,7 @@ export const Common: GlobalConfig = {
{ {
name: 'staging', name: 'staging',
type: 'group', type: 'group',
fields: [{ name: 'banner', type: 'text', required: true }], fields: [{ name: 'banner', type: 'text', required: true, localized: true }],
}, },
{ {
name: 'footer', name: 'footer',
@@ -65,6 +66,7 @@ export const Common: GlobalConfig = {
name: 'copyright', name: 'copyright',
type: 'text', type: 'text',
required: true, required: true,
localized: true,
admin: { admin: {
description: 'A {year} placeholder futásidőben cserélődik ki.', description: 'A {year} placeholder futásidőben cserélődik ki.',
}, },
@@ -76,8 +78,8 @@ export const Common: GlobalConfig = {
name: 'a11y', name: 'a11y',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'openMenu', type: 'text', required: true }, { name: 'openMenu', type: 'text', required: true, localized: true },
{ name: 'closeMenu', type: 'text', required: true }, { name: 'closeMenu', type: 'text', required: true, localized: true },
], ],
}, },
], ],
+35 -35
View File
@@ -22,25 +22,25 @@ export const Contact: GlobalConfig = {
name: 'meta', name: 'meta',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'description', type: 'textarea', required: true }, { name: 'description', type: 'textarea', required: true, localized: true },
], ],
}, },
{ {
name: 'hero', name: 'hero',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'text', required: true }, { name: 'subtitle', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'form', name: 'form',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'successMessage', type: 'text', required: true }, { name: 'successMessage', type: 'text', required: true, localized: true },
{ name: 'errorMessage', type: 'text', required: true }, { name: 'errorMessage', type: 'text', required: true, localized: true },
{ {
name: 'fields', name: 'fields',
type: 'group', type: 'group',
@@ -49,79 +49,79 @@ export const Contact: GlobalConfig = {
name: 'name', name: 'name',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'label', type: 'text', required: true }, { name: 'label', type: 'text', required: true, localized: true },
{ name: 'placeholder', type: 'text', required: true }, { name: 'placeholder', type: 'text', required: true, localized: true },
{ name: 'error', type: 'text', required: true }, { name: 'error', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'email', name: 'email',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'label', type: 'text', required: true }, { name: 'label', type: 'text', required: true, localized: true },
{ name: 'placeholder', type: 'text', required: true }, { name: 'placeholder', type: 'text', required: true, localized: true },
{ name: 'errorRequired', type: 'text', required: true }, { name: 'errorRequired', type: 'text', required: true, localized: true },
{ name: 'errorInvalid', type: 'text', required: true }, { name: 'errorInvalid', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'subject', name: 'subject',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'label', type: 'text', required: true }, { name: 'label', type: 'text', required: true, localized: true },
{ name: 'placeholder', type: 'text', required: true }, { name: 'placeholder', type: 'text', required: true, localized: true },
{ name: 'error', type: 'text', required: true }, { name: 'error', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'message', name: 'message',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'label', type: 'text', required: true }, { name: 'label', type: 'text', required: true, localized: true },
{ name: 'placeholder', type: 'text', required: true }, { name: 'placeholder', type: 'text', required: true, localized: true },
{ name: 'errorRequired', type: 'text', required: true }, { name: 'errorRequired', type: 'text', required: true, localized: true },
{ name: 'errorMinLength', type: 'text', required: true }, { name: 'errorMinLength', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'gdpr', name: 'gdpr',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'label', type: 'textarea', required: true }, { name: 'label', type: 'textarea', required: true, localized: true },
{ name: 'error', type: 'text', required: true }, { name: 'error', type: 'text', required: true, localized: true },
], ],
}, },
], ],
}, },
{ name: 'submitButton', type: 'text', required: true }, { name: 'submitButton', type: 'text', required: true, localized: true },
{ name: 'submittingButton', type: 'text', required: true }, { name: 'submittingButton', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'info', name: 'info',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ {
name: 'email', name: 'email',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'responseTime', type: 'text', required: true }, { name: 'responseTime', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'company', name: 'company',
type: 'group', type: 'group',
fields: [{ name: 'title', type: 'text', required: true }], fields: [{ name: 'title', type: 'text', required: true, localized: true }],
}, },
{ {
name: 'webmail', name: 'webmail',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'linkText', type: 'text', required: true }, { name: 'linkText', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'text', required: true }, { name: 'subtitle', type: 'text', required: true, localized: true },
], ],
}, },
], ],
@@ -130,13 +130,13 @@ export const Contact: GlobalConfig = {
name: 'faq', name: 'faq',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ {
name: 'items', name: 'items',
type: 'array', type: 'array',
fields: [ fields: [
{ name: 'question', type: 'text', required: true }, { name: 'question', type: 'text', required: true, localized: true },
{ name: 'answer', type: 'textarea', required: true }, { name: 'answer', type: 'textarea', required: true, localized: true },
], ],
}, },
], ],
+27 -21
View File
@@ -10,6 +10,12 @@ import { globalVersions } from '../lib/payload-versions'
* beágyazott lista, de a Payload oldalon önálló `Partners` collection lesz * beágyazott lista, de a Payload oldalon önálló `Partners` collection lesz
* (logó = Media upload reference) — lásd MITHOME-89. Itt szándékosan * (logó = Media upload reference) — lásd MITHOME-89. Itt szándékosan
* kihagyjuk, nehogy két, egymásnak ellentmondó forrás legyen. * 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 = { export const Home: GlobalConfig = {
slug: 'home', slug: 'home',
@@ -22,10 +28,10 @@ export const Home: GlobalConfig = {
name: 'hero', name: 'hero',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'text', required: true }, { name: 'subtitle', type: 'text', required: true, localized: true },
{ name: 'description', type: 'textarea', required: true }, { name: 'description', type: 'textarea', required: true, localized: true },
stringArrayField('trustBullets', 'Trust bullets'), stringArrayField('trustBullets', 'Trust bullets', { localized: true }),
{ {
name: 'cta', name: 'cta',
type: 'group', type: 'group',
@@ -34,8 +40,8 @@ export const Home: GlobalConfig = {
name: 'primary', name: 'primary',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'text', type: 'text', required: true }, { name: 'text', type: 'text', required: true, localized: true },
{ name: 'href', type: 'text', required: true }, { name: 'href', type: 'text', required: true, localized: true },
{ name: 'external', type: 'checkbox', defaultValue: false }, { name: 'external', type: 'checkbox', defaultValue: false },
], ],
}, },
@@ -43,8 +49,8 @@ export const Home: GlobalConfig = {
name: 'secondary', name: 'secondary',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'text', type: 'text', required: true }, { name: 'text', type: 'text', required: true, localized: true },
{ name: 'href', type: 'text', required: true }, { name: 'href', type: 'text', required: true, localized: true },
{ name: 'external', type: 'checkbox', defaultValue: false }, { name: 'external', type: 'checkbox', defaultValue: false },
], ],
}, },
@@ -56,14 +62,14 @@ export const Home: GlobalConfig = {
name: 'about', name: 'about',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ {
name: 'usps', name: 'usps',
type: 'array', type: 'array',
fields: [ fields: [
{ name: 'id', type: 'text', required: true }, { name: 'id', type: 'text', required: true },
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'description', type: 'textarea', required: true }, { name: 'description', type: 'textarea', required: true, localized: true },
{ name: 'icon', type: 'text', required: true }, { name: 'icon', type: 'text', required: true },
], ],
}, },
@@ -73,18 +79,18 @@ export const Home: GlobalConfig = {
name: 'services', name: 'services',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'text', required: true }, { name: 'subtitle', type: 'text', required: true, localized: true },
{ {
name: 'items', name: 'items',
type: 'array', type: 'array',
fields: [ fields: [
{ name: 'id', type: 'text', required: true }, { name: 'id', type: 'text', required: true },
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'description', type: 'textarea', required: true }, { name: 'description', type: 'textarea', required: true, localized: true },
{ name: 'icon', type: 'text', required: true }, { name: 'icon', type: 'text', required: true },
stringArrayField('features', 'Features'), stringArrayField('features', 'Features', { localized: true }),
{ name: 'ctaText', type: 'text', required: true }, { name: 'ctaText', type: 'text', required: true, localized: true },
], ],
}, },
], ],
@@ -93,15 +99,15 @@ export const Home: GlobalConfig = {
name: 'cta', name: 'cta',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'textarea', required: true }, { name: 'subtitle', type: 'textarea', required: true, localized: true },
{ name: 'button', type: 'text', required: true }, { name: 'button', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'serviceFeatures', name: 'serviceFeatures',
type: 'group', type: 'group',
fields: [{ name: 'title', type: 'text', required: true }], fields: [{ name: 'title', type: 'text', required: true, localized: true }],
}, },
], ],
} }
+19 -19
View File
@@ -15,38 +15,38 @@ export const Services: GlobalConfig = {
name: 'meta', name: 'meta',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'description', type: 'textarea', required: true }, { name: 'description', type: 'textarea', required: true, localized: true },
{ name: 'ogDescription', type: 'textarea', required: true }, { name: 'ogDescription', type: 'textarea', required: true, localized: true },
], ],
}, },
{ {
name: 'hero', name: 'hero',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'text', required: true }, { name: 'subtitle', type: 'text', required: true, localized: true },
], ],
}, },
{ {
name: 'details', name: 'details',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'text', required: true }, { name: 'subtitle', type: 'text', required: true, localized: true },
{ {
name: 'services', name: 'services',
type: 'array', type: 'array',
fields: [ fields: [
{ name: 'icon', type: 'text', required: true }, { name: 'icon', type: 'text', required: true },
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'description', type: 'textarea', required: true }, { name: 'description', type: 'textarea', required: true, localized: true },
{ {
name: 'specs', name: 'specs',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
stringArrayField('items', 'Items'), stringArrayField('items', 'Items', { localized: true }),
], ],
}, },
], ],
@@ -57,15 +57,15 @@ export const Services: GlobalConfig = {
name: 'support', name: 'support',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'text', required: true }, { name: 'subtitle', type: 'text', required: true, localized: true },
{ {
name: 'channels', name: 'channels',
type: 'array', type: 'array',
fields: [ fields: [
{ name: 'icon', type: 'text', required: true }, { name: 'icon', type: 'text', required: true },
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'description', type: 'text', required: true }, { name: 'description', type: 'text', required: true, localized: true },
], ],
}, },
], ],
@@ -74,10 +74,10 @@ export const Services: GlobalConfig = {
name: 'cta', name: 'cta',
type: 'group', type: 'group',
fields: [ fields: [
{ name: 'title', type: 'text', required: true }, { name: 'title', type: 'text', required: true, localized: true },
{ name: 'subtitle', type: 'textarea', required: true }, { name: 'subtitle', type: 'textarea', required: true, localized: true },
{ name: 'primaryButton', type: 'text', required: true }, { name: 'primaryButton', type: 'text', required: true, localized: true },
{ name: 'secondaryButton', type: 'text', required: true }, { name: 'secondaryButton', type: 'text', required: true, localized: true },
], ],
}, },
], ],
@@ -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)
})
})
+15 -1
View File
@@ -1,5 +1,14 @@
import type { ArrayField } from 'payload' 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 * Payload has no native "array of plain strings" field — the closest
* built-in shape is an array of one-field objects. Used for every * 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 * features, spec items, …) so the JSON -> Payload migration script has a
* single, consistent shape to transform into. * 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 { return {
name, name,
type: 'array', type: 'array',
label, label,
...(localized ? { localized: true } : {}),
fields: [ fields: [
{ {
name: 'value', name: 'value',
+131
View File
@@ -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<string, unknown>
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'])
})
})
+111
View File
@@ -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<string, unknown> {
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<number>((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<string, unknown>, 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<string, unknown>,
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<string, unknown>,
paths: readonly LocalizedPath[],
locale = 'hu',
) {
return applyAll(doc, paths, (value) =>
isPlainObject(value) ? { value: value[locale] ?? null, changed: true } : { value, changed: false },
)
}
@@ -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<string, unknown>, paths: readonly LocalizedPath[]) => number
type Args = MigrateUpArgs | MigrateDownArgs
function pick(doc: Record<string, unknown>, 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<void> {
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<void> {
await migrateAll(args, (doc, paths) => unwrapLocalized(doc, paths))
}
+13
View File
@@ -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',
},
]
+51
View File
@@ -142,4 +142,55 @@ describe('Payload globals', () => {
expect(field.localized).toBe(true) 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)
})
})
}) })
+7
View File
@@ -21,6 +21,8 @@
* nyers, Payload-on kívüli Mongo collection-be (`contact_submissions`, * 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 * 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. * 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 path from 'path'
import { fileURLToPath } from 'url' import { fileURLToPath } from 'url'
@@ -39,6 +41,7 @@ import { About } from './globals/About'
import { Services } from './globals/Services' import { Services } from './globals/Services'
import { Contact } from './globals/Contact' import { Contact } from './globals/Contact'
import { Common } from './globals/Common' import { Common } from './globals/Common'
import { migrations } from './migrations'
const filename = fileURLToPath(import.meta.url) const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename) const dirname = path.dirname(filename)
@@ -81,6 +84,10 @@ export default buildConfig({
db: mongooseAdapter({ db: mongooseAdapter({
url: process.env.MONGODB_URI || '', 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 // WHY: Payload sends anonymous usage telemetry to its own servers by