Compare commits

..
2 Commits
Author SHA1 Message Date
Do SikiandClaude Opus 5.5 678fa3ba7e sync: update Plane issues + TODO [MITHOME-123 CTA page links]
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 01:27:01 +02:00
Do SikiandClaude Opus 5.5 e8ff7adeb5 fix(cms): resolve internal CTA links per locale via a page selector (MITHOME-123)
The home hero CTA stored a free-text href "/kapcsolat" that predated the
locale-prefixed routing (MITHOME-114), so the main call-to-action led to
a 404. Internal targets were typed by hand and could never follow the
locale or its translated slug.

CTA links now choose between an internal page (home/about/services/
contact/privacy/terms) and an external URL. Page links are resolved per
request with localePath(), giving /hu/kapcsolat and /en/contact; external
links (webmail) keep their localized href. A Payload migration converts
existing internal paths to page links on the published global and every
draft/version, idempotently and independent of the locale migration's
order. The global-doc iteration shared with MITHOME-111 moved to
src/lib/migrate-global-docs.ts; the JSON seed emits the new shape too.

Verified on a copy of the staging DB: both migrations ran on startup,
/hu and /en CTAs point to their contact pages (200), webmail unchanged,
admin shows the selector, toggles the fields and blocks publishing a URL
link without a URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 01:26:42 +02:00
13 changed files with 462 additions and 65 deletions
+2
View File
@@ -135,6 +135,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-110 | Payload localization config bekapcsolása | ✅ |
| MITHOME-111 | Globals retrofit: localized mezők (Home/About/Services/Contact/Common) | ✅ |
| MITHOME-123 | Bug: főoldali CTA link 404 — belső linkek oldalválasztóval, locale-helyes útvonallal | ✅ |
| 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-114 | Next.js /hu/ + /en/ szimmetrikus prefix routing (egy menetben MITHOME-91-gyel) | ✅ |
@@ -208,6 +209,7 @@ docker-compose -f docker-compose.dev.yml down
---
## Frissítési Napló
- **2026-09-29**: MITHOME-123 (bug: főoldali CTA 404) kész. A fő CTA `href` értéke a szabad szöveges `/kapcsolat` volt, ez a MITHOME-114 locale-prefixes routingja óta 404-et adott. Tartós javítás: a CTA link típusa választható (Belső oldal: oldalválasztó / Külső URL). A belső oldalt a frontend `localePath()`-szal oldja fel (`/hu/kapcsolat`, `/en/contact`), így nem gépelhető el és nyelvhelyes. Payload-migráció (`20260929_cta_page_links`) alakítja át a meglévő adatot a publikált dokumentumon, a draftokon és a verziókon; a MITHOME-111-gyel közös bejáró helper a `src/lib/migrate-global-docs.ts`-be került. Élesben ellenőrizve a staging-DB másolatán: publikus oldalak, admin oldalválasztó, feltételes mezők és publikálási validáció. Külön OpenSpec change nem készült, mert bugfix (fix-bug workflow, exploration + preservation tesztekkel).
- **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-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.
@@ -34,6 +34,7 @@ import path from 'path'
import { fileURLToPath } from 'url'
import { getPayload, type Payload } from 'payload'
import config from '../src/payload.config'
import { internalPathToPageKey } from '../src/lib/cta-link'
import homeJson from '../src/content/pages/home.json'
import aboutJson from '../src/content/pages/about.json'
@@ -51,12 +52,23 @@ function toStringArray(items: readonly string[]): { value: string }[] {
return items.map((value) => ({ value }))
}
type CtaJson = { text: string; href: string; external?: boolean }
/** MITHOME-123: internal JSON paths become page links, the rest stay URLs. */
function toCtaLink({ text, href, external }: CtaJson) {
const page = internalPathToPageKey(href)
return page
? { text, linkType: 'page' as const, page, external }
: { text, linkType: 'url' as const, href, external }
}
function buildHomeData(json: typeof homeJson) {
const { hero, about, services, cta, serviceFeatures } = json
return {
hero: {
...hero,
trustBullets: toStringArray(hero.trustBullets),
cta: { primary: toCtaLink(hero.cta.primary), secondary: toCtaLink(hero.cta.secondary) },
},
about,
services: {
@@ -0,0 +1,95 @@
import { down, toPageLink, up } from '../migrations/20260929_cta_page_links'
import { up as localizeUp } 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) => ({})),
}
}
const heroWith = (primaryHref: unknown, secondaryHref: unknown) => ({
title: 'Cím',
cta: {
primary: { text: { hu: 'Kapcsolat' }, href: primaryHref, external: false },
secondary: { text: { hu: 'Webmail' }, href: secondaryHref, external: true },
},
})
function setup(primaryHref: unknown = { hu: '/kapcsolat' }, secondaryHref: unknown = { hu: 'https://mail.mozdit.hu' }) {
const home: Doc = { _id: 'g-home', globalType: 'home', hero: heroWith(primaryHref, secondaryHref) }
const version: Doc = { _id: 'v1', version: { hero: heroWith({ hu: '/hu/kapcsolat' }, 'https://mail.mozdit.hu') } }
const globals = fakeCollection([home])
const versions = fakeCollection([version])
const payload = {
db: { globals: { collection: globals }, versions: { home: { collection: versions } } },
logger: { info: jest.fn() },
}
return { args: { payload, session: undefined, req: {} } as never, home, version, payload }
}
const cta = (doc: Doc) => (doc.hero as { cta: Record<string, Doc> }).cta
describe('20260929_cta_page_links migration (MITHOME-123)', () => {
it('should turn the legacy internal path into a page link and drop the href', async () => {
const { args, home } = setup()
await up(args)
expect(cta(home).primary).toEqual({ text: { hu: 'Kapcsolat' }, linkType: 'page', page: 'contact', external: false })
})
it('should keep external URLs as URL links', async () => {
const { args, home } = setup()
await up(args)
expect(cta(home).secondary).toMatchObject({ linkType: 'url', href: { hu: 'https://mail.mozdit.hu' } })
})
it('should migrate version records, including legacy string hrefs', async () => {
const { args, version } = setup()
await up(args)
const versionCta = cta(version.version as Doc)
expect(versionCta.primary).toMatchObject({ linkType: 'page', page: 'contact' })
expect(versionCta.secondary).toMatchObject({ linkType: 'url', href: 'https://mail.mozdit.hu' })
})
it('should be idempotent', async () => {
const { args, home, payload } = setup()
await up(args)
const snapshot = JSON.stringify(home)
await up(args)
expect(JSON.stringify(home)).toBe(snapshot)
expect(payload.logger.info).toHaveBeenLastCalledWith('MITHOME-123 CTA link migration: home — 0 CTA(s) rewritten')
})
it('should give the same result regardless of order with the locale migration', async () => {
const localeFirst = setup('/kapcsolat', 'https://mail.mozdit.hu')
await localizeUp(localeFirst.args)
await up(localeFirst.args)
const ctaFirst = setup('/kapcsolat', 'https://mail.mozdit.hu')
await up(ctaFirst.args)
await localizeUp(ctaFirst.args)
expect(cta(ctaFirst.home)).toEqual(cta(localeFirst.home))
})
it('should treat a missing href as a URL link without inventing a target', () => {
const link: Doc = { text: { hu: 'x' } }
expect(toPageLink(link)).toBe(1)
expect(link).toEqual({ text: { hu: 'x' }, linkType: 'url' })
})
it('should restore a hu href on down', async () => {
const { args, home } = setup()
await up(args)
await down(args)
expect(cta(home).primary).toEqual({ text: { hu: 'Kapcsolat' }, href: { hu: '/hu/kapcsolat' }, external: false })
expect(cta(home).secondary).toEqual({ text: { hu: 'Webmail' }, href: { hu: 'https://mail.mozdit.hu' }, external: true })
})
})
+8 -21
View File
@@ -1,6 +1,7 @@
import type { GlobalConfig } from 'payload'
import { stringArrayField } from './fields/stringArray'
import { ctaLinkGroup } from './fields/ctaLink'
import { globalVersions } from '../lib/payload-versions'
/**
@@ -13,9 +14,11 @@ import { globalVersions } from '../lib/payload-versions'
*
* 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.
* lokalizált: egy külső cél nyelvenként eltérhet. Belső oldalra a CTA
* oldalválasztóval mutat (MITHOME-123, fields/ctaLink.ts) — a nyelvhelyes
* útvonalat a frontend számolja (/hu/kapcsolat vs /en/contact). A
* string-listák (trustBullets, features) tömb-szinten lokalizáltak —
* nyelvenként eltérő elemszám lehet.
*/
export const Home: GlobalConfig = {
slug: 'home',
@@ -36,24 +39,8 @@ export const Home: GlobalConfig = {
name: 'cta',
type: 'group',
fields: [
{
name: 'primary',
type: 'group',
fields: [
{ name: 'text', type: 'text', required: true, localized: true },
{ name: 'href', type: 'text', required: true, localized: true },
{ name: 'external', type: 'checkbox', defaultValue: false },
],
},
{
name: 'secondary',
type: 'group',
fields: [
{ name: 'text', type: 'text', required: true, localized: true },
{ name: 'href', type: 'text', required: true, localized: true },
{ name: 'external', type: 'checkbox', defaultValue: false },
],
},
ctaLinkGroup('primary'),
ctaLinkGroup('secondary'),
],
},
],
+63
View File
@@ -0,0 +1,63 @@
import type { GroupField } from 'payload'
import { CTA_PAGES, type CtaPage } from '../../lib/cta-link'
const PAGE_LABELS: Record<CtaPage, string> = {
home: 'Főoldal',
about: 'Rólunk',
services: 'Szolgáltatások',
contact: 'Kapcsolat',
privacy: 'Adatvédelem',
terms: 'Felhasználási feltételek',
}
type Sibling = { linkType?: string } | undefined
const isPageLink = (sibling: Sibling) => (sibling?.linkType ?? 'page') === 'page'
/**
* MITHOME-123: CTA button = localized text + either an internal page
* (resolved per locale by src/lib/cta-link.ts) or an external URL.
*
* WHY custom `validate` instead of `required`: `page` and `href` are only
* required for their own link type; the other one is hidden and empty.
* DECISION: `href` stays localized (MITHOME-111) — an external target may
* differ per language; `linkType`/`page` are shared across locales.
*/
export function ctaLinkGroup(name: string): GroupField {
return {
name,
type: 'group',
fields: [
{ name: 'text', type: 'text', required: true, localized: true },
{
name: 'linkType',
type: 'radio',
required: true,
defaultValue: 'page',
options: [
{ label: 'Belső oldal', value: 'page' },
{ label: 'Külső URL', value: 'url' },
],
admin: { layout: 'horizontal' },
},
{
name: 'page',
type: 'select',
options: CTA_PAGES.map((value) => ({ label: PAGE_LABELS[value], value })),
admin: { condition: (_data, sibling) => isPageLink(sibling) },
validate: (value: unknown, { siblingData }: { siblingData: Sibling }) =>
!isPageLink(siblingData) || Boolean(value) || 'Válassz oldalt.',
},
{
name: 'href',
type: 'text',
localized: true,
admin: { condition: (_data, sibling) => !isPageLink(sibling) },
validate: (value: unknown, { siblingData }: { siblingData: Sibling }) =>
isPageLink(siblingData) || Boolean(value) || 'Add meg az URL-t.',
},
{ name: 'external', type: 'checkbox', defaultValue: false },
],
}
}
+50
View File
@@ -0,0 +1,50 @@
import { internalPathToPageKey, resolveCtaHref } from './cta-link'
describe('resolveCtaHref (MITHOME-123)', () => {
// Exploration: a CTA pointing at an internal page must follow the locale
// routing (MITHOME-114) — the legacy free-text "/kapcsolat" was a 404.
it.each([
['hu', '/hu/kapcsolat'],
['en', '/en/contact'],
] as const)('should link a contact-page CTA to the %s contact page', (locale, expected) => {
expect(resolveCtaHref({ linkType: 'page', page: 'contact' }, locale)).toBe(expected)
})
it('should link a home-page CTA to the locale home', () => {
expect(resolveCtaHref({ linkType: 'page', page: 'home' }, 'en')).toBe('/en')
})
// Preservation: external links (e.g. webmail) keep their stored URL.
it('should keep the stored URL for external links', () => {
expect(resolveCtaHref({ linkType: 'url', href: 'https://mail.mozdit.hu' }, 'en')).toBe('https://mail.mozdit.hu')
})
it('should treat a record without linkType as a URL link (pre-migration data)', () => {
expect(resolveCtaHref({ href: 'https://mail.mozdit.hu' }, 'hu')).toBe('https://mail.mozdit.hu')
})
it('should fall back to the locale home when a page link has no page selected', () => {
expect(resolveCtaHref({ linkType: 'page', page: null }, 'hu')).toBe('/hu')
})
})
describe('internalPathToPageKey', () => {
it.each([
['/kapcsolat', 'contact'],
['/hu/kapcsolat', 'contact'],
['/en/contact', 'contact'],
['/hu/rolunk/', 'about'],
['/', 'home'],
['/hu', 'home'],
['/en', 'home'],
])('should map %s to %s', (path, key) => {
expect(internalPathToPageKey(path)).toBe(key)
})
it.each(['https://mail.mozdit.hu', '/nincs-ilyen', '/hu/kapcsolat/extra', 'mailto:info@mozdit.hu', ''])(
'should not map %s',
(path) => {
expect(internalPathToPageKey(path)).toBeUndefined()
},
)
})
+46
View File
@@ -0,0 +1,46 @@
/**
* MITHOME-123: CTA link resolution.
*
* WHY a page selector instead of a free-text href for internal links: the
* stored "/kapcsolat" predated the locale-prefixed routing (MITHOME-114)
* and silently became a 404. Internal targets are now stored as a PageKey
* and turned into a URL per request with localePath(), so they always
* follow the current locale and its translated slug.
*/
import { LOCALES, PAGE_SLUGS, isLocale, localePath, type Locale, type PageKey } from './i18n'
export type CtaPage = PageKey | 'home'
export type CtaLinkType = 'page' | 'url'
export const CTA_PAGES: readonly CtaPage[] = ['home', ...(Object.keys(PAGE_SLUGS) as PageKey[])]
export type CtaLink = {
linkType?: CtaLinkType | null
page?: CtaPage | null
href?: string | null
}
export function resolveCtaHref(link: CtaLink, locale: Locale): string {
if (link.linkType === 'page') {
return !link.page || link.page === 'home' ? localePath(locale) : localePath(locale, link.page)
}
// DECISION: missing linkType == URL link, so un-migrated data keeps working.
return link.href ?? localePath(locale)
}
/**
* Maps a legacy internal path (with or without locale prefix, any
* locale's slug) to the page it meant. Used by the data migration.
*/
export function internalPathToPageKey(path: string): CtaPage | undefined {
if (!path.startsWith('/')) return undefined
const segments = path.split('/').filter(Boolean)
if (segments.length > 0 && isLocale(segments[0])) segments.shift()
if (segments.length === 0) return 'home'
if (segments.length > 1) return undefined
const [slug] = segments
return (Object.keys(PAGE_SLUGS) as PageKey[]).find((key) =>
LOCALES.some((locale) => PAGE_SLUGS[key][locale] === slug),
)
}
+55
View File
@@ -0,0 +1,55 @@
/**
* Shared plumbing for Payload data migrations on Globals (MITHOME-111/123).
*
* Applies `transform` in place to a global's field data — the published
* document AND every draft/version record (`version` sub-document) — and
* writes back only what changed.
*
* DECISION: direct Mongo `updateOne` instead of the Local API — no new
* version is created, no hooks run, `updatedAt` stays untouched.
*/
import type { MigrateDownArgs, MigrateUpArgs, MongooseAdapter } from '@payloadcms/db-mongodb'
type Args = MigrateUpArgs | MigrateDownArgs
type Data = Record<string, unknown>
function pick(doc: Data, keys: readonly string[]) {
return Object.fromEntries(keys.filter((key) => key in doc).map((key) => [key, doc[key]]))
}
/**
* @param keys top-level field names `transform` may touch (the `$set` scope)
* @returns the number of values `transform` reported as changed
*/
export async function rewriteGlobalDocs(
{ payload, session }: Args,
slug: string,
keys: readonly string[],
transform: (data: Data) => number,
): Promise<number> {
const db = payload.db as unknown as MongooseAdapter
let changed = 0
const main = await db.globals.collection.findOne({ globalType: slug }, { session })
if (main) {
const count = transform(main)
if (count > 0) {
await db.globals.collection.updateOne({ _id: main._id }, { $set: pick(main, keys) }, { session })
changed += count
}
}
const versions = db.versions[slug]
if (versions) {
for await (const doc of versions.collection.find({}, { session })) {
if (typeof doc.version !== 'object' || doc.version === null) continue
const count = transform(doc.version)
if (count > 0) {
await versions.collection.updateOne({ _id: doc._id }, { $set: { version: doc.version } }, { session })
changed += count
}
}
}
return changed
}
+14 -1
View File
@@ -11,6 +11,7 @@
import { getPayload } from 'payload'
import config from '@payload-config'
import type { Locale } from './i18n'
import { resolveCtaHref, type CtaLink } from './cta-link'
let cached: ReturnType<typeof getPayload> | undefined
@@ -19,6 +20,11 @@ function payloadClient() {
return cached
}
/** MITHOME-123: internal CTA targets are stored as a page, resolved per locale. */
function withHref<T extends CtaLink>(link: T, locale: Locale): T & { href: string } {
return { ...link, href: resolveCtaHref(link, locale) }
}
function unwrap(items: readonly { value: string }[] | null | undefined): string[] {
return (items ?? []).map((item) => item.value)
}
@@ -33,7 +39,14 @@ export async function getHomeContent(locale: Locale) {
const home = await payload.findGlobal({ slug: 'home', locale })
return {
...home,
hero: { ...home.hero, trustBullets: unwrap(home.hero?.trustBullets) },
hero: {
...home.hero,
trustBullets: unwrap(home.hero?.trustBullets),
cta: {
primary: withHref(home.hero.cta.primary, locale),
secondary: withHref(home.hero.cta.secondary, locale),
},
},
services: {
...home.services,
items: (home.services?.items ?? []).map((item) => ({
@@ -0,0 +1,72 @@
/**
* MITHOME-123: a Home hero CTA-k szabad szöveges belső linkjeit
* (pl. "/kapcsolat" — a MITHOME-114 óta 404) oldalválasztóra alakítja:
* `{ linkType: 'page', page: 'contact' }`, a `href` törlődik. Külső URL
* (pl. webmail) esetén `linkType: 'url'`, a `href` változatlan marad.
*
* WHY mindkét `href`-alakot kezeli (`"…"` és `{ hu: "…" }`): így független
* a MITHOME-111 lokalizációs migrációtól való sorrendtől — a prodMigrations
* utána futtatja, a Payload CLI viszont fájlnév szerint (ábécé) rendez.
* Idempotens: ha a `linkType` már be van állítva, a CTA-hoz nem nyúl.
*/
import type { MigrateDownArgs, MigrateUpArgs } from '@payloadcms/db-mongodb'
import { internalPathToPageKey, resolveCtaHref, type CtaLink } from '../lib/cta-link'
import { rewriteGlobalDocs } from '../lib/migrate-global-docs'
type Data = Record<string, unknown>
const CTA_NAMES = ['primary', 'secondary'] as const
function isRecord(value: unknown): value is Data {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function ctaGroups(data: Data): Data[] {
const cta = isRecord(data.hero) && isRecord(data.hero.cta) ? data.hero.cta : undefined
return cta ? CTA_NAMES.map((name) => cta[name]).filter(isRecord) : []
}
/** The Hungarian (default-locale) value of a possibly localized href. */
function storedPath(href: unknown): string | undefined {
if (typeof href === 'string') return href
return isRecord(href) && typeof href.hu === 'string' ? href.hu : undefined
}
export function toPageLink(cta: Data): number {
if (cta.linkType) return 0
const path = storedPath(cta.href)
const page = path === undefined ? undefined : internalPathToPageKey(path)
if (page) {
cta.linkType = 'page'
cta.page = page
delete cta.href
} else {
cta.linkType = 'url'
}
return 1
}
/** Inverse: restores a hu-locale href for page links, drops the new fields. */
export function toFreeTextLink(cta: Data): number {
if (!cta.linkType) return 0
if (cta.linkType === 'page') cta.href = { hu: resolveCtaHref(cta as CtaLink, 'hu') }
delete cta.linkType
delete cta.page
return 1
}
async function migrate(args: MigrateUpArgs | MigrateDownArgs, transform: (cta: Data) => number) {
const changed = await rewriteGlobalDocs(args, 'home', ['hero'], (data) =>
ctaGroups(data).reduce((sum, cta) => sum + transform(cta), 0),
)
args.payload.logger.info(`MITHOME-123 CTA link migration: home — ${changed} CTA(s) rewritten`)
}
export async function up(args: MigrateUpArgs): Promise<void> {
await migrate(args, toPageLink)
}
export async function down(args: MigrateDownArgs): Promise<void> {
await migrate(args, toFreeTextLink)
}
@@ -6,13 +6,13 @@
* ü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.
* Az írás módja (közvetlen Mongo, hookok/új verzió nélkül): lásd
* src/lib/migrate-global-docs.ts.
*
* 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 { MigrateDownArgs, MigrateUpArgs } from '@payloadcms/db-mongodb'
import type { GlobalConfig } from 'payload'
import { Home } from '../globals/Home'
@@ -27,48 +27,18 @@ import {
wrapLocalized,
type LocalizedPath,
} from '../lib/localize-paths'
import { rewriteGlobalDocs } from '../lib/migrate-global-docs'
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)
const paths = collectLocalizedPaths(global.fields as never)
const changed = await rewriteGlobalDocs(args, global.slug, topLevelKeys(paths), (data) => transform(data, paths))
args.payload.logger.info(`MITHOME-111 locale migration: ${global.slug} — ${changed} value(s) rewritten`)
}
}
+7
View File
@@ -1,4 +1,5 @@
import * as migration_20260929_localize_globals from './20260929_localize_globals'
import * as migration_20260929_cta_page_links from './20260929_cta_page_links'
/**
* Payload migrations, in order. Passed to `mongooseAdapter({ prodMigrations })`
@@ -10,4 +11,10 @@ export const migrations = [
down: migration_20260929_localize_globals.down,
name: '20260929_localize_globals',
},
{
// MITHOME-123 — order-independent from the locale migration (handles both href shapes).
up: migration_20260929_cta_page_links.up,
down: migration_20260929_cta_page_links.down,
name: '20260929_cta_page_links',
},
]
+31 -6
View File
@@ -148,7 +148,7 @@ describe('Payload globals', () => {
const SHARED_TEXT_FIELDS = new Set(['icon', 'id', 'address'])
type Node = FieldLike & { localized?: boolean; fields?: Node[] }
type Finding = { path: string; localized: boolean }
type Finding = { path: string; type?: string; localized: boolean }
const isStringArray = (f: Node) =>
f.type === 'array' && f.fields?.length === 1 && f.fields[0].name === 'value'
@@ -163,7 +163,7 @@ describe('Payload globals', () => {
out.push({ path: `${path}(container)`, localized: f.localized === true })
walk(f.fields ?? [], `${path}.`, out)
} else {
out.push({ path, localized: f.localized === true })
out.push({ path, type: f.type, localized: f.localized === true })
}
}
return out
@@ -172,9 +172,9 @@ describe('Payload globals', () => {
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)
// Checkbox/radio/select (external, linkType, page) are structural.
if (finding.type !== 'text' && finding.type !== 'textarea') return false
return !SHARED_TEXT_FIELDS.has(finding.path.split('.').pop()!)
}
it.each([Home, About, Services, Contact, Common].map((g) => [g.slug, g] as const))(
@@ -186,11 +186,36 @@ describe('Payload globals', () => {
},
)
it('should localize the locale-dependent CTA hrefs but share the external flag', () => {
it('should localize the CTA URL but share the link type, page and 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.linkType']).toBe(false)
expect(byPath['hero.cta.primary.page']).toBe(false)
expect(byPath['hero.cta.primary.external']).toBe(false)
})
})
describe('MITHOME-123 CTA links', () => {
type Validate = (value: unknown, opts: { siblingData: { linkType?: string } }) => true | string
const cta = (name: string) => {
const hero = findField(Home.fields, 'hero') as { fields: unknown[] }
const group = findField(hero.fields, 'cta') as { fields: unknown[] }
return (findField(group.fields, name) as { fields: unknown[] }).fields
}
const validate = (field: string) => (findField(cta('primary'), field) as unknown as { validate: Validate }).validate
it('should offer every routable page, including home, in the page selector', () => {
const page = findField(cta('primary'), 'page') as unknown as { options: { value: string }[] }
expect(page.options.map((o) => o.value)).toEqual(['home', 'about', 'services', 'contact', 'privacy', 'terms'])
})
it('should require a page only for internal links and a URL only for external links', () => {
expect(validate('page')(null, { siblingData: { linkType: 'page' } })).toEqual(expect.any(String))
expect(validate('page')(null, { siblingData: { linkType: 'url' } })).toBe(true)
expect(validate('href')('', { siblingData: { linkType: 'url' } })).toEqual(expect.any(String))
expect(validate('href')(null, { siblingData: { linkType: 'page' } })).toBe(true)
expect(validate('href')('https://mail.mozdit.hu', { siblingData: { linkType: 'url' } })).toBe(true)
})
})
})