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>
This commit is contained in:
Do Siki
2026-09-29 00:52:26 +02:00
co-authored by Claude Opus 5.5
parent 9b5ca94030
commit 829f543962
21 changed files with 839 additions and 111 deletions
@@ -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',
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 },
],
},
],
+14 -12
View File
@@ -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 },
],
},
],
+35 -35
View File
@@ -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 },
],
},
],
+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
* (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 }],
},
],
}
+19 -19
View File
@@ -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 },
],
},
],
@@ -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'
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',
+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)
}
})
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`,
* 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