feat(cms): switch Payload to PostgreSQL with a fresh baseline migration (MITHOME-136)

- postgresAdapter (uuid ids, no push, prodMigrations), DATABASE_URI
- src/payload.shared.ts: the config without the db adapter, shared with the
  one-off MongoDB content transfer
- baseline migration 20260929_200306_initial (86 tables; applied twice on a
  disposable PostgreSQL 16: second run is a no-op)
- seed copy (references, hosting plans) moved to src/content/seeds/
- MongoDB data migrations, their helpers/tests and the dead lib/mongodb.ts
  removed (kept in git history)
- npm scripts for the Payload CLI (works now that the package is ESM)

Branch only: staging has no PostgreSQL yet (tasks 3.x).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Do Siki
2026-09-29 22:09:00 +02:00
co-authored by Claude Opus 5.5
parent a3d6cbe404
commit e3ec6a9ac3
40 changed files with 14226 additions and 2160 deletions
+2
View File
@@ -20,6 +20,8 @@ const eslintConfig = [
"playwright-report/**",
"test-results/**",
"coverage/**",
// MITHOME-136: generated by `payload migrate:create` — not edited by hand.
"src/migrations/2*.ts",
],
},
{
+1374 -3
View File
File diff suppressed because it is too large Load Diff
+7 -1
View File
@@ -31,10 +31,16 @@
"docker:build": "docker build -t mozdit-app .",
"docker:run": "docker run -p 3000:3000 --env-file .env.local mozdit-app",
"migrate:content": "node --env-file=.env.local --import tsx scripts/migrate-content-to-payload.ts",
"test:payload": "node --env-file=.env.local --import tsx scripts/test-payload-local-api.ts"
"test:payload": "node --env-file=.env.local --import tsx scripts/test-payload-local-api.ts",
"payload": "payload",
"generate:types": "payload generate:types",
"generate:importmap": "payload generate:importmap",
"migrate:create": "payload migrate:create",
"migrate:status": "payload migrate:status"
},
"dependencies": {
"@payloadcms/db-mongodb": "^3.88.0",
"@payloadcms/db-postgres": "^3.88.0",
"@payloadcms/next": "^3.88.0",
"@payloadcms/richtext-lexical": "^3.88.0",
"graphql": "^16.14.2",
+1 -1
View File
@@ -35,7 +35,7 @@ import { fileURLToPath } from 'url'
import { getPayload, type Payload } from 'payload'
import config from '../src/payload.config'
import { internalPathToPageKey } from '../src/lib/cta-link'
import { CONFIRMED_CLIENT_REFERENCES, REFERENCES_SECTION_COPY } from '../src/migrations/20260929_partner_references'
import { CONFIRMED_CLIENT_REFERENCES, REFERENCES_SECTION_COPY } from '../src/content/seeds/references'
import homeJson from '../src/content/pages/home.json'
import aboutJson from '../src/content/pages/about.json'
@@ -1,83 +0,0 @@
import { down, toPageLink, up } from '../migrations/20260929_cta_page_links'
import { up as localizeUp } from '../migrations/20260929_localize_globals'
import { fakeArgs, fakeCollection } from './helpers/fake-mongo'
type Doc = Record<string, 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 { args, payload } = fakeArgs({ globals, versions: { home: versions } })
return { args, 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 })
})
})
@@ -1,66 +0,0 @@
import { up } from '../migrations/20260929_en_ai_draft'
import { fakeArgs, fakeCollection } from './helpers/fake-mongo'
type Doc = Record<string, unknown>
// Texts taken from the real translation memory (en.json).
const homeData = (title: unknown): Doc => ({
hero: { title, trustBullets: { hu: [{ value: 'Saját dedikált infrastruktúra', id: 'b1' }] } },
})
function setup() {
const globals = fakeCollection([{ _id: 'g-home', globalType: 'home', ...homeData({ hu: 'Webtárhely, üzleti e-mail és domainkezelés egy helyen' }) }])
const homeVersions = fakeCollection([
{ _id: 'old', latest: false, version: homeData({ hu: 'Régi cím' }) },
{ _id: 'cur', latest: true, version: homeData({ hu: 'Webtárhely, üzleti e-mail és domainkezelés egy helyen' }) },
])
const legal = fakeCollection([
// legacy (unwrapped) shape: the migration must not depend on running after 20260929_localize_legal_pages
{ _id: 'lp', slug: 'adatvedelem', title: 'Adatvédelmi Tájékoztató', lastUpdated: '2026. augusztus 22.', sections: [{ id: 's1', title: 'Ismeretlen fejezet', content: '1. Bevezetés' }] },
])
return {
globals,
homeVersions,
legal,
...fakeArgs({ globals, collections: { 'legal-pages': legal }, versions: { home: homeVersions } }),
}
}
describe('20260929_en_ai_draft migration (MITHOME-113)', () => {
it('should fill English values on the published global and mark it as AI draft', async () => {
const { args, globals } = setup()
await up(args)
const home = globals.docs[0] as { hero: { title: Doc; trustBullets: { en: { value: string }[] } }; enTranslationStatus: string }
expect(home.hero.title.en).toBe('Web hosting, business email and domain management in one place')
expect(home.hero.trustBullets.en.map((r) => r.value)).toEqual(['Our own dedicated infrastructure'])
expect(home.enTranslationStatus).toBe('ai-draft')
expect(globals.updateOne.mock.calls[0][1].$set).toHaveProperty('enTranslationStatus', 'ai-draft')
})
it('should only fill the latest version, not history', async () => {
const { args, homeVersions } = setup()
await up(args)
expect(homeVersions.updateOne).toHaveBeenCalledTimes(1)
expect(homeVersions.updateOne.mock.calls[0][0]).toEqual({ _id: 'cur' })
})
it('should wrap legacy legal page values first and report untranslated Hungarian texts', async () => {
const { args, legal, payload } = setup()
await up(args)
expect(legal.docs[0]).toMatchObject({
slug: 'adatvedelem',
title: { hu: 'Adatvédelmi Tájékoztató', en: 'Privacy Notice' },
sections: [{ id: 's1', title: { hu: 'Ismeretlen fejezet' }, content: { hu: '1. Bevezetés', en: '1. Introduction' } }],
enTranslationStatus: 'ai-draft',
})
expect(payload.logger.warn).toHaveBeenCalledWith('MITHOME-113 no translation (legal-pages): Ismeretlen fejezet')
})
it('should be idempotent', async () => {
const { args, globals, legal } = setup()
await up(args)
const snapshot = JSON.stringify([globals.docs, legal.docs])
await up(args)
expect(JSON.stringify([globals.docs, legal.docs])).toBe(snapshot)
})
})
-30
View File
@@ -1,30 +0,0 @@
/** Minimal in-memory stand-in for a Mongo collection used by migration tests. */
type Doc = Record<string, unknown>
const matches = (doc: Doc, filter: Doc) => Object.entries(filter).every(([key, value]) => doc[key] === value)
export function fakeCollection(docs: Doc[]) {
return {
docs,
find: jest.fn((filter: Doc = {}) => ({
async *[Symbol.asyncIterator]() {
yield* docs.filter((doc) => matches(doc, filter))
},
})),
updateOne: jest.fn<Promise<object>, [filter: Doc, update: { $set: Doc }, options?: unknown]>(async () => ({})),
}
}
export type FakeCollection = ReturnType<typeof fakeCollection>
export function fakeArgs(db: { globals?: FakeCollection; collections?: Record<string, FakeCollection>; versions?: Record<string, FakeCollection> }) {
const payload = {
db: {
globals: { collection: db.globals ?? fakeCollection([]) },
collections: Object.fromEntries(Object.entries(db.collections ?? {}).map(([k, c]) => [k, { collection: c }])),
versions: Object.fromEntries(Object.entries(db.versions ?? {}).map(([k, c]) => [k, { collection: c }])),
},
logger: { info: jest.fn(), warn: jest.fn() },
}
return { payload, args: { payload, session: undefined, req: {} } as never }
}
@@ -1,74 +0,0 @@
import { HOSTING_PLAN_SEEDS, productData, up } from '../migrations/20260929_hosting_plans'
type Doc = Record<string, unknown>
/** Minimal Local API stand-in: products by slug + one global. */
function fakePayload(products: Doc[] = [], page: Doc = {}) {
const payload = {
find: jest.fn(async ({ where }: { where: { slug: { equals: string } } }) => ({
docs: products.filter((p) => p.slug === where.slug.equals),
})),
create: jest.fn(async ({ data }: { data: Doc }) => {
const doc = { id: `id-${products.length}`, ...data }
products.push(doc)
return doc
}),
update: jest.fn(async () => ({})),
findGlobal: jest.fn(async () => page),
updateGlobal: jest.fn(async ({ data, locale }: { data: Doc; locale: string }) => {
if (locale === 'hu') Object.assign(page, data)
return page
}),
logger: { info: jest.fn(), warn: jest.fn() },
}
return { payload, args: { payload, req: {} } as never }
}
describe('20260929_hosting_plans migration (MITHOME-130)', () => {
it('should seed the catalogue figures and prices as a draft, with an English AI draft', () => {
const start = productData(HOSTING_PLAN_SEEDS[0], 'hu')
expect(start).toMatchObject({
slug: 'mit-start',
productType: 'hosting',
status: 'draft',
enTranslationStatus: 'ai-draft',
pricing: { netAmount: 14900, billingPeriod: 'yearly' },
serviceDefinition: { storageGb: 3, mailStorageGb: 1, databases: 1, mailboxes: 5, ssl: true, spamFilter: true },
_status: 'published',
})
expect(productData(HOSTING_PLAN_SEEDS[1], 'hu')).toMatchObject({
highlighted: true,
pricing: { netAmount: 23900 },
serviceDefinition: { storageGb: 8, mailStorageGb: 4, domainAliases: 2, databases: 2, mailboxes: 10 },
})
})
it('should write only localized fields in English', () => {
const en = productData(HOSTING_PLAN_SEEDS[0], 'en')
expect(Object.keys(en).sort()).toEqual(['_status', 'public', 'serviceDefinition'])
expect(en.serviceDefinition).toEqual({ backup: 'Daily, with 7-day restore' })
})
it('should create the missing products and page copy once', async () => {
const products: Doc[] = []
const { args, payload } = fakePayload(products)
await up(args)
expect(payload.create).toHaveBeenCalledTimes(2)
expect(payload.update).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en' }))
expect(payload.updateGlobal).toHaveBeenCalledWith(
expect.objectContaining({ locale: 'hu', data: expect.objectContaining({ vatRatePercent: 27, hero: expect.objectContaining({ title: 'Tárhelycsomagok' }) }) }),
)
expect(payload.logger.info).toHaveBeenLastCalledWith('MITHOME-130 hosting plans: 2 product(s) created, 1 page copy seeded')
await up(args)
expect(payload.create).toHaveBeenCalledTimes(2)
expect(payload.logger.info).toHaveBeenLastCalledWith('MITHOME-130 hosting plans: 0 product(s) created, 0 page copy seeded')
})
it('should not overwrite an existing product or edited page copy', async () => {
const { args, payload } = fakePayload([{ id: 'x', slug: 'mit-start', pricing: { netAmount: 1 } }], { hero: { title: 'Saját cím' } })
await up(args)
expect(payload.create).toHaveBeenCalledTimes(1)
expect(payload.updateGlobal).not.toHaveBeenCalled()
})
})
@@ -1,67 +0,0 @@
import { down, up } from '../migrations/20260929_localize_globals'
import { fakeArgs, fakeCollection } from './helpers/fake-mongo'
type Doc = Record<string, 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 { args, payload } = fakeArgs({ globals, versions: { home: homeVersions } })
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' })
})
})
@@ -1,46 +0,0 @@
import { down, up } from '../migrations/20260929_localize_legal_pages'
import { fakeArgs, fakeCollection } from './helpers/fake-mongo'
const legacyPage = () => ({
_id: 'p1',
slug: 'adatvedelem',
title: 'Adatvédelmi tájékoztató',
lastUpdated: '2026. augusztus 22.',
sections: [{ id: 'bevezetes', title: 'Bevezetés', content: 'Szöveg' }],
_status: 'published',
})
function setup() {
const pages = fakeCollection([legacyPage()])
const versions = fakeCollection([{ _id: 'v1', latest: true, version: legacyPage() }])
return { pages, versions, ...fakeArgs({ collections: { 'legal-pages': pages }, versions: { 'legal-pages': versions } }) }
}
describe('20260929_localize_legal_pages migration (MITHOME-112)', () => {
it('should wrap title, date and section texts under hu, keeping slug and section ids shared', async () => {
const { args, pages } = setup()
await up(args)
expect(pages.docs[0]).toMatchObject({
slug: 'adatvedelem',
title: { hu: 'Adatvédelmi tájékoztató' },
lastUpdated: { hu: '2026. augusztus 22.' },
sections: [{ id: 'bevezetes', title: { hu: 'Bevezetés' }, content: { hu: 'Szöveg' } }],
})
expect(pages.updateOne.mock.calls[0][1].$set).not.toHaveProperty('slug')
})
it('should migrate version records and be idempotent', async () => {
const { args, versions, payload } = setup()
await up(args)
expect((versions.docs[0].version as { title: unknown }).title).toEqual({ hu: 'Adatvédelmi tájékoztató' })
await up(args)
expect(payload.logger.info).toHaveBeenLastCalledWith('MITHOME-112 locale migration: legal-pages — 0 value(s) rewritten')
})
it('should restore the legacy shape on down', async () => {
const { args, pages } = setup()
await up(args)
await down(args)
expect(pages.docs[0]).toEqual(legacyPage())
})
})
-59
View File
@@ -1,59 +0,0 @@
import { rewriteDocs } from '../lib/migrate-global-docs'
import { fakeArgs, fakeCollection } from './helpers/fake-mongo'
type Doc = Record<string, unknown>
const upper = (data: Doc) => {
if (typeof data.title !== 'string') return 0
data.title = data.title.toUpperCase()
return 1
}
describe('rewriteDocs (MITHOME-112)', () => {
it('should rewrite every document of a collection and all its versions by default', async () => {
const docs = fakeCollection([
{ _id: 'a', slug: 'adatvedelem', title: 'a' },
{ _id: 'b', slug: 'hasznalati-feltetelek', title: 'b' },
])
const versions = fakeCollection([
{ _id: 'v1', latest: false, version: { title: 'old' } },
{ _id: 'v2', latest: true, version: { title: 'new' } },
])
const { args } = fakeArgs({ collections: { 'legal-pages': docs }, versions: { 'legal-pages': versions } })
const changed = await rewriteDocs(args, { kind: 'collection', slug: 'legal-pages' }, ['title'], upper)
expect(changed).toBe(4)
expect(docs.updateOne).toHaveBeenCalledWith({ _id: 'a' }, { $set: { title: 'A' } }, { session: undefined })
expect(versions.updateOne).toHaveBeenCalledTimes(2)
})
it('should only touch the latest version when scoped to latest', async () => {
const versions = fakeCollection([
{ _id: 'v1', latest: false, version: { title: 'old' } },
{ _id: 'v2', latest: true, version: { title: 'new' } },
])
const { args } = fakeArgs({ collections: { 'legal-pages': fakeCollection([]) }, versions: { 'legal-pages': versions } })
await rewriteDocs(args, { kind: 'collection', slug: 'legal-pages' }, ['title'], upper, { versions: 'latest' })
expect(versions.updateOne).toHaveBeenCalledTimes(1)
expect(versions.updateOne).toHaveBeenCalledWith({ _id: 'v2' }, { $set: { version: { title: 'NEW' } } }, { session: undefined })
})
it('should only read the targeted global', async () => {
const globals = fakeCollection([
{ _id: 'h', globalType: 'home', title: 'home' },
{ _id: 'c', globalType: 'common', title: 'common' },
])
const { args } = fakeArgs({ globals })
expect(await rewriteDocs(args, { kind: 'global', slug: 'home' }, ['title'], upper)).toBe(1)
expect(globals.docs[1].title).toBe('common')
})
it('should skip a collection that does not exist and version records without data', async () => {
const versions = fakeCollection([{ _id: 'v', version: null }])
const { args } = fakeArgs({ versions: { nope: versions } })
expect(await rewriteDocs(args, { kind: 'collection', slug: 'nope' }, ['title'], upper)).toBe(0)
})
})
@@ -1,68 +0,0 @@
import { classifyPartner, seedReferencesSection, up } from '../migrations/20260929_partner_references'
import { markAtlantiszPending, PENDING_REFERENCE } from '../migrations/20260929_atlantisz_pending'
import { fakeArgs, fakeCollection } from './helpers/fake-mongo'
type Doc = Record<string, unknown>
describe('20260929_partner_references migration (MITHOME-131)', () => {
it('should mark the confirmed client as a client reference with written permission', () => {
const doc: Doc = { name: 'Angele Pihenőház', url: 'https://angelepihenohaz.hu' }
expect(classifyPartner(doc)).toBe(1)
expect(doc).toMatchObject({ relationship: 'client-reference', publicationPermission: 'granted' })
expect(doc.permissionReference).toMatch(/Írásos engedély/)
})
it('should mark the Atlantisz contracted client as a client reference, pending until its logo is settled', () => {
const doc: Doc = { name: 'Atlantisz Horgászüdülő és Halásztanya' }
classifyPartner(doc)
expect(doc).toMatchObject({ relationship: 'client-reference', publicationPermission: 'pending' })
})
it('should move an already granted Atlantisz entry to pending, but respect later admin decisions', () => {
const auto: Doc = {
name: 'Atlantisz Horgászüdülő és Halásztanya',
publicationPermission: 'granted',
permissionReference: 'Írásos engedély megvan (tulajdonosi megerősítés, 2026-09-29)',
}
expect(markAtlantiszPending(auto)).toBe(1)
expect(auto).toMatchObject({ publicationPermission: 'pending', permissionReference: PENDING_REFERENCE })
expect(markAtlantiszPending(auto)).toBe(0)
const admin: Doc = { name: 'Atlantisz Horgászüdülő és Halásztanya', publicationPermission: 'granted', permissionReference: 'E-mail, 2026-10-05' }
expect(markAtlantiszPending(admin)).toBe(0)
const angele: Doc = { name: 'Angele Pihenőház', publicationPermission: 'granted', permissionReference: 'Írásos engedély megvan (tulajdonosi megerősítés, 2026-09-29)' }
expect(markAtlantiszPending(angele)).toBe(0)
})
it('should hide any other uncategorised entry until someone classifies it', () => {
const doc: Doc = { name: 'Ismeretlen Kft.' }
classifyPartner(doc)
expect(doc).toEqual({ name: 'Ismeretlen Kft.', publicationPermission: 'none' })
})
it('should not touch an already categorised entry', () => {
const doc: Doc = { name: 'Angele Pihenőház', relationship: 'supplier', publicationPermission: 'pending' }
expect(classifyPartner(doc)).toBe(0)
expect(doc.relationship).toBe('supplier')
})
it('should seed the section copy in both languages only when missing', () => {
const doc: Doc = {}
seedReferencesSection(doc)
expect(doc.referencesSection).toMatchObject({
clientsTitle: { hu: 'Akik már minket választottak', en: 'Clients who chose us' },
relationshipLabels: { infrastructure: { hu: 'Technológiai háttér', en: 'Infrastructure provider' } },
})
const edited: Doc = { referencesSection: { clientsTitle: { hu: 'Saját cím' } } }
expect(seedReferencesSection(edited)).toBe(0)
})
it('should update the partners collection and the home global, idempotently', async () => {
const partners = fakeCollection([{ _id: 'p1', name: 'Angele Pihenőház' }])
const globals = fakeCollection([{ _id: 'h', globalType: 'home' }])
const { args, payload } = fakeArgs({ globals, collections: { partners } })
await up(args)
expect(payload.logger.info).toHaveBeenLastCalledWith('MITHOME-131 references: 1 partner record(s) classified, 1 home record(s) seeded')
await up(args)
expect(payload.logger.info).toHaveBeenLastCalledWith('MITHOME-131 references: 0 partner record(s) classified, 0 home record(s) seeded')
})
})
@@ -1,68 +0,0 @@
import { SERVICE_CLAIM_INSERTIONS, SERVICE_CLAIM_REVISIONS, up } from '../migrations/20260929_service_claims'
import translations from '../content/translations/en.json'
import { fakeArgs, fakeCollection } from './helpers/fake-mongo'
type Doc = Record<string, unknown>
const memory: Record<string, string> = translations
describe('20260929_service_claims migration (MITHOME-129)', () => {
it('should know the old AI-draft English of every revised text', () => {
for (const revision of SERVICE_CLAIM_REVISIONS) {
expect(revision.enWas).toBe(memory[revision.from])
expect(revision.enWas).toBeTruthy()
}
})
it('should keep the translation memory in sync with the new texts', () => {
for (const revision of SERVICE_CLAIM_REVISIONS) expect(memory[revision.to]).toBe(revision.enTo)
for (const insertion of SERVICE_CLAIM_INSERTIONS) expect(memory[insertion.hu]).toBe(insertion.en)
})
it('should not promise 99.9%, unlimited traffic, Python/Node/PostgreSQL or immediate response any more', () => {
const newTexts = SERVICE_CLAIM_REVISIONS.flatMap((r) => [r.to, r.enTo]).join('\n')
expect(newTexts).not.toMatch(/99,9|99\.9|korlátlan|unlimited|Python|Node\.js|PostgreSQL|Azonnali|világszerte|100GB|20GB/i)
})
it('should revise the services global: text, list items, inserted e-mail feature', async () => {
const services: Doc = {
_id: 's',
globalType: 'services',
details: {
services: [
{
icon: '📧',
description: { hu: 'Más leírás' },
specs: {
items: {
hu: [{ value: 'Mobilalkalmazás szinkronizáció', id: 'a' }, { value: 'Backup és archiválás ', id: 'b' }],
en: [{ value: memory['Mobilalkalmazás szinkronizáció'], id: 'c' }, { value: memory['Backup és archiválás '], id: 'd' }],
},
},
},
],
},
support: { channels: [{ icon: '🚨', title: { hu: 'Sürgős esetek' }, description: { hu: 'Azonnali beavatkozás', en: memory['Azonnali beavatkozás'] } }] },
enTranslationStatus: 'ai-draft',
}
const globals = fakeCollection([services])
const { args, payload } = fakeArgs({ globals })
await up(args)
const items = (services.details as { services: { specs: { items: { hu: { value: string }[]; en: { value: string }[] } } }[] }).services[0].specs.items
expect(items.hu.map((r) => r.value)).toEqual([
'Mobilalkalmazás szinkronizáció',
'Napi mentés, 7 napos visszaállítással',
'Automatikus figyelmeztetés 90%-os postafiók-telítettségnél',
])
expect(items.en.map((r) => r.value)).toEqual(['Mobile app synchronisation', 'Daily backup with 7-day restore', 'Automatic warning when a mailbox is 90% full'])
expect((services.support as { channels: { description: Doc }[] }).channels[0].description).toEqual({
hu: '0–24 órás riasztás, a beavatkozás tipikusan 2–4 órán belül megkezdődik',
en: '24/7 alerting; work typically starts within 2–4 hours',
})
expect(payload.logger.info).toHaveBeenCalledWith('MITHOME-129 service claims: services — 3 text(s) revised')
await up(args)
expect(payload.logger.info).toHaveBeenLastCalledWith('MITHOME-129 service claims: contact — 0 text(s) revised')
expect(items.hu).toHaveLength(3)
})
})
@@ -1,7 +1,7 @@
import { render, screen, within } from '@testing-library/react'
import '@testing-library/jest-dom'
import HostingPlansView from './HostingPlansView'
import { HOSTING_PLANS_PAGE_COPY, pickLanguage } from '@/migrations/20260929_hosting_plans'
import { HOSTING_PLANS_PAGE_COPY, pickLanguage } from '@/content/seeds/hosting-plans'
import type { HostingPlanView } from '@/lib/products'
type Content = Parameters<typeof HostingPlansView>[0]['content']
@@ -0,0 +1,27 @@
import { HOSTING_PLAN_SEEDS, productData } from './hosting-plans'
describe('hosting plans seed (MITHOME-130)', () => {
it('should seed the catalogue figures and prices as a draft, with an English AI draft', () => {
const start = productData(HOSTING_PLAN_SEEDS[0], 'hu')
expect(start).toMatchObject({
slug: 'mit-start',
productType: 'hosting',
status: 'draft',
enTranslationStatus: 'ai-draft',
pricing: { netAmount: 14900, billingPeriod: 'yearly' },
serviceDefinition: { storageGb: 3, mailStorageGb: 1, databases: 1, mailboxes: 5, ssl: true, spamFilter: true },
_status: 'published',
})
expect(productData(HOSTING_PLAN_SEEDS[1], 'hu')).toMatchObject({
highlighted: true,
pricing: { netAmount: 23900 },
serviceDefinition: { storageGb: 8, mailStorageGb: 4, domainAliases: 2, databases: 2, mailboxes: 10 },
})
})
it('should write only localized fields in English', () => {
const en = productData(HOSTING_PLAN_SEEDS[0], 'en')
expect(Object.keys(en).sort()).toEqual(['_status', 'public', 'serviceDefinition'])
expect(en.serviceDefinition).toEqual({ backup: 'Daily, with 7-day restore' })
})
})
@@ -1,21 +1,10 @@
/**
* MITHOME-130: seed the hosting plans (mIT Start, mIT Mid) and the copy of
* the hosting plans page.
*
* Figures and prices come from the central catalogue — mitplatform
* docs/plans/PLATFM-14-products-v0.json, catalogVersion 0.1.1 (owner
* decision 2026-09-29: variant B, yearly billing, net + 27% VAT).
*
* - Products are created in the "draft" lifecycle status: staging shows
* them for review, production does not (src/lib/products.ts).
* - English is an AI draft (enTranslationStatus "ai-draft").
* - Only creates what is missing (product by slug, page copy when empty);
* never touches existing data. Idempotent.
*
* WHY the Local API (not rewriteDocs): these are new documents, and the
* Local API writes the version records and the Payload `_status` for us.
* MITHOME-130: hosting plans (mIT Start, mIT Mid) and the hosting plans page
* copy, hu + en. Figures and prices from the central catalogue — mitplatform
* docs/plans/PLATFM-14-products-v0.json (owner decision 2026-09-29: variant B,
* yearly billing, net + 27% VAT). Seed data for a fresh database; moved here
* from the MongoDB data migration (MITHOME-136).
*/
import type { MigrateDownArgs, MigrateUpArgs } from '@payloadcms/db-mongodb'
type Copy = { hu: string; en: string }
type ListCopy = { hu: string[]; en: string[] }
@@ -146,31 +135,3 @@ export function productData(seed: Seed, lang: Lang): Record<string, unknown> {
_status: 'published',
}
}
export async function up({ payload, req }: MigrateUpArgs): Promise<void> {
let created = 0
for (const seed of HOSTING_PLAN_SEEDS) {
const existing = await payload.find({ collection: 'products', where: { slug: { equals: seed.slug } }, limit: 1, depth: 0, req })
if (existing.docs.length > 0) continue
const doc = await payload.create({ collection: 'products', data: productData(seed, 'hu') as never, locale: 'hu', req })
await payload.update({ collection: 'products', id: doc.id, data: productData(seed, 'en') as never, locale: 'en', req })
created += 1
}
let pageSeeded = 0
const page = await payload.findGlobal({ slug: 'hosting-plans', locale: 'hu', depth: 0, req })
if (!page?.hero?.title) {
const copy = HOSTING_PLANS_PAGE_COPY as unknown as Tree
const hu = { ...pickLanguage(copy, 'hu'), vatRatePercent: 27, enTranslationStatus: 'ai-draft', _status: 'published' }
await payload.updateGlobal({ slug: 'hosting-plans', data: hu as never, locale: 'hu', req })
await payload.updateGlobal({ slug: 'hosting-plans', data: { ...pickLanguage(copy, 'en'), _status: 'published' } as never, locale: 'en', req })
pageSeeded = 1
}
payload.logger.info(`MITHOME-130 hosting plans: ${created} product(s) created, ${pageSeeded} page copy seeded`)
}
/** DECISION: no automatic down — restore the pre-deploy dump instead. */
export async function down({ payload }: MigrateDownArgs): Promise<void> {
payload.logger.warn('MITHOME-130 hosting plans: down is a no-op — restore the pre-deploy dump instead')
}
+44
View File
@@ -0,0 +1,44 @@
/**
* MITHOME-131/133: confirmed client references and the references section
* copy (hu + en). Seed data for a fresh database; the live values are edited
* in the Payload admin. Moved here from the MongoDB data migration when the
* site switched to PostgreSQL (MITHOME-136).
*/
export const CONFIRMED_CLIENT_REFERENCES = [
{
name: 'Angele Pihenőház',
permission: 'granted',
permissionReference: 'Írásos engedély megvan (tulajdonosi megerősítés, 2026-09-29)',
},
{
// Contracted client (its site runs on our infrastructure) — a client
// reference, not a partner, per the research's categories.
// Kept "pending" until the logo (white text, unreadable on a light
// background) and the official name are settled (MITHOME-133).
name: 'Atlantisz Horgászüdülő és Halásztanya',
permission: 'pending',
permissionReference: 'Írásos engedély megvan; logó és hivatalos név egyeztetés alatt (MITHOME-133)',
},
] as const
type Copy = Record<'hu' | 'en', string>
export const REFERENCES_SECTION_COPY: {
clientsTitle: Copy
clientsSubtitle: Copy
partnersTitle: Copy
partnersSubtitle: Copy
relationshipLabels: Record<'technologyPartner' | 'infrastructure' | 'supplier' | 'technologyUsed' | 'professionalPartner', Copy>
} = {
clientsTitle: { hu: 'Akik már minket választottak', en: 'Clients who chose us' },
clientsSubtitle: { hu: 'Ügyfeleink, akik hozzájárultak a bemutatásukhoz', en: 'Clients who agreed to be featured' },
partnersTitle: { hu: 'Partnereink és technológiai hátterünk', en: 'Our partners and technology' },
partnersSubtitle: { hu: 'Szervezetek, amelyek közreműködnek a szolgáltatásainkban', en: 'Organisations that contribute to our services' },
relationshipLabels: {
technologyPartner: { hu: 'Technológiai partner', en: 'Technology partner' },
infrastructure: { hu: 'Technológiai háttér', en: 'Infrastructure provider' },
supplier: { hu: 'Beszállító', en: 'Supplier' },
technologyUsed: { hu: 'Általunk használt technológia', en: 'Technology we use' },
professionalPartner: { hu: 'Szakmai partner', en: 'Professional partner' },
},
}
-105
View File
@@ -1,105 +0,0 @@
import { reviseContent, type ListInsertion, type TextRevision } from './content-revision'
import { collectLocalizedPaths } from './localize-paths'
type Doc = Record<string, unknown>
const FIELDS = [
{ name: 'title', type: 'text', localized: true },
{ name: 'items', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] },
]
const PATHS = collectLocalizedPaths(FIELDS)
const REVISIONS: TextRevision[] = [
{ from: 'Régi cím', to: 'Új cím', enWas: 'Old title', enTo: 'New title' },
{ from: 'Régi elem', to: 'Új elem', enWas: 'Old item', enTo: 'New item' },
]
const INSERTIONS: ListInsertion[] = [{ afterHu: 'Új elem', hu: 'Beszúrt', afterEn: 'New item', en: 'Inserted' }]
let seq = 0
const newId = () => `id-${++seq}`
beforeEach(() => {
seq = 0
})
const doc = (): Doc => ({
title: { hu: 'Régi cím', en: 'Old title' },
items: {
hu: [{ value: 'Régi elem', id: 'h1' }, { value: 'Marad', id: 'h2' }],
en: [{ value: 'Old item', id: 'e1' }, { value: 'Stays', id: 'e2' }],
},
enTranslationStatus: 'ai-draft',
})
describe('reviseContent (MITHOME-129)', () => {
it('should replace exact Hungarian matches and their AI-draft English', () => {
const d = doc()
const report = reviseContent(d, PATHS, REVISIONS, [], newId)
expect(d.title).toEqual({ hu: 'Új cím', en: 'New title' })
expect(d.items).toEqual({
hu: [{ value: 'Új elem', id: 'h1' }, { value: 'Marad', id: 'h2' }],
en: [{ value: 'New item', id: 'e1' }, { value: 'Stays', id: 'e2' }],
})
expect(report).toEqual({ changed: 2, enKept: [] })
})
it('should leave text an editor already rewrote untouched', () => {
const d: Doc = { title: { hu: 'Szerkesztett cím', en: 'Edited title' } }
expect(reviseContent(d, PATHS, REVISIONS, [], newId)).toEqual({ changed: 0, enKept: [] })
expect(d.title).toEqual({ hu: 'Szerkesztett cím', en: 'Edited title' })
})
it('should keep and report a human English edit', () => {
const d: Doc = { title: { hu: 'Régi cím', en: 'Human title' } }
const report = reviseContent(d, PATHS, REVISIONS, [], newId)
expect(d.title).toEqual({ hu: 'Új cím', en: 'Human title' })
expect(report.enKept).toEqual(['Régi cím'])
})
it('should report a list item whose English row was edited by a person', () => {
const d = doc()
;(d.items as { en: { value: string }[] }).en[0].value = 'Human item'
const report = reviseContent(d, PATHS, REVISIONS, [], newId)
expect(report.enKept).toEqual(['Régi elem'])
expect((d.items as { en: { value: string }[] }).en[0].value).toBe('Human item')
})
it('should fill an empty English value', () => {
const d: Doc = { title: { hu: 'Régi cím' } }
reviseContent(d, PATHS, REVISIONS, [], newId)
expect(d.title).toEqual({ hu: 'Új cím', en: 'New title' })
})
it('should insert a list item after its anchor in both languages, once', () => {
const d = doc()
reviseContent(d, PATHS, REVISIONS, INSERTIONS, newId)
reviseContent(d, PATHS, REVISIONS, INSERTIONS, newId)
const items = d.items as { hu: { value: string }[]; en: { value: string }[] }
expect(items.hu.map((r) => r.value)).toEqual(['Új elem', 'Beszúrt', 'Marad'])
expect(items.en.map((r) => r.value)).toEqual(['New item', 'Inserted', 'Stays'])
})
it('should be idempotent', () => {
const d = doc()
reviseContent(d, PATHS, REVISIONS, INSERTIONS, newId)
const snapshot = JSON.stringify(d)
expect(reviseContent(d, PATHS, REVISIONS, INSERTIONS, newId)).toEqual({ changed: 0, enKept: [] })
expect(JSON.stringify(d)).toBe(snapshot)
})
it('should send an approved page back to AI draft when its English changed', () => {
const d = { ...doc(), enTranslationStatus: 'approved' }
reviseContent(d, PATHS, REVISIONS, [], newId)
expect(d.enTranslationStatus).toBe('ai-draft')
})
it('should keep an approved status when only Hungarian changed', () => {
const d: Doc = { title: { hu: 'Régi cím', en: 'Human title' }, enTranslationStatus: 'approved' }
reviseContent(d, PATHS, REVISIONS, [], newId)
expect(d.enTranslationStatus).toBe('approved')
})
it('should ignore legacy unwrapped values and lists without an anchor', () => {
const d: Doc = { title: 'Régi cím', items: { hu: [{ value: 'Más', id: 'x' }] } }
expect(reviseContent(d, PATHS, REVISIONS, INSERTIONS, newId)).toEqual({ changed: 0, enKept: [] })
})
})
-96
View File
@@ -1,96 +0,0 @@
/**
* MITHOME-129: exact-match content revision on localized fields, in place.
*
* Used by data migrations that correct published copy (e.g. service claims
* aligned with the real product range). Rules:
* - a value changes only when its current Hungarian text is EXACTLY the
* expected old text — anything an editor already rewrote is left alone;
* - English is replaced only when it is empty or still the old AI draft
* (`enWas`) — a human English edit is kept and reported instead;
* - if English changed on a page whose translation was approved, the page
* goes back to "ai-draft": the new English has not been reviewed yet.
* Works for localized text leaves and whole-array localized string lists
* ({ value } rows), where it can also insert a new item after an anchor.
*/
import { applyAll, isPlainObject, type LocalizedPath } from './localize-paths'
export type TextRevision = { from: string; to: string; enWas?: string; enTo: string }
export type ListInsertion = { afterHu: string; hu: string; afterEn: string; en: string }
export type RevisionReport = { changed: number; enKept: string[] }
type Row = { value?: unknown; id?: unknown }
const isEmpty = (value: unknown) => value === undefined || value === null || value === ''
function reviseText(value: Record<string, unknown>, revisions: readonly TextRevision[], report: RevisionReport) {
const revision = revisions.find((r) => r.from === value.hu)
if (!revision) return { hu: false, en: false }
value.hu = revision.to
if (isEmpty(value.en) || value.en === revision.enWas) {
value.en = revision.enTo
return { hu: true, en: true }
}
report.enKept.push(revision.from)
return { hu: true, en: false }
}
function reviseRows(rows: Row[], match: (text: string) => string | undefined): number {
let count = 0
for (const row of rows) {
const next = typeof row.value === 'string' ? match(row.value) : undefined
if (next !== undefined) {
row.value = next
count += 1
}
}
return count
}
function insertRow(rows: Row[], after: string, text: string, newId: () => string): boolean {
if (rows.some((row) => row.value === text)) return false
const index = rows.findIndex((row) => row.value === after)
if (index === -1) return false
rows.splice(index + 1, 0, { value: text, id: newId() })
return true
}
export function reviseContent(
doc: Record<string, unknown>,
paths: readonly LocalizedPath[],
revisions: readonly TextRevision[],
insertions: readonly ListInsertion[],
newId: () => string,
): RevisionReport {
const report: RevisionReport = { changed: 0, enKept: [] }
let enChanged = false
applyAll(doc, paths, (value) => {
if (!isPlainObject(value)) return { value, changed: false }
if (typeof value.hu === 'string') {
const result = reviseText(value, revisions, report)
enChanged ||= result.en
if (result.hu) report.changed += 1
return { value, changed: result.hu }
}
if (!Array.isArray(value.hu)) return { value, changed: false }
const hu = value.hu as Row[]
const en = Array.isArray(value.en) ? (value.en as Row[]) : undefined
const huMatched = revisions.filter((r) => hu.some((row) => row.value === r.from))
let count = reviseRows(hu, (text) => revisions.find((r) => r.from === text)?.to)
const enCount = en ? reviseRows(en, (text) => revisions.find((r) => r.enWas !== undefined && r.enWas === text)?.enTo) : 0
// A Hungarian row changed but its English row was not the old AI draft.
if (en && enCount < huMatched.length) report.enKept.push(...huMatched.map((r) => r.from).slice(enCount))
for (const insertion of insertions) {
if (insertRow(hu, insertion.afterHu, insertion.hu, newId)) count += 1
if (en && insertRow(en, insertion.afterEn, insertion.en, newId)) enChanged = true
}
enChanged ||= enCount > 0
report.changed += count
return { value, changed: count > 0 || enCount > 0 }
})
if (enChanged && doc.enTranslationStatus === 'approved') doc.enTranslationStatus = 'ai-draft'
return report
}
-95
View File
@@ -1,95 +0,0 @@
import { fillEnglishDraft } from './english-draft'
import { collectLocalizedPaths } from './localize-paths'
type Doc = Record<string, unknown>
const FIELDS = [
{ name: 'title', type: 'text', localized: true },
{ name: 'paragraphs', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] },
{ name: 'items', type: 'array', fields: [{ name: 'icon', type: 'text' }, { name: 'label', type: 'text', localized: true }] },
]
const PATHS = collectLocalizedPaths(FIELDS)
const MEMORY = { Cím: 'Title', Egy: 'One', Kettő: 'Two', Címke: 'Label' }
let seq = 0
const newId = () => `new-${++seq}`
beforeEach(() => {
seq = 0
})
const doc = (): Doc => ({
title: { hu: 'Cím' },
paragraphs: { hu: [{ value: 'Egy', id: 'p1' }, { value: 'Kettő', id: 'p2' }] },
items: [{ id: 'r1', icon: 'star', label: { hu: 'Címke' } }],
})
describe('fillEnglishDraft (MITHOME-113)', () => {
it('should fill empty English values from the memory and mark the page as AI draft', () => {
const d = doc()
const report = fillEnglishDraft(d, PATHS, MEMORY, newId)
expect(report).toEqual({ filled: 3, unmatched: [] })
expect(d.title).toEqual({ hu: 'Cím', en: 'Title' })
expect(d.paragraphs).toEqual({
hu: [{ value: 'Egy', id: 'p1' }, { value: 'Kettő', id: 'p2' }],
en: [{ value: 'One', id: 'new-1' }, { value: 'Two', id: 'new-2' }],
})
expect(d.items).toEqual([{ id: 'r1', icon: 'star', label: { hu: 'Címke', en: 'Label' } }])
expect(d.enTranslationStatus).toBe('ai-draft')
})
it('should leave an edited Hungarian text without English and report it', () => {
const d = doc()
d.title = { hu: 'Új cím' }
const report = fillEnglishDraft(d, PATHS, MEMORY, newId)
expect(d.title).toEqual({ hu: 'Új cím' })
expect(report.unmatched).toEqual(['Új cím'])
})
it('should never overwrite an existing English value', () => {
const d = doc()
d.title = { hu: 'Cím', en: 'Human title' }
fillEnglishDraft(d, PATHS, MEMORY, newId)
expect(d.title).toEqual({ hu: 'Cím', en: 'Human title' })
})
it('should not fill a list partially', () => {
const d = doc()
d.paragraphs = { hu: [{ value: 'Egy', id: 'p1' }, { value: 'Ismeretlen', id: 'p2' }] }
const report = fillEnglishDraft(d, PATHS, MEMORY, newId)
expect(d.paragraphs).not.toHaveProperty('en')
expect(report.unmatched).toHaveLength(1)
})
it('should treat an empty English list as empty', () => {
const d = doc()
d.paragraphs = { hu: [{ value: 'Egy', id: 'p1' }], en: [] }
fillEnglishDraft(d, PATHS, MEMORY, newId)
expect((d.paragraphs as { en: unknown[] }).en).toHaveLength(1)
})
it('should be idempotent', () => {
const d = doc()
fillEnglishDraft(d, PATHS, MEMORY, newId)
const snapshot = JSON.stringify(d)
expect(fillEnglishDraft(d, PATHS, MEMORY, newId)).toEqual({ filled: 0, unmatched: [] })
expect(JSON.stringify(d)).toBe(snapshot)
})
it.each(['approved', 'ai-draft'])('should keep an existing "%s" status', (status) => {
const d = { ...doc(), enTranslationStatus: status }
fillEnglishDraft(d, PATHS, MEMORY, newId)
expect(d.enTranslationStatus).toBe(status)
})
it('should not change the status when nothing was filled', () => {
const d: Doc = { title: { hu: 'Ismeretlen' }, enTranslationStatus: 'none' }
fillEnglishDraft(d, PATHS, MEMORY, newId)
expect(d.enTranslationStatus).toBe('none')
})
it('should skip empty Hungarian values and legacy (unwrapped) strings', () => {
const d: Doc = { title: 'Cím', paragraphs: { hu: [] } }
expect(fillEnglishDraft(d, PATHS, MEMORY, newId)).toEqual({ filled: 0, unmatched: [] })
})
})
-54
View File
@@ -1,54 +0,0 @@
/**
* MITHOME-113: fills empty English values from the hu -> en translation
* memory (src/content/translations/en.json), in place.
*
* Rules (design D5):
* - only an EMPTY `en` is filled — human English edits are never touched;
* - only when the current `hu` text is EXACTLY a memory key — a Hungarian
* text edited after translation gets no (stale) English;
* - a whole-array localized list is filled all-or-nothing, so a list is
* never half English;
* - `enTranslationStatus` goes none -> ai-draft when something was filled;
* "approved" is never set here.
*/
import { applyAll, isPlainObject, type LocalizedPath } from './localize-paths'
type Row = { value?: unknown; id?: unknown }
export type DraftReport = { filled: number; unmatched: string[] }
const isEmpty = (value: unknown) =>
value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)
function translateList(rows: Row[], memory: Record<string, string>, newId: () => string): Row[] | undefined {
const values = rows.map((row) => row.value)
if (!values.every((v): v is string => typeof v === 'string' && v in memory)) return undefined
return values.map((v) => ({ value: memory[v], id: newId() }))
}
export function fillEnglishDraft(
doc: Record<string, unknown>,
paths: readonly LocalizedPath[],
memory: Record<string, string>,
newId: () => string,
): DraftReport {
const report: DraftReport = { filled: 0, unmatched: [] }
applyAll(doc, paths, (value) => {
if (!isPlainObject(value) || !isEmpty(value.en) || isEmpty(value.hu)) return { value, changed: false }
const hu = value.hu
const en =
typeof hu === 'string' ? memory[hu] : Array.isArray(hu) ? translateList(hu as Row[], memory, newId) : undefined
if (en === undefined) {
report.unmatched.push(typeof hu === 'string' ? hu : JSON.stringify(hu))
return { value, changed: false }
}
value.en = en
report.filled += 1
return { value, changed: true }
})
if (report.filled > 0 && (isEmpty(doc.enTranslationStatus) || doc.enTranslationStatus === 'none')) {
doc.enTranslationStatus = 'ai-draft'
}
return report
}
-140
View File
@@ -1,140 +0,0 @@
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 look through unnamed row/collapsible wrappers', () => {
expect(
collectLocalizedPaths([
{ name: 'g', type: 'group', fields: [{ type: 'row', fields: [{ name: 't', type: 'text', localized: true }] }] },
{ type: 'collapsible', fields: [{ name: 'u', type: 'text', localized: true }] },
]),
).toEqual([['g', 't'], ['u']])
})
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'])
})
})
-119
View File
@@ -1,119 +0,0 @@
/**
* 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', 'blocks'])
/** Unnamed layout wrappers: their children are stored at the same level. */
const TRANSPARENT_CONTAINERS = new Set(['row', 'collapsible'])
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 (TRANSPARENT_CONTAINERS.has(field.type)) {
paths.push(...collectLocalizedPaths(field.fields ?? [], prefix))
continue
}
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
}
export type Transform = (value: unknown) => { value: unknown; changed: boolean }
export 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.
/** Applies `transform` to every value at `paths`, in place; returns the change count. */
export 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 },
)
}
-82
View File
@@ -1,82 +0,0 @@
/**
* Shared plumbing for Payload data migrations (MITHOME-111/112/113/123).
*
* Applies `transform` in place to a global's or collection's field data —
* the stored document(s) AND the draft/version records (`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>
export type DocTarget = { kind: 'global' | 'collection'; slug: string }
type RewriteOptions = {
/**
* 'all' rewrites the whole history (shape changes must reach every
* version); 'latest' only the working copy the admin form loads (content
* imports should not rewrite history).
*/
versions?: 'all' | 'latest'
}
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 rewriteDocs(
{ payload, session }: Args,
target: DocTarget,
keys: readonly string[],
transform: (data: Data) => number,
{ versions: scope = 'all' }: RewriteOptions = {},
): Promise<number> {
const db = payload.db as unknown as MongooseAdapter
let changed = 0
const main =
target.kind === 'global' ? db.globals.collection : db.collections[target.slug]?.collection
const mainFilter = target.kind === 'global' ? { globalType: target.slug } : {}
if (main) {
for await (const doc of main.find(mainFilter, { session })) {
const count = transform(doc)
if (count > 0) {
await main.updateOne({ _id: doc._id }, { $set: pick(doc, keys) }, { session })
changed += count
}
}
}
const versions = db.versions[target.slug]
if (versions) {
const filter = scope === 'latest' ? { latest: true } : {}
for await (const doc of versions.collection.find(filter, { 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
}
/** Global shorthand kept for the MITHOME-111/123 migrations. */
export function rewriteGlobalDocs(
args: Args,
slug: string,
keys: readonly string[],
transform: (data: Data) => number,
): Promise<number> {
return rewriteDocs(args, { kind: 'global', slug }, keys, transform)
}
-162
View File
@@ -1,162 +0,0 @@
// Mock the MongoDB module completely
const mockDb = {
collection: jest.fn().mockReturnValue({
findOne: jest.fn(),
insertOne: jest.fn(),
updateOne: jest.fn(),
deleteOne: jest.fn()
}),
admin: jest.fn().mockReturnValue({
ping: jest.fn().mockResolvedValue(true)
})
}
const mockClient = {
connect: jest.fn(),
close: jest.fn().mockResolvedValue(undefined),
db: jest.fn().mockReturnValue(mockDb)
}
const mockMongoLoggerError = jest.fn()
jest.mock('./logger', () => ({
dbLogger: { error: mockMongoLoggerError },
getSafeErrorDetails: (error: unknown) => ({
errorName: error instanceof Error ? error.name : 'Error'
})
}))
// The connect method should resolve to the client itself
mockClient.connect.mockResolvedValue(mockClient)
const MockedMongoClient = jest.fn().mockImplementation(() => mockClient)
// Mock the mongodb module
jest.mock('mongodb', () => ({
MongoClient: MockedMongoClient
}))
// Restore environment before tests
const originalEnv = process.env
describe('MongoDB Connection (Unit Tests)', () => {
beforeEach(() => {
jest.resetModules()
process.env = {
...originalEnv,
MONGODB_URI: 'mongodb://localhost:27017/test',
MONGODB_DB: 'test'
}
jest.clearAllMocks()
mockMongoLoggerError.mockReset()
// Reset the mock implementation
MockedMongoClient.mockImplementation(() => mockClient as any)
mockClient.db.mockReturnValue(mockDb)
})
afterEach(() => {
process.env = originalEnv
})
describe('MongoDB URI validation', () => {
it('should throw error when MONGODB_URI is not set', () => {
// This test is tricky because the module is cached
// We'll test this by clearing the module cache and mocking process.env
const originalMongodbUri = process.env.MONGODB_URI
delete process.env.MONGODB_URI
// Clear module cache to force re-import
jest.resetModules()
const { getClientPromise } = require('./mongodb')
expect(() => getClientPromise()).toThrow('Please add MONGODB_URI to your environment variables')
// Restore environment
process.env.MONGODB_URI = originalMongodbUri
})
})
describe('Database connection', () => {
it('should create MongoClient with correct URI and options', async () => {
// Import after setting up the mock
const { getClientPromise } = await import('./mongodb')
await getClientPromise()
expect(MockedMongoClient).toHaveBeenCalledWith(
process.env.MONGODB_URI,
expect.objectContaining({
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000
})
)
})
it('should return database instance', async () => {
const { getDb } = await import('./mongodb')
const result = await getDb()
expect(result).toBe(mockDb)
expect(typeof result.collection).toBe('function')
})
it('should check MongoDB connection successfully', async () => {
const { checkMongoConnection } = await import('./mongodb')
const result = await checkMongoConnection()
expect(result).toBe(true)
})
it('should return false on MongoDB connection failure', async () => {
// Create a failing client
const failingClient = {
connect: jest.fn().mockRejectedValue(new Error('Connection failed')),
db: jest.fn().mockRejectedValue(new Error('Connection failed')),
close: jest.fn()
}
MockedMongoClient.mockImplementation(() => failingClient as any)
// Clear the module cache and re-import
jest.resetModules()
const { checkMongoConnection } = await import('./mongodb')
const result = await checkMongoConnection()
expect(result).toBe(false)
expect(mockMongoLoggerError).toHaveBeenCalledWith('MongoDB connection check failed', { errorName: 'Error' })
})
})
describe('Connection reuse and caching', () => {
it('should reuse the same MongoClient instance for multiple calls', async () => {
const { getClientPromise } = await import('./mongodb')
const client1 = await getClientPromise()
const client2 = await getClientPromise()
// Should be the same client instance
expect(client1).toBe(client2)
})
it('should not cache a rejected connection promise and retry on next call', async () => {
// First attempt fails (e.g. transient DB outage at startup)
const failingClient = {
connect: jest.fn().mockRejectedValueOnce(new Error('transient failure')),
db: jest.fn(),
close: jest.fn()
}
MockedMongoClient.mockImplementation(() => failingClient)
const { getClientPromise } = await import('./mongodb')
await expect(getClientPromise()).rejects.toThrow('transient failure')
// Second call must retry instead of replaying the cached rejection
failingClient.connect.mockResolvedValueOnce(failingClient as any)
await expect(getClientPromise()).resolves.toBe(failingClient)
})
})
})
-70
View File
@@ -1,70 +0,0 @@
import { MongoClient, Db } from 'mongodb'
import { dbLogger, getSafeErrorDetails } from './logger'
// WHY this file only exposes getDb/checkMongoConnection now: it used to also
// export getCollection(), used by src/app/api/contact/route.ts for a raw,
// Payload-external `contact_submissions` collection. MITHOME-94 moved that
// write to a proper Payload collection (ContactSubmissions) via the Local
// API — getDb() itself stays alive only for /api/health's connectivity check.
const options = {
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
}
let clientPromise: Promise<MongoClient> | undefined
function createClientPromise(): Promise<MongoClient> {
const uri = process.env.MONGODB_URI
if (!uri) {
throw new Error('Please add MONGODB_URI to your environment variables')
}
return new MongoClient(uri, options).connect()
}
export function getClientPromise(): Promise<MongoClient> {
// In development mode, use a global variable so that the client is not recreated between hot reloads.
// The connection is intentionally created lazily: `next build` must not require runtime secrets.
if (process.env.NODE_ENV === 'development') {
// @ts-expect-error - Global variable for development hot reload
if (!global._mongoClientPromise) {
// @ts-expect-error - Global variable for development hot reload
global._mongoClientPromise = createClientPromise().catch((error: Error) => {
// A rejected promise must not stay cached: a transient failure would
// otherwise break every subsequent request in this process.
// @ts-expect-error - Global variable for development hot reload
global._mongoClientPromise = undefined
throw error
})
}
// @ts-expect-error - Global variable for development hot reload
return global._mongoClientPromise
}
clientPromise ??= createClientPromise().catch((error: Error) => {
// See the development branch above: drop the cached rejection so the next
// call can retry the connection.
clientPromise = undefined
throw error
})
return clientPromise
}
export async function getDb(): Promise<Db> {
const client = await getClientPromise()
return client.db(process.env.MONGODB_DB || 'mozdit')
}
// Health check for MongoDB connection
export async function checkMongoConnection(): Promise<boolean> {
try {
const db = await getDb()
await db.admin().ping()
return true
} catch (error) {
dbLogger.error('MongoDB connection check failed', getSafeErrorDetails(error))
return false
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,42 +0,0 @@
/**
* MITHOME-133: az Atlantisz Horgászüdülő és Halásztanya bejegyzést
* "Egyeztetés alatt" állapotba teszi, amíg a logó (fehér felirat, világos
* háttéren olvashatatlan) és a hivatalos név rendeződik.
*
* WHY külön migráció: a 20260929_partner_references a stagingen már
* "granted" állapottal lefutott; a még le nem futott környezetekben az
* eleve "pending"-et állít. Csak a saját, automatikus besorolást írja
* felül (egyező permissionReference) — egy későbbi admin-döntéshez nem nyúl.
*/
import type { MigrateDownArgs, MigrateUpArgs } from '@payloadcms/db-mongodb'
import { rewriteDocs } from '../lib/migrate-global-docs'
const NAME = 'Atlantisz Horgászüdülő és Halásztanya'
const AUTO_GRANTED_REFERENCE = 'Írásos engedély megvan (tulajdonosi megerősítés, 2026-09-29)'
export const PENDING_REFERENCE = 'Írásos engedély megvan; logó és hivatalos név egyeztetés alatt (MITHOME-133)'
export function markAtlantiszPending(doc: Record<string, unknown>): number {
if (doc.name !== NAME || doc.publicationPermission !== 'granted' || doc.permissionReference !== AUTO_GRANTED_REFERENCE) {
return 0
}
doc.publicationPermission = 'pending'
doc.permissionReference = PENDING_REFERENCE
return 1
}
export async function up(args: MigrateUpArgs): Promise<void> {
const changed = await rewriteDocs(
args,
{ kind: 'collection', slug: 'partners' },
['publicationPermission', 'permissionReference'],
markAtlantiszPending,
{ versions: 'latest' },
)
args.payload.logger.info(`MITHOME-133 Atlantisz: ${changed} record(s) set to pending`)
}
/** DECISION: no automatic down — set the status in the admin instead. */
export async function down(args: MigrateDownArgs): Promise<void> {
args.payload.logger.warn('MITHOME-133 Atlantisz: down is a no-op — change the status in the admin instead')
}
@@ -1,72 +0,0 @@
/**
* 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)
}
@@ -1,76 +0,0 @@
/**
* MITHOME-113: AI-draft angol tartalom importja a fordítási memóriából
* (src/content/translations/en.json) minden Globalra és jogi oldalra.
*
* Csak üres angol értéket tölt ki, pontos magyar egyezés esetén (lásd
* src/lib/english-draft.ts); a kitöltött oldalak állapota `ai-draft` lesz,
* így a publikus /en oldal jóváhagyásig továbbra is magyar (readGated).
*
* WHY csak a legutóbbi verzió (+ a publikált dokumentum): az admin a
* legutóbbi verziót tölti be szerkesztéskor; a régebbi verziók történeti
* rekordok, azokat egy tartalmi import nem írja át.
*
* WHY előbb wrapLocalized: így független a lokalizációs migrációk
* sorrendjétől — a prodMigrations utánuk futtatja, a Payload CLI viszont
* fájlnév szerint (ábécé) rendez, és ott ez futna elsőként.
*/
import type { MigrateDownArgs, MigrateUpArgs } from '@payloadcms/db-mongodb'
import { randomBytes } from 'crypto'
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 { LegalPages } from '../collections/LegalPages'
import translations from '../content/translations/en.json'
import { fillEnglishDraft } from '../lib/english-draft'
import { collectLocalizedPaths, topLevelKeys, wrapLocalized } from '../lib/localize-paths'
import { rewriteDocs, type DocTarget } from '../lib/migrate-global-docs'
const MEMORY: Record<string, string> = translations
const TARGETS: readonly { target: DocTarget; fields: unknown[] }[] = [
...[Home, About, Services, Contact, Common].map((g) => ({
target: { kind: 'global', slug: g.slug } as const,
fields: g.fields,
})),
{ target: { kind: 'collection', slug: LegalPages.slug }, fields: LegalPages.fields },
]
// Array row ids are stored as 24-hex strings (ObjectId-shaped), like Payload's own.
const newId = () => randomBytes(12).toString('hex')
export async function up(args: MigrateUpArgs): Promise<void> {
for (const { target, fields } of TARGETS) {
const paths = collectLocalizedPaths(fields as never)
const unmatched = new Set<string>()
let filled = 0
await rewriteDocs(
args,
target,
[...topLevelKeys(paths), 'enTranslationStatus'],
(data) => {
const wrapped = wrapLocalized(data, paths)
const report = fillEnglishDraft(data, paths, MEMORY, newId)
report.unmatched.forEach((text) => unmatched.add(text))
filled += report.filled
return wrapped + report.filled
},
{ versions: 'latest' },
)
args.payload.logger.info(
`MITHOME-113 English AI draft: ${target.slug} — ${filled} value(s) filled, ${unmatched.size} Hungarian text(s) without translation`,
)
for (const text of unmatched) {
args.payload.logger.warn(`MITHOME-113 no translation (${target.slug}): ${text.slice(0, 120)}`)
}
}
}
/**
* DECISION: no automatic down — English values cannot be told apart from
* later human edits. Roll back by restoring the pre-deploy DB dump.
*/
export async function down(args: MigrateDownArgs): Promise<void> {
args.payload.logger.warn('MITHOME-113 English AI draft: down is a no-op — restore the pre-deploy dump instead')
}
@@ -1,52 +0,0 @@
/**
* 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.
*
* 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 } 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'
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
async function migrateAll(args: Args, transform: Transform) {
for (const global of LOCALIZED_GLOBALS) {
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`)
}
}
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))
}
@@ -1,29 +0,0 @@
/**
* MITHOME-112: a LegalPages mezők utólagos `localized: true` jelölése után a
* meglévő értékeket `{ hu: érték }` alakba csomagolja — minden jogi oldalon
* és a teljes verziótörténetben. Ugyanaz a minta, mint a Globaloknál
* (MITHOME-111, 20260929_localize_globals.ts); idempotens.
*/
import type { MigrateDownArgs, MigrateUpArgs } from '@payloadcms/db-mongodb'
import { LegalPages } from '../collections/LegalPages'
import { collectLocalizedPaths, topLevelKeys, unwrapLocalized, wrapLocalized } from '../lib/localize-paths'
import { rewriteDocs } from '../lib/migrate-global-docs'
const PATHS = collectLocalizedPaths(LegalPages.fields as never)
const TARGET = { kind: 'collection', slug: LegalPages.slug } as const
async function migrate(args: MigrateUpArgs | MigrateDownArgs, direction: 'up' | 'down') {
const transform = direction === 'up' ? wrapLocalized : unwrapLocalized
const changed = await rewriteDocs(args, TARGET, topLevelKeys(PATHS), (data) => transform(data, PATHS))
args.payload.logger.info(`MITHOME-112 locale migration: ${LegalPages.slug} — ${changed} value(s) rewritten`)
}
export async function up(args: MigrateUpArgs): Promise<void> {
await migrate(args, 'up')
}
/** TRADEOFF: drops every non-hu value — restore from a DB dump instead if possible. */
export async function down(args: MigrateDownArgs): Promise<void> {
await migrate(args, 'down')
}
@@ -1,101 +0,0 @@
/**
* MITHOME-131: partner- és referenciaszabályok bevezetése a meglévő adaton.
*
* - A Partners bejegyzések kapcsolati kategóriát és közzétételi engedélyt
* kapnak. A tulajdonos 2026-09-29-i megerősítése szerint az Angele
* Pihenőház ÜGYFÉL (nem partner), és írásos engedély van a név- és
* logóhasználatra. Minden más, kategória nélküli bejegyzés "nincs
* engedély" állapotba kerül, tehát rejtve marad, amíg valaki be nem sorolja.
* - A Home global megkapja a korábban beégetett szekció-szövegeket
* (hu + en), csak ha még üresek.
*
* Csak a dokumentumot és a legutóbbi verziót írja. Idempotens.
*/
import type { MigrateDownArgs, MigrateUpArgs } from '@payloadcms/db-mongodb'
import { rewriteDocs } from '../lib/migrate-global-docs'
type Data = Record<string, unknown>
export const CONFIRMED_CLIENT_REFERENCES = [
{
name: 'Angele Pihenőház',
permission: 'granted',
permissionReference: 'Írásos engedély megvan (tulajdonosi megerősítés, 2026-09-29)',
},
{
// Contracted client (its site runs on our infrastructure) — a client
// reference, not a partner, per the research's categories.
// Kept "pending" until the logo (white text, unreadable on a light
// background) and the official name are settled (MITHOME-133).
name: 'Atlantisz Horgászüdülő és Halásztanya',
permission: 'pending',
permissionReference: 'Írásos engedély megvan; logó és hivatalos név egyeztetés alatt (MITHOME-133)',
},
] as const
type Copy = Record<'hu' | 'en', string>
export const REFERENCES_SECTION_COPY: {
clientsTitle: Copy
clientsSubtitle: Copy
partnersTitle: Copy
partnersSubtitle: Copy
relationshipLabels: Record<'technologyPartner' | 'infrastructure' | 'supplier' | 'technologyUsed' | 'professionalPartner', Copy>
} = {
clientsTitle: { hu: 'Akik már minket választottak', en: 'Clients who chose us' },
clientsSubtitle: { hu: 'Ügyfeleink, akik hozzájárultak a bemutatásukhoz', en: 'Clients who agreed to be featured' },
partnersTitle: { hu: 'Partnereink és technológiai hátterünk', en: 'Our partners and technology' },
partnersSubtitle: { hu: 'Szervezetek, amelyek közreműködnek a szolgáltatásainkban', en: 'Organisations that contribute to our services' },
relationshipLabels: {
technologyPartner: { hu: 'Technológiai partner', en: 'Technology partner' },
infrastructure: { hu: 'Technológiai háttér', en: 'Infrastructure provider' },
supplier: { hu: 'Beszállító', en: 'Supplier' },
technologyUsed: { hu: 'Általunk használt technológia', en: 'Technology we use' },
professionalPartner: { hu: 'Szakmai partner', en: 'Professional partner' },
},
}
/** The same copy as stored by Payload for localized fields: { hu, en }. */
function localizedCopy(): Data {
const { relationshipLabels, ...titles } = REFERENCES_SECTION_COPY
return { ...titles, relationshipLabels: { ...relationshipLabels } }
}
export function classifyPartner(doc: Data): number {
if (doc.relationship) return 0
const confirmed = CONFIRMED_CLIENT_REFERENCES.find((c) => c.name === doc.name)
if (confirmed) {
doc.relationship = 'client-reference'
doc.publicationPermission = confirmed.permission
doc.permissionReference = confirmed.permissionReference
} else {
doc.publicationPermission = 'none'
}
return 1
}
export function seedReferencesSection(doc: Data): number {
if (doc.referencesSection) return 0
doc.referencesSection = localizedCopy()
return 1
}
export async function up(args: MigrateUpArgs): Promise<void> {
const partners = await rewriteDocs(
args,
{ kind: 'collection', slug: 'partners' },
['relationship', 'publicationPermission', 'permissionReference'],
classifyPartner,
{ versions: 'latest' },
)
const home = await rewriteDocs(args, { kind: 'global', slug: 'home' }, ['referencesSection'], seedReferencesSection, {
versions: 'latest',
})
args.payload.logger.info(`MITHOME-131 references: ${partners} partner record(s) classified, ${home} home record(s) seeded`)
}
/** DECISION: no automatic down — restore the pre-deploy dump instead. */
export async function down(args: MigrateDownArgs): Promise<void> {
args.payload.logger.warn('MITHOME-131 references: down is a no-op — restore the pre-deploy dump instead')
}
@@ -1,122 +0,0 @@
/**
* MITHOME-129: a weboldal szolgáltatási állításainak összehangolása a valós
* termékkörrel (docs/termekkor-es-szerverkapacitas-elemzes.md, 9. fejezet,
* C1–C14). A jogi szövegek (C15 ÁSZF, C16 Adatvédelem) NEM itt változnak —
* azok jogi átnézés után jönnek.
*
* Csak pontos magyar egyezésnél cserél; az angolt csak akkor, ha még a régi
* AI-draft (src/lib/content-revision.ts). Csak a publikált dokumentumot és a
* legutóbbi verziót írja, a történetet nem. Idempotens.
*
* DECISION: a mIT csomagneveket itt nem írjuk a szövegbe (C4, C7) — a nevek
* bevezetése előtt védjegyjogászi vizsgálat kell (PLATFM-3); a nevek a
* „Csomagok” oldallal (MITHOME-130) kerülnek ki.
*/
import type { MigrateDownArgs, MigrateUpArgs } from '@payloadcms/db-mongodb'
import { randomBytes } from 'crypto'
import { Home } from '../globals/Home'
import { About } from '../globals/About'
import { Services } from '../globals/Services'
import { Contact } from '../globals/Contact'
import translations from '../content/translations/en.json'
import { reviseContent, type ListInsertion, type TextRevision } from '../lib/content-revision'
import { collectLocalizedPaths, topLevelKeys } from '../lib/localize-paths'
import { rewriteDocs } from '../lib/migrate-global-docs'
const MEMORY: Record<string, string> = translations
/** [old hu, new hu, new en] — the old English is looked up in the memory. */
const CHANGES: readonly [string, string, string][] = [
// C1
['Éves szinten 99,9%-os rendelkezésre állási cél, tervezett karbantartások kivételével',
'Éves szinten 99,5%-os rendelkezésre állási cél, az előre bejelentett karbantartások kivételével',
'99.5% annual availability target, excluding pre-announced maintenance'],
// C2
['24/7 monitoring biztosítja szolgáltatásaink közel 100%-os rendelkezésre állását.',
'0–24 órás automatizált felügyelet riasztással és gyors hibaelhárítással.',
'Round-the-clock automated monitoring with alerting and fast troubleshooting.'],
// C3
['Weboldalak biztonságos és gyors üzemeltetése SSD tárolással, automatikus biztonsági mentéssel és 24/7 monitoringgal. Támogatjuk a PHP, Python, Node.js technológiákat és MySQL/PostgreSQL adatbázisokat.',
'Weboldalak biztonságos és gyors üzemeltetése Enterprise SSD tárolással, hardveres RAID-1 tükrözéssel, napi külső mentéssel és 0–24 órás automatizált felügyelettel. PHP (több verzió) és MariaDB/MySQL adatbázis.',
'Secure, fast website hosting on enterprise SSD storage with hardware RAID-1 mirroring, daily off-site backups and round-the-clock automated monitoring. PHP (multiple versions) and MariaDB/MySQL databases.'],
// C4
['SSD tárhely 1GB-tól 100GB-ig', 'Enterprise SSD tárhely: 3 GB vagy 8 GB, csomagtól függően', 'Enterprise SSD storage: 3 GB or 8 GB, depending on the plan'],
// C5
['Havi adatforgalom: korlátlan', 'Bőséges havi adatforgalom, méltányos használat mellett', 'Generous monthly traffic under fair use'],
// C6
['Automatikus napi biztonsági mentés',
'Automatikus napi mentés független, külső mentési szerverre, 7 napos visszaállítással',
'Automatic daily backup to an independent off-site server, with 7-day restore'],
// C7
['1GB–20GB tárhelyet fiókként',
'Levéltárhely csomagszinten: 1 GB vagy 4 GB, szabadon elosztva a fiókok között',
'Mail storage per plan: 1 GB or 4 GB, freely shared between mailboxes'],
// C8
['Backup és archiválás ', 'Napi mentés, 7 napos visszaállítással', 'Daily backup with 7-day restore'],
// C10
['Teljes DNS kezelés domain regisztrációval, átvitellel és professzionális beállításokkal. Gyors propagáció és megbízható névszerverek világszerte.',
'Teljes DNS-kezelés domainregisztrációval, átvitellel és szakszerű beállításokkal. Redundáns elsődleges és másodlagos névszerver két független szerveren.',
'Complete DNS management including domain registration, transfers and professional configuration. Redundant primary and secondary name servers on two independent servers.'],
// C11
['DNSSEC támogatás', 'DNSSEC egyedi egyeztetés alapján', 'DNSSEC on request'],
// C12
['API hozzáférés fejlesztőknek', 'Egyedi API-integráció egyeztetés alapján', 'Custom API integration on request'],
// C13
['Azonnali beavatkozás', '0–24 órás riasztás, a beavatkozás tipikusan 2–4 órán belül megkezdődik', '24/7 alerting; work typically starts within 2–4 hours'],
// C14a–d
['24 órán belüli válasz', 'Munkanapokon 24 órán belüli válasz', 'Reply within 24 hours on business days'],
['Munkaidőben elérhető', 'Hétköznap 8–17 óra között', 'Weekdays 8:00–17:00'],
['24 órán belül válaszolunk', 'Munkanapokon 24 órán belül válaszolunk', 'We reply within 24 hours on business days'],
['Email üzenetekre 24 órán belül, sürgős esetekben telefonon is elérhetők vagyunk.',
'Munkanapokon 24 órán belül válaszolunk. Kritikus üzemzavar esetén 0–24 órás riasztási és beavatkozási rend működik.',
'We reply within 24 hours on business days. For critical outages, a 24/7 alerting and response process is in place.'],
]
export const SERVICE_CLAIM_REVISIONS: readonly TextRevision[] = CHANGES.map(([from, to, enTo]) => ({
from,
to,
enWas: MEMORY[from],
enTo,
}))
/** C9 — new e-mail feature, placed right after the (revised) C8 item. */
export const SERVICE_CLAIM_INSERTIONS: readonly ListInsertion[] = [
{
afterHu: 'Napi mentés, 7 napos visszaállítással',
hu: 'Automatikus figyelmeztetés 90%-os postafiók-telítettségnél',
afterEn: 'Daily backup with 7-day restore',
en: 'Automatic warning when a mailbox is 90% full',
},
]
const newId = () => randomBytes(12).toString('hex')
export async function up(args: MigrateUpArgs): Promise<void> {
for (const global of [Home, About, Services, Contact]) {
const paths = collectLocalizedPaths(global.fields as never)
const enKept = new Set<string>()
let changed = 0
await rewriteDocs(
args,
{ kind: 'global', slug: global.slug },
[...topLevelKeys(paths), 'enTranslationStatus'],
(data) => {
const report = reviseContent(data, paths, SERVICE_CLAIM_REVISIONS, SERVICE_CLAIM_INSERTIONS, newId)
report.enKept.forEach((text) => enKept.add(text))
changed += report.changed
return report.changed
},
{ versions: 'latest' },
)
args.payload.logger.info(`MITHOME-129 service claims: ${global.slug} — ${changed} text(s) revised`)
for (const text of enKept) {
args.payload.logger.warn(`MITHOME-129 English kept (edited by a person), review manually (${global.slug}): ${text.slice(0, 100)}`)
}
}
}
/** DECISION: no automatic down — restore the pre-deploy dump instead. */
export async function down(args: MigrateDownArgs): Promise<void> {
args.payload.logger.warn('MITHOME-129 service claims: down is a no-op — restore the pre-deploy dump instead')
}
+5 -58
View File
@@ -1,62 +1,9 @@
import * as migration_20260929_localize_globals from './20260929_localize_globals'
import * as migration_20260929_cta_page_links from './20260929_cta_page_links'
import * as migration_20260929_localize_legal_pages from './20260929_localize_legal_pages'
import * as migration_20260929_en_ai_draft from './20260929_en_ai_draft'
import * as migration_20260929_service_claims from './20260929_service_claims'
import * as migration_20260929_partner_references from './20260929_partner_references'
import * as migration_20260929_atlantisz_pending from './20260929_atlantisz_pending'
import * as migration_20260929_hosting_plans from './20260929_hosting_plans'
import * as migration_20260929_200306_initial from './20260929_200306_initial';
/**
* 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',
up: migration_20260929_200306_initial.up,
down: migration_20260929_200306_initial.down,
name: '20260929_200306_initial'
},
{
// 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',
},
{
// MITHOME-112 — LegalPages counterpart of the globals locale migration.
up: migration_20260929_localize_legal_pages.up,
down: migration_20260929_localize_legal_pages.down,
name: '20260929_localize_legal_pages',
},
{
// MITHOME-113 — needs both locale migrations above ({ hu } shapes).
up: migration_20260929_en_ai_draft.up,
down: migration_20260929_en_ai_draft.down,
name: '20260929_en_ai_draft',
},
{
// MITHOME-129 — after the English import (revises the AI-draft English too).
up: migration_20260929_service_claims.up,
down: migration_20260929_service_claims.down,
name: '20260929_service_claims',
},
{
// MITHOME-131 — partner categories/permissions + references section copy.
up: migration_20260929_partner_references.up,
down: migration_20260929_partner_references.down,
name: '20260929_partner_references',
},
{
// MITHOME-133 — Atlantisz on hold until logo and official name are settled.
up: migration_20260929_atlantisz_pending.up,
down: migration_20260929_atlantisz_pending.down,
name: '20260929_atlantisz_pending',
},
{
// MITHOME-130 — hosting plans (draft) + page copy, from the PLATFM-14 catalogue.
up: migration_20260929_hosting_plans.up,
down: migration_20260929_hosting_plans.down,
name: '20260929_hosting_plans',
},
]
];
+18 -72
View File
@@ -1,9 +1,10 @@
/**
* Payload CMS configuration (MITHOME-86 — alapinstalláció).
*
* WHY a saját MongoDB kapcsolatot használjuk: a projekt már MongoDB-t futtat
* (proto/src/lib/mongodb.ts) — Payload a `mongooseAdapter`-en keresztül
* ugyanabba az adatbázisba ír, nincs szükség külön DB-re/szerverre.
* MITHOME-136: PostgreSQL (`postgresAdapter`) — a platform egy PostgreSQL-
* szervert használ, a weboldal saját adatbázissal (mitplatform ADR-0001).
* A MongoDB-korszak adatmigrációi a git-előzményben vannak; a tartalom
* egyszeri átvitele: scripts/transfer-content.ts.
*
* MITHOME-87: Home/About/Services/Contact/Common Globals hozzáadva — ezek
* tükrözik a proto/src/content/pages/*.json + common.json struktúráját.
@@ -21,82 +22,27 @@
* 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).
* MITHOME-111: a Globals fordítható mezői lokalizáltak.
* MITHOME-130: Products collection + HostingPlans global (tárhelycsomagok).
*/
import path from 'path'
import { fileURLToPath } from 'url'
import { buildConfig } from 'payload'
import { mongooseAdapter } from '@payloadcms/db-mongodb'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import sharp from 'sharp'
import { postgresAdapter } from '@payloadcms/db-postgres'
import { Users } from './collections/Users'
import { LegalPages } from './collections/LegalPages'
import { Media } from './collections/Media'
import { Partners } from './collections/Partners'
import { ContactSubmissions } from './collections/ContactSubmissions'
import { Products } from './collections/Products'
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 { HostingPlans } from './globals/HostingPlans'
import { sharedConfig } from './payload.shared'
import { migrations } from './migrations'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
export default buildConfig({
// Admin felület — bejelentkezés az Users collection-nel. Access control /
// jelszó-politika: MITHOME-90 (src/collections/Users.ts).
admin: {
user: Users.slug,
components: {
// MITHOME-120: gyorskeresés minden admin oldal tetején.
// WHY 'src/...' és nem './components/...': a Payload komponens-útvonal
// az admin.importMap.baseDir-hez relatív, ami alapértelmezésben
// process.cwd() (a `generate:importmap` a proto/ mappából fut, NEM a
// payload.config.ts mappájából).
header: ['./src/components/admin/QuickSearch#QuickSearch'],
},
},
editor: lexicalEditor(),
collections: [Users, LegalPages, Media, Partners, ContactSubmissions, Products],
globals: [Home, About, Services, Contact, Common, HostingPlans],
// MITHOME-109/110: hu alapértelmezett (URL-prefix nélkül), en /en/ alatt
// (Next.js routing oldala: MITHOME-114). fallback:true -> amíg egy mezőnek
// nincs angol fordítása, a magyar érték jelenik meg — nem üres oldal.
localization: {
locales: ['hu', 'en'],
defaultLocale: 'hu',
fallback: true,
},
secret: process.env.PAYLOAD_SECRET || '',
typescript: {
outputFile: path.resolve(dirname, 'payload-types.ts'),
},
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.
...sharedConfig,
db: postgresAdapter({
pool: { connectionString: process.env.DATABASE_URI || '' },
// WHY uuid: opaque ids that do not reveal record counts and never clash
// when content is transferred or joined with the catalogue (PLATFM-15).
idType: 'uuid',
// WHY no push: the schema changes only through migrations, the same way
// locally, on staging and in production.
push: false,
// Pending migrations run automatically on production-mode startup
// (staging + prod containers) before the site serves requests.
prodMigrations: migrations,
}),
// WHY: Payload sends anonymous usage telemetry to its own servers by
// default — GDPR-tudatosan kikapcsolva, mivel a projekt self-hosted és
// az ügyfél adatai nem hagyhatják el a saját infrastruktúránkat.
telemetry: false,
sharp,
})
+73
View File
@@ -0,0 +1,73 @@
/**
* MITHOME-136: everything in the Payload config except the database adapter.
*
* WHY separate: the site runs on PostgreSQL (src/payload.config.ts), but the
* one-off content transfer (scripts/transfer-content.ts) must read the same
* collections and globals through the MongoDB adapter. Both configs are built
* from this object, so the content model cannot drift between them.
*/
import path from 'path'
import { fileURLToPath } from 'url'
import type { Config } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import sharp from 'sharp'
import { Users } from './collections/Users'
import { LegalPages } from './collections/LegalPages'
import { Media } from './collections/Media'
import { Partners } from './collections/Partners'
import { ContactSubmissions } from './collections/ContactSubmissions'
import { Products } from './collections/Products'
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 { HostingPlans } from './globals/HostingPlans'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
export const sharedConfig: Omit<Config, 'db'> = {
// Admin felület — bejelentkezés az Users collection-nel. Access control /
// jelszó-politika: MITHOME-90 (src/collections/Users.ts).
admin: {
user: Users.slug,
components: {
// MITHOME-120: gyorskeresés minden admin oldal tetején.
// WHY 'src/...' és nem './components/...': a Payload komponens-útvonal
// az admin.importMap.baseDir-hez relatív, ami alapértelmezésben
// process.cwd() (a `generate:importmap` a proto/ mappából fut, NEM a
// payload.config.ts mappájából).
header: ['./src/components/admin/QuickSearch#QuickSearch'],
},
},
editor: lexicalEditor(),
collections: [Users, LegalPages, Media, Partners, ContactSubmissions, Products],
globals: [Home, About, Services, Contact, Common, HostingPlans],
// MITHOME-109/110: hu alapértelmezett (URL-prefix nélkül), en /en/ alatt
// (Next.js routing oldala: MITHOME-114). fallback:true -> amíg egy mezőnek
// nincs angol fordítása, a magyar érték jelenik meg — nem üres oldal.
localization: {
locales: ['hu', 'en'],
defaultLocale: 'hu',
fallback: true,
},
secret: process.env.PAYLOAD_SECRET || '',
typescript: {
outputFile: path.resolve(dirname, 'payload-types.ts'),
},
// WHY: Payload sends anonymous usage telemetry to its own servers by
// default — GDPR-tudatosan kikapcsolva, mivel a projekt self-hosted és
// az ügyfél adatai nem hagyhatják el a saját infrastruktúránkat.
telemetry: false,
sharp,
}