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>
This commit is contained in:
Do Siki
2026-09-29 01:26:42 +02:00
co-authored by Claude Opus 5.5
parent 38d34fab4c
commit e8ff7adeb5
12 changed files with 460 additions and 65 deletions
+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) => ({