Compare commits

..
4 Commits
Author SHA1 Message Date
Do SikiandClaude Opus 5.5 fe5594b869 Merge branch 'feature/MITHOME-136-postgres' (MITHOME-136: PostgreSQL)
CI Pipeline with Test Management / 🧪 Run Tests & Generate Reports (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 🧪 Run Tests & Generate Reports (push) Canceled after 0s
CI Pipeline with Test Management / 🐳 Docker Integration Tests (push) Canceled after 0s
CI Pipeline with Test Management / 🏗️ Build Docker Image (push) Canceled after 0s
CI Pipeline with Test Management / 📊 Generate Test Summary (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 📊 Analyze Test Coverage (push) Canceled after 0s
Test Reporting & Gherkin Analysis / 🔄 Sync with Linear (push) Canceled after 0s
Test Reporting & Gherkin Analysis / ⚡ Performance Monitoring (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:43:33 +02:00
Do SikiandClaude Opus 5.5 0ec5714676 feat(infra): PostgreSQL in the compose stacks, automatic pre-deploy backups (MITHOME-136)
- staging/prod: postgres:16-alpine per the llmdev Docker spec (healthcheck,
  log and memory limits, no host port); the app builds DATABASE_URI from
  POSTGRES_PASSWORD and waits for a healthy database; MongoDB kept for one
  release (rollback path, transfer source)
- dev: PostgreSQL replaces MongoDB and Mongo Express (host port 5433, checked
  and registered); integration test rewritten with pg
- deploy.sh: pg_dump (and, during the switch, mongodump) before the build
- pg/@types/pg pinned to the adapter's 8.20.0 (one copy, no type clash)
- docs: CLAUDE.md, architecture/testing steering, deploy workflow, DOCKER.md;
  staging switch runbook in the design

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:35:56 +02:00
Do SikiandClaude Opus 5.5 a68fb94b61 feat(cms): MongoDB → PostgreSQL content transfer; fix two schema issues it found (MITHOME-136)
- scripts/transfer-content.ts: export (shared config + MongoDB adapter,
  locale 'all', drafts, upload files) and import (PostgreSQL, one transaction,
  refuses a non-empty target); pure helpers in src/lib/content-transfer.ts
- LegalPages: the section anchor is its own field; as the array row id it was
  a table-wide primary key in PostgreSQL and the two pages collided
- Products.status: own enumName; the default name equalled the drafts
  _status enum, so only draft/published were accepted
- baseline migration regenerated

Verified on a staging copy (disposable MongoDB + PostgreSQL on llmdev): counts
match, all 14 public pages (hu/en) render identical text, partner logo loads,
second import writes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:27:11 +02:00
Do SikiandClaude Opus 5.5 e3ec6a9ac3 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>
2026-09-29 22:09:00 +02:00
61 changed files with 14964 additions and 2368 deletions
+1 -1
View File
@@ -97,7 +97,7 @@ websitedev/
│ │ ├── collections/ # Payload Collections (LegalPages, Partners, Media, ContactSubmissions, Users)
│ │ ├── payload.config.ts # Payload CMS konfiguráció
│ │ ├── content/ # RÉGI JSON rendszer — csak migrációs seed + teszt-fixture (MITHOME-91/93/96)
│ │ ├── lib/ # payload-content.ts (Local API adapter), MongoDB health-check, Logger
│ │ ├── lib/ # payload-content.ts (Local API adapter), content-transfer, Logger
│ │ ├── config/ # Statikus site konfiguráció
│ │ └── types/ # TypeScript típusdefiníciók
│ └── public/ # Statikus fájlok
+3 -3
View File
@@ -13,7 +13,7 @@ A projekt egy **Next.js 15 alapú marketing weboldal** a mozdIT Bt. számára, A
- **Frontend**: Next.js 15 App Router (dinamikus renderelés — lásd MITHOME-97 WHY: SSG helyett, hogy egy admin publikálás azonnal látszódjon), React 19, Tailwind CSS 4
- **CMS**: Payload CMS — Globals (Home/About/Services/Contact/Common) + Collections (LegalPages/Partners/Media/ContactSubmissions/Users), hu/en lokalizáció, draft/publish + verziózás
- **Backend**: Next.js API Routes (`/api/*`), Payload REST/GraphQL API + Local API
- **Adatbázis**: MongoDB — Payload-collection-önként (mongooseAdapter), plusz egy vékony natív `mongodb` driveres réteg (`proto/src/lib/mongodb.ts`) csak az `/api/health` connectivity-ellenőrzéséhez
- **Adatbázis**: PostgreSQL 16 (MITHOME-136, mitplatform ADR-0001) — Payload `postgresAdapter`, UUID-azonosítók, a séma csak migrációval változik (`proto/src/migrations/`, `push: false`). Egy PostgreSQL-szerver, a weboldalnak saját adatbázisa van (`mozdit_web`)
- **Logging**: Winston strukturált szerveroldali naplózás stdout/stderr kimenetre; a központi gyűjtés hostoldali collector feladata, külön Hosting-infrastruktúra.
- **Infrastructure**: Docker + Docker Compose, natív deploy (`deploy.sh`)
@@ -44,7 +44,7 @@ A projekt egy **Next.js 15 alapú marketing weboldal** a mozdIT Bt. számára, A
2. **Next.js middleware**: Auth ellenőrzés (ha szükséges)
3. **API Route**: Input validáció
4. **Lib/Service**: Üzleti logika végrehajtása
5. **MongoDB**: Adatbázis művelet
5. **PostgreSQL** (Payload Local API-n át): Adatbázis művelet
6. **Responder**: Egységes formátumú JSON válasz
## Design System szabályok
@@ -91,4 +91,4 @@ kerüljön, mert a Payload CLI minden `.ts` fájlt migrációnak tekint.
- Új NPM package bevezetéséhez **jóváhagyás szükséges**
- Előnyben részesítjük a Next.js beépített megoldásait (Image, Link, Font, stb.)
- MongoDB driver helyett Mongoose ODM-et használunk
- Adatbázis-hozzáférés a Payload Local API-n át; nyers SQL csak migrációban és ellenőrző tesztben
+5 -5
View File
@@ -22,7 +22,7 @@ Ez a fájl automatikusan betöltődik tesztfájlok érintésekor, és segít a t
- Utility függvények: **>90%**
- API endpoint-ok: minden happy path + fő error case-ek
- A tesztek legyenek **izoláltak** és **determinisztikusak**.
- Használj mock-okat a külső függőségekhez (MongoDB, Loki, HTTP hívások).
- Használj mock-okat a külső függőségekhez (adatbázis, Loki, HTTP hívások).
## Elnevezési konvenciók
@@ -44,7 +44,7 @@ npm run test:coverage # lefedettség riport
npm run test:browser # browser integration
npm run test:integration # Docker integration (Docker kell!)
npm run test:e2e # E2E tesztek (Docker kell!)
npm run test:payload # Payload Local API integráció (élő MongoDB + migrált tartalom kell!)
npm run test:payload # Payload Local API integráció (élő PostgreSQL + tartalom kell!)
npm run test:all # teljes proto suite
npm run test:smoke:staging # Playwright smoke a staging ellen
```
@@ -92,15 +92,15 @@ Plane-sync unit tesztek. Bármelyik hibája megszakítja a kiadást.
> hozzá élő DB, csak a Collection/Global config objektumokat vizsgálja —
> köztük két, MITHOME-121-ben talált éles hibára regresszió-őrt: a Media
> publikus olvashatósága, a Partners.logo opcionalitása). A Local API elleni,
> élő MongoDB-t igénylő tesztek külön scriptben vannak
> élő adatbázist igénylő tesztek külön scriptben vannak
> (`scripts/test-payload-local-api.ts`, `npm run test:payload`) — WHY nem
> Jest: a `payload` csomag ESM-only dist-et ad ki, amit a next/jest
> transzform alapból nem fordít le (a teljes függőségi fa
> `transformIgnorePatterns`-be vétele törékeny lenne), ezért ugyanazt a
> bevált `node --import tsx` mintát követi, mint `migrate-content-to-payload.ts`.
> Nincs a `pre-deploy-tests.sh`-ban (élő, migrált tartalmú MongoDB kell hozzá,
> Nincs a `pre-deploy-tests.sh`-ban (élő, tartalommal feltöltött adatbázis kell hozzá,
> mint a régi, eltávolított CMS-teszteknek is), de a `npm run test:payload`
> paranccsal bármikor lefuttatható egy futó dev MongoDB ellen. A régi,
> paranccsal bármikor lefuttatható egy futó dev PostgreSQL ellen (MITHOME-136). A régi,
> Docker-stack-hez kötött `integration.test.ts`/`e2e-docker.test.ts` is
> frissítve lett a locale-prefixes útvonalakra és a Payload collection-nevekre
> (korábban a pre-Payload, unprefixelt útvonalakra és `site_config`/
+12 -19
View File
@@ -7,8 +7,8 @@ description: Deployment munkafolyamata — lokális teszttől a stagingen át a
## Architektúra áttekintés
- **Nincs Dokploy / registry push** — a deploy natív Docker Compose-zal, a szerveren buildelve történik.
- **Környezetenként külön compose fájl**: `docker-compose.staging.yml` (app: 127.0.0.1:8081, saját Mongo) és `docker-compose.prod.yml` (app: 8080). A két környezet ugyanazon a hoston, külön hálózaton és volume-mal fut.
- **Környezeti változók**: kötelező `.env.staging` / `.env.production` fájlból jönnek (minta: `.env.staging.example`, `.env.production.example`). Bizalmas értékeknek (MONGO_ROOT_PASSWORD, MONGODB_URI) **nincs fallback** — hiányzó env hangosan hibázik.
- **Környezetenként külön compose fájl**: `docker-compose.staging.yml` (app: 127.0.0.1:8081, saját PostgreSQL) és `docker-compose.prod.yml` (app: 8080). A két környezet ugyanazon a hoston, külön hálózaton és volume-mal fut.
- **Környezeti változók**: kötelező `.env.staging` / `.env.production` fájlból jönnek (minta: `.env.staging.example`, `.env.production.example`). Bizalmas értékeknek (POSTGRES_PASSWORD, PAYLOAD_SECRET, az átállás idejére MONGO_ROOT_PASSWORD) **nincs fallback** — hiányzó env hangosan hibázik.
- **Staging megkülönböztetés**: a `NEXT_PUBLIC_DEPLOY_ENV=staging` build arg amber banner-t jelenít meg a weboldalon.
## Előfeltételek
@@ -59,23 +59,16 @@ scripts/check-ports.sh --host sadmin@10.8.0.1 --project websitedev --compose doc
A szabad portot a használat előtt be kell jegyezni a portregiszterbe (`~/Projects/maintenance/docker-hatter-specifikacio.md`, 5. pont).
## Payload adatmigrációk és kötelező DB-mentés (MITHOME-111)
## Payload adatmigrációk és automatikus DB-mentés (MITHOME-111, MITHOME-136)
A `proto/src/migrations/` alatti Payload migrációk a `mongooseAdapter({ prodMigrations })` révén **az app konténer indulásakor automatikusan lefutnak** (`NODE_ENV=production`, tehát stagingen és productionben is). A lefutottakat a `payload-migrations` collection tartja nyilván, ezért minden migráció csak egyszer fut. A `deploy.sh`-ban ehhez nincs külön lépés. A lefutást az app-log mutatja (`Migrating: …` / `Migrated: …`).
A `proto/src/migrations/` alatti Payload migrációk a `postgresAdapter({ prodMigrations })` révén **az app konténer indulásakor automatikusan lefutnak** (`NODE_ENV=production`, stagingen és productionben is). A lefutottakat a `payload_migrations` tábla tartja nyilván, ezért minden migráció csak egyszer fut. A lefutást az app-log mutatja (`Migrating: …` / `Migrated: …`).
**Ha a kiadás migrációt tartalmaz, deploy előtt kötelező a mentés** (a szerveren, a projekt mappájából; a hitelesítő adatok a konténeren belül maradnak):
```bash
ENV=staging # vagy production
mkdir -p ~/backups && chmod 700 ~/backups
docker exec mozdit-mongodb-$ENV sh -c 'mongodump --quiet --username "$MONGO_INITDB_ROOT_USERNAME" --password "$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin --db mozdit --archive' \
> ~/backups/mozdit-$ENV-$(date +%Y%m%d-%H%M%S).archive
chmod 600 ~/backups/*.archive
```
- **Új migráció:** `npm run migrate:create <név>` (proto/), egy futó PostgreSQL-re mutató `DATABASE_URI`-vel. A séma csak migrációval változik; a generált fájlt kézzel nem szerkesztjük.
- **Mentés:** a `deploy.sh` **a build előtt automatikusan ment**: `pg_dump -Fc` → `~/backups/mozdit-<env>-<időbélyeg>-pre-deploy.pgdump`, az átállás idejére a MongoDB-t is (`.archive`), 600-as jogosultsággal.
## Tartalom publikálása (Payload admin)
A régi Content Editor (`content-editor.js`, git push-alapú publikálás) helyét a Payload admin (`/admin`) draft/publish + verziózás funkciója vette át (MITHOME-92/93) — ez nem jár git commit-tal vagy automatikus deployjal, a tartalom közvetlenül a MongoDB-be íródik. Kódváltozás (Globals/Collections séma, frontend) továbbra is a lenti git-alapú deploy folyamaton megy át.
A régi Content Editor (`content-editor.js`, git push-alapú publikálás) helyét a Payload admin (`/admin`) draft/publish + verziózás funkciója vette át (MITHOME-92/93) — ez nem jár git commit-tal vagy automatikus deployjal, a tartalom közvetlenül az adatbázisba (PostgreSQL) íródik. Kódváltozás (Globals/Collections séma, frontend) továbbra is a lenti git-alapú deploy folyamaton megy át.
## Production deploy (élesítés)
@@ -125,14 +118,14 @@ git checkout HEAD~1
./deploy.sh <env>
```
Ha a visszavont kiadás adatmigrációt tartalmazott, a régi kód a migrált adatot nem feltétlenül tudja olvasni. Ilyenkor a deploy előtti mentést is vissza kell állítani (a `--drop` felülírja a jelenlegi adatbázist):
Ha a visszavont kiadás adatmigrációt tartalmazott, a régi kód a migrált adatot nem feltétlenül tudja olvasni. Ilyenkor a deploy előtti mentést is vissza kell állítani (a `--clean` felülírja a jelenlegi adatbázist; `CONTAINER_ENV` = `staging` vagy `prod`):
```bash
docker exec -i mozdit-mongodb-$ENV sh -c 'mongorestore --quiet --drop --username "$MONGO_INITDB_ROOT_USERNAME" --password "$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin --archive' \
< ~/backups/mozdit-$ENV-<időbélyeg>.archive
docker exec -i mozdit-postgres-$CONTAINER_ENV pg_restore --clean --if-exists -U mozdit_web -d mozdit_web \
< ~/backups/mozdit-$ENV-<időbélyeg>-pre-deploy.pgdump
```
A migrációk `down` függvénye csak végső esetre való: a lokalizációs migráció `down`-ja minden nem magyar értéket eldob.
A migrációk `down` függvénye csak végső esetre való.
---
@@ -151,4 +144,4 @@ npm run docker:dev:down # leállítás
npm run docker:dev:logs # logok követése
```
Szolgáltatások: weboldal http://localhost:8080, MongoDB (host port 27018), Mongo Express http://localhost:8082, Loki :3100, Grafana http://localhost:3012 (MITHOME-137: a 8081 és a 3001 az llmdev-en foglalt).
Szolgáltatások: weboldal http://localhost:8080, PostgreSQL (host port 5433, MITHOME-136), Loki :3100, Grafana http://localhost:3012 (MITHOME-137: a 8081 és a 3001 az llmdev-en foglalt).
+8 -3
View File
@@ -1,9 +1,14 @@
# Production környezeti változók — másold .env.production néven a prod szerveren!
# Másold le és töltsd ki a valódi értékekkel. SOHA ne commitold.
# MongoDB (production saját konténere a docker-compose.prod.yml-ben)
MONGODB_URI=mongodb://admin:password123@mongodb:27017/mozdit?authSource=admin
MONGODB_DB=mozdit
# PostgreSQL (MITHOME-136) — a weboldal saját adatbázisa (mozdit_web). A
# compose ebből állítja össze a DATABASE_URI-t; URL-biztos jelszót használj
# (pl. `openssl rand -hex 32`). Egyedi érték környezetenként.
POSTGRES_USER=mozdit_web
POSTGRES_PASSWORD=changeme
# MongoDB — MITHOME-136: csak az átállás idejére (visszaút és a tartalom-
# átvitel forrása); egy kiadás múlva törlendő. Az app már nem használja.
MONGO_ROOT_USER=admin
MONGO_ROOT_PASSWORD=changeme
+8 -3
View File
@@ -1,9 +1,14 @@
# Staging környezeti változók — másold .env.staging néven a szerveren!
# Másold le és töltsd ki a valódi értékekkel. SOHA ne commitold.
# MongoDB (staging saját konténere a docker-compose.staging.yml-ben)
MONGODB_URI=mongodb://admin:password123@mongodb:27017/mozdit?authSource=admin
MONGODB_DB=mozdit
# PostgreSQL (MITHOME-136) — a weboldal saját adatbázisa (mozdit_web). A
# compose ebből állítja össze a DATABASE_URI-t; URL-biztos jelszót használj
# (pl. `openssl rand -hex 32`). Egyedi érték környezetenként.
POSTGRES_USER=mozdit_web
POSTGRES_PASSWORD=changeme
# MongoDB — MITHOME-136: csak az átállás idejére (visszaút és a tartalom-
# átvitel forrása); egy kiadás múlva törlendő. Az app már nem használja.
MONGO_ROOT_USER=admin
MONGO_ROOT_PASSWORD=changeme
+5 -5
View File
@@ -11,7 +11,7 @@
- **Projekt**: mozdIT Bt. weboldal (websitedev)
- **Plane workspace**: `developments` — `pm.llmdev.mozdit.hu`
- **Plane MCP**: kizárólag a `plane-developments_*` eszközöket használd; a `priws` workspace nem ehhez a projekthez tartozik.
- **Stack**: Next.js 15, React 19, TypeScript, Tailwind CSS 4, Payload CMS (self-hosted, `/admin`), MongoDB, Winston
- **Stack**: Next.js 15, React 19, TypeScript, Tailwind CSS 4, Payload CMS (self-hosted, `/admin`), PostgreSQL (MITHOME-136), Winston
- **Fő könyvtár**: `proto/` — **minden parancsot innen futtatunk**
---
@@ -60,7 +60,7 @@ websitedev/
│ ├── content/ # RÉGI JSON rendszer — csak migrációs seed + teszt-fixture (MITHOME-91/93/96)
│ │ ├── common.json
│ │ └── pages/
│ ├── lib/ # payload-content.ts (Local API adapter), MongoDB health-check, Logger
│ ├── lib/ # payload-content.ts (Local API adapter), content-transfer, Logger
│ ├── config/ # Statikus site konfiguráció
│ └── types/ # TypeScript típusok
├── docs/ # Projekt dokumentáció (Magyar)
@@ -80,8 +80,8 @@ websitedev/
## Környezeti változók
Szükséges változók (`.env` és `proto/.env.local`):
- `MONGODB_URI` — MongoDB connection string
- `MONGODB_DB` — Adatbázis neve (default: `mozdit`)
- `DATABASE_URI` — PostgreSQL connection string (a staging/prod compose a `POSTGRES_PASSWORD`-ből állítja össze; MITHOME-136)
- `POSTGRES_USER` / `POSTGRES_PASSWORD` — staging/production: a `mozdit_web` adatbázis felhasználója
- `NEXT_PUBLIC_SITE_URL` — Publikus site URL
- `NEXT_PUBLIC_WEBMAIL_URL` — Webmail service URL
- `NEXT_PUBLIC_CONTACT_EMAIL` — Kapcsolati email cím
@@ -93,7 +93,7 @@ Szükséges változók (`.env` és `proto/.env.local`):
## API struktúra
- `GET /api/health` — Rendszer állapot + MongoDB kapcsolat ellenőrzés
- `GET /api/health` — Rendszer állapot (build- és környezetazonosító)
- Minden endpoint egységes válasz formátumban: `{ success, data, error }`
- Rate limiting érzékeny endpoint-okon (pl. `/api/contact`)
+22 -25
View File
@@ -22,16 +22,15 @@ A Docker stack a következő szolgáltatásokat indítja:
| Szolgáltatás | Port | URL | Leírás |
|--------------|------|-----|--------|
| **Next.js App** | 8080 | http://localhost:8080 | Fő alkalmazás |
| **MongoDB** | 27018 | mongodb://localhost:27018 | Adatbázis |
| **Mongo Express** | 8082 | http://localhost:8082 | MongoDB Web UI |
| **PostgreSQL** | 5433 | postgresql://localhost:5433/mozdit_web | Adatbázis (MITHOME-136) |
| **Loki** | 3100 | http://localhost:3100 | Log aggregátor |
| **Grafana** | 3012 | http://localhost:3012 | Monitoring dashboard |
### 🔐 Alapértelmezett Bejelentkezési Adatok
**MongoDB:**
- Username: `admin`
- Password: `password123`
**PostgreSQL (csak dev, nem titkos):**
- Username: `mozdit_web`
- Password: `devpassword`
**Grafana:**
- Username: `admin`
@@ -39,28 +38,23 @@ A Docker stack a következő szolgáltatásokat indítja:
**Payload CMS admin** (http://localhost:8080/admin): nincs előre létrehozott felhasználó — az első betöltéskor a Payload felkínálja az admin fiók létrehozását. A `docker-compose.dev.yml` egy fix, nem titkos `PAYLOAD_SECRET`-et ad át (MITHOME-97) — staging/production környezetben ez kötelezően a saját `.env.<env>` fájlból jön, nincs alapértelmezett érték (a konténer el sem indul nélküle).
## 📊 MongoDB Hozzáférés
## 📊 PostgreSQL-hozzáférés
### 1. Mongo Express Web UI
- URL: http://localhost:8082
- Böngészőben egyszerűen elérhető
- Adatbázis: `mozdit`
### 2. MongoDB Shell (ha telepítve van)
```bash
# Kapcsolódás a containerhez
docker exec -it mozdit-mongodb-dev mongosh
# psql a konténerben
docker exec -it mozdit-postgres-dev psql -U mozdit_web -d mozdit_web
# Vagy közvetlenül
mongosh "mongodb://admin:password123@localhost:27017/mozdit"
# Payload-migrációk állapota (proto/ mappából, a dev adatbázisra)
DATABASE_URI=postgresql://mozdit_web:devpassword@localhost:5433/mozdit_web PAYLOAD_SECRET=dev npm run migrate:status
```
### 3. Alkalmazásból
Az alkalmazás automatikusan csatlakozik:
Az alkalmazás a Compose-hálózaton csatlakozik:
```
MONGODB_URI=mongodb://admin:password123@mongodb:27017/mozdit?authSource=admin
DATABASE_URI=postgresql://mozdit_web:devpassword@postgres:5432/mozdit_web
```
A séma csak migrációval változik (`npm run migrate:create <név>`); a fejlesztői „push” ki van kapcsolva. Tartalom egy friss adatbázisba: `node --import tsx scripts/transfer-content.ts import <csomag.json>`.
## 🛠️ Fejlesztési Parancsok
```bash
@@ -83,7 +77,7 @@ npm run docker:run
## 📁 Adatok Perzisztencia
A következő Docker volume-ok tárolják az adatokat:
- `mongodb_data` - MongoDB adatok
- `postgres_data_dev` - PostgreSQL adatok
- `loki_data` - Log adatok
- `grafana_data` - Grafana beállítások
@@ -96,12 +90,14 @@ docker-compose -f docker-compose.dev.yml down -v
A fejlesztői környezet támogatja a hot reload-ot:
- Kód változások automatikusan frissülnek
- MongoDB adatok megmaradnak restart után
- Az adatbázis adatai megmaradnak restart után
- Volume mounting biztosítja a gyors fejlesztést
## 🚨 Hibaelhárítás
### Port foglaltság
Minden port használata előtt: `scripts/check-ports.sh --host sadmin@10.8.0.1 --project websitedev --compose docker-compose.dev.yml` (MITHOME-137).
Ha a 3000-es port foglalt:
```bash
# Meglévő process keresése
@@ -111,13 +107,13 @@ lsof -i :3000
docker-compose -f docker-compose.dev.yml up --build -p 3002:3000
```
### MongoDB kapcsolat hiba
### Adatbázis-kapcsolat hiba
```bash
# Container logok ellenőrzése
docker logs mozdit-mongodb-dev
docker logs mozdit-postgres-dev
# Újraindítás
docker-compose -f docker-compose.dev.yml restart mongodb
docker-compose -f docker-compose.dev.yml restart postgres
```
### Teljes tisztítás
@@ -136,7 +132,8 @@ docker build -t mozdit-app:latest ./proto
# Production futtatás
docker run -p 3000:3000 \
-e NODE_ENV=production \
-e MONGODB_URI=mongodb://your-prod-db:27017/mozdit \
-e DATABASE_URI=postgresql://user:password@your-db:5432/mozdit_web \
-e PAYLOAD_SECRET=... \
mozdit-app:latest
```
+23
View File
@@ -59,6 +59,29 @@ if [ "$ENV" = "production" ] && grep -hsE '^[[:space:]-]*NEXT_PUBLIC_DEPLOY_ENV[
exit 1
fi
# 2b2. Adatbázis-mentés — build ELŐTT (MITHOME-111, MITHOME-136)
# WHY: a prodMigrations induláskor sémát módosíthat; egy hibás kiadás után
# a deploy előtti mentésből kell tudni visszaállni. Ami fut, azt mentjük:
# PostgreSQL (pg_dump, egyedi formátum) és — az átállás idejére — MongoDB.
CONTAINER_ENV="$ENV"
[ "$ENV" = "production" ] && CONTAINER_ENV="prod"
BACKUP_DIR="$HOME/backups"
STAMP="$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR" # shared directory: only our own files get chmod 600
if docker ps --format '{{.Names}}' | grep -qx "mozdit-postgres-${CONTAINER_ENV}"; then
PG_BACKUP="$BACKUP_DIR/mozdit-${ENV}-${STAMP}-pre-deploy.pgdump"
PG_USER="$(env_value POSTGRES_USER)"
docker exec "mozdit-postgres-${CONTAINER_ENV}" pg_dump -U "${PG_USER:-mozdit_web}" -Fc mozdit_web > "$PG_BACKUP"
chmod 600 "$PG_BACKUP"
echo "💾 PostgreSQL-mentés: $PG_BACKUP"
fi
if docker ps --format '{{.Names}}' | grep -qx "mozdit-mongodb-${CONTAINER_ENV}"; then
MONGO_BACKUP="$BACKUP_DIR/mozdit-${ENV}-${STAMP}-pre-deploy.archive"
docker exec "mozdit-mongodb-${CONTAINER_ENV}" sh -c 'mongodump --quiet --username "$MONGO_INITDB_ROOT_USERNAME" --password "$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin --db mozdit --archive' > "$MONGO_BACKUP"
chmod 600 "$MONGO_BACKUP"
echo "💾 MongoDB-mentés: $MONGO_BACKUP"
fi
# 2c. Port-ellenőrzés — build ELŐTT, hogy egy ütközés ne egy teljes build után
# derüljön ki. A saját projekt (újraindítandó) konténerei által foglalt port
# rendben van; minden más foglaltság hiba. Szabály: llmdev Docker-háttér
+20 -36
View File
@@ -10,12 +10,8 @@ services:
- "127.0.0.1:8080:3000"
environment:
- NODE_ENV=development
# WHY authSource=admin: the mongodb service below only creates a root
# user (via MONGO_INITDB_ROOT_USERNAME/PASSWORD), which forces --auth
# on the mongod process — an unauthenticated URI fails every query
# with "Command find requires authentication" (MITHOME-98).
- MONGODB_URI=mongodb://admin:password123@mongodb:27017/mozdit?authSource=admin
- MONGODB_DB=mozdit
# MITHOME-136: PostgreSQL; dev-only, not secret credentials.
- DATABASE_URI=postgresql://mozdit_web:devpassword@postgres:5432/mozdit_web
# Dev-only, nem titkos (MITHOME-97) — Payload ez nélkül el sem indul
# ("missing secret key"), és ez a compose fájl eddig nem adta át.
- PAYLOAD_SECRET=dev-only-insecure-secret-do-not-use-in-staging-or-prod
@@ -29,42 +25,30 @@ services:
- /app/.next
command: npm run dev
depends_on:
- mongodb
postgres:
condition: service_healthy
networks:
- mozdit-network
restart: unless-stopped
# MongoDB Database
mongodb:
image: mongo:7.0
container_name: mozdit-mongodb-dev
# PostgreSQL (MITHOME-136). Host port 5433 is registered in the llmdev port
# registry (5432 is peakxi-dev) — for the integration tests and local tools.
postgres:
image: postgres:16-alpine
container_name: mozdit-postgres-dev
ports:
- "127.0.0.1:27018:27017"
- "127.0.0.1:5433:5432"
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=password123
- MONGO_INITDB_DATABASE=mozdit
- POSTGRES_DB=mozdit_web
- POSTGRES_USER=mozdit_web
- POSTGRES_PASSWORD=devpassword
volumes:
- mongodb_data:/data/db
- ./docker/mongodb/init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
networks:
- mozdit-network
restart: unless-stopped
# MongoDB Express (Web UI)
mongo-express:
image: mongo-express:1.0.2
container_name: mozdit-mongo-express-dev
ports:
# MITHOME-137: 8081 is the mozdit staging app on llmdev (port registry)
- "127.0.0.1:8082:8081"
environment:
- ME_CONFIG_MONGODB_ADMINUSERNAME=admin
- ME_CONFIG_MONGODB_ADMINPASSWORD=password123
- ME_CONFIG_MONGODB_URL=mongodb://admin:password123@mongodb:27017/
- ME_CONFIG_BASICAUTH=false
depends_on:
- mongodb
- postgres_data_dev:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U mozdit_web -d mozdit_web"]
interval: 10s
timeout: 5s
retries: 5
networks:
- mozdit-network
restart: unless-stopped
@@ -101,7 +85,7 @@ services:
restart: unless-stopped
volumes:
mongodb_data:
postgres_data_dev:
driver: local
loki_data:
driver: local
+48 -6
View File
@@ -13,10 +13,11 @@ services:
- "127.0.0.1:8080:3000" # Belső port — csak nginx reverse proxy-n keresztül elérhető
environment:
- NODE_ENV=production
# No fallback for MONGODB_URI: with root auth enabled on the Mongo container an
# unauthenticated default URI would silently break the app — fail loudly instead.
- MONGODB_URI=${MONGODB_URI}
- MONGODB_DB=${MONGODB_DB:-mozdit}
# MITHOME-136: PostgreSQL (the site's own database on the shared server).
# Built from POSTGRES_PASSWORD so the secret lives in one place; no
# fallback — a missing password must fail the deploy loudly. Use a
# URL-safe password (e.g. `openssl rand -hex 32`).
- DATABASE_URI=postgresql://${POSTGRES_USER:-mozdit_web}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}@postgres:5432/mozdit_web
# No fallback either (MITHOME-97): Payload refuses to start without a real
# secret ("missing secret key"), which is exactly what we want here.
- PAYLOAD_SECRET=${PAYLOAD_SECRET}
@@ -28,7 +29,14 @@ services:
# kommentjét (MITHOME-97).
- media_data_prod:/app/media
depends_on:
- mongodb
postgres:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/api/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 60s
networks:
- mozdit-network
restart: always
@@ -38,7 +46,39 @@ services:
max-size: "10m"
max-file: "3"
# MongoDB Database
# PostgreSQL (MITHOME-136) — llmdev Docker spec: healthcheck, log limit,
# memory limit, no host port (the app reaches it on the project network).
postgres:
image: postgres:16-alpine
container_name: mozdit-postgres-prod
environment:
- POSTGRES_DB=mozdit_web
- POSTGRES_USER=${POSTGRES_USER:-mozdit_web}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
volumes:
- postgres_data_prod:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-mozdit_web} -d mozdit_web"]
interval: 10s
timeout: 5s
retries: 5
start_period: 20s
deploy:
resources:
limits:
memory: 1G
logging:
driver: "json-file"
options:
max-size: "100m"
max-file: "3"
networks:
- mozdit-network
restart: unless-stopped
# MongoDB — MITHOME-136: no longer used by the app. Kept for one release as
# the rollback path and the source of the one-off content transfer
# (proto/scripts/transfer-content.ts); remove afterwards (tasks 4.3).
mongodb:
image: mongo:7.0
container_name: mozdit-mongodb-prod
@@ -56,6 +96,8 @@ services:
restart: always
volumes:
postgres_data_prod:
driver: local
mongodb_data_prod:
driver: local
media_data_prod:
+48 -6
View File
@@ -14,10 +14,11 @@ services:
- "127.0.0.1:8081:3000" # Belső port — csak nginx-en keresztül elérhető
environment:
- NODE_ENV=production
# No fallback for MONGODB_URI: with root auth enabled on the Mongo container an
# unauthenticated default URI would silently break the app — fail loudly instead.
- MONGODB_URI=${MONGODB_URI}
- MONGODB_DB=${MONGODB_DB:-mozdit}
# MITHOME-136: PostgreSQL (the site's own database on the shared server).
# Built from POSTGRES_PASSWORD so the secret lives in one place; no
# fallback — a missing password must fail the deploy loudly. Use a
# URL-safe password (e.g. `openssl rand -hex 32`).
- DATABASE_URI=postgresql://${POSTGRES_USER:-mozdit_web}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}@postgres:5432/mozdit_web
# No fallback either (MITHOME-97): Payload refuses to start without a real
# secret ("missing secret key"), which is exactly what we want here.
- PAYLOAD_SECRET=${PAYLOAD_SECRET}
@@ -32,7 +33,14 @@ services:
# korábban feltöltött logókat/képeket (MITHOME-97).
- media_data_staging:/app/media
depends_on:
- mongodb
postgres:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/api/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 60s
networks:
- mozdit-network-staging
restart: always
@@ -42,7 +50,39 @@ services:
max-size: "10m"
max-file: "3"
# MongoDB Database (külön a prod-tól)
# PostgreSQL (MITHOME-136) — llmdev Docker spec: healthcheck, log limit,
# memory limit, no host port (the app reaches it on the project network).
postgres:
image: postgres:16-alpine
container_name: mozdit-postgres-staging
environment:
- POSTGRES_DB=mozdit_web
- POSTGRES_USER=${POSTGRES_USER:-mozdit_web}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
volumes:
- postgres_data_staging:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-mozdit_web} -d mozdit_web"]
interval: 10s
timeout: 5s
retries: 5
start_period: 20s
deploy:
resources:
limits:
memory: 1G
logging:
driver: "json-file"
options:
max-size: "100m"
max-file: "3"
networks:
- mozdit-network-staging
restart: unless-stopped
# MongoDB — MITHOME-136: no longer used by the app. Kept for one release as
# the rollback path and the source of the one-off content transfer
# (proto/scripts/transfer-content.ts); remove afterwards (tasks 4.3).
mongodb:
image: mongo:7.0
container_name: mozdit-mongodb-staging
@@ -60,6 +100,8 @@ services:
restart: always
volumes:
postgres_data_staging:
driver: local
mongodb_data_staging:
driver: local
media_data_staging:
@@ -39,19 +39,33 @@
- A kiinduló migráció a teljes jelenlegi config sémája: `payload migrate:create initial`. A `src/migrations/index.ts` ezzel indul újra.
- **A parancssori eszköz hibájának valódi oka** (az 1.1-es feladatban derült ki): nem a Node-verzió. A `proto/package.json`-ban nem volt `"type": "module"`, ezért a Payload parancssori eszköze a configot CommonJS-ként töltötte be, és nem tudta behúzni az ESM-es, top-level await-es `@payloadcms/richtext-lexical`-t. Node 22 alatt is ugyanez a hiba jött.
- **Megoldás:** `"type": "module"`, ahogy a Payload hivatalos sablonja is csinálja. A CommonJS jest-fájlok és a `src/content/schema.js` `.cjs` kiterjesztést kaptak. Ellenőrizve: a parancssori eszköz Node 26-on is betölti a configot; a Next `standalone` `server.js` ESM-es, és elindul. A `--input-type=module` kerülőút megszűnik.
- A generált migráció (`src/migrations/<időbélyeg>_*.ts`, a kiinduló 1548 soros) kivétel a 400 soros fájlkorlát és a lint alól: generált kód, kézzel nem szerkesztjük.
- **Közös config:** a `src/payload.shared.ts` mindent tartalmaz az adatbázis-illesztő kivételével. A `payload.config.ts` ebből épül PostgreSQL-lel, az átviteli script MongoDB-vel, így a tartalommodell nem térhet el.
- **Seed-konstansok:** a referenciák és a tárhelycsomagok szövegei a `src/content/seeds/` alá költöztek.
- A Mongo-adatmigrációk (8 fájl) és a segédfüggvényeik törlődnek. Az általuk elért állapot a stagingadatban van, és azt a D3 hozza át.
### D3: Egyszeri adatmigráció (`proto/scripts/migrate-mongo-to-postgres.ts`)
### D3: Egyszeri adatátvitel (`proto/scripts/transfer-content.ts`)
- **Forrás:** a Mongo-dokumentumok közvetlenül, a `mongodb` driverrel, csak olvasva. A lokalizált mezők `{ hu, en }` alakban vannak. A publikált állapot a fő dokumentum; a nyitott vázlat a legutolsó verzió, ha `_status: draft`.
- **Cél:** a Payload Local API, PostgreSQL-configgal. Először `locale: 'hu'` létrehozás, utána `locale: 'en'` frissítés, mindkét esetben `_status` megtartásával. A vázlat publikálás után külön vázlatmentésként kerül be.
- **Média:** új Media dokumentum ugyanarra a fájlra (`filePath` a `media/` könyvtárból). Egy azonosítótérkép (régi ObjectId → új UUID) oldja fel a hivatkozásokat (Partners.logo).
- **Felhasználók:** nem visszük át, mert a jelszó-hash nem írható a Local API-n. Az admint a `deploy.sh` meglévő `ADMIN_EMAIL`/`ADMIN_PASSWORD` seedelése hozza létre.
- **Idempotencia:** ha a cél már tartalmaz dokumentumot, a script leáll, és nem ír.
- **Ellenőrzés:**
- dokumentumszámok gyűjteményenként;
- a publikus oldalak szövegének összevetése hu/en nyelven a migráció előtti pillanatképpel (MITHOME-111 módszer);
- a média- és partnerhivatkozások.
Két lépés, lépésenként egy Payload-példánnyal, a Payload saját interfészén. Nem nyers Mongo-dokumentumokkal dolgozik:
- **`export`:** a `sharedConfig` + MongoDB-illesztő olvas mindent `locale: 'all'`-lal (a lokalizált mező `{ hu, en }`), a nyitott vázlatokkal és a médiafájlokkal együtt, egy önálló JSON-csomagba (600-as jogosultság; kapcsolatfelvételi üzenetekkel személyes adatot tartalmaz, `--no-submissions` nélkül nem kerülhet Gitbe). A felhasználókat nem visszük át; az admint a `deploy.sh` seedelése hozza létre.
- **`import`:** a webhely configja (PostgreSQL) **egy tranzakcióban** ír. Hibánál semmi nem marad bent; nem üres célnál el sem indul.
- Nyelvenként ír: `hu` létrehozás, `en` frissítés, a config mezőleírása alapján (`src/lib/content-transfer.ts`, tiszta, tesztelt függvények).
- A tömbsorok azonosítója megmarad, hogy az angol frissítés ugyanazokat a sorokat találja meg.
- Az upload-hivatkozások az új azonosítókra képződnek le. A média `overwriteExistingFiles`-szal íródik, így a fájlnév változatlan marad.
- **Futtatás:** 2026-09-29-én egy staging-másolaton, eldobható MongoDB-vel és PostgreSQL-lel az llmdev-en.
- A számok egyeznek.
- Mind a 14 publikus oldal szövege (hu és en) betűre egyezik a MongoDB-s staginggel.
- A partnerlogó betölt, a partnervázlat átjött, a második futás semmit sem ír.
**A próba során talált két adatmodell-hiba** (MongoDB-ben rejtve maradtak):
1. **A jogi szakasz `id`-ja tartalmi horgony volt** (`bevezetes`), és egyben a tömbsor azonosítója. PostgreSQL-ben a tömbsor azonosítója táblaszinten egyedi kulcs, így a két jogi oldal ütközött. Javítás:
- új `anchor` mező, a sorazonosítót a Payload adja;
- az átvitel az `id`-t `anchor`-ra képezi, a sorazonosító `<slug>-<horgony>` lesz (`upgradeDoc`).
2. **A `Products.status` enumja ugyanazt a nevet kapta**, mint a vázlatrendszer `_status`-a (`enum_products_status`). Emiatt csak a `draft` és a `published` érték volt menthető, az `active` nem. Javítás: saját `enumName` (`enum_products_lifecycle_status`), regressziós teszttel.
**Ismert korlát:** a Home `about.usps` és `services.items` sorai szintén saját, szerkeszthető `id`-t használnak. Egyetlen Global-dokumentum van, ezért nem ütközik, de egy duplikált azonosító mentési hibát adna. Külön ticket (átnevezés `key`-re).
### D4: Infrastruktúra
@@ -86,6 +100,22 @@
## Migration Plan
**Staging-átállás lépései** (4.1; a Macről, a WireGuard VPN-en át az llmdev-re):
1. **Merge:** a `feature/MITHOME-136-postgres` ág a `main`-re. A `.env.staging`-be a szerveren felkerül a `POSTGRES_PASSWORD` (`openssl rand -hex 32`).
2. **Export a futó staging MongoDB-ből**, még a deploy előtt. SSH-alagút a `127.0.0.1:27019`-re (port-ellenőrzés után), a staging MongoDB hitelesítő adataival:
`transfer-content.ts export <csomag> --media-dir <a staging media volume másolata>`.
3. **Deploy:** `deploy_to_stage_on_local.sh`. A `deploy.sh` a build előtt ment (`mongodump`), a PostgreSQL üresen indul, az app induláskor lefuttatja a kiinduló migrációt, és a `first-register` létrehozza az admint.
4. **Import:** SSH-alagút a `mozdit-postgres-staging` konténer címére, `transfer-content.ts import <csomag>`. Ellenőrzés:
- a számok;
- a 14 publikus oldal szövege a 2. lépés előtti pillanatképpel;
- a partnerlogó;
- a smoke tesztek.
5. **Rövid állásidő:** a 3. és 4. lépés között a staging oldalai tartalom nélkül futnak. Ez stagingen elfogadható.
**Visszaút az élesítésig:** a MongoDB-szolgáltatás és a volume érintetlen. A `main` visszaállítása az átállás előtti commitra, majd `deploy.sh staging`.
1. Staging-másolaton (eldobható Mongo és PostgreSQL az llmdev-en): kiinduló migráció, adatmigráció, ellenőrzés (D3).
2. Staging deploy:
- `mongodump` archív mentés;
@@ -3,23 +3,23 @@
## 1. Eszközök és illesztő
- [x] 1.1 `"type": "module"`, a CommonJS jest-fájlok és a `schema` `.cjs`-re nevezve, az ESLint-globok frissítve (D2). Ellenőrzés: a `payload migrate:status` betölti a configot; 516 unit teszt, tsc, lint, build és a `standalone` `server.js` indítása zöld.
- [ ] 1.2 `@payloadcms/db-postgres` (Payload-verzióval azonos), `postgresAdapter({ idType: 'uuid', push: false })`, `DATABASE_URI`. Ellenőrzés: `tsc`, `npm test`.
- [ ] 1.3 Kiinduló migráció (`migrate:create initial`), új `src/migrations/index.ts`; a 8 Mongo-migráció, a `migrate-global-docs`, a `localize-paths`, a `mongodb.ts` és a fake-Mongo tesztek törlése. Ellenőrzés: eldobható PostgreSQL-en a migráció kétszer fut, a második 0 lépés.
- [x] 1.2 `@payloadcms/db-postgres` (Payload-verzióval azonos), `postgresAdapter({ idType: 'uuid', push: false })`, `DATABASE_URI`. Ellenőrzés: `tsc`, `npm test`.
- [x] 1.3 Kiinduló migráció (`migrate:create initial`), új `src/migrations/index.ts`; a 8 Mongo-migráció, a `migrate-global-docs`, a `localize-paths`, a `mongodb.ts` és a fake-Mongo tesztek törlése. Ellenőrzés: eldobható PostgreSQL-en a migráció kétszer fut, a második 0 lépés.
## 2. Adatmigráció
- [ ] 2.1 `scripts/migrate-mongo-to-postgres.ts`: tiszta transzformációs függvények unit tesztekkel (lokalizált alak, vázlat kiválasztása, azonosítótérkép) (D3).
- [ ] 2.2 Futtatás egy staging-másolaton (eldobható Mongo és PostgreSQL az llmdev-en). Ellenőrzés: dokumentumszámok, a publikus hu/en oldalak szöveg-összevetése a pillanatképpel, partnerlogók, idempotens második futás.
- [x] 2.1 `scripts/transfer-content.ts` (export/import) és `src/lib/content-transfer.ts` tiszta, tesztelt függvényekkel (nyelvi bontás, sorazonosítók, azonosítótérkép, `upgradeDoc`) (D3).
- [x] 2.2 Futtatás egy staging-másolaton (eldobható Mongo és PostgreSQL az llmdev-en). Ellenőrzés: dokumentumszámok, a publikus hu/en oldalak szöveg-összevetése a pillanatképpel, partnerlogók, idempotens második futás.
## 3. Infrastruktúra
- [ ] 3.1 Port-ellenőrzés (`scripts/check-ports.sh`) az új Compose-fájlokra, az indítás előtt. Compose (staging, prod): PostgreSQL 16 szolgáltatás, `mozdit_web` adatbázis és felhasználó, belső hálózat, volume; `.env` sablonok (D4).
- [ ] 3.2 `deploy.sh`: `pg_dump` mentés a deploy előtt; az admin-seedelés a PostgreSQL-lel. Ellenőrzés: a `pre-deploy-tests.sh` és a staging smoke tesztek.
- [ ] 3.3 Az integrációs és e2e tesztek eldobható PostgreSQL-lel (D5).
- [x] 3.1 Port-ellenőrzés (`scripts/check-ports.sh`) az új Compose-fájlokra, az indítás előtt. Compose (staging, prod): PostgreSQL 16 szolgáltatás, `mozdit_web` adatbázis és felhasználó, belső hálózat, volume; `.env` sablonok (D4).
- [x] 3.2 `deploy.sh`: automatikus mentés a build előtt (`pg_dump` és az átállás idejére `mongodump`); a mentési blokkot a szerveren kipróbáltuk. Az admin-seedelés változatlanul a `first-register` végponttal. Ellenőrzés: a `pre-deploy-tests.sh` és a staging smoke tesztek.
- [ ] 3.3 Az integrációs és e2e tesztek eldobható PostgreSQL-lel (D5). *Átírva (a `pg` klienssel; a dev compose PostgreSQL-re állt, host-port 5433, bejegyezve); élő dev stacken még nem futott.*
## 4. Kiadás és kivezetés
- [ ] 4.1 Staging-átállás a Migration Plan szerint (külön jóváhagyással), `mongodump` archívummal.
- [ ] 4.2 Dokumentáció: `CLAUDE.md` (stack, környezeti változók), `.agent/steering/architecture.md`, `DOCKER.md`, `.agent/workflows/deploy.md`.
- [x] 4.2 Dokumentáció: `CLAUDE.md` (stack, környezeti változók), `.agent/steering/architecture.md`, `DOCKER.md`, `.agent/workflows/deploy.md`.
- [ ] 4.3 Egy kiadás múlva: a MongoDB-szolgáltatás és a `mongodb`, illetve `@payloadcms/db-mongodb` csomag törlése; a végső archívum helyének rögzítése.
- [ ] 4.4 Plane (MITHOME-136) és `TODO.md` szinkron, commit, push.
+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",
],
},
{
+1376 -3
View File
File diff suppressed because it is too large Load Diff
+9 -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",
@@ -55,6 +61,7 @@
"@testing-library/user-event": "^14.5",
"@types/jest": "^29.5",
"@types/node": "^20",
"@types/pg": "8.20.0",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/winston": "^2.4",
@@ -62,6 +69,7 @@
"eslint-config-next": "^16.3.4",
"jest": "^29.7",
"jest-environment-jsdom": "^29.7",
"pg": "8.20.0",
"tailwindcss": "^4",
"tsx": "^4.23.13",
"typescript": "^5",
+8 -3
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'
@@ -142,6 +142,11 @@ type LegalPageJson = {
sections: { id: string; title: string; content: string }[]
}
/** MITHOME-136: the JSON section `id` is the section anchor. */
function toLegalData({ sections, ...rest }: LegalPageJson) {
return { ...rest, sections: sections.map(({ id, ...section }) => ({ anchor: id, ...section })) }
}
/** Collections have no per-document "known slug" API like Globals do —
* find-by-slug, then update or create. Idempotent across re-runs. */
async function upsertLegalPage(payload: Payload, slug: string, json: LegalPageJson) {
@@ -155,12 +160,12 @@ async function upsertLegalPage(payload: Payload, slug: string, json: LegalPageJs
await payload.update({
collection: 'legal-pages',
id: existing.docs[0].id,
data: { slug, ...json, _status: 'published' },
data: { slug, ...toLegalData(json), _status: 'published' },
})
} else {
await payload.create({
collection: 'legal-pages',
data: { slug, ...json, _status: 'published' },
data: { slug, ...toLegalData(json), _status: 'published' },
})
}
}
+198
View File
@@ -0,0 +1,198 @@
/**
* MITHOME-136: one-off content transfer MongoDB → PostgreSQL, in two steps
* so that only one Payload instance runs per process and the bundle can be
* reviewed (and reused to seed a fresh database).
*
* export — reads through the shared config with the MongoDB adapter:
* MONGODB_URI=… PAYLOAD_SECRET=… node --import tsx scripts/transfer-content.ts export <bundle.json> [--no-submissions] [--media-dir media]
* import — writes through the site's config (PostgreSQL); refuses a non-empty target:
* DATABASE_URI=… PAYLOAD_SECRET=… node --import tsx scripts/transfer-content.ts import <bundle.json>
*
* The bundle holds every global and collection except users (the admin is
* re-created by deploy.sh), the published state in both locales, open drafts,
* and the upload files. It contains personal data (contact submissions) unless
* exported with --no-submissions: keep it out of git, chmod 600.
*/
import fs from 'fs'
import path from 'path'
import {
buildConfig,
commitTransaction,
createLocalReq,
getPayload,
initTransaction,
killTransaction,
type CollectionConfig,
type Payload,
type PayloadRequest,
} from 'payload'
import { mongooseAdapter } from '@payloadcms/db-mongodb'
import { sharedConfig } from '../src/payload.shared'
import { bundleCounts, localeData, upgradeDoc, type BundleDoc, type IdMap, type TransferBundle } from '../src/lib/content-transfer'
type Data = Record<string, unknown>
type Slug = Parameters<Payload['find']>[0]['collection']
type GlobalSlug = Parameters<Payload['findGlobal']>[0]['slug']
const [mode, bundlePath, ...flags] = process.argv.slice(2)
const flag = (name: string) => flags.includes(name)
const option = (name: string, fallback: string) => {
const i = flags.indexOf(name)
return i >= 0 && flags[i + 1] ? flags[i + 1] : fallback
}
const collections = (sharedConfig.collections ?? []).filter((c) => c.slug !== 'users')
const globals = sharedConfig.globals ?? []
const hasDrafts = (c: { versions?: unknown }) => typeof c.versions === 'object' && c.versions !== null && 'drafts' in c.versions && Boolean((c.versions as { drafts?: unknown }).drafts)
const LOCALES = ['hu', 'en'] as const
async function exportBundle(file: string) {
const config = buildConfig({ ...sharedConfig, db: mongooseAdapter({ url: process.env.MONGODB_URI || '' }) })
const payload = await getPayload({ config })
const mediaDir = path.resolve(option('--media-dir', 'media'))
const bundle: TransferBundle = { exportedAt: new Date().toISOString(), source: 'mongodb', globals: {}, collections: {}, files: {} }
for (const g of globals) {
const slug = g.slug as GlobalSlug
const published = (await payload.findGlobal({ slug, locale: 'all', depth: 0 })) as unknown as Data
const latest = (await payload.findGlobal({ slug, locale: 'all', depth: 0, draft: true })) as unknown as Data
bundle.globals[slug] = { published, ...(hasDrafts(g) && latest._status === 'draft' ? { draft: latest } : {}) }
}
for (const c of collections) {
if (c.slug === 'contact-submissions' && flag('--no-submissions')) continue
const slug = c.slug as Slug
const published = (await payload.find({ collection: slug, locale: 'all', depth: 0, pagination: false })).docs as unknown as Data[]
const latest = hasDrafts(c)
? ((await payload.find({ collection: slug, locale: 'all', depth: 0, pagination: false, draft: true })).docs as unknown as Data[])
: []
const byId = new Map<string, BundleDoc>(published.map((doc) => [String(doc.id), { published: doc }]))
for (const doc of latest) {
const entry = byId.get(String(doc.id))
if (doc._status !== 'draft') continue
if (entry) entry.draft = doc
else byId.set(String(doc.id), { published: { ...doc }, draft: doc }) // never published
}
bundle.collections[slug] = [...byId.values()]
if (c.upload) {
for (const { published: doc } of bundle.collections[slug]) {
const name = String(doc.filename)
bundle.files[name] = { mimeType: String(doc.mimeType), base64: fs.readFileSync(path.join(mediaDir, name)).toString('base64') }
}
}
}
fs.writeFileSync(file, JSON.stringify(bundle, null, 2), { mode: 0o600 })
payload.logger.info(`MITHOME-136 export: ${JSON.stringify(bundleCounts(bundle))} → ${file}`)
}
async function assertEmptyTarget(payload: Payload) {
for (const c of collections) {
const { totalDocs } = await payload.count({ collection: c.slug as Slug })
if (totalDocs > 0) throw new Error(`Target is not empty: ${c.slug} has ${totalDocs} document(s). Nothing was written.`)
}
}
async function importCollection(payload: Payload, req: PayloadRequest, c: CollectionConfig, docs: BundleDoc[], bundle: TransferBundle, ids: IdMap) {
const slug = c.slug as Slug
const drafts = hasDrafts(c)
for (const raw of docs) {
const entry: BundleDoc = { published: upgradeDoc(c.slug, raw.published), ...(raw.draft ? { draft: upgradeDoc(c.slug, raw.draft) } : {}) }
const oldId = String(entry.published.id)
const neverPublished = entry.published._status === 'draft'
const status = drafts ? { _status: neverPublished ? 'draft' : 'published' } : {}
const file = c.upload
? (() => {
const name = String(entry.published.filename)
const stored = bundle.files[name]
const data = Buffer.from(stored.base64, 'base64')
return { data, mimetype: stored.mimeType, name, size: data.length }
})()
: undefined
const created = await payload.create({
req,
collection: slug,
locale: 'hu',
data: { ...localeData(c.fields, entry.published, 'hu', ids), ...status } as never,
...(file ? { file, overwriteExistingFiles: true } : {}),
draft: neverPublished,
})
ids.set(oldId, String(created.id))
await payload.update({
req,
collection: slug,
id: created.id,
locale: 'en',
data: { ...localeData(c.fields, entry.published, 'en', ids), ...status } as never,
draft: neverPublished,
})
if (entry.draft && !neverPublished) {
for (const locale of LOCALES) {
await payload.update({ req, collection: slug, id: created.id, locale, draft: true, data: localeData(c.fields, entry.draft, locale, ids) as never })
}
}
}
}
async function importBundle(file: string) {
const bundle = JSON.parse(fs.readFileSync(file, 'utf8')) as TransferBundle
const { default: config } = await import('../src/payload.config')
const payload = await getPayload({ config })
await assertEmptyTarget(payload)
// One transaction: a failure leaves the target untouched ("change nothing").
const req = await createLocalReq({}, payload)
await initTransaction(req)
try {
const ids: IdMap = new Map()
// Uploads first, so relationships can be mapped to the new ids.
const ordered = [...collections].sort((a, b) => Number(Boolean(b.upload)) - Number(Boolean(a.upload)))
for (const c of ordered) {
await importCollection(payload, req, c, bundle.collections[c.slug] ?? [], bundle, ids)
}
for (const g of globals) {
const entry = bundle.globals[g.slug]
if (!entry) continue
const slug = g.slug as GlobalSlug
const status = hasDrafts(g) ? { _status: 'published' } : {}
for (const locale of LOCALES) {
await payload.updateGlobal({ req, slug, locale, data: { ...localeData(g.fields, entry.published, locale, ids), ...status } as never })
}
if (entry.draft) {
for (const locale of LOCALES) {
await payload.updateGlobal({ req, slug, locale, draft: true, data: localeData(g.fields, entry.draft, locale, ids) as never })
}
}
}
await commitTransaction(req)
} catch (error) {
await killTransaction(req)
throw error
}
const counts: Record<string, number> = {}
for (const c of collections) counts[c.slug] = (await payload.count({ collection: c.slug as Slug })).totalDocs
payload.logger.info(`MITHOME-136 import: expected ${JSON.stringify(bundleCounts(bundle))}, got ${JSON.stringify(counts)}`)
}
async function main() {
if (!bundlePath || (mode !== 'export' && mode !== 'import')) {
console.error('Usage: transfer-content.ts export|import <bundle.json> [--no-submissions] [--media-dir DIR]')
process.exit(2)
}
if (mode === 'export') await exportBundle(bundlePath)
else await importBundle(bundlePath)
process.exit(0)
}
main().catch((error) => {
// Payload validation errors carry the failing fields in data.errors.
const details = (error as { data?: { collection?: string; errors?: unknown } })?.data
console.error('MITHOME-136 transfer failed:', error instanceof Error ? error.message : error)
if (details) console.error(JSON.stringify(details, null, 2))
process.exit(1)
})
@@ -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()
})
})
+36 -67
View File
@@ -9,21 +9,31 @@
* Mongoose collections. Assumes the Docker dev DB already has content
* migrated (`npm run migrate:content`) — see docs/backups for a snapshot if
* you need to reseed a throwaway environment.
*
* MITHOME-136: the stack runs PostgreSQL (dev host port 5433, registered);
* MITHOME-137: grafana moved to 3012 (3001 is taken on llmdev).
*/
import { MongoClient, ObjectId } from 'mongodb'
import { Client } from 'pg'
const DOCKER_SERVICES = {
app: 'http://localhost:8080',
mongoExpress: 'http://localhost:8081',
grafana: 'http://localhost:3001',
grafana: 'http://localhost:3012',
loki: 'http://localhost:3100',
mongodb: 'mongodb://admin:password123@localhost:27018/mozdit?authSource=admin'
postgres: 'postgresql://mozdit_web:devpassword@localhost:5433/mozdit_web',
}
async function query<T extends Record<string, unknown>>(sql: string, params: unknown[] = []): Promise<T[]> {
const client = new Client({ connectionString: DOCKER_SERVICES.postgres })
await client.connect()
try {
return (await client.query<T>(sql, params)).rows
} finally {
await client.end()
}
}
describe('Docker Environment Integration Tests', () => {
let mongoClient: MongoClient | null = null
beforeAll(async () => {
// Skip integration tests if not in Docker environment
if (process.env.NODE_ENV === 'test' && !process.env.INTEGRATION_TESTS) {
@@ -32,12 +42,6 @@ describe('Docker Environment Integration Tests', () => {
}
})
afterAll(async () => {
if (mongoClient) {
await mongoClient.close()
}
})
describe('Service Health Checks', () => {
it('should connect to Next.js app', async () => {
if (process.env.NODE_ENV === 'test' && !process.env.INTEGRATION_TESTS) {
@@ -55,40 +59,28 @@ describe('Docker Environment Integration Tests', () => {
expect(data).toHaveProperty('environment')
})
it('should connect to MongoDB directly', async () => {
it('should connect to PostgreSQL directly', async () => {
if (process.env.NODE_ENV === 'test' && !process.env.INTEGRATION_TESTS) {
return
}
mongoClient = new MongoClient(DOCKER_SERVICES.mongodb)
await mongoClient.connect()
const adminDb = mongoClient.db('admin')
const result = await adminDb.admin().ping()
expect(result).toEqual({ ok: 1 })
const [row] = await query<{ ok: number }>('select 1 as ok')
expect(row.ok).toBe(1)
})
it('should verify MongoDB initialization', async () => {
it('should verify the schema migrations ran', async () => {
if (process.env.NODE_ENV === 'test' && !process.env.INTEGRATION_TESTS) {
return
}
if (!mongoClient) {
mongoClient = new MongoClient(DOCKER_SERVICES.mongodb)
await mongoClient.connect()
const tables = (await query<{ table_name: string }>(
"select table_name from information_schema.tables where table_schema = 'public'",
)).map((t) => t.table_name)
for (const table of ['home', 'legal_pages', 'partners', 'contact_submissions', 'users', 'products', 'payload_migrations']) {
expect(tables).toContain(table)
}
const mozditDb = mongoClient.db('mozdit')
const collections = await mozditDb.listCollections().toArray()
const collectionNames = collections.map(c => c.name)
// Payload Globals (Home/About/Services/Contact/Common) live in a
// single `globals` collection, one document per global.
expect(collectionNames).toContain('globals')
expect(collectionNames).toContain('legal-pages')
expect(collectionNames).toContain('partners')
expect(collectionNames).toContain('contact-submissions')
expect(collectionNames).toContain('users')
const migrations = await query<{ name: string }>('select name from payload_migrations')
expect(migrations.map((m) => m.name)).toEqual(expect.arrayContaining([expect.stringMatching(/_initial$/)]))
})
it('should verify the Home global exists and is published', async () => {
@@ -96,30 +88,11 @@ describe('Docker Environment Integration Tests', () => {
return
}
if (!mongoClient) {
mongoClient = new MongoClient(DOCKER_SERVICES.mongodb)
await mongoClient.connect()
}
const mozditDb = mongoClient.db('mozdit')
const home = await mozditDb.collection('globals').findOne({ globalType: 'home' })
if (!home) throw new Error('Home global document not found')
expect(home).toHaveProperty('_status', 'published')
expect(home).toHaveProperty('hero')
expect(home.hero).toHaveProperty('title')
})
it('should access Mongo Express UI', async () => {
if (process.env.NODE_ENV === 'test' && !process.env.INTEGRATION_TESTS) {
return
}
const response = await fetch(DOCKER_SERVICES.mongoExpress)
expect(response.status).toBe(200)
const html = await response.text()
expect(html).toContain('Mongo Express')
const [home] = await query<{ _status: string }>('select _status from home limit 1')
if (!home) throw new Error('Home global row not found')
expect(home._status).toBe('published')
const titles = await query<{ hero_title: string }>("select hero_title from home_locales where _locale = 'hu'")
expect(titles[0]?.hero_title).toBeTruthy()
})
it('should access Grafana UI', async () => {
@@ -182,14 +155,10 @@ describe('Docker Environment Integration Tests', () => {
expect(result).toHaveProperty('timestamp')
expect(result).toHaveProperty('submissionId')
if (!mongoClient) {
mongoClient = new MongoClient(DOCKER_SERVICES.mongodb)
await mongoClient.connect()
}
const savedSubmission = await mongoClient
.db('mozdit')
.collection('contact-submissions')
.findOne({ _id: new ObjectId(result.submissionId) })
const [savedSubmission] = await query(
'select name, email, subject, message, gdpr_consent as "gdprConsent", status from contact_submissions where id = $1',
[result.submissionId],
)
expect(savedSubmission).toEqual(expect.objectContaining({
name: contactData.name,
email: contactData.email,
@@ -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)
})
})
+6 -4
View File
@@ -17,9 +17,8 @@ import { legalValidationGroup } from './fields/legalValidation'
* nem vezetünk be külön szerializációt egy még nem létező render-rétegért.
*
* MITHOME-112 lokalizáció: a cím, a dátumszöveg és a szakaszok címe/tartalma
* lokalizált; a `slug` (URL-azonosító) és a szakasz-`id` közös, a `sections`
* tömb maga is közös (sorrend nyelvenként azonos). A meglévő adatot a
* src/migrations/20260929_localize_legal_pages.ts alakítja át.
* lokalizált; a `slug` (URL-azonosító) és a szakasz-`anchor` közös, a `sections`
* tömb maga is közös (sorrend nyelvenként azonos).
*/
export const LegalPages: CollectionConfig = {
slug: 'legal-pages',
@@ -53,7 +52,10 @@ export const LegalPages: CollectionConfig = {
type: 'array',
required: true,
fields: [
{ name: 'id', type: 'text', required: true },
// MITHOME-136: the section anchor is its own field. It used to be the
// array row `id`, which PostgreSQL stores as a table-wide primary key,
// so two pages with the same anchor ("bevezetes") collided.
{ name: 'anchor', type: 'text', required: true, admin: { description: 'A szakasz horgonya (pl. bevezetes), minden nyelven azonos.' } },
{ name: 'title', type: 'text', required: true, localized: true },
{ name: 'content', type: 'textarea', required: true, localized: true },
],
+4
View File
@@ -62,6 +62,10 @@ export const Products: CollectionConfig = {
name: 'status',
label: 'Életciklus-állapot',
type: 'select',
// MITHOME-136: own PostgreSQL enum name. The default "enum_products_status"
// is also Payload's name for the drafts `_status` enum, so the two
// collided and only draft/published were accepted.
enumName: 'enum_products_lifecycle_status',
required: true,
defaultValue: 'draft',
options: PRODUCT_STATUSES.map((value) => ({ label: PRODUCT_STATUS_LABELS[value], value })),
@@ -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
@@ -0,0 +1,95 @@
import type { Field } from 'payload'
import { bundleCounts, localeData, upgradeDoc } from './content-transfer'
const FIELDS: Field[] = [
{ name: 'name', type: 'text' },
{ name: 'title', type: 'text', localized: true },
{
name: 'hero',
type: 'group',
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'icon', type: 'text' },
],
},
{
name: 'items',
type: 'array',
fields: [
{ name: 'label', type: 'text', localized: true },
{ name: 'order', type: 'number' },
],
},
{ name: 'paragraphs', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] },
{ type: 'row', fields: [{ name: 'result', type: 'text' }] },
{ name: 'logo', type: 'upload', relationTo: 'media' },
]
const DOC = {
id: 'old-doc',
_id: 'old-doc',
__v: 0,
_status: 'published',
updatedAt: '2026-09-29T10:00:00.000Z',
createdAt: '2026-09-01T08:00:00.000Z',
name: 'mIT Start',
title: { hu: 'Cím', en: 'Title' },
hero: { title: { hu: 'Hős', en: 'Hero' }, icon: '🔥' },
items: [{ id: 'row1', label: { hu: 'Egy', en: 'One' }, order: 1 }],
paragraphs: { hu: [{ id: 'p1', value: 'Első' }, { id: 'p2', value: 'Második' }], en: [{ id: 'p3', value: 'First' }] },
result: 'ok',
logo: { id: 'old-media', filename: 'logo.png' },
}
describe('content transfer (MITHOME-136)', () => {
it('should split a locale-all document into Hungarian data', () => {
expect(localeData(FIELDS, DOC, 'hu')).toEqual({
name: 'mIT Start',
title: 'Cím',
hero: { title: 'Hős', icon: '🔥' },
items: [{ id: 'row1', label: 'Egy', order: 1 }],
paragraphs: [{ id: 'p1', value: 'Első' }, { id: 'p2', value: 'Második' }],
result: 'ok',
logo: 'old-media',
createdAt: '2026-09-01T08:00:00.000Z',
})
})
it('should keep array row ids so the English update hits the same rows', () => {
const en = localeData(FIELDS, DOC, 'en')
expect(en.items).toEqual([{ id: 'row1', label: 'One', order: 1 }])
expect(en.paragraphs).toEqual([{ id: 'p3', value: 'First' }])
expect(en.title).toBe('Title')
})
it('should map upload ids to the new documents', () => {
const ids = new Map([['old-media', 'new-media']])
expect(localeData(FIELDS, DOC, 'hu', ids).logo).toBe('new-media')
})
it('should drop system fields and leave missing fields out', () => {
const data = localeData(FIELDS, { name: 'x', _status: 'draft', globalType: 'home' }, 'hu')
expect(data).toEqual({ name: 'x' })
})
it('should count the documents of a bundle', () => {
expect(
bundleCounts({
exportedAt: '',
source: '',
globals: { home: { published: {} } },
collections: { partners: [{ published: {} }, { published: {} }] },
files: {},
}),
).toEqual({ partners: 2, 'global:home': 1 })
})
it('should move the legal section anchor out of the row id, unique per page', () => {
const doc = { slug: 'adatvedelem', sections: [{ id: 'bevezetes', title: { hu: 'Bevezetés' } }] }
expect(upgradeDoc('legal-pages', doc).sections).toEqual([
{ id: 'adatvedelem-bevezetes', anchor: 'bevezetes', title: { hu: 'Bevezetés' } },
])
expect(upgradeDoc('legal-pages', upgradeDoc('legal-pages', doc))).toEqual(upgradeDoc('legal-pages', doc))
expect(upgradeDoc('partners', doc)).toBe(doc)
})
})
+100
View File
@@ -0,0 +1,100 @@
/**
* MITHOME-136: pure helpers of the one-off MongoDB → PostgreSQL content
* transfer (scripts/transfer-content.ts).
*
* The export reads every document with `locale: 'all'`, so each localized
* field arrives as `{ hu, en }`. Payload writes one locale at a time, so the
* import splits a document into per-locale data using the field config:
* localized fields take the locale's value, groups/unnamed rows recurse,
* array rows keep their ids (the English update must hit the same rows), and
* upload/relationship ids are mapped from the old to the new id.
*/
import type { Field } from 'payload'
export type Locale = 'hu' | 'en'
type Data = Record<string, unknown>
export type IdMap = Map<string, string>
const SYSTEM_KEYS = new Set(['id', '_id', '__v', 'globalType', 'updatedAt', '_status'])
const isObject = (value: unknown): value is Data =>
typeof value === 'object' && value !== null && !Array.isArray(value)
function mapId(value: unknown, ids: IdMap): unknown {
if (value === null || value === undefined) return value
const id = isObject(value) ? value.id : value
return typeof id === 'string' ? (ids.get(id) ?? id) : id
}
function splitFields(fields: readonly Field[], source: Data, locale: Locale, ids: IdMap, out: Data): Data {
for (const field of fields) {
if (!('name' in field) || !field.name) {
// row / collapsible: unnamed wrappers keep their fields on the same level
if ('fields' in field) splitFields(field.fields, source, locale, ids, out)
continue
}
if (!(field.name in source)) continue
const raw = source[field.name]
const value = 'localized' in field && field.localized && isObject(raw) ? raw[locale] : raw
if (field.type === 'group' && isObject(value)) {
out[field.name] = splitFields(field.fields, value, locale, ids, {})
} else if (field.type === 'array' && Array.isArray(value)) {
out[field.name] = value.map((row) =>
isObject(row) ? { ...(row.id ? { id: row.id } : {}), ...splitFields(field.fields, row, locale, ids, {}) } : row,
)
} else if (field.type === 'upload' || field.type === 'relationship') {
out[field.name] = Array.isArray(value) ? value.map((v) => mapId(v, ids)) : mapId(value, ids)
} else {
out[field.name] = value
}
}
return out
}
/**
* Shape changes between the MongoDB schema and the current one, applied to an
* exported document before it is split by locale.
* - legal-pages: the section anchor was the array row `id`; it is now the
* `anchor` field, and the row id must be unique across all pages (it is a
* table-wide primary key in PostgreSQL), so it becomes `<slug>-<anchor>`.
*/
export function upgradeDoc(collection: string, doc: Data): Data {
if (collection !== 'legal-pages' || !Array.isArray(doc.sections)) return doc
return {
...doc,
sections: doc.sections.map((section) =>
isObject(section) && typeof section.id === 'string' && !('anchor' in section)
? { ...section, id: `${doc.slug}-${section.id}`, anchor: section.id }
: section,
),
}
}
/** The data of one locale, ready for `create`/`update` with that `locale`. */
export function localeData(fields: readonly Field[], doc: Data, locale: Locale, ids: IdMap = new Map()): Data {
const out = splitFields(fields, doc, locale, ids, {})
for (const key of SYSTEM_KEYS) delete out[key]
// Keep the original creation time (contact submission retention).
if (typeof doc.createdAt === 'string') out.createdAt = doc.createdAt
return out
}
/** Count documents per collection/global in an export bundle. */
export function bundleCounts(bundle: TransferBundle): Record<string, number> {
const counts: Record<string, number> = {}
for (const [slug, docs] of Object.entries(bundle.collections)) counts[slug] = docs.length
for (const slug of Object.keys(bundle.globals)) counts[`global:${slug}`] = 1
return counts
}
export type BundleDoc = { published: Data; draft?: Data }
export type TransferBundle = {
exportedAt: string
source: string
globals: Record<string, BundleDoc>
collections: Record<string, BundleDoc[]>
/** Upload files by filename, base64 — the bundle is self-contained. */
files: Record<string, { mimeType: string; base64: string }>
}
-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
}
@@ -4,14 +4,14 @@ const hu = {
title: 'Adatvédelmi Tájékoztató',
lastUpdated: '2026. augusztus 22.',
sections: [
{ id: 'bevezetes', title: '1. Bevezetés', content: 'A mozdIT Bt. mint adatkezelő…' },
{ id: 'jogok', title: '5. Az érintettek jogai', content: 'Az érintettek bármikor…' },
{ id: 'r1', anchor: 'bevezetes', title: '1. Bevezetés', content: 'A mozdIT Bt. mint adatkezelő…' },
{ id: 'r2', anchor: 'jogok', title: '5. Az érintettek jogai', content: 'Az érintettek bármikor…' },
],
}
const en = {
title: 'Privacy Notice',
lastUpdated: '22 August 2026',
sections: [{ id: 'bevezetes', title: '1. Introduction', content: 'mozdIT Bt., as controller…' }],
sections: [{ id: 'r1', anchor: 'bevezetes', title: '1. Introduction', content: 'mozdIT Bt., as controller…' }],
}
describe('buildLegalValidationPrompt (MITHOME-113)', () => {
@@ -34,7 +34,7 @@ describe('buildLegalValidationPrompt (MITHOME-113)', () => {
})
it('should return undefined when there is no English text', () => {
expect(buildLegalValidationPrompt(hu, { title: ' ', sections: [{ id: 'bevezetes', title: null, content: '' }] })).toBeUndefined()
expect(buildLegalValidationPrompt(hu, { title: ' ', sections: [{ id: 'r1', anchor: 'bevezetes', title: null, content: '' }] })).toBeUndefined()
expect(hasEnglishContent({})).toBe(false)
})
})
+2 -2
View File
@@ -11,7 +11,7 @@
* document texts stay in their original languages.
*/
export type LegalSection = { id?: string | null; title?: string | null; content?: string | null }
export type LegalSection = { id?: string | null; anchor?: string | null; title?: string | null; content?: string | null }
export type LegalText = { title?: string | null; lastUpdated?: string | null; sections?: LegalSection[] | null }
const MISSING = '(missing — report as high severity)'
@@ -55,7 +55,7 @@ export function buildLegalValidationPrompt(hu: LegalText, en: LegalText): string
const sections = (hu.sections ?? []).map((section, index) => {
const english = enById.get(section.id) ?? {}
return [
`--- Section ${index + 1}${section.id ? ` (${section.id})` : ''} ---`,
`--- Section ${index + 1}${section.anchor ? ` (${section.anchor})` : ''} ---`,
block('HU', section.title, section.content),
block('EN', english.title, english.content),
].join('\n')
-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_202255_initial from './20260929_202255_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_202255_initial.up,
down: migration_20260929_202255_initial.down,
name: '20260929_202255_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',
},
]
];
+9 -1
View File
@@ -158,7 +158,8 @@ describe('Payload globals', () => {
// MITHOME-112: `slug` is the shared URL identifier of LegalPages.
// MITHOME-113: `result`/`notes` are legal-validation metadata, not copy.
// MITHOME-130: a product `name` is a brand, the same in every language.
const SHARED_TEXT_FIELDS = new Set(['icon', 'id', 'address', 'slug', 'result', 'notes', 'name'])
// MITHOME-136: the legal section `anchor` (formerly its row `id`) is shared too.
const SHARED_TEXT_FIELDS = new Set(['icon', 'id', 'anchor', 'address', 'slug', 'result', 'notes', 'name'])
type Node = FieldLike & { localized?: boolean; fields?: Node[] }
type Finding = { path: string; type?: string; localized: boolean }
@@ -285,6 +286,13 @@ describe('MITHOME-130 hosting plans', () => {
expect(slug).toMatchObject({ required: true, unique: true })
})
it('should give the lifecycle status its own PostgreSQL enum (MITHOME-136)', () => {
// Regression: the default enum name equals the drafts `_status` enum, and
// PostgreSQL then only accepted draft/published.
const status = findField(Products.fields, 'status') as unknown as { enumName?: string }
expect(status.enumName).toBe('enum_products_lifecycle_status')
})
it('should require a whole, non-negative net price and default to yearly billing', () => {
const net = findField(group('pricing'), 'netAmount') as unknown as FieldLike & { validate: Validate }
expect(net.required).toBe(true)
+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,
}