diff --git a/proto/scripts/migrate-content-to-payload.ts b/proto/scripts/migrate-content-to-payload.ts index d1f4b59..9286781 100644 --- a/proto/scripts/migrate-content-to-payload.ts +++ b/proto/scripts/migrate-content-to-payload.ts @@ -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: { diff --git a/proto/src/__tests__/cta-links-migration.test.ts b/proto/src/__tests__/cta-links-migration.test.ts new file mode 100644 index 0000000..f223897 --- /dev/null +++ b/proto/src/__tests__/cta-links-migration.test.ts @@ -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 + +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 }).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 }) + }) +}) diff --git a/proto/src/globals/Home.ts b/proto/src/globals/Home.ts index cc2dbee..b5686df 100644 --- a/proto/src/globals/Home.ts +++ b/proto/src/globals/Home.ts @@ -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'), ], }, ], diff --git a/proto/src/globals/fields/ctaLink.ts b/proto/src/globals/fields/ctaLink.ts new file mode 100644 index 0000000..b131110 --- /dev/null +++ b/proto/src/globals/fields/ctaLink.ts @@ -0,0 +1,63 @@ +import type { GroupField } from 'payload' + +import { CTA_PAGES, type CtaPage } from '../../lib/cta-link' + +const PAGE_LABELS: Record = { + 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 }, + ], + } +} diff --git a/proto/src/lib/cta-link.test.ts b/proto/src/lib/cta-link.test.ts new file mode 100644 index 0000000..a35ed7e --- /dev/null +++ b/proto/src/lib/cta-link.test.ts @@ -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() + }, + ) +}) diff --git a/proto/src/lib/cta-link.ts b/proto/src/lib/cta-link.ts new file mode 100644 index 0000000..4311349 --- /dev/null +++ b/proto/src/lib/cta-link.ts @@ -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), + ) +} diff --git a/proto/src/lib/migrate-global-docs.ts b/proto/src/lib/migrate-global-docs.ts new file mode 100644 index 0000000..af8c8aa --- /dev/null +++ b/proto/src/lib/migrate-global-docs.ts @@ -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 + +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 { + 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 +} diff --git a/proto/src/lib/payload-content.ts b/proto/src/lib/payload-content.ts index cf1b26c..0e5db62 100644 --- a/proto/src/lib/payload-content.ts +++ b/proto/src/lib/payload-content.ts @@ -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 | undefined @@ -19,6 +20,11 @@ function payloadClient() { return cached } +/** MITHOME-123: internal CTA targets are stored as a page, resolved per locale. */ +function withHref(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) => ({ diff --git a/proto/src/migrations/20260929_cta_page_links.ts b/proto/src/migrations/20260929_cta_page_links.ts new file mode 100644 index 0000000..538d5cd --- /dev/null +++ b/proto/src/migrations/20260929_cta_page_links.ts @@ -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 + +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 { + await migrate(args, toPageLink) +} + +export async function down(args: MigrateDownArgs): Promise { + await migrate(args, toFreeTextLink) +} diff --git a/proto/src/migrations/20260929_localize_globals.ts b/proto/src/migrations/20260929_localize_globals.ts index 424decf..89129d2 100644 --- a/proto/src/migrations/20260929_localize_globals.ts +++ b/proto/src/migrations/20260929_localize_globals.ts @@ -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, paths: readonly LocalizedPath[]) => number type Args = MigrateUpArgs | MigrateDownArgs -function pick(doc: Record, keys: readonly string[]) { - return Object.fromEntries(keys.filter((key) => key in doc).map((key) => [key, doc[key]])) -} - -async function migrateGlobal(global: GlobalConfig, { payload, session }: Args, transform: Transform) { - const db = payload.db as unknown as MongooseAdapter - const paths = collectLocalizedPaths(global.fields as never) - let changed = 0 - - const main = await db.globals.collection.findOne({ globalType: global.slug }, { session }) - if (main) { - const count = transform(main, paths) - if (count > 0) { - await db.globals.collection.updateOne({ _id: main._id }, { $set: pick(main, topLevelKeys(paths)) }, { session }) - changed += count - } - } - - const versions = db.versions[global.slug] - if (versions) { - const versionPaths = paths.map((path) => ['version', ...path]) - for await (const doc of versions.collection.find({}, { session })) { - const count = transform(doc, versionPaths) - if (count > 0) { - await versions.collection.updateOne({ _id: doc._id }, { $set: { version: doc.version } }, { session }) - changed += count - } - } - } - - payload.logger.info(`MITHOME-111 locale migration: ${global.slug} — ${changed} value(s) rewritten`) -} - async function migrateAll(args: Args, transform: Transform) { for (const global of LOCALIZED_GLOBALS) { - await migrateGlobal(global, args, transform) + 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`) } } diff --git a/proto/src/migrations/index.ts b/proto/src/migrations/index.ts index c24d604..a7fa4f1 100644 --- a/proto/src/migrations/index.ts +++ b/proto/src/migrations/index.ts @@ -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', + }, ] diff --git a/proto/src/payload-config.test.ts b/proto/src/payload-config.test.ts index 0f30867..21dd810 100644 --- a/proto/src/payload-config.test.ts +++ b/proto/src/payload-config.test.ts @@ -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) + }) + }) })