Compare commits
40
Commits
f71bcb2b67
...
main
No files matched your search
@@ -9,6 +9,11 @@ DATABASE_URL="postgresql://wabenhain:wabenhain@localhost:5432/wabenhain?schema=p
|
||||
# MySQL/MariaDB stattdessen:
|
||||
# DATABASE_URL="mysql://wabenhain:wabenhain@localhost:3306/wabenhain"
|
||||
|
||||
# Optional: Groesse des Datenbank-Verbindungspools PRO Instanz (Standard 20,
|
||||
# siehe src/lib/db-adapter.ts). Beim Hochskalieren mitziehen, damit
|
||||
# Instanzen x Poolgroesse plus CronJobs unter max_connections bleiben.
|
||||
# DATABASE_POOL_SIZE=20
|
||||
|
||||
# Postgres-Zugangsdaten fuer docker-compose.yml (Datenbank-Container)
|
||||
POSTGRES_USER=wabenhain
|
||||
POSTGRES_PASSWORD=change-me
|
||||
@@ -31,6 +36,11 @@ STRIPE_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxxxxx
|
||||
STRIPE_PUBLISHABLE_KEY=pk_test_xxxxxxxxxxxxxxxxxxxxxxxx
|
||||
# Webhook-Secret aus `stripe listen` bzw. dem Stripe-Dashboard-Webhook-Endpoint
|
||||
STRIPE_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxxxxxxxxxx
|
||||
# Optional: Kundenportal-Konfiguration (bpc_...) fuer "Zahlungsart aendern" im
|
||||
# Abo, angelegt von `pnpm tsx scripts/stripe-setup.ts --apply`. Leer = die App
|
||||
# findet sie ueber ihre Metadaten; fehlt sie ganz, bietet das Konto "Zahlungsart
|
||||
# aendern" nicht an (die Stripe-Standardkonfiguration wird nie benutzt).
|
||||
STRIPE_PORTAL_CONFIGURATION_ID=
|
||||
|
||||
# Admin-Zugang: Der interne /admin-Bereich wird NICHT per Basic-Auth
|
||||
# geschuetzt, sondern ueber das normale Kundenkonto-Login (/konto) und die
|
||||
@@ -100,6 +110,19 @@ SMTP_FROM="Wabenhain <[email protected]>"
|
||||
# Details siehe src/lib/apicore-client.ts.
|
||||
APICORE_API_URL=
|
||||
APICORE_API_KEY=
|
||||
# Bestandsabgleich: der Schluessel braucht zusaetzlich "Verkaeufe und
|
||||
# Rueckbuchungen des Shops buchen" (shop-sync:write). In ApiCore einen Webhook
|
||||
# fuer "stock.changed" auf https://<shop>/api/apicore/webhook anlegen und das
|
||||
# dort angezeigte Secret hier eintragen. Ohne Secret wird der Webhook
|
||||
# abgelehnt; der CronJob gleicht dann alle 10 Minuten ab.
|
||||
APICORE_WEBHOOK_SECRET=
|
||||
|
||||
# Rechnungsexport fuer die Buchhaltung (ERPNext, collab.vycept.com): ERPNext
|
||||
# holt damit stuendlich alle Rechnungen samt PDF ab und ordnet sie der
|
||||
# Stripe-Zahlung zu (GET /api/erp/rechnungen, nur lesend, siehe
|
||||
# src/lib/erp-export.ts). Mindestens 32 Zeichen, z. B. `openssl rand -hex 32`;
|
||||
# derselbe Wert steht in ERPNext als WABENHAIN_ERP_TOKEN. Leer = Export aus.
|
||||
ERP_EXPORT_TOKEN=
|
||||
|
||||
# DHL Parcel DE Shipping API ("Post & Parcel Germany", developer.dhl.com) —
|
||||
# ermoeglicht das Erstellen von DHL-Versandmarken per Knopfdruck im
|
||||
@@ -225,6 +248,18 @@ UPLOAD_DIR=./uploads
|
||||
# k8s/04-uploads-pvc.yaml und den Sicherungs-CronJob k8s/07-backup-cronjob.yaml.
|
||||
INVOICE_DIR=./invoices
|
||||
|
||||
# Ablage der Urkunden-PDFs der Bienenpatenschaft (lib/sponsorship/storage.ts).
|
||||
# Aus demselben Grund wie INVOICE_DIR NIE unterhalb von UPLOAD_DIR — eine
|
||||
# Urkunde traegt Namen und eine persoenliche Widmung. Die Anwendung startet
|
||||
# nicht, wenn das Verzeichnis im Upload-Verzeichnis liegt. In Kubernetes ein
|
||||
# Unterordner des gesicherten Rechnungs-Volumes (siehe k8s/01-configmap.yaml).
|
||||
CERTIFICATE_DIR=./certificates
|
||||
|
||||
# Hintergrundaufgaben im App-Prozess (src/instrumentation.ts): Urkunden
|
||||
# nachholen, Abo-Lieferungen anlegen, Verzug pruefen. "off" schaltet sie ab,
|
||||
# z.B. fuer eine zweite Instanz, die nur Seiten ausliefern soll.
|
||||
BACKGROUND_JOBS=on
|
||||
|
||||
# Umsatzsteuersatz in GANZEN Prozent, ausgewiesen auf jeder Rechnung.
|
||||
# 7 = ermaessigter Satz (Honig als Lebensmittel, Anlage 2 zum UStG)
|
||||
# 19 = voller Satz
|
||||
@@ -250,6 +285,10 @@ VAT_RATE_PERCENT=7
|
||||
VAT_RATE_PERCENT_HONIG=7
|
||||
VAT_RATE_PERCENT_KERZEN=19
|
||||
VAT_RATE_PERCENT_PROPOLIS=19
|
||||
# Weitere Bienenprodukte (Kategorie SONSTIGES, z. B. Salben, Wachstuecher)
|
||||
VAT_RATE_PERCENT_SONSTIGES=19
|
||||
# Bienenpatenschaft (Leistung, Regelsatz; Honiganteil eigene Position).
|
||||
VAT_RATE_PERCENT_PATENSCHAFT=19
|
||||
|
||||
# Threads, die ffmpeg beim Umrechnen eines hochgeladenen Videos benutzen darf
|
||||
# (Admin -> Inhalte -> Hero-Video). Leer lassen heisst 2, erlaubt sind 1 bis 8.
|
||||
|
||||
@@ -3,14 +3,89 @@ name: Docker Image bauen und veroeffentlichen
|
||||
# Laeuft bei jedem Push auf main (rollierendes ":latest" + ":<kurzer-commit-hash>")
|
||||
# und bei Versions-Tags wie "v1.2.3" (zusaetzlich als eigener Tag). Manuell
|
||||
# ueber "Run workflow" in der Gitea-Weboberflaeche ebenfalls startbar.
|
||||
#
|
||||
# Qualitaets-Gate: Ein Image entsteht nur, wenn lint (inkl. audit), typecheck
|
||||
# und test gruen sind. Die Pruefungen laufen auf "ci-isolated" (Jobs ohne
|
||||
# Docker-Socket und ohne Clusternetz, Runner-Doku im VyCept-Repo,
|
||||
# docs/BETRIEB.md 11b); nur der Image-Build braucht "docker-builder".
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
workflow_dispatch:
|
||||
|
||||
# Ein neuer Push bricht den ueberholten Lauf ab, statt ihn zu Ende zu rechnen.
|
||||
concurrency:
|
||||
group: docker-build-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
NEXT_TELEMETRY_DISABLED: "1"
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ci-isolated
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- name: Runner-Isolation pruefen
|
||||
run: bash scripts/ci-runner-isolation.sh
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with: { node-version: "22" }
|
||||
- uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
|
||||
with:
|
||||
path: |
|
||||
~/.cache/pnpm
|
||||
~/.cache/pnpm-store
|
||||
key: pnpm-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: pnpm-
|
||||
- run: export pnpm_config_store_dir="$HOME/.cache/pnpm-store" pnpm_config_cache_dir="$HOME/.cache/pnpm" && corepack enable && pnpm install --frozen-lockfile
|
||||
- run: pnpm lint
|
||||
# Bekannte Luecken in Laufzeit-Abhaengigkeiten (ab "high") brechen den Lauf ab.
|
||||
- run: pnpm audit --prod --audit-level high
|
||||
|
||||
typecheck:
|
||||
runs-on: ci-isolated
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- name: Runner-Isolation pruefen
|
||||
run: bash scripts/ci-runner-isolation.sh
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with: { node-version: "22" }
|
||||
- uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
|
||||
with:
|
||||
path: |
|
||||
~/.cache/pnpm
|
||||
~/.cache/pnpm-store
|
||||
key: pnpm-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: pnpm-
|
||||
# postinstall erzeugt beide Prisma-Clients (Postgres + MySQL), die tsc braucht.
|
||||
- run: export pnpm_config_store_dir="$HOME/.cache/pnpm-store" pnpm_config_cache_dir="$HOME/.cache/pnpm" && corepack enable && pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
|
||||
test:
|
||||
runs-on: ci-isolated
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- name: Runner-Isolation pruefen
|
||||
run: bash scripts/ci-runner-isolation.sh
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with: { node-version: "22" }
|
||||
- uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
|
||||
with:
|
||||
path: |
|
||||
~/.cache/pnpm
|
||||
~/.cache/pnpm-store
|
||||
key: pnpm-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: pnpm-
|
||||
- run: export pnpm_config_store_dir="$HOME/.cache/pnpm-store" pnpm_config_cache_dir="$HOME/.cache/pnpm" && corepack enable && pnpm install --frozen-lockfile
|
||||
# Unit- und Komponententests (jsdom), ohne Datenbank.
|
||||
- run: pnpm test
|
||||
|
||||
build-and-push:
|
||||
needs: [lint, typecheck, test]
|
||||
runs-on: docker-builder
|
||||
env:
|
||||
# Fest hinterlegt statt ${{ gitea.server_url }}: das hat in manchen
|
||||
@@ -77,6 +152,16 @@ jobs:
|
||||
type=sha,format=short
|
||||
type=semver,pattern={{version}}
|
||||
|
||||
- name: Metadaten Werkzeuge
|
||||
id: meta-tools
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY_PUSH }}/${{ steps.image.outputs.name }}-tools
|
||||
tags: |
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
type=sha,format=short
|
||||
type=semver,pattern={{version}}
|
||||
|
||||
# Ein einzelnes Image traegt beide Prisma-Client-Varianten (Postgres +
|
||||
# MySQL, waehlt zur Laufzeit per DATABASE_PROVIDER, siehe
|
||||
# src/lib/prisma.ts) UND die Migrations-/Seed-Tools (siehe Dockerfile-
|
||||
@@ -86,8 +171,22 @@ jobs:
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
target: runner
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
# Werkzeug-Image fuer die CronJobs (Dockerfile "AS tools"); nutzt die
|
||||
# gemeinsamen Build-Stufen aus dem Cache des ersten Builds.
|
||||
- name: Werkzeuge bauen und pushen
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
target: tools
|
||||
push: true
|
||||
tags: ${{ steps.meta-tools.outputs.tags }}
|
||||
labels: ${{ steps.meta-tools.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -56,3 +56,6 @@ next-env.d.ts
|
||||
|
||||
# Lokal abgelegte Rechnungs-PDFs (INVOICE_DIR) — Belege gehoeren nie ins Repository.
|
||||
/invoices
|
||||
|
||||
# Lokal abgelegte Urkunden-PDFs der Bienenpatenschaft (CERTIFICATE_DIR).
|
||||
/certificates
|
||||
+24
@@ -52,6 +52,27 @@ RUN pnpm add --save-prod \
|
||||
@prisma/client@^7.9.1 @prisma/adapter-pg@^7.9.1 \
|
||||
@prisma/adapter-mariadb@^7.9.1 mariadb@^3.5.3
|
||||
|
||||
# --- Werkzeuge (CronJobs) -------------------------------------------------
|
||||
# Eigenes Image <repo>-tools fuer die Skripte unter scripts/, die als
|
||||
# CronJob laufen (Bestandsabgleich mit ApiCore, Freigabe haengender
|
||||
# Bestellungen), nach dem Muster von artista-modelcamp-tools. Das runner-
|
||||
# Image enthaelt nur den Standalone-Output: dort fehlen tsconfig.json (der
|
||||
# Pfad-Alias "@/") und Pakete wie stripe, die Skripte brechen dort mit
|
||||
# "Cannot find module" ab. Steht VOR runner, damit ein Build ohne --target
|
||||
# weiterhin das App-Image liefert.
|
||||
FROM base AS tools
|
||||
ENV NODE_ENV=production
|
||||
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 --ingroup nodejs nextjs
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/node_modules ./node_modules
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/src ./src
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/scripts ./scripts
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/assets ./assets
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/prisma.config.ts /app/package.json /app/tsconfig.json ./
|
||||
ENV PATH="/app/node_modules/.bin:${PATH}"
|
||||
USER 1001
|
||||
CMD ["tsx", "scripts/apicore-stock-sync.ts"]
|
||||
|
||||
# --- Runtime --------------------------------------------------------------
|
||||
FROM base AS runner
|
||||
ENV NODE_ENV=production
|
||||
@@ -67,6 +88,9 @@ RUN addgroup --system --gid 1001 nodejs \
|
||||
&& adduser --system --uid 1001 nextjs
|
||||
|
||||
COPY --from=builder /app/public ./public
|
||||
# Eingebettete Schriften der Rechnungs-PDFs (PDF/A-3, lib/einvoice/facturx-pdf.ts
|
||||
# liest sie zur Laufzeit aus process.cwd()/assets/fonts).
|
||||
COPY --from=builder /app/assets ./assets
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
COPY --from=builder /app/prisma ./prisma
|
||||
|
||||
@@ -4,6 +4,17 @@ Regionale Imkerei-Website und Shop für Wabenhain (Altenmünster) — MVP-Stufe.
|
||||
|
||||
> **Neu einrichten?** Alle Secrets, die Microsoft-Anmeldung, den Mailversand über Microsoft 365, Stripe und das Ausrollen beschreibt Schritt für Schritt **[docs/EINRICHTUNG.md](docs/EINRICHTUNG.md)**.
|
||||
|
||||
## Projektstand
|
||||
|
||||
Was gebaut, geprüft, gemergt und ausgerollt ist, was offen ist und was nur der Inhaber erledigen kann, steht in den Gitea-Issues. Einstieg ist das Übersichts-Issue **[Projektstand und Übersicht](https://git.encry.de/Nick.Rosenloecher/Wabenhain/issues/34)**, die Aufgaben des Inhabers sammelt **[Inhaber-Aufgaben](https://git.encry.de/Nick.Rosenloecher/Wabenhain/issues/33)**.
|
||||
|
||||
Kurzfassung (Stand 2026-10-16):
|
||||
|
||||
- Produktiv läuft der Build `sha-0d254db` (Client-IP-Härtung vom 2026-10-12). Die drei neueren Commits auf `main` (Abhängigkeits-Updates, Qualitäts-Gate in der CI) sind gebaut, aber noch nicht ausgerollt.
|
||||
- Im Cluster laufen App, Datenbank und die tägliche Sicherung `wabenhain-db-backup`. Die CronJobs `wabenhain-release-stale-orders` und `wabenhain-apicore-stock` sind angelegt, aber ausgesetzt (`suspend: true`).
|
||||
- Für den Bestandsabgleich mit ApiCore fehlt im Cluster-Secret `APICORE_WEBHOOK_SECRET`, für die ERPNext-Schnittstelle `ERP_EXPORT_TOKEN`.
|
||||
- Offene Spezifikation: [Versandstaffel je Kategorie](docs/superpowers/specs/2026-09-22-versandstaffel-je-kategorie-design.md) (freigegeben, nicht umgesetzt).
|
||||
|
||||
## Tech-Stack
|
||||
|
||||
| Bereich | Technologie |
|
||||
@@ -14,7 +25,7 @@ Regionale Imkerei-Website und Shop für Wabenhain (Altenmünster) — MVP-Stufe.
|
||||
| Animationen | Motion for React (Scroll-Reveal, Hero, Menü, Warenkorb, Karten) |
|
||||
| Datenbank | PostgreSQL (Standard) oder MySQL/MariaDB, per `DATABASE_PROVIDER` wählbar — siehe „Datenbank-Provider wechseln" |
|
||||
| ORM | Prisma 7 (`@prisma/adapter-pg` bzw. `@prisma/adapter-mariadb`) |
|
||||
| Payment | Stripe Checkout |
|
||||
| Payment | Stripe Checkout, eingebettet (`ui_mode: "embedded_page"`) |
|
||||
| Hosting | Docker / Node.js |
|
||||
|
||||
## Was ist enthalten
|
||||
@@ -38,7 +49,7 @@ Regionale Imkerei-Website und Shop für Wabenhain (Altenmünster) — MVP-Stufe.
|
||||
- Ernten-Übersicht + verschachtelte Ernten-Detailseite (`/ernten/[jahr]/[typ]`)
|
||||
- Herkunft, Imkerei, Kontakt, Unternehmen (B2B-Formular)
|
||||
- Honigwissen mit allen 9 im Briefing genannten Artikeln
|
||||
- Rechtliches: Impressum, Datenschutz, AGB, Widerrufsbelehrung, Versand und Zahlung (**Platzhaltertexte, rechtlich prüfen lassen**)
|
||||
- Rechtliches: Impressum, Datenschutz, AGB, Widerrufsbelehrung, Cookie-Richtlinie, Versand und Zahlung sowie die elektronische Widerrufsfunktion „Vertrag widerrufen“ (`/vertrag-widerrufen`, Eingänge unter Admin → Widerrufe). Die Texte sind ausformuliert und im Admin unter „Inhalte“ pflegbar; `pnpm preflight` meldet verbliebene Platzhalter. Eine anwaltliche Prüfung steht noch aus.
|
||||
- **Kundenkonto** unter `/konto`: Registrierung mit **Pflicht-E-Mail-Verifizierung** (siehe „Sicherheit" unten) und Login (Passwort-Hash + signiertes Session-Cookie), optionale **Zwei-Faktor-Authentifizierung** (TOTP-Authenticator-App + Backup-Codes, `/konto/zwei-faktor`), Konto-Sperre nach Fehlversuchen, "Alle Geräte abmelden", "Passwort vergessen"-Link mit E-Mail-Reset, Bestellhistorie mit Versand-/Abholstatus, "Bestellung erneut auslösen", Adressverwaltung (mehrere Adressen, Standardadresse), **Wunschliste**, Rechnungsansicht als HTML und PDF-Download (`/rechnung/[nummer]`), Newsletter-Verwaltung mit Double-Opt-In
|
||||
- **Admin-Backend** unter `/admin` (Zugriff über das normale Kundenkonto-Login + Rolle `ADMIN`, siehe „Admin-Zugang" unten): Dashboard mit Kennzahlen, Top-Produkten, Umsatz nach Kategorie, **Umsatzverlauf der letzten 14 Tage**, **Stammkund:innen-Zähler** und **meistgenutzten Gutscheinen**, Bestellliste mit Detailseite (`/admin/bestellungen/[id]`: vollständige Adresse, Artikel, Zahlung, Rabatt, Rechnungs-PDF) inkl. Status-Änderung (setzt automatisch Versand-/Abholdatum **und verschickt eine Versand-/Abholbereit-E-Mail**), Produkte/Ernten/Chargen jeweils mit Anlegen- und Bearbeiten-Formularen, Firmenanfragen-Inbox mit Statuspflege, **Benutzerverwaltung** (`/admin/benutzer`, siehe „Admin-Zugang" unten), **Versandkosten-Verwaltung** (`/admin/versand`, siehe „Versandkosten" unten), **Gutschein-Verwaltung** (`/admin/gutscheine`), **Bewertungsmoderation** (`/admin/bewertungen`: freischalten oder löschen), **Audit-Log** (`/admin/audit-log`, siehe „Sicherheit" unten)
|
||||
- **ApiCore-Synchronisierung**: Ernten, Chargen und der Produktkatalog lassen sich per Knopfdruck aus dem Imkerei-Verwaltungssystem ApiCore übernehmen, statt dieselben Daten zweimal einzutippen — jeweils in einen Entwurfszustand, den erst ein Mensch freigibt, und ohne je etwas zu überschreiben, was im Admin bewusst gesetzt wurde (siehe „ApiCore-Synchronisierung" unten)
|
||||
@@ -59,8 +70,8 @@ Regionale Imkerei-Website und Shop für Wabenhain (Altenmünster) — MVP-Stufe.
|
||||
|
||||
### Bewusst vereinfacht
|
||||
|
||||
- **Bilder**: Alle Foto-Flächen sind hochwertige, markenkonforme Platzhalter (Farbverläufe) statt echter Produkt-/Naturfotografie. Ich kann keine echten Fotos erzeugen oder beschaffen — hierfür werden eure tatsächlichen Aufnahmen benötigt.
|
||||
- Rechtstexte sind Platzhalter und **müssen** vor Live-Gang anwaltlich geprüft werden.
|
||||
- **Bilder**: Fotos für Produkte, Ernten, Chargen, Inhalte, Logo und das Hero-Video lädt der Admin hoch (siehe `k8s/README.md` zu Speicher und Video-Upload). Solange zu einer Fläche kein Foto hinterlegt ist, erscheint ein Platzhalter im Stil des Glas-Etiketts.
|
||||
- Rechtstexte sind ausformuliert, **müssen** aber anwaltlich geprüft werden — das kann kein Skript feststellen.
|
||||
|
||||
## Admin-Zugang
|
||||
|
||||
@@ -326,19 +337,38 @@ Die Reihenfolge ist zwingend, weil jede Stufe auf der vorherigen aufbaut: eine C
|
||||
|
||||
Wiedererkannt wird ein Jahrgang über `Product.apicoreBottlingId` (die ApiCore-ID der Abfüllung), nicht über den Slug — der ist die öffentliche Adresse und soll lesbar bleiben.
|
||||
|
||||
Jeder Jahrgang entsteht als deaktivierter Entwurf **ohne Preis**: ApiCore führt überhaupt keine Verkaufspreise, das ist reine Betriebsdatenhaltung. Den Preis kann nur ein Mensch setzen. Solange er fehlt, lässt sich das Produkt nicht aktiv schalten (`admin/actions/products.ts`), und der Checkout lehnt es zusätzlich ab (`api/checkout/route.ts`) — ein importiertes Produkt kann also nie versehentlich für 0 € verkauft werden. Gewicht kommt aus der Glasgröße der Abfüllung, nicht aus dem Artikel: sie sagt, was tatsächlich in dieses Glas kam. Der Lagerbestand startet bei 0, denn wie viele Gläser in den Webshop gehen und wie viele in Hofladen oder Wiederverkauf, entscheidet Wabenhain.
|
||||
Jeder Jahrgang entsteht als deaktivierter Entwurf **ohne Preis**: ApiCore führt überhaupt keine Verkaufspreise, das ist reine Betriebsdatenhaltung. Den Preis kann nur ein Mensch setzen. Solange er fehlt, lässt sich das Produkt nicht aktiv schalten (`admin/actions/products.ts`), und der Checkout lehnt es zusätzlich ab (`api/checkout/route.ts`) — ein importiertes Produkt kann also nie versehentlich für 0 € verkauft werden. Gewicht kommt aus der Glasgröße der Abfüllung, nicht aus dem Artikel: sie sagt, was tatsächlich in dieses Glas kam. Der Lagerbestand kommt aus ApiCore (siehe „Bestandsabgleich" unten): der Shop verkauft aus dem gesamten Restbestand der Abfüllung.
|
||||
|
||||
Ein bereits vorhandener Jahrgang wird übersprungen, nie aktualisiert: genau die Felder, die ApiCore liefert (Name, Beschreibung, Gewicht), zieht der Admin vor der Freischaltung von Hand nach, und ein Update würde diese Arbeit bei jedem weiteren Lauf wegwerfen. Soll ein Jahrgang wirklich frisch aus ApiCore kommen, löscht man ihn in Wabenhain und synchronisiert erneut.
|
||||
|
||||
Findet sich zu einer Abfüllung keine Charge, meldet der Lauf das als Hinweis statt als Fehler — meist steht dahinter eine Ernte, die in ApiCore noch fehlt.
|
||||
- **Chargen** werden ausschließlich neu angelegt, nie aktualisiert. Ein Update würde `remainingGlasses` überschreiben — das ist Wabenhains eigener, durch echte Verkäufe veränderter Lagerbestand.
|
||||
- **Chargen**: Losnummer, Abfüll- und MHD-Datum und abgefüllte Menge kommen aus ApiCore. `remainingGlasses` zeigt den Rest laut ApiCore (Bestandsabgleich).
|
||||
- **Hergestellte Waren** (Kerzen, Propolis-Tinkturen, Salben, … — in ApiCore Artikel der Art „Hergestellte Ware" mit Herstellungschargen): **ein** Shop-Produkt je Artikel, nicht je Charge. Neue Artikel entstehen als deaktivierte Entwürfe ohne Preis; schon vorhandene Shop-Produkte verknüpft man stattdessen im Produkt-Formular („ApiCore-Artikel") — am besten vor dem ersten Sync, sonst entsteht ein zusätzlicher Entwurf.
|
||||
- Charge und Ernte hängen von Anfang an am Jahrgang — er entsteht ja aus genau einer Abfüllung. Das ist die Verknüpfung, die die Herkunftsseite hinter dem QR-Code auf dem Glas füttert. Eine Abfüllung, die in ApiCore keinem Artikel zugeordnet ist (etwa Rohware für den Direktverkauf ab Hof), wird bewusst übergangen: daraus ließe sich kein Shop-Produkt bilden, es gäbe weder Namen noch Artikelnummer.
|
||||
- Ein in ApiCore ausgelaufenes Produkt (`DISCONTINUED`) wird **nicht** automatisch deaktiviert: solange Gläser im Regal stehen, ist „nicht mehr produziert" kein Grund, den Abverkauf zu stoppen. Der Fall wird stattdessen im Ergebnis gemeldet.
|
||||
|
||||
Wiederholte Läufe sind gefahrlos: Ernten werden über den stabilen Schlüssel `apicore-<ApiCore-ID>` als `Harvest.slug` wiedererkannt, Chargen über die ApiCore-Losnummer als `Batch.code`, Produkte über `Product.apicoreBottlingId`.
|
||||
Wiederholte Läufe sind gefahrlos: Ernten werden über `Harvest.apicoreHarvestId` wiedererkannt, Chargen über `Batch.apicoreBottlingId`, Honig-Produkte über `Product.apicoreBottlingId`, hergestellte Waren über `Product.apicoreProductId`.
|
||||
|
||||
**Einrichtung:** `APICORE_API_URL` und `APICORE_API_KEY` in `.env` setzen (siehe `.env.example`). Den Schlüssel in ApiCore unter Verwaltung → Automatisierung → API-Schlüssel anlegen; er darf nur die freigegebenen Shop-Daten lesen (`GET /shop-sync`, Berechtigung `shop-sync:read`), hat kein Passwort und lässt sich dort jederzeit widerrufen. Einen Zugang per Benutzer und Passwort gibt es nicht mehr. Fehlt eine Berechtigung, meldet der Sync das konkret als HTTP 403 statt still nichts zu tun. Zuständigkeit: Imkerei-Fakten (Datum, Losnummer, MHD, Abfüllmenge) kommen aus ApiCore, alles Verkaufsbezogene (Preise, Texte, Bilder, Sichtbarkeit, Shop-Bestand) wird nur hier gepflegt. Details und die Zuordnung Feld für Feld: `src/lib/apicore-client.ts`, `src/lib/apicore-mapping.ts` und `src/app/admin/actions/apicore-sync.ts`.
|
||||
|
||||
### Bestandsabgleich
|
||||
|
||||
**ApiCore führt den Restbestand je Charge; Shop und ApiCore zeigen dieselbe Zahl.** Design: `ApiCore/docs/superpowers/specs/2026-10-02-bestandsabgleich-design.md`.
|
||||
|
||||
- **Verkauft = bezahlt.** Beim Bezahlen geht je Position ein Verkauf an ApiCore; Storno einer bezahlten Bestellung und erstattete Retoure buchen zurück — auf genau die Chargen, aus denen verkauft wurde. Unbezahlte Bestellungen erreichen ApiCore nie.
|
||||
- **Warteschlange:** Jede Buchung landet in `apicore_stock_events`, in derselben Transaktion wie der Statuswechsel, und wird danach gesendet. Ist ApiCore nicht erreichbar, verkauft der Shop weiter; der CronJob `wabenhain-apicore-stock` (alle 10 Minuten, `pnpm stock:apicore-sync`) reicht nach. Jede Buchung trägt eine feste ID — ApiCore bucht sie nur einmal.
|
||||
- **Shop-Bestand** verknüpfter Produkte = ApiCore-Rest − noch nicht bestätigte Buchungen − Reservierungen unbezahlter Bestellungen. Das Bestandsfeld im Admin ist für sie gesperrt; Entnahmen (Hofladen, Eigenbedarf, Bruch) und Inventur bucht man in ApiCore.
|
||||
- **Entnahmen in ApiCore** kommen per Webhook `stock.changed` sofort an (`POST /api/apicore/webhook`, HMAC-signiert). Der Webhook nennt nur, *was* sich geändert hat — die Zahlen holt der Shop selbst über die API.
|
||||
- **Chargen-Zuordnung:** Welche Charge(n) ApiCore einem Verkauf zugeordnet hat, steht an der Bestellposition (`OrderItem.apicoreAllocations`) — für Rückverfolgung und Rückruf.
|
||||
- **Dashboard:** Buchungen, die länger als 15 Minuten hängen oder von ApiCore abgelehnt wurden, sowie aktive, noch nicht verknüpfte Produkte erscheinen unter „Zu tun".
|
||||
|
||||
**Einrichtung zusätzlich zum Sync:**
|
||||
|
||||
1. In ApiCore dem Wabenhain-API-Schlüssel die Berechtigung „Verkäufe und Rückbuchungen des Shops buchen" (`shop-sync:write`) geben.
|
||||
2. In ApiCore unter Automatisierung → Webhooks einen Webhook für `stock.changed` auf `https://<shop>/api/apicore/webhook` anlegen und dessen Secret als `APICORE_WEBHOOK_SECRET` setzen.
|
||||
3. CronJob `wabenhain-apicore-stock` aus `k8s/07-backup-cronjob.yaml` anwenden.
|
||||
4. Kerzen/Propolis-Produkte in ApiCore als „Hergestellte Ware" mit Herstellungscharge (aktueller Bestand) anlegen, in Wabenhain verknüpfen, dann synchronisieren.
|
||||
|
||||
## Vollständiger Docker-Betrieb
|
||||
|
||||
```bash
|
||||
@@ -381,7 +411,7 @@ Prüft die Konfiguration gegen alles, was einen öffentlichen Shop still unbrauc
|
||||
|
||||
Ist die Datenbank vom ausführenden Rechner aus nicht erreichbar, meldet das Skript diese Punkte ausdrücklich als **ungeprüft** — es rät weder „in Ordnung" noch „blockiert".
|
||||
|
||||
Unabhängig davon bleiben die Rechtstexte (AGB, Datenschutz, Widerrufsbelehrung) Platzhalter und **müssen** vor dem Live-Gang anwaltlich geprüft werden — das kann kein Skript feststellen.
|
||||
Unabhängig davon **müssen** die Rechtstexte (AGB, Datenschutz, Widerrufsbelehrung) anwaltlich geprüft werden — das kann kein Skript feststellen.
|
||||
|
||||
## Rechnungen
|
||||
|
||||
@@ -399,16 +429,16 @@ Das Jahr steht zuerst, weil sich die Aufbewahrungsfrist danach richtet: ein abge
|
||||
|
||||
**Abgelegt wird genau das Dokument, das versendet wurde.** Der Abruf liefert die Datei aus und rendert nur dann neu, wenn keine vorhanden ist. Sonst sähe dieselbe Rechnungsnummer nach einer Änderung an Firmendaten oder Layout anders aus als der Beleg beim Kunden.
|
||||
|
||||
**Sicherung:** der CronJob in `k8s/07-backup-cronjob.yaml` packt das Verzeichnis täglich als `rechnungen-<Zeitstempel>.tar.gz` neben den Datenbank-Dump. Ein Datenbank-Dump allein genügt nicht — die Datenbank kennt nur Nummer, Betrag und Pfad, das PDF liegt ausschließlich auf dem Volume.
|
||||
**Sicherung:** der CronJob in `k8s/07-backup-cronjob.yaml` packt das Verzeichnis täglich als `rechnungen-<Zeitstempel>.tar.gz` neben den Datenbank-Dump auf die Storage Box (30 Tage Aufbewahrung). Ein Datenbank-Dump allein genügt nicht — die Datenbank kennt nur Nummer, Betrag und Pfad, das PDF liegt ausschließlich auf dem Volume. Die zehnjährige Aufbewahrung nach § 147 AO deckt das nicht ab. Vorgesehen ist dafür, dass ERPNext jede Rechnung samt PDF über `/api/erp/rechnungen` übernimmt; im Cluster fehlt dafür Stand 2026-10-16 noch `ERP_EXPORT_TOKEN` (siehe „Projektstand“).
|
||||
|
||||
> Bei **mehr als einem Knoten**: das PVC `wabenhain-invoices` ist `ReadWriteOnce` und lässt sich nur von Pods auf demselben Knoten einhängen. Landet der Sicherungs-Pod woanders als die App, bleibt er in „Pending" — ohne Fehlermeldung. Dann das PVC auf `ReadWriteMany` umstellen (NFS/SMB/CephFS).
|
||||
> Bei **mehr als einem Knoten**: im Repo ist das PVC `wabenhain-invoices` als `ReadWriteOnce` angelegt und ließe sich nur von Pods auf demselben Knoten einhängen; landet der Sicherungs-Pod woanders als die App, bleibt er ohne Fehlermeldung in „Pending“. Im Cluster sind `wabenhain-invoices` und `wabenhain-uploads` deshalb bereits `ReadWriteMany` auf SMB (Stand 2026-10-16); das Repo-Manifest weicht davon ab.
|
||||
|
||||
### Umsatzsteuer
|
||||
|
||||
Der Steuersatz hängt an der Art der Ware, nicht am Betrieb: Honig ist ein Lebensmittel und ermäßigt besteuert (Anlage 2 zum UStG), eine Bienenwachskerze nicht. Der Satz wird deshalb in drei Stufen bestimmt — die erste, die etwas liefert, gewinnt:
|
||||
|
||||
1. **Am Produkt** — Feld „Umsatzsteuersatz" unter Admin → Produkte. Für Ausnahmen, die sich nicht aus der Kategorie ergeben, etwa ein gemischtes Geschenkset. Leer lassen ist der Normalfall.
|
||||
2. **An der Kategorie** — `VAT_RATE_PERCENT_HONIG`, `VAT_RATE_PERCENT_KERZEN`, `VAT_RATE_PERCENT_PROPOLIS`.
|
||||
2. **An der Kategorie** — `VAT_RATE_PERCENT_HONIG`, `VAT_RATE_PERCENT_KERZEN`, `VAT_RATE_PERCENT_PROPOLIS`, `VAT_RATE_PERCENT_SONSTIGES` (weitere Bienenprodukte wie Salben oder Wachstücher, Vorgabe in `k8s/01-configmap.yaml`: 19).
|
||||
3. **Gemeinsamer Rückfallwert** — `VAT_RATE_PERCENT`, sonst 7.
|
||||
|
||||
Der Vorteil der Kategorie-Stufe: ändern sich die gesetzlichen Sätze, genügt eine Änderung an der Konfiguration statt an jedem einzelnen Produkt.
|
||||
@@ -439,6 +469,36 @@ Vor dem Hochzählen prüft dieselbe Transaktion, ob zur Bestellung bereits eine
|
||||
|
||||
Vier Stellen halten die Nummern gleich lang und damit sortierbar. Gibt es in einem Jahr mehr als 9999 Rechnungen, wächst die Nummer mit, statt abgeschnitten zu werden.
|
||||
|
||||
### E-Rechnung
|
||||
|
||||
Jedes Rechnungs-PDF ist eine hybride E-Rechnung nach **ZUGFeRD 2.x / Factur-X, Profil EN 16931**: ein PDF/A-3b mit eingebettetem `factur-x.xml` (UN/CEFACT CII D16B). Das XML ist der maßgebliche Teil; Buchhaltungsprogramme (ERPNext, DATEV, lexoffice …) lesen es direkt. Erzeugt in `lib/einvoice/cii.ts` (XML) und `lib/einvoice/facturx-pdf.ts` (PDF/A, XMP-Metadaten, Anhang).
|
||||
|
||||
- **Summen:** Netto und Steuer je Satz kommen unverändert aus der Aufstellung des PDFs. Die Positionen tragen ihren Nettoanteil (centgenau verteilt), Versand und Rabatt stehen als Zu- und Abschlag je Satz. Bei Bruttopreisen kann ein Prüfprogramm, das die Steuer aus dem Netto nachrechnet, einen Cent Unterschied melden; EN 16931 lässt das ausdrücklich zu (BR-S-09/BR-CO-17), der Steuerbetrag entspricht dem aus dem Bruttopreis herausgerechneten.
|
||||
- **Schriften:** PDF/A verlangt eingebettete Schriften. Statt Helvetica/Times werden Liberation Sans/Serif aus `assets/fonts` eingebettet (gleiche Laufweiten, SIL Open Font License); das Dockerfile kopiert das Verzeichnis ins Image.
|
||||
- **Ohne USt-IdNr.** (Einstellungen → Firma) oder bei Positionen ohne Steuersatz entsteht nur das PDF, mit Warnung im Log.
|
||||
- Geprüft mit XSD und CEN-Schematron EN 16931 sowie Mustang (veraPDF): PDF/A-3b konform, XML gültig.
|
||||
|
||||
### Rechnungskopie
|
||||
|
||||
Unter Einstellungen → Firma → **„Rechnungskopie an“** lässt sich eine Adresse hinterlegen (z. B. die Buchhaltung). Jede Rechnung und jede Stornorechnung geht dann zusätzlich als eigene Mail mit derselben E-Rechnung dorthin (`lib/invoice-mail.ts`). Leer = keine Kopie.
|
||||
|
||||
### Stornorechnung
|
||||
|
||||
Eine ausgestellte Rechnung wird nie gelöscht oder geändert. Wird eine Bestellung mit Rechnung storniert (Admin), eine Retoure erstattet oder die Zahlung bei Stripe voll erstattet, entsteht **eine** Stornorechnung `ST-<Jahr>-<laufende Nummer>` (eigener Nummernkreis, Tabelle `cancellation_counters`) mit allen Positionen der Rechnung, negativen Beträgen auf dem PDF und Bezug auf die Rechnung (XML: Gutschrift 381 mit Verweis). Sie geht als E-Rechnung an die Kundschaft und als Kopie an die hinterlegte Adresse. Laufen Admin-Stornierung und Stripe-Webhook derselben Erstattung gleichzeitig, bleibt es bei einer Stornorechnung (eindeutige `invoiceId`, die zweite Transaktion rollt samt Zähler zurück). Eine Bestellung mit Stornorechnung lässt sich nicht wieder öffnen. Teilerstattungen bei Stripe erzeugen keine Stornorechnung (Hinweis im Log).
|
||||
|
||||
ERPNext holt Stornorechnungen über `GET /api/erp/rechnungen?seit=…&art=storno` und bucht sie als Rechnungskorrektur gegen die Ausgangsrechnung; die PDFs liegen unter `/api/erp/rechnungen/ST-…/pdf`.
|
||||
|
||||
### Kunden und Firmenanfragen im CRM (ERPNext)
|
||||
|
||||
Zwei weitere nur lesende Endpunkte mit demselben `ERP_EXPORT_TOKEN` (`lib/erp-crm-export.ts`):
|
||||
|
||||
| Endpunkt | Inhalt | In ERPNext |
|
||||
|---|---|---|
|
||||
| `GET /api/erp/kunden?nach=<id>&limit=<1-200>` | Kundenkonten (ohne Admins, ohne Passwort/2FA), Standardadresse | Kunde in der Gruppe **Privat** mit Kontakt und Adresse |
|
||||
| `GET /api/erp/anfragen?nach=<id>&limit=<1-200>` | Firmenanfragen der Geschäftskunden-Seite | Kunde (Firma) in der Gruppe **Gewerblich** mit Ansprechpartner, je Anfrage eine Chance |
|
||||
|
||||
ERPNext holt bei jedem Lauf die vollständige Liste (Cursor `nach` = letzte ID der vorigen Seite, `next` in der Antwort). Ein im Shop gelöschtes Konto ohne Rechnung verschwindet dadurch auch aus ERPNext; mit Rechnung bleibt der Kunde wegen der Aufbewahrungspflicht stehen.
|
||||
|
||||
## Health-Endpunkte
|
||||
|
||||
Zwei getrennte Endpunkte, bewusst mit unterschiedlicher Aufgabe:
|
||||
@@ -452,7 +512,9 @@ Die Trennung ist der Grund für die Endpunkte: eine Liveness-Probe, die an der D
|
||||
|
||||
## Kubernetes / Gitea CI
|
||||
|
||||
`.gitea/workflows/docker-build.yml` baut bei jedem Push auf `main` automatisch ein Docker-Image und veröffentlicht es in der Gitea-eigenen Container-Registry. Der Container migriert/seedet die Datenbank beim Start selbst (idempotent), kein separates Migrations-Image oder -Job nötig. `k8s/` enthält vollständige, rohe Kubernetes-Manifeste (Namespace, ConfigMap, Secret-Vorlage, Postgres/MySQL-StatefulSet, App-Deployment, Ingress) für den Betrieb dieses Images im Cluster — Einrichtung und Deployment-Ablauf stehen in [`k8s/README.md`](k8s/README.md).
|
||||
`.gitea/workflows/docker-build.yml` prüft bei jedem Push auf `main` zuerst `pnpm lint`, `pnpm audit --prod --audit-level high`, `pnpm typecheck` und `pnpm test` (Runner `ci-isolated`). Nur wenn alle grün sind, baut der Job `build-and-push` (Runner `docker-builder`) zwei Images und veröffentlicht sie in der Gitea-eigenen Container-Registry: `wabenhain` (App) und `wabenhain-tools` (Skripte für die CronJobs), jeweils mit den Tags `latest` und `sha-<kurzer Commit>`. Der App-Container migriert/seedet die Datenbank beim Start selbst (idempotent), kein separates Migrations-Image oder -Job nötig.
|
||||
|
||||
Die Pipeline wendet **keine** Manifeste an und rollt nichts aus. Das Deployment ist auf Tag und Digest gepinnt; ein neuer Build geht per `kubectl -n wabenhain set image deploy/wabenhain-app app=git.encry.de/nick.rosenloecher/wabenhain:sha-<commit>@sha256:<digest>` in Betrieb, danach wird `image:` in `k8s/05-app-deployment.yaml` nachgezogen. `k8s/` enthält vollständige, rohe Kubernetes-Manifeste (Namespace, ConfigMap, Secret-Vorlage, Postgres/MySQL-StatefulSet, App-Deployment, Ingress) für den Betrieb dieses Images im Cluster — Einrichtung und Deployment-Ablauf stehen in [`k8s/README.md`](k8s/README.md).
|
||||
|
||||
Ein einzelnes Image unterstützt beide Datenbank-Provider gleichzeitig (siehe „Datenbank-Provider wechseln" oben) — welcher tatsächlich läuft, entscheidet allein `DATABASE_PROVIDER`/`DATABASE_URL` zur Laufzeit, kein separater Image-Build nötig.
|
||||
|
||||
@@ -464,36 +526,37 @@ Ein einzelnes Image unterstützt beide Datenbank-Provider gleichzeitig (siehe
|
||||
- **Passwörter**: bcrypt mit Cost-Faktor 12; Limit 72 Zeichen (bcrypt-Grenze) wird validiert statt still abgeschnitten.
|
||||
- **Login-Härtung**: Vergleich gegen Dummy-Hash bei unbekannter E-Mail (kein User-Enumeration über Antwortzeiten); E-Mails werden normalisiert (trim/lowercase); Konto-Sperre für 15 Minuten nach 5 aufeinanderfolgenden Fehlversuchen (`Customer.failedLoginAttempts`/`lockedUntil`, überlebt im Gegensatz zum IP-Rate-Limit einen Server-Neustart).
|
||||
- **Admin-Sperre** (`Customer.blockedAt`, unter `/admin/benutzer`): getrennt von der automatischen Fehlversuchs-Sperre — ein Admin kann ein Konto gezielt und dauerhaft sperren. Der Login wird dabei noch vor der Passwortprüfung mit einer eigenen Meldung abgelehnt, `getCurrentCustomer()` beendet zusätzlich jede bereits bestehende Session sofort (nicht erst beim natürlichen Cookie-Ablauf), und ein Passwort-Reset kann die Sperre nicht mehr eigenständig umgehen.
|
||||
- **Rate-Limiting** (In-Memory): Login 10/15 min pro IP **und** 8/15 min pro E-Mail-Adresse (schützt auch gegen verteilte Versuche über viele IPs auf ein einzelnes Konto), Registrierung 5/h, Passwort-Reset-Anfrage 5/h, 2FA-Code-Prüfung 8/10 min, Newsletter & Firmenanfragen 5/h, Checkout 10/h. Die Client-IP wird aus dem **letzten** `X-Forwarded-For`-Eintrag gelesen (vom eigenen Reverse-Proxy angehängt), nicht dem ersten — der wäre vom Client frei wählbar und würde jedes Rate-Limit hier aushebeln. Bei horizontaler Skalierung auf einen gemeinsamen Store (z.B. Redis) umstellen.
|
||||
- **Rate-Limiting** (In-Memory): Login 10/15 min pro IP **und** 8/15 min pro E-Mail-Adresse (schützt auch gegen verteilte Versuche über viele IPs auf ein einzelnes Konto), Registrierung 5/h, Passwort-Reset-Anfrage 5/h, 2FA-Code-Prüfung 8/10 min, Newsletter & Firmenanfragen 5/h, Checkout 10/h. Die Client-IP wird aus dem **letzten** `X-Forwarded-For`-Eintrag gelesen (vom eigenen Reverse-Proxy angehängt), nicht dem ersten — der wäre vom Client frei wählbar und würde jedes Rate-Limit hier aushebeln. Ist dieser letzte Eintrag eine Cloudflare-Edge, gilt stattdessen `CF-Connecting-IP`; IPv6-Adressen zählen je /64-Netz (`lib/rate-limit.ts`). Bei horizontaler Skalierung auf einen gemeinsamen Store (z.B. Redis) umstellen.
|
||||
- **CAPTCHA** (Cloudflare Turnstile, optional): siehe Abschnitt „CAPTCHA" oben — zusätzlicher Bot-Schutz auf Registrierung, Newsletter und Firmenanfrage.
|
||||
- **E-Mail-Verifizierung**: neu registrierte Konten erhalten einen Bestätigungslink (`EmailVerificationToken`, SHA-256-Hash wie beim Passwort-Reset, 24 Stunden gültig) und müssen ihre E-Mail-Adresse bestätigen, bevor sie mit ihrem Konto bestellen können (`/api/checkout` prüft `Customer.emailVerifiedAt`) — Gastbestellungen sind davon nicht betroffen. Ein erfolgreich über einen zugesandten Link gesetztes Passwort (Reset oder admin-angelegtes Konto) gilt ebenfalls als Bestätigung, ohne eine weitere E-Mail zu benötigen.
|
||||
- **Admin-Audit-Log** (`/admin/audit-log`, `AuditLog`-Modell): protokolliert jede sicherheitsrelevante Admin-Mutation (Produkte, Bestellstatus, Gutscheine, Versandkosten, Benutzerrollen, Bewertungsmoderation, …) mit Zeitstempel, Admin-E-Mail (als Snapshot, bleibt auch nach Kontolöschung lesbar), Aktion und Details.
|
||||
- **Abhängigkeits-Sicherheitsscan**: `pnpm audit` vor jedem Release ausführen, um bekannte Schwachstellen in Paketen frühzeitig zu erkennen (siehe „Nützliche Befehle" unten). Aktuell 0 bekannte Schwachstellen (zuletzt geprüft: eine transitive `nanoid`-DoS-Lücke über `pnpm-workspace.yaml`s `overrides` gepatcht).
|
||||
- **Abhängigkeits-Sicherheitsscan**: Die CI bricht ab, sobald `pnpm audit --prod --audit-level high` eine Lücke ab „high“ in Laufzeit-Abhängigkeiten findet; ohne grünen Audit entsteht kein Image. Lokal mit `pnpm audit` prüfen (siehe „Nützliche Befehle“ unten). Zuletzt geschlossen wurden High-/Critical-Advisories in Commit `835323e` (2026-10-14).
|
||||
- **Security-Header**: CSP (keine externen Skript-Hosts außer dem optionalen Turnstile-Widget), `X-Frame-Options: DENY`, `nosniff`, Referrer-Policy, Permissions-Policy, HSTS.
|
||||
- **Formularfelder**: korrekte `autocomplete`-Attribute (`email`, `current-password`, `new-password`, `one-time-code`) auf allen Auth-Formularen für Passwort-Manager und Autofill.
|
||||
- **TOTP-Replay-Schutz** (`Customer.lastTotpStep`): ein beim Login akzeptierter 2FA-Code kann nicht ein zweites Mal eingelöst werden, selbst innerhalb seines eigentlichen 30-Sekunden-Gültigkeitsfensters.
|
||||
- **Passwort-Reset respektiert 2FA**: ein erfolgreicher Reset loggt bei aktivem 2FA nicht direkt ein, sondern verlangt wie beim normalen Login den zweiten Faktor — sonst würde ein Reset-Link den zweiten Faktor genau in dem Szenario aushebeln, für das er gedacht ist.
|
||||
- **Registrierung ohne E-Mail-Enumeration**: eine bereits vergebene E-Mail-Adresse erzeugt dieselbe generische Antwort (Text und Zeitaufwand) wie eine erfolgreiche Neuanmeldung, statt "Konto existiert bereits" zu bestätigen.
|
||||
- **Gutschein-Einlösung race-sicher**: bei einem Nutzungslimit zählt die Prüfung beim Checkout zusätzlich zu `usedCount` auch bereits laufende, aber noch unbezahlte Bestellungen mit demselben Code — verhindert, dass mehrere parallele Checkout-Versuche einen `maxUses:1`-Code alle gleichzeitig als gültig durchgehen lassen.
|
||||
- **Rate-Limit-IP vertrauenswürdig ermittelt**: die Client-IP für alle Limits (Login, 2FA, Checkout, Registrierung, Passwort-Reset) kommt aus dem letzten, vom eigenen Reverse-Proxy gesetzten `X-Forwarded-For`-Eintrag, nicht dem ersten (vom Client frei wählbaren).
|
||||
- **Rate-Limit-IP vertrauenswürdig ermittelt**: die Client-IP für alle Limits (Login, 2FA, Checkout, Registrierung, Passwort-Reset) kommt aus dem letzten, vom eigenen Reverse-Proxy gesetzten `X-Forwarded-For`-Eintrag, nicht dem ersten (vom Client frei wählbaren); hinter Cloudflare aus `CF-Connecting-IP`, siehe Rate-Limiting oben.
|
||||
- **Nur über Cloudflare erreichbar**: Der Ingress hängt an der Middleware `wabenhain-cloudflare-only` (nur Cloudflare-Adressen und private Netze), direkte Zugriffe auf den Origin beantwortet Traefik mit 403. Die Middleware liegt nicht in diesem Repo, sondern in den Cluster-Manifesten (siehe Kommentar in `k8s/06-ingress.yaml`).
|
||||
- **Admin-Sperre invalidiert aktive Sessions sofort** statt erst beim natürlichen Cookie-Ablauf, und ein Passwort-Reset kann eine Sperre nicht mehr eigenständig umgehen.
|
||||
- **Zahlungsbestätigung transaktional und idempotent**: der Webhook-Handler markiert eine Bestellung nur aus dem Status "NEU" heraus als bezahlt (verhindert doppelte Gutschein-Zählung bei wiederholter Webhook-Zustellung und verhindert, dass eine bereits stornierte Bestellung durch eine verspätete Zahlungsbestätigung wiederbelebt wird) und löst eine abgelaufene, nie bezahlte Checkout-Sitzung (`checkout.session.expired`) samt Bestandsreservierung wieder auf.
|
||||
- **Admin-Zugriff**: kein separates Passwort/Basic-Auth mehr — die Rolle des eingeloggten Kontos entscheidet (siehe „Admin-Zugang" oben). Zweistufig geprüft: Proxy auf Request-Ebene (JWT-Claim) und jede Admin-Server-Action zusätzlich autoritativ gegen die Datenbank.
|
||||
- **Checkout**: Lagerbestand wird transaktional geprüft und reserviert (kein Überverkauf bei parallelen Bestellungen); Stornierung im Admin bucht den Bestand zurück. Bestell-/Rechnungsnummern kommen aus `crypto.randomBytes`.
|
||||
- **Checkout**: Lagerbestand wird transaktional geprüft und reserviert (kein Überverkauf bei parallelen Bestellungen); Stornierung im Admin bucht den Bestand zurück. Bestellnummern (`WH-<Jahr>-<8 Hex-Zeichen>`) kommen aus `crypto.randomBytes`; Rechnungsnummern sind dagegen fortlaufend (siehe „Rechnungsnummer“).
|
||||
- **Stripe-Webhook**: Signaturprüfung über `STRIPE_WEBHOOK_SECRET`.
|
||||
- Server Actions prüfen Besitzrechte (Adressen/Bestellungen/Rechnungen nur für das eigene Konto); Next.js validiert bei Actions zusätzlich den Origin-Header (CSRF).
|
||||
|
||||
## Datenmodell
|
||||
|
||||
Siehe [`prisma/schema.prisma`](prisma/schema.prisma) für das vollständige Schema:
|
||||
`Customer`, `Address`, `PasswordResetToken`, `EmailVerificationToken`, `TwoFactorBackupCode`, `Harvest`, `Batch`, `Product`, `Inventory`, `Review`, `WishlistItem`, `StockNotification`, `Order`, `OrderItem`, `Payment`, `Shipment`, `Pickup`, `Invoice`, `ReturnRequest`, `ShippingTier`, `DiscountCode`, `AuditLog`, `NewsletterSubscriber`, `BusinessInquiry`.
|
||||
`Customer`, `Address`, `PasswordResetToken`, `EmailVerificationToken`, `TwoFactorBackupCode`, `Harvest`, `Batch`, `Product`, `Inventory`, `Review`, `WishlistItem`, `StockNotification`, `Order`, `OrderItem`, `ApiCoreStockEvent`, `Payment`, `Shipment`, `Pickup`, `InvoiceCounter`, `Invoice`, `CancellationCounter`, `CancellationInvoice`, `ReturnRequest`, `ShippingTier`, `DiscountCode`, `AuditLog`, `SiteContent`, `NewsletterSubscriber`, `BusinessInquiry`, `WithdrawalDeclaration`.
|
||||
|
||||
Ein `Product` ist optional einer `Harvest` und einer `Batch` zugeordnet (Pflicht bei Honig, leer bei Kerzen/Propolis); jede `OrderItem` speichert die `Batch`, aus der das jeweilige Glas stammt, sodass sich jede Honig-Bestellung bis zur Charge zurückverfolgen lässt. `Customer.role` (`KUNDE` | `ADMIN`) steuert den Zugriff auf `/admin`, `Customer.blockedAt` die admin-gesperrten Konten, siehe „Admin-Zugang" oben.
|
||||
|
||||
## Tests
|
||||
|
||||
- **Unit-/Integrationstests** (`src/**/*.test.ts`, [Vitest](https://vitest.dev/)): decken die geldrelevante und sicherheitsrelevante Kernlogik ab, die absichtlich als reine Funktionen ohne Datenbankzugriff ausgelagert ist — `lib/shipping-calc.ts`, `lib/discount-calc.ts`, `lib/format.ts` sowie die Zod-Schemas in `lib/validation.ts`. `pnpm test` ausführen.
|
||||
- **E2E-Tests** (`e2e/*.spec.ts`, [Playwright](https://playwright.dev/)): Smoke-Tests für die kritischsten Nutzerpfade (Startseite, Shop-Übersicht, Warenkorb inkl. Mengenänderung/Entfernen, Checkout-Preisanzeige inkl. Versand/Abholung-Umschaltung, Login-/Registrierungsvalidierung) gegen eine laufende Instanz. `pnpm test:e2e` ausführen — startet bei Bedarf automatisch `pnpm dev`, nutzt aber einen bereits laufenden Dev-Server, falls vorhanden.
|
||||
- **Unit-/Integrationstests** (`src/**/*.test.ts(x)`, [Vitest](https://vitest.dev/), Stand 2026-10-16: 65 Testdateien, die meisten unter `src/lib`): decken die geldrelevante und sicherheitsrelevante Kernlogik ab, die absichtlich als reine Funktionen ohne Datenbankzugriff ausgelagert ist — unter anderem Versand- und Rabattberechnung, Umsatzsteuer, Rechnung und E-Rechnung, Checkout-, Abbruch- und Webhook-Route, Bestandsabgleich mit ApiCore, Sessions, CSRF, Client-IP und die Zod-Schemas in `lib/validation.ts`. `pnpm test` ausführen; die CI führt sie bei jedem Push aus.
|
||||
- **E2E-Tests** (`e2e/*.spec.ts`, [Playwright](https://playwright.dev/)): Smoke-Tests für die kritischsten Nutzerpfade (Startseite, Shop-Übersicht, Warenkorb inkl. Mengenänderung/Entfernen, Checkout-Preisanzeige inkl. Versand/Abholung-Umschaltung, Login-/Registrierungsvalidierung) gegen eine laufende Instanz. `pnpm test:e2e` ausführen — startet bei Bedarf automatisch `pnpm dev`, nutzt aber einen bereits laufenden Dev-Server, falls vorhanden. Die CI führt sie bisher **nicht** aus.
|
||||
|
||||
Dies ist eine bewusst schlanke Startabdeckung der riskantesten Logik (Geldberechnung, Auth-Validierung, Kern-Flows), kein vollständiger Coverage-Anspruch — die Infrastruktur ist eingerichtet, weitere Tests lassen sich unkompliziert ergänzen.
|
||||
|
||||
@@ -505,7 +568,13 @@ Beim Ausbau der Warenkorb-/Checkout-Tests kam ein echter, vorher unentdeckter Bu
|
||||
pnpm dev # Entwicklungsserver
|
||||
pnpm build # Produktions-Build
|
||||
pnpm lint # ESLint
|
||||
pnpm typecheck # TypeScript ohne Ausgabe (erzeugt vorher Prisma-Clients und Next-Routentypen)
|
||||
pnpm test # Vitest (Unit-/Komponententests)
|
||||
pnpm test:e2e # Playwright gegen eine laufende Instanz
|
||||
pnpm preflight # Go-Live-Pruefung (siehe "Vor dem Live-Gang")
|
||||
pnpm orders:release-stale # haengende, bei Stripe abgelaufene Bestellungen freigeben (wie CronJob)
|
||||
pnpm stock:apicore-sync # Bestandsabgleich mit ApiCore nachholen (wie CronJob)
|
||||
pnpm places:find "Name Ort" # Google-Place-ID nachschlagen
|
||||
pnpm db:studio # Prisma Studio (DB-GUI)
|
||||
pnpm db:migrate # neue Migration erstellen/anwenden (Dev)
|
||||
pnpm audit # Abhängigkeiten auf bekannte Schwachstellen prüfen
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,93 @@
|
||||
Copyright 2015 the Cormorant Project Authors (github.com/CatharsisFonts/Cormorant)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,92 @@
|
||||
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION AND CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,102 @@
|
||||
Digitized data copyright (c) 2010 Google Corporation
|
||||
with Reserved Font Arimo, Tinos and Cousine.
|
||||
Copyright (c) 2012 Red Hat, Inc.
|
||||
with Reserved Font Name Liberation.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License,
|
||||
Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
|
||||
PREAMBLE The goals of the Open Font License (OFL) are to stimulate
|
||||
worldwide development of collaborative font projects, to support the font
|
||||
creation efforts of academic and linguistic communities, and to provide
|
||||
a free and open framework in which fonts may be shared and improved in
|
||||
partnership with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves.
|
||||
The fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply to
|
||||
any document created using the fonts or their derivatives.
|
||||
|
||||
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such.
|
||||
This may include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components
|
||||
as distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting ? in part or in whole ?
|
||||
any of the components of the Original Version, by changing formats or
|
||||
by porting the Font Software to a new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical writer
|
||||
or other person who contributed to the Font Software.
|
||||
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,in
|
||||
Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the
|
||||
corresponding Copyright Holder. This restriction only applies to the
|
||||
primary font name as presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole, must
|
||||
be distributed entirely under this license, and must not be distributed
|
||||
under any other license. The requirement for fonts to remain under
|
||||
this license does not apply to any document created using the Font
|
||||
Software.
|
||||
|
||||
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are not met.
|
||||
|
||||
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
|
||||
DEALINGS IN THE FONT SOFTWARE.
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+68
-2
@@ -260,6 +260,59 @@ Nach dem Anlegen **Signaturgeheimnis** anzeigen (`whsec_…`) → `STRIPE_WEBHOO
|
||||
|
||||
**Einstellungen** → **Zahlungsmethoden**: gewünschte Arten aktivieren (Karte, SEPA-Lastschrift, PayPal, Klarna, Apple Pay, Google Pay). Der Shop zeigt automatisch an, was dort aktiv ist. Für Apple Pay die Domain `wabenhain.com` unter **Apple Pay** registrieren.
|
||||
|
||||
### 5.4 Abo der Bienenpatenschaft
|
||||
|
||||
**Stand Livekonto (2026-10-16, eingerichtet):**
|
||||
|
||||
- Webhook `https://wabenhain.com/api/checkout/webhook` mit allen zwölf
|
||||
Ereignissen (die sechs bisherigen plus `charge.dispute.closed`,
|
||||
`customer.subscription.created/updated/deleted`, `invoice.paid`,
|
||||
`invoice.payment_failed`). Das Signatur-Geheimnis bleibt dasselbe.
|
||||
- Kundenportal `bpc_1URCIfEvHaDWQ1U0nD4jVWXc`: nur Zahlungsart ändern, keine
|
||||
Kündigung, kein Tarifwechsel, keine Kundendaten, keine Rechnungshistorie.
|
||||
Steht als `STRIPE_PORTAL_CONFIGURATION_ID` in `k8s/01-configmap.yaml`.
|
||||
- Zahlungsmethoden-Domains `wabenhain.com` und `www.wabenhain.com` registriert
|
||||
(Apple Pay, Google Pay, PayPal, Link, Klarna im eingebetteten Checkout).
|
||||
|
||||
**Nur im Dashboard möglich (Stripe bietet dafür keine API):**
|
||||
|
||||
1. Einstellungen → Billing → Abos und E-Mails → Wiederholungsversuche:
|
||||
Smart Retries an, nach dem letzten Versuch **Abo kündigen**.
|
||||
2. Einstellungen → Billing → Abos und E-Mails → Kunden-E-Mails: Mails zu
|
||||
erfolgreichen Zahlungen, anstehenden Verlängerungen und fehlgeschlagenen
|
||||
Zahlungen **aus** (Wabenhain verschickt eigene Rechnungen und Mails).
|
||||
3. Einstellungen → Zahlungsmethoden: Google Pay ist in der Konfiguration
|
||||
„Default“ als nicht verfügbar markiert — dort aktivieren.
|
||||
|
||||
Das Abo läuft über Stripe Billing (Checkout im Modus „subscription“). Produkte und Monatspreise der Abo-Angebote legt Wabenhain selbst an, sobald ein Abo-Angebot im Admin gespeichert oder zum ersten Mal abgeschlossen wird — **nicht** von Hand im Dashboard anlegen.
|
||||
|
||||
**Einrichtungsskript** (wiederholbar, schreibt ohne `--apply` nichts):
|
||||
|
||||
```bash
|
||||
# Probelauf: zeigt, was fehlt
|
||||
pnpm tsx scripts/stripe-setup.ts --base-url=https://wabenhain.com
|
||||
# Schreiben (Testmodus)
|
||||
pnpm tsx scripts/stripe-setup.ts --base-url=https://wabenhain.com --apply
|
||||
# Livekonto: nur nach Freigabe des Inhabers, zusätzlich --live-ok
|
||||
pnpm tsx scripts/stripe-setup.ts --base-url=https://wabenhain.com --apply --live-ok
|
||||
```
|
||||
|
||||
Das Skript liest `STRIPE_SECRET_KEY` aus der Umgebung (`.env`) und
|
||||
|
||||
1. ergänzt den Webhook-Endpunkt `<BASE_URL>/api/checkout/webhook` um die Abo-Ereignisse (bestehende bleiben): `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid`, `invoice.payment_failed`, `charge.dispute.closed`. Legt es den Endpunkt neu an, steht das Signaturgeheimnis nur im Dashboard → `STRIPE_WEBHOOK_SECRET`.
|
||||
2. legt eine Kundenportal-Konfiguration an, die **nur das Ändern der Zahlungsart** erlaubt (keine Kündigung, kein Tarifwechsel, keine Kundendaten, kein Rechnungsverlauf). Die App findet sie über die Metadaten `wabenhain=abo-zahlungsart`; alternativ `STRIPE_PORTAL_CONFIGURATION_ID` setzen. Ohne diese Konfiguration bietet das Konto „Zahlungsart ändern“ nicht an — die Standardkonfiguration wird bewusst nie benutzt.
|
||||
|
||||
**Nur im Dashboard** (Checkliste, das Skript gibt sie ebenfalls aus):
|
||||
|
||||
- [ ] **Billing → Einstellungen → Abos und E-Mails → Fehlgeschlagene Zahlungen:** Smart Retries an; nach dem letzten erfolglosen Versuch **Abo kündigen** (nicht „unbezahlt markieren“). Wabenhain beendet das Abo dann über `customer.subscription.deleted`.
|
||||
- [ ] **… Kunden-E-Mails:** Stripe-Mails zu erfolgreichen Zahlungen/Rechnungen, bevorstehenden Verlängerungen und fehlgeschlagenen Zahlungen **aus** — Wabenhain verschickt eigene Rechnungen (Nummernkreis RE-…) und Mails.
|
||||
- [ ] **Einstellungen → Zahlungsmethoden:** Karte, Apple Pay, Google Pay und SEPA-Lastschrift aktiv. Im Abo zeigt Checkout nur Zahlarten, die wiederkehrende Zahlungen können. Google Pay prüfen; für Apple Pay/Google Pay im eingebetteten Checkout die Domain registrieren.
|
||||
- [ ] **Stripe Tax** nur mit aktiver Registrierung einschalten (Preise sind Bruttopreise; ohne Registrierung berechnet Stripe nichts).
|
||||
|
||||
**Im Admin:** SEPA-Neukunden-Frist (Vorgabe 56 Tage, 0 schaltet ab), Kontingente und Erntefenster der Abo-Angebote.
|
||||
|
||||
**Was automatisch passiert:** Jede bezahlte Monatsrechnung wird eine Wabenhain-Bestellung mit Rechnung und Mail; die erste erzeugt die Urkunde. Nach drei bezahlten Monaten (Ernte-Variante: im Erntefenster nach sechs) legt der Hintergrundlauf alle zehn Minuten eine 0-€-Lieferbestellung an, die in der normalen Pack- und DHL-Liste erscheint. Eine Rückbuchung setzt das Abo in Verzug, sperrt SEPA für das Konto und beendet das Abo nach 14 Tagen ohne Ausgleich. Kündigungen kommen aus dem Konto oder von `/vertraege-kuendigen` (Footer „Verträge hier kündigen“); öffentliche Kündigungen stehen im Audit-Log (`subscription.cancellation_request`) und gehen zusätzlich an `ADMIN_EMAIL`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Optionale Dienste
|
||||
@@ -271,7 +324,9 @@ Alle folgenden Werte dürfen leer bleiben. Die Funktion ruht dann, der Shop läu
|
||||
| **Cloudflare Turnstile** (CAPTCHA) — *dringend empfohlen* | `TURNSTILE_SECRET_KEY` (Secret), `NEXT_PUBLIC_TURNSTILE_SITE_KEY` (ConfigMap) | Keine Bot-Abwehr an Formularen | dash.cloudflare.com → Turnstile → Widget für `wabenhain.com` anlegen. Beide setzen oder beide leer. |
|
||||
| **Google-Rezensionen** | `GOOGLE_PLACES_API_KEY` (Secret), `GOOGLE_PLACE_ID` (ConfigMap) | Statische Beispiel-Stimmen | Google Cloud: „Places API (New)“ aktivieren, Abrechnung an, API-Schlüssel ohne Referrer-Beschränkung |
|
||||
| **DHL** (Versandmarken, Packstation, Sendungsverfolgung) | `DHL_API_KEY`, `DHL_API_SECRET`, `DHL_GKP_USERNAME`, `DHL_GKP_PASSWORD`, `DHL_ACCOUNT_NUMBER`, `DHL_TRACKING_API_KEY` (Secret), `DHL_ENVIRONMENT` (ConfigMap) | Kein Etikettendruck, keine Packstation im Checkout | developer.dhl.com, Geschäftskundenvertrag — Schritt für Schritt in `.env.example` |
|
||||
| **ApiCore-Synchronisierung** | `APICORE_SYNC_EMAIL`, `APICORE_SYNC_PASSWORD` (Secret), `APICORE_API_URL` (ConfigMap) | Sync-Knopf meldet Konfigurationsfehler | Eigenes, MFA-freies Service-Konto mit nur lesenden Rechten, siehe `.env.example` |
|
||||
| **ApiCore-Synchronisierung** | `APICORE_API_KEY` (Secret), `APICORE_API_URL` (ConfigMap) | Sync-Knopf meldet Konfigurationsfehler | API-Schlüssel aus ApiCore → Verwaltung → Automatisierung → API-Schlüssel, nur Berechtigung `shop-sync:read`; kein Benutzerkonto, kein Passwort |
|
||||
| **Bestandsabgleich mit ApiCore** | zusätzlich `APICORE_WEBHOOK_SECRET` (Secret), Berechtigung `shop-sync:write` am Schlüssel, CronJob `wabenhain-apicore-stock` | Der Webhook `/api/apicore/webhook` antwortet mit 503, Entnahmen in ApiCore kommen erst mit dem nächsten Abgleich an | ApiCore → Automatisierung → Webhooks: Webhook für `stock.changed` auf `https://wabenhain.com/api/apicore/webhook`, dessen Secret hier eintragen. Einzelheiten im README, Abschnitt „Bestandsabgleich“ |
|
||||
| **ERPNext-Export** (Rechnungen, Stornorechnungen, Kunden, Firmenanfragen) | `ERP_EXPORT_TOKEN` (Secret), mindestens 32 Zeichen | Die Endpunkte unter `/api/erp/…` lehnen jeden Abruf ab, ERPNext übernimmt nichts | Zufallswert erzeugen (wie `SESSION_SECRET` in Abschnitt 2) und denselben Wert in ERPNext als Token für Wabenhain hinterlegen |
|
||||
|
||||
---
|
||||
|
||||
@@ -301,7 +356,9 @@ cp k8s/02-secret.example.yaml k8s/02-secret.yaml
|
||||
| `ENTRA_REDIRECT_URI` | ja* | `https://wabenhain.com/api/auth/entra/callback` | 3.1 |
|
||||
| `TURNSTILE_SECRET_KEY` | empfohlen | Turnstile-Secret | 6 |
|
||||
| `GOOGLE_PLACES_API_KEY` | nein | Google-API-Schlüssel | 6 |
|
||||
| `APICORE_SYNC_EMAIL`, `APICORE_SYNC_PASSWORD` | nein | Service-Konto | 6 |
|
||||
| `APICORE_API_KEY` | nein | ApiCore-API-Schlüssel (`ack_…`) | 6 |
|
||||
| `APICORE_WEBHOOK_SECRET` | nein | Secret des ApiCore-Webhooks `stock.changed` | 6 |
|
||||
| `ERP_EXPORT_TOKEN` | nein | Bearer-Token für den ERPNext-Export, ≥ 32 Zeichen | 6 |
|
||||
| `DHL_*` (6 Werte) | nein | DHL-Zugangsdaten | 6 |
|
||||
|
||||
\* Ohne die `ENTRA_*`-Werte gibt es weder „Mit Microsoft anmelden“ **noch Mailversand** — keine Bestellbestätigungen, keine Passwort-Resets. Für den Live-Betrieb daher Pflicht.
|
||||
@@ -364,6 +421,15 @@ kubectl -n wabenhain patch secret wabenhain-secrets --type=json -p '[{"op":"remo
|
||||
|
||||
> Wer `k8s/02-secret.yaml` lokal pflegt, trägt jede Änderung auch dort ein — sonst setzt das nächste `kubectl apply` den alten Stand zurück.
|
||||
|
||||
**Neuen Build ausrollen:** Die Pipeline baut nur Images und rollt nichts aus. Das Deployment ist auf Tag und Digest gepinnt, ein `rollout restart` startet deshalb nur denselben Build neu. Einen neuen Build setzt man so ein (Digest aus der Gitea-Registry, Paket `wabenhain`, Tag `sha-<kurzer Commit>`):
|
||||
|
||||
```bash
|
||||
kubectl -n wabenhain set image deploy/wabenhain-app app=git.encry.de/nick.rosenloecher/wabenhain:sha-<commit>@sha256:<digest>
|
||||
kubectl -n wabenhain rollout status deploy/wabenhain-app
|
||||
```
|
||||
|
||||
Danach `image:` in `k8s/05-app-deployment.yaml` auf denselben Wert ziehen. Einzelheiten: `k8s/README.md`, Abschnitt „Bei einem neuen Image“.
|
||||
|
||||
---
|
||||
|
||||
## 9. Prüfen
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
# Bienenpatenschaft Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Bienenpatenschaften als Einmalkauf und Abo verkaufen, mit deterministisch erzeugter Urkunde, Medaillen, 3D-Ansicht im Konto, Übertragung, Treuestufen und Stripe-Abo.
|
||||
|
||||
**Architecture:** Eine reine Layout-Engine (`src/lib/certificate`) erzeugt aus Personalisierung, Textbausteinen und Vorlagenversion positionierte Elemente; daraus entstehen PDF (pdfkit) und Bilder (SVG mit Glyphenpfaden → sharp). Einmal-Angebote hängen an je einem `Product` der neuen Kategorie `PATENSCHAFT`, damit Warenkorb, Checkout, Rechnung, ERP-Export und ApiCore-Buchung weiterlaufen; der Honig eines Pakets wird beim Checkout als eigene Position des verknüpften Honigprodukts angelegt (Steueraufteilung, Bestandsreservierung und ApiCore-Abbuchung ohne Sonderweg). Abos laufen über Stripe Billing; jede bezahlte Monatsrechnung wird zu einer Wabenhain-Bestellung mit Rechnung, jede fällige Lieferung zu einer 0-€-Bestellung mit Honigpositionen.
|
||||
|
||||
**Tech Stack:** Next.js 16 (App Router, Server Actions), Prisma 7 (Postgres + MySQL), pdfkit, fontkit, sharp, three + @react-three/fiber + drei, fflate, Stripe (API 2026-08-26.dahlia), vitest, Playwright.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-10-16-bienenpatenschaft-design.md`
|
||||
|
||||
Abweichung vom Standard „ein Plan je Teilprojekt“: Der Inhaber hat alle fünf Teilprojekte auf einmal freigegeben. Der Plan ist deshalb in Teile A–E gegliedert, jeder Teil ist für sich lauffähig und testbar und wird einzeln committet.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Kein Versprechen von Besuchen, Events, Videos, Fotos, Berichten, Umweltwirkungen – in keinem Text, keiner Mail, keiner Urkunde.
|
||||
- Urkunde: A4 hochkant (595.28 × 841.89 pt), genau eine Seite, Inhalt ≥ 15 mm (42.52 pt) vom Rand, Rahmen ≥ 12 mm (34.02 pt), kleinste Schrift 8 pt, Fließtext ≥ 11 pt.
|
||||
- Schriften Cormorant Garamond und Inter, statische TTF unter SIL OFL, mit Lizenzdatei in `assets/fonts/`.
|
||||
- Farben: Forest `#24352b`, Honey Dark `#8a6531`, Honey `#b88a44`, Sage `#788774`; auf Papier kein Verlauf, keine Folienimitation.
|
||||
- Eingabelimits (Start): Bienenname 2–24, Name 2–60, Schenkende ≤ 80, Widmung ≤ 280 Zeichen und ≤ 5 Zeilenumbrüche; NFC, Steuerzeichen raus, Glyphenprüfung.
|
||||
- Keine Pronomen, keine abgeleiteten Anreden, keine Behauptung individueller Betreuung einer Biene.
|
||||
- Patenschaftsnummer `WH-P-JJJJ-NNNNN`. Vorlagenkennung `<name>@<version>`.
|
||||
- Patenschaften nur mit angemeldetem, verifiziertem Konto. Gastbestellungen anderer Produkte bleiben.
|
||||
- PDFs in `CERTIFICATE_DIR` (nie unter `UPLOAD_DIR`), Downloads nur nach Besitzprüfung, fremde IDs → 404.
|
||||
- Wasserzeichen der Vorschau: „Unverbindliche Vorschau“ / „Preview – not binding“.
|
||||
- Abo: Lieferanspruch nach 3 (vierteljährlich) bzw. 6 (Ernte) bezahlten Monaten; SEPA-Neukunden-Frist 56 Tage (Admin, 0 = aus); Rückbuchung → `IM_VERZUG`, nach 14 Tagen ohne Ausgleich Ende; Konto mit Rückbuchung → kein SEPA mehr.
|
||||
- Abo-Stufen 1–24 je bezahltem Monat, danach VIP; Stammkunden-Stufen ab 2/5/10/25 bezahlten Bestellungen; beides im Admin pflegbar.
|
||||
- Übertragungslinks: 24 h / 7 Tage / 30 Tage, einmalig, widerrufbar, Token ≥ 128 Bit, nur Hash gespeichert.
|
||||
- Zahlarten nie per `payment_method_types`; Stripe-Livekonto nur über Einrichtungsskript bzw. Stripe-Anbindung ändern.
|
||||
- Codekommentare und Texte auf Deutsch, Stil wie im Repo (Warum-Kommentare, keine console.log zum Debuggen).
|
||||
- Agents committen nicht; der Hauptlauf committet zentral.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. Zwei Patenschaften desselben Pakets im Warenkorb dürfen nicht verschmelzen → Tests in A7 (Warenkorbschlüssel) und A8 (Checkout mit doppelter productId).
|
||||
2. Webhook mehrfach oder parallel: genau eine Patenschaft, genau eine Mail → Test in A9.
|
||||
3. Manipulierte Personalisierung (überlange Widmung, fremde Zeichen, `<script>`): Checkout lehnt ab, Urkunde zeigt nur Text → Tests in A2 und A8.
|
||||
4. Abo gekündigt, während eine Lieferung fällig wird: keine Lieferung über bezahlte Monate hinaus → Test in D4.
|
||||
5. Honig knapp, während Abos reserviert sind: Einzelverkauf und Pakete können reservierte Gläser nicht kaufen → Test in D5.
|
||||
|
||||
---
|
||||
|
||||
## Teil A – Urkunde und Einmal-Patenschaft (Teilprojekt 1)
|
||||
|
||||
### Task A1: Schriften, Personalisierungsschema, Textbausteine
|
||||
|
||||
**Files:** Create `assets/fonts/CormorantGaramond-{Regular,Italic,SemiBold,SemiBoldItalic}.ttf`, `assets/fonts/Inter-{Regular,Medium}.ttf`, Lizenzdateien; `src/lib/certificate/{schema,text,fonts}.ts`, `src/types/fontkit.d.ts`; Tests `src/lib/certificate/{schema,text}.test.ts`
|
||||
|
||||
**Produces:**
|
||||
- `OCCASIONS = ["SELBST","GEBURTSTAG","WEIHNACHTEN","DANKESCHOEN","GESCHENK"] as const`, `type Occasion`
|
||||
- `CERTIFICATE_LIMITS = { beeName:{min:2,max:24}, recipientName:{min:2,max:60}, giverNames:{max:80}, dedication:{max:280,maxLineBreaks:5} }`
|
||||
- `normalizeCertificateText(value: string, opts?: { multiline?: boolean }): string`
|
||||
- `personalizationSchema` (zod) → `Personalization = { beeName; recipientName; giverNames?; dedication?; occasion: Occasion; startDate: "YYYY-MM-DD" }`; `giverNames` wird bei `SELBST` verworfen
|
||||
- `CertificateTerm = {kind:"FIXED";start;end} | {kind:"OPEN";start} | {kind:"ENDED";start;end}`, `fixedTermFor(start)` (Ende = Start + 12 Monate − 1 Tag)
|
||||
- `composeCertificateText({ personalization, locale, term, number }): CertificateText` = `{ title; subtitle; occasionLine|null; leadLine|null; beforeBee; beeName; afterBee; giverLine|null; dedication|null; termLine; numberLine; notice }`
|
||||
- `loadCertificateFonts(): CertificateFonts` (gecacht; Schlüssel `serif`, `serifItalic`, `serifBold`, `serifBoldItalic`, `sans`, `sansMedium`), `findUnsupportedCharacters(text, fontKeys): string[]`
|
||||
|
||||
- [ ] Tests (Schema-Grenzen, „Zoë“, Steuerzeichen, giverNames bei SELBST, 6 Umbrüche, Emoji; Text: eigene/verschenkte Variante, Anlasszeilen, leere Felder ohne Zeile, drei Laufzeitformen de/en, Hinweis wörtlich)
|
||||
- [ ] Implementieren, `pnpm vitest run src/lib/certificate` grün
|
||||
|
||||
### Task A2: Layout-Engine
|
||||
|
||||
**Files:** `src/lib/certificate/layout.ts`, `src/lib/certificate/templates/{index,<vorlage>}.ts`; Test `layout.test.ts`
|
||||
|
||||
**Produces:**
|
||||
- `LayoutElement = {kind:"text"; font; size; color; x; y; width; text; align; role} | {kind:"path"; d; stroke?; fill?; strokeWidth?; opacity?} | {kind:"image"; src:"logo"; x; y; width; height}`
|
||||
- `CertificateLayout = { templateVersion; width: 595.28; height: 841.89; elements }`
|
||||
- `CertificateTemplate { version; layout(text, fonts): CertificateLayout }`, `CURRENT_TEMPLATE_VERSION`, `getTemplate(version)`
|
||||
- `layoutCertificate(text, templateVersion?)`, `CertificateLayoutError { field }`, `checkCertificateFits(p, locale)`
|
||||
|
||||
- [ ] Testmatrix der Spec: keine Überlappung, Sicherheitszone, Mindestgrößen, Namen ≤ 2 Zeilen, Umbruch nur an Leerzeichen/Bindestrich
|
||||
- [ ] Implementieren, grün
|
||||
|
||||
### Task A3: Renderer und Designvarianten
|
||||
|
||||
**Files:** `src/lib/certificate/{render-pdf,render-image}.ts`, `scripts/render-certificate-samples.ts`; Test `render.test.ts`
|
||||
|
||||
**Produces:** `renderCertificatePdf(layout, { title, logo? }): Promise<Buffer>`, `renderCertificateSvg(layout, { watermark? }): string` (Glyphenpfade), `renderCertificateImage(layout, { widthPx, watermark?, format }): Promise<Buffer>`, `layoutLines(layout): string[]`
|
||||
|
||||
- [ ] Tests: `%PDF`, genau eine Seite, eingebettete Fonts; SVG ohne `<text>`; Wasserzeichen; Bildbreite
|
||||
- [ ] Drei Vorlagen rendern, ansehen, eine wählen, andere entfernen
|
||||
|
||||
### Task A4: Datenmodell
|
||||
Enums `SponsorshipOfferKind`, `SponsorshipCycle`, `MedalTier`, `SponsorshipStatus`; `ProductCategory.PATENSCHAFT`; `FulfillmentMethod.DIGITAL`; Modelle `SponsorshipOffer`, `Sponsorship`, `SponsorshipRevision`, `SponsorshipCounter`; `OrderItem.personalization`, `OrderItem.sponsorshipOfferId`, `OrderItem.sponsorshipRole`. Migration `prisma/migrations/20261016010000_sponsorship`. `DIGITAL` überall behandeln, `pnpm typecheck` grün.
|
||||
|
||||
### Task A5: Angebote im Admin + Startdaten
|
||||
`src/lib/sponsorship/offers.ts` (`getActiveOffers`, `getOfferBySlug`), Admin `/admin/patenschaften/angebote`, Upsert legt das `Product` (Kategorie `PATENSCHAFT`, Preis = Paketpreis − Honiganteil) mit an; Seed der drei Pakete; `PATENSCHAFT` aus Shop-Listen und Produktseite filtern.
|
||||
|
||||
### Task A6: Vorschau-API und Verkaufsseite
|
||||
`/api/patenschaft/vorschau` (Origin, Rate-Limit 60/10 min, Schema + Fit, WebP 900 px mit Wasserzeichen, `no-store`); `/patenschaft` mit Konfigurator (Einmalig/Abo, Schritte, Zähler, Debounce 400 ms, Bestätigung, Anmeldezwang mit Entwurf in `sessionStorage` `wabenhain-sponsorship-draft`).
|
||||
|
||||
### Task A7: Warenkorb
|
||||
`CartItem.key`, `CartItem.sponsorship?: { offerSlug; personalization }`, Operationen über `key`, `persist` Version 2 mit `migrate`, Patenschaft Menge fest 1. Tests: zwei gleiche Pakete bleiben zwei Positionen; alter Speicherstand wird migriert.
|
||||
|
||||
### Task A8: Checkout
|
||||
`expandSponsorshipItems(...)` in `src/lib/sponsorship/checkout-expand.ts`: Hauptposition ohne Reservierung, Honigposition aus verknüpftem Produkt (`unitPriceCents = honeyShareCentsPerJar`, Menge = Gläser, Steuer des Honigs), Kontopflicht, erneute Prüfung, reine Digitalbestellung → `DIGITAL` ohne Versand, doppelte productIds erlaubt. Tests inkl. Manipulation.
|
||||
|
||||
### Task A9: Ausstellung nach Zahlung
|
||||
`createSponsorshipsForOrder(tx, orderId)` im Claim-Lauf; `issuePendingSponsorships({orderId?, limit?})`; Mail-Claim über `mailSentAt`; Backoff `min(2^n × 5 min, 12 h)`, 8 Versuche → `FEHLER`; `scripts/sponsorship-jobs.ts` + CronJob `wabenhain-sponsorship`; `CERTIFICATE_DIR` mit Startprüfung. Tests: doppelter Aufruf, Fehler beim Rendern, Wiederholung.
|
||||
|
||||
### Task A10: Kontobereich und Download
|
||||
`/konto/patenschaft`, `/konto/patenschaft/[id]`, PDF-Route mit Besitzprüfung, `getOwnedSponsorship(customerId, id)`.
|
||||
|
||||
### Task A11: Admin Patenschaften, Druck, Korrektur
|
||||
Liste/Filter, Detail, Druck-PDF, „gedruckt“, „erneut erzeugen“, „Mail erneut“, `reviseSponsorship(...)` mit Revision und Audit-Log; Aufmerksamkeitsliste.
|
||||
|
||||
## Teil B – Medaillen, 3D, Gesamtdownload (Teilprojekt 2)
|
||||
- B1 `src/lib/medals/`: `renderMedalSvg(input: MedalInput)`, `renderMedalPng(input, sizePx = 2048)`; `MedalInput` = Patenschaft (tier, beeName, year, number) | Stammkunde (level, name) | Abo (months) | VIP.
|
||||
- B2 Routen `textur.webp`, `medaille.png`, `medaille.svg`, `alles.zip` (fflate) mit Besitzprüfung.
|
||||
- B3 `src/components/patenschaft-3d/`: `<SponsorshipStage textureUrl backTextureUrl medalSvgUrl tier fallbackImageUrl />`, dynamisch geladen, Wölbung, Reflex, Ziehen mit Nachschwung, Doppelklick wendet, Zoom begrenzt, Neigung nach Tipp, reduced motion, WebGL-Fallback, Tastatur, Pause außerhalb der Sicht.
|
||||
|
||||
## Teil C – Übertragung (Teilprojekt 3)
|
||||
`SponsorshipTransfer`, `createTransferAction(id, validity)`, `revokeTransferAction`, `/patenschaft/uebernehmen/[token]`, Audit-Log, neutrale Fehlerseite. Tests: Ablauf, Widerruf, Doppel-Einlösung, Abo nicht übertragbar.
|
||||
|
||||
## Teil D – Abo (Teilprojekt 4)
|
||||
- D1 Modelle `SponsorshipSubscription`, `SubscriptionPayment`, `SubscriptionDelivery`, `HarvestWindow`; `Customer.stripeCustomerId`, `Customer.sepaBlockedAt`; Einstellung SEPA-Frist (56).
|
||||
- D2 Stripe Product/Price aus Admin; `POST /api/patenschaft/abo` (Checkout `mode: "subscription"`, eingebettet; `excluded_payment_method_types: ["sepa_debit"]` nur bei Sperre).
|
||||
- D3 Webhooks Abo/Rechnung/Rückbuchung idempotent; `invoice.paid` → Zahlung + Bestellung `DIGITAL` + Rechnung + Mail; erste Zahlung → Patenschaft (OPEN).
|
||||
- D4 `computeDeliveryEntitlement(...)`, täglicher Lauf erzeugt 0-€-Lieferbestellungen.
|
||||
- D5 `availableForSale(productId)` = Bestand − Abo-Reservierung; Kontingent; Deckungsanzeige; Stopp neuer Abos.
|
||||
- D6 Kündigung im Konto und unter `/vertraege-kuendigen`, `cancel_at_period_end`, Mail, ENDED-Revision bei Wirksamkeit.
|
||||
- D7 `scripts/stripe-setup.ts` und Livekonto über die Stripe-Anbindung (Webhook-Ereignisse, Kundenportal nur Zahlungsart), Checkliste in `docs/EINRICHTUNG.md`.
|
||||
|
||||
## Teil E – Treuestufen (Teilprojekt 5)
|
||||
`LoyaltyLevel`, Seed (2/5/10/25; Abo 1–24 + VIP), `getCustomerLoyalty(customerId)`, Medaillenleiste, Admin-Pflege. Tests: Erstattung senkt Stufe, Kündigung entfernt Abo-Stufe.
|
||||
|
||||
## Abschluss
|
||||
- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test`, `pnpm build` grün
|
||||
- [ ] Browserprüfung Desktop + 390 px, reduced motion, Tastatur
|
||||
- [ ] Code-Review und `code-simplifier` auf den Diff
|
||||
- [ ] Commits, Push, CI grün; Rollout nur nach Freigabe
|
||||
@@ -0,0 +1,877 @@
|
||||
# Bienenpatenschaft: Urkunde, Abo, Medaillen und 3D-Ansicht im Konto
|
||||
|
||||
Datum: 2026-10-16
|
||||
Status: Entwurf zur Freigabe, Implementierung ausstehend
|
||||
Gitea: #31
|
||||
|
||||
Dieses Dokument ersetzt den bisherigen Implementierungsauftrag zur
|
||||
Bienenpatenschaft vollständig. Grundlage sind die verbindlichen Vorgaben des
|
||||
Inhabers vom 2026-10-16 und seine Ergänzungen vom selben Tag (Abo,
|
||||
Kundenkonto, 3D-Ansicht, Medaillen, Treuestufen, Übertragung). Wo ältere
|
||||
Fassungen etwas anderes sagen, gilt dieses Dokument.
|
||||
|
||||
## Problem und Ziel
|
||||
|
||||
Wabenhain verkauft symbolische Bienenpatenschaften als Geschenk oder für sich
|
||||
selbst, einmalig bezahlt oder als monatliches Abo. Das zentrale Produkt ist
|
||||
eine hochwertige, persönlich gestaltete Urkunde. Im Kundenkonto erleben
|
||||
Kunden ihre Urkunde und ihre Medaillen in einer interaktiven 3D-Ansicht und
|
||||
laden alles herunter.
|
||||
|
||||
Nach dem Kauf läuft alles automatisch: Zahlung, Urkunde, Medaillen,
|
||||
Abo-Abrechnung, Rechnungen, Lieferaufträge für den Abo-Honig. Die Handarbeit
|
||||
des Inhabers beschränkt sich auf Drucken, Verpacken und Versenden.
|
||||
|
||||
Erfolg heißt: Eine Testbestellung erzeugt ohne manuelle Nachbearbeitung eine
|
||||
korrekt personalisierte, hochwertige und druckfähige Urkunde, die sofort im
|
||||
Konto in 3D erscheint. Ein Test-Abo rechnet monatlich ab und erzeugt die
|
||||
Honiglieferung erst, wenn sie bezahlt ist.
|
||||
|
||||
## Teilprojekte und Reihenfolge
|
||||
|
||||
Der Umfang ist zu groß für einen Plan. Jedes Teilprojekt bekommt einen
|
||||
eigenen Umsetzungsplan und wird einzeln geprüft und ausgerollt:
|
||||
|
||||
| Nr. | Teilprojekt | Hängt ab von | Schätzung |
|
||||
|---|---|---|---|
|
||||
| 1 | Urkunde, Einmal-Patenschaft, Kontopflicht, Kontobereich mit Downloads, Admin (Druck, Korrektur) | – | 4–5 Tage |
|
||||
| 2 | 3D-Ansicht von Urkunde und Medaille, Patenschafts-Medaillen je Paket, „Alles herunterladen“ | 1 | 3–4 Tage |
|
||||
| 3 | Übertragung an Beschenkte per befristetem Link | 1 | 1 Tag |
|
||||
| 4 | Abo: Stripe-Abrechnung, Kündigungsbutton, Lieferzyklen, Honigkontingent, Rechnungen | 1 | 5–7 Tage |
|
||||
| 5 | Treuestufen: Stammkunden-Stufen, Abo-Stufen, VIP | 2, 4 | 2 Tage |
|
||||
|
||||
Teilprojekt 1 ist allein verkaufsfähig. Jedes weitere macht das Angebot
|
||||
reicher, ohne das vorherige umzubauen.
|
||||
|
||||
## Nicht im Umfang
|
||||
|
||||
Diese Leistungen entfallen. Sie werden weder auf der Verkaufsseite noch in
|
||||
E-Mails, Urkunden, FAQs oder Rechtstexten versprochen:
|
||||
|
||||
- Besuche beim Imker oder am Bienenstand
|
||||
- Patentage, Veranstaltungen, Terminbuchungen
|
||||
- Videos, individuelle Bienenfotos, Saisonberichte
|
||||
- jede Pflicht zur laufenden Erstellung von Inhalten
|
||||
- Veranstaltungs- oder Teilnehmerverwaltung
|
||||
- Zusagen zu Naturschutzprojekten oder unbelegte Umweltversprechen
|
||||
- ein Vorlagen-Auswahlschritt für Kunden (es gibt genau eine Gestaltung)
|
||||
- Gastbestellungen von Patenschaften
|
||||
|
||||
Später möglich, jetzt nicht gebaut: Bilder oder andere Medien im
|
||||
Patenschaftsbereich des Kontos. Das Datenmodell lässt dafür Platz (siehe
|
||||
„Erweiterbarkeit“), es gibt aber keine Oberfläche und kein Versprechen.
|
||||
|
||||
## Angebote
|
||||
|
||||
Alle Angebote sind im Admin pflegbar: Name, Beschreibung, Leistungsliste,
|
||||
Preis, aktiv/inaktiv, Reihenfolge, verknüpftes Honigprodukt, Gläser,
|
||||
Steueraufteilung, Medaillenstufe. Es kann beliebig viele Angebote beider Arten
|
||||
geben.
|
||||
|
||||
### Einmal-Patenschaften
|
||||
|
||||
| Paket | Testpreis | Leistungen | Versand |
|
||||
|---|---:|---|---|
|
||||
| Bienenfreund | 19 € | symbolische Namensgebung, PDF-Urkunde, Medaille, Konto mit 3D-Ansicht und Downloads | keiner |
|
||||
| Honigfreund | 39 € | digitale Leistungen, gedruckte Urkunde, 1 × 500 g Honig, Grußkarte, Geschenkverpackung | ja |
|
||||
| Wabenfreund | 59 € | digitale Leistungen, gedruckte Urkunde, 3 × 500 g Honig, Grußkarte, Geschenkverpackung | ja |
|
||||
|
||||
- Laufzeit zwölf Monate ab Startdatum, endet automatisch.
|
||||
- Nach Ablauf trägt die Urkunde weiter ihr Von-bis-Datum. Urkunde, Medaille
|
||||
und Downloads bleiben im Konto verfügbar.
|
||||
- Alle Pakete bekommen dieselbe Urkunde in derselben Qualität. Sie
|
||||
unterscheiden sich in den physischen Leistungen und in der Medaillenstufe.
|
||||
|
||||
### Abo-Patenschaften
|
||||
|
||||
Zwei Ausgangsangebote, Preise vom Inhaber festzulegen:
|
||||
|
||||
| Angebot | Zahlung | Honig | Lieferung |
|
||||
|---|---|---|---|
|
||||
| Patenschaft im Abo, vierteljährlich | monatlich | z. B. 2 × 500 g je Lieferung | nach jeweils 3 bezahlten Monaten |
|
||||
| Patenschaft im Abo, nach der Ernte | monatlich | z. B. 3 × 500 g je Lieferung | in den Erntefenstern, frühestens nach 6 bezahlten Monaten seit der letzten Lieferung |
|
||||
|
||||
- Monatlich kündbar zum Ende des bezahlten Monats.
|
||||
- Versand ist im Monatspreis enthalten. Die Verkaufsseite sagt das deutlich.
|
||||
- Ein Abo gilt einer Biene mit einem Namen und hat eine Urkunde.
|
||||
- Abo und Einmalkauf werden getrennt bezahlt (eigene Stripe-Sitzung je Abo).
|
||||
- Ein Abo lässt sich in dieser Fassung nicht übertragen, weil die Zahlung am
|
||||
Konto des Käufers hängt.
|
||||
|
||||
### Grußkarte
|
||||
|
||||
Vorgedruckt, nicht personalisiert, im Wabenhain-Design. Persönliche Worte
|
||||
stehen in der Widmung auf der Urkunde. So entsteht kein Handschreiben.
|
||||
|
||||
## Kundenkonto ist Pflicht
|
||||
|
||||
- Patenschaften kauft nur, wer angemeldet ist. Das betrifft Einmal- und
|
||||
Abo-Angebote. Für andere Produkte bleibt die Gastbestellung wie heute.
|
||||
- Die Personalisierung lässt sich ohne Anmeldung ausprobieren, samt Vorschau.
|
||||
Beim Klick auf „In den Warenkorb“ oder „Abo abschließen“ führt die Seite zur
|
||||
Anmeldung oder Registrierung. Die Eingaben bleiben dabei erhalten
|
||||
(Entwurf im `sessionStorage`, nach der Anmeldung zurückgeschrieben).
|
||||
- Der Checkout prüft serverseitig, dass ein Konto angemeldet ist, sobald eine
|
||||
Patenschaft im Warenkorb liegt.
|
||||
|
||||
## Personalisierung
|
||||
|
||||
### Felder
|
||||
|
||||
| Feld | Pflicht | Hinweis |
|
||||
|---|---|---|
|
||||
| Name der Patenbiene | ja | symbolischer Name |
|
||||
| Name der Person auf der Urkunde | ja | für wen die Urkunde ausgestellt ist |
|
||||
| Schenkende | nein | eine oder mehrere Personen als Freitext („Anna und Ben“) |
|
||||
| Widmung | nein | wird unverändert übernommen |
|
||||
| Anlass | ja | für mich selbst, Geburtstag, Weihnachten, Dankeschön, allgemeines Geschenk |
|
||||
| Startdatum | ja | Einmal: frühestens Bestelltag, spätestens sechs Monate danach. Abo: Tag der ersten Zahlung |
|
||||
|
||||
Bei „für mich selbst“ blendet das Formular „Schenkende“ aus.
|
||||
|
||||
### Eingabelimits
|
||||
|
||||
Die endgültigen Limits ergeben sich aus der Layout-Testmatrix. Startwerte:
|
||||
|
||||
- Bienenname: 2–24 Zeichen
|
||||
- Name auf der Urkunde: 2–60 Zeichen
|
||||
- Schenkende: bis 80 Zeichen
|
||||
- Widmung: bis 280 Zeichen und höchstens 5 Zeilenumbrüche
|
||||
|
||||
Das Formular zeigt jedes Limit vor der Bestellung als Zeichenzähler an. Server
|
||||
und Client prüfen mit demselben zod-Schema.
|
||||
|
||||
### Zeichen
|
||||
|
||||
- Eingaben werden nach Unicode NFC normalisiert, Steuerzeichen entfernt,
|
||||
Mehrfach-Leerzeichen zusammengefasst.
|
||||
- Zulässig ist jedes Zeichen, für das die eingebetteten Schriften eine Glyphe
|
||||
haben. Die Prüfung läuft serverseitig über die Font-Metriken (fontkit).
|
||||
Fehlt eine Glyphe (zum Beispiel Emoji), lehnt das Formular die Eingabe mit
|
||||
klarer Meldung ab, statt ein Ersatzkästchen zu drucken.
|
||||
- Umlaute, ß, Akzente, Bindestriche und Apostrophe funktionieren.
|
||||
|
||||
## Urkundentext
|
||||
|
||||
Der Text entsteht aus hinterlegten Bausteinen. Es gibt keine KI-Anfrage pro
|
||||
Bestellung. Der Kunde sieht den endgültigen Wortlaut vor dem Kauf in der
|
||||
Vorschau.
|
||||
|
||||
### Regeln
|
||||
|
||||
- Eigene und verschenkte Patenschaft haben unterschiedliche Formulierungen.
|
||||
- Geburtstag, Weihnachten und Dankeschön haben je eine kurze Anlasszeile.
|
||||
„Für mich selbst“ und „allgemeines Geschenk“ haben keine.
|
||||
- Leere Felder erzeugen keine Platzhalter, keine leeren Zeilen und keine
|
||||
verwaisten Bezeichnungen wie „Von:“ ohne Namen.
|
||||
- Keine erfundenen Eigenschaften, Beziehungen oder Ereignisse.
|
||||
- Keine Geschlechtszuordnung: keine Pronomen, keine aus dem Namen
|
||||
abgeleiteten Anreden.
|
||||
- Keine Formulierung, die eine individuelle Betreuung oder Verfolgung einer
|
||||
einzelnen Biene behauptet.
|
||||
- Die Widmung wird wörtlich übernommen, nur sicher dargestellt (kein HTML,
|
||||
kein Markup) und sauber umbrochen.
|
||||
|
||||
### Bausteine (Entwurf, vor Abnahme sprachlich final prüfen)
|
||||
|
||||
Überschrift: „Bienenpatenschaft“, darunter klein „Urkunde“.
|
||||
|
||||
Anlasszeile: „Zum Geburtstag“, „Zu Weihnachten“, „Als Dankeschön“.
|
||||
|
||||
Haupttext, eigene Patenschaft:
|
||||
|
||||
> {Name auf der Urkunde} hat einer Biene der Imkerei Wabenhain symbolisch den
|
||||
> Namen
|
||||
> **{Bienenname}**
|
||||
> gegeben und unterstützt damit die Imkerei und ihre Bienenvölker.
|
||||
|
||||
Haupttext, verschenkte Patenschaft:
|
||||
|
||||
> Für {Name auf der Urkunde}
|
||||
> Einer Biene der Imkerei Wabenhain wurde symbolisch der Name
|
||||
> **{Bienenname}**
|
||||
> gegeben. Die Patenschaft unterstützt die Imkerei und ihre Bienenvölker.
|
||||
|
||||
Schenkende, nur wenn ausgefüllt: „Geschenkt von {Schenkende}“.
|
||||
|
||||
Widmung, nur wenn ausgefüllt: eigener, typografisch abgesetzter Block.
|
||||
|
||||
Laufzeit:
|
||||
|
||||
- Einmal: „Patenschaft vom {Start} bis {Ende}“, Ende = Start plus zwölf Monate
|
||||
minus ein Tag.
|
||||
- Abo, aktiv: „Patenschaft seit {Start}“.
|
||||
- Abo, gekündigt: „Patenschaft vom {Start} bis {Ende}“, Ende = letzter
|
||||
bezahlter Tag. Diese Fassung entsteht automatisch als neue Revision, sobald
|
||||
die Kündigung wirksam wird (siehe „Abo“).
|
||||
|
||||
Kennung: „Nr. {Patenschaftsnummer}“, Format `WH-P-JJJJ-NNNNN`, fortlaufend über
|
||||
einen eigenen Zähler (wie `InvoiceCounter`).
|
||||
|
||||
Hinweis, immer vorhanden und gut lesbar:
|
||||
|
||||
> Die Namensgebung ist symbolisch. Sie gilt keiner einzeln begleiteten Biene,
|
||||
> sondern unterstützt die Imkerei Wabenhain und ihre Bienenvölker.
|
||||
|
||||
Sprache: Die Urkunde erscheint in der beim Kauf gewählten Sprache (de/en).
|
||||
Beide Fassungen durchlaufen dieselbe Testmatrix.
|
||||
|
||||
## Gestaltung der Urkunde
|
||||
|
||||
### Anspruch
|
||||
|
||||
Die Urkunde soll wie ein rahmenwürdiges Geschenk wirken:
|
||||
|
||||
- elegante Typografie mit klarer Hierarchie
|
||||
- großzügiger Weißraum, ausgewogene Proportionen
|
||||
- Bienenname und Name auf der Urkunde als gestalterischer Mittelpunkt
|
||||
- dezente Bienen-, Blüten- oder Wabenillustration als feine Strichgrafik
|
||||
- zurückhaltende Markenfarben, feine Rahmen oder Ornamente
|
||||
- harmonisch eingebundene Widmung
|
||||
- diskrete Patenschaftsnummer und Datumsangaben
|
||||
- keine Cliparts, keine Office-Vorlagenoptik, keine erfundenen Gütesiegel,
|
||||
keine Unterschrift
|
||||
|
||||
### Markengrundlage
|
||||
|
||||
- Schriften: Cormorant Garamond für Überschrift, Namen und Widmung, Inter für
|
||||
Kleintext. Beide stehen unter der SIL Open Font License und dürfen in PDFs
|
||||
eingebettet werden. Die TTF-Dateien kommen samt Lizenz nach `assets/fonts/`.
|
||||
- Farben aus `src/app/globals.css`: Forest `#24352b` für Text, Honey Dark
|
||||
`#8a6531` für Akzente und Linien, Honey `#b88a44` nur klein, Sage `#788774`
|
||||
für Ornamente. Gold ist auf Papier eine flache Druckfarbe, nie Verlauf oder
|
||||
Folienimitat. Die Urkunde verspricht keine Goldfolie.
|
||||
- Logo: das hochgeladene Markenlogo (`getBrandAssets`), für den Druck als SVG
|
||||
oder als PNG mit mindestens 300 dpi in Druckgröße. Fehlt es, nutzt die
|
||||
Urkunde das gezeichnete Waben-Zeichen aus `lib/brand-icon.ts`. Das Logo
|
||||
wird nicht verzerrt, umgefärbt oder nachgezeichnet.
|
||||
- Weißes Papier, keine randlosen Farbflächen.
|
||||
|
||||
### Drei Varianten, dann eine Entscheidung
|
||||
|
||||
Zuerst entstehen drei Varianten mit identischen Beispieldaten:
|
||||
|
||||
1. Klassisch-editorial: zentrierte Achse, feiner Doppelrahmen in Honey Dark,
|
||||
kleine Biene als Strichzeichnung über der Überschrift.
|
||||
2. Wabe: asymmetrischer Aufbau, feines Hexagon-Linienraster als Eckmotiv,
|
||||
Namen linksbündig groß.
|
||||
3. Botanisch: Lindenblüten- oder Kleezweig als Strichillustration, die den
|
||||
Textblock an zwei Ecken einfasst.
|
||||
|
||||
Alle drei werden als echte PDFs gerendert und nebeneinander beurteilt. Die
|
||||
passendste Variante wird vollständig umgesetzt. Die anderen bleiben nicht im
|
||||
Produktcode. Illustrationen werden selbst als Vektor gezeichnet. Es gibt
|
||||
keine fremden Bildrechte und keine Rasterillustrationen.
|
||||
|
||||
## Druck- und PDF-Anforderungen
|
||||
|
||||
- A4 hochkant, genau eine Seite
|
||||
- Text als echter Text mit eingebetteten Schrift-Teilmengen, Illustrationen
|
||||
und Rahmen als Vektor
|
||||
- Rasterbilder (nur das Logo, falls kein SVG) mit mindestens 300 dpi
|
||||
- sicherer Rand: Inhalt mindestens 15 mm vom Blattrand, Rahmenlinien
|
||||
mindestens 12 mm
|
||||
- keine abgeschnittenen Namen, keine Überlagerungen
|
||||
- kleinste Schrift 8 pt (Kennung, Hinweis), Fließtext mindestens 11 pt
|
||||
- PDF-Metadaten: Titel „Bienenpatenschaft {Bienenname}“, Autor „Imkerei
|
||||
Wabenhain“
|
||||
|
||||
Lange Inhalte löst das Layout über Regeln, nicht durch Verkleinern der ganzen
|
||||
Seite:
|
||||
|
||||
1. Layoutvarianten: ohne Widmung, mit kurzer Widmung, mit langer Widmung. Die
|
||||
Variante folgt aus der gemessenen Höhe.
|
||||
2. Kontrollierte Umbrüche: Namen brechen nur an Leerzeichen oder Bindestrich,
|
||||
höchstens auf zwei Zeilen, nie mitten im Wort.
|
||||
3. Begrenzte Schriftstufen: jedes Feld hat eine feste Liste von Größen (zum
|
||||
Beispiel Bienenname 54, 46, 40 pt). Passt der Inhalt in der kleinsten
|
||||
Stufe nicht, ist das ein Validierungsfehler. Die Eingabelimits verhindern
|
||||
diesen Fall im Betrieb.
|
||||
|
||||
## Medaillen und Treuestufen
|
||||
|
||||
Es gibt drei Arten von Medaillen. Alle werden deterministisch als Vektor
|
||||
erzeugt (SVG), im Konto in 3D gezeigt und als PNG (2048 px, transparent) und
|
||||
SVG heruntergeladen. Auf dem Bildschirm dürfen Medaillen metallisch glänzen.
|
||||
Das betrifft nur die digitale Darstellung, nicht den Druck.
|
||||
|
||||
### 1. Patenschafts-Medaille (Teilprojekt 2)
|
||||
|
||||
- Eine je Patenschaft, mit Bienenname, Jahr und Patenschaftsnummer.
|
||||
- Die Stufe richtet sich nach dem Angebot: Bienenfreund, Honigfreund und
|
||||
Wabenfreund haben eigene Prägung und eigenes Metall (zum Beispiel Bronze,
|
||||
Silber, Gold). Abo-Angebote haben eine eigene Prägung. Die Zuordnung ist am
|
||||
Angebot im Admin einstellbar.
|
||||
- Sie gehört zur Patenschaft und bleibt dauerhaft, auch nach Ablauf oder
|
||||
Kündigung. Bei einer Übertragung wandert sie mit.
|
||||
|
||||
### 2. Stammkunden-Stufen (Teilprojekt 5)
|
||||
|
||||
- Für alle Kunden mit Konto, über den ganzen Shop.
|
||||
- Grundlage: Anzahl bezahlter, nicht erstatteter oder stornierter
|
||||
Bestellungen. Abo-Monatszahlungen zählen hier nicht, sie haben eigene
|
||||
Stufen.
|
||||
- Stufen und Schwellen im Admin pflegbar. Vorschlag: „Blütenbesuch“ ab 2,
|
||||
„Wabenbau“ ab 5, „Honigschatz“ ab 10, „Goldwabe“ ab 25 Bestellungen.
|
||||
- Die Stufe bleibt, sie sinkt nur, wenn Bestellungen erstattet oder storniert
|
||||
werden.
|
||||
|
||||
### 3. Abo-Stufen und VIP (Teilprojekt 5)
|
||||
|
||||
- Grundlage: ununterbrochen bezahlte Abo-Monate.
|
||||
- Vorgabe: Stufe 1 bis 24, je bezahltem Monat eine Stufe, danach eine Stufe
|
||||
ohne Zahl, „VIP“, als Zeichen besonders hoher Wertschätzung. Die Schwellen
|
||||
sind im Admin pflegbar und lassen sich ohne Codeänderung anpassen.
|
||||
- VIP bekommt eine eigene Medaille und eine VIP-Kennzeichnung im Konto. Weitere
|
||||
Vorteile (Rabatt, Versand) gehören nicht zum Umfang und lassen sich später
|
||||
über die bestehenden Rabattcodes ergänzen.
|
||||
- Wird das Abo gekündigt, verschwindet die Abo-Stufe samt Medaille, sobald die
|
||||
Kündigung wirksam ist. Ein neues Abo beginnt wieder bei null.
|
||||
- Ausfälle durch fehlgeschlagene Zahlung unterbrechen die Dauer nur, wenn das
|
||||
Abo deshalb endet.
|
||||
|
||||
Stufen werden aus den Daten berechnet, nicht als Zustand gespeichert. So gibt
|
||||
es keine Abweichung zwischen Stufe und tatsächlichen Bestellungen oder
|
||||
Zahlungen.
|
||||
|
||||
## Kontobereich „Patenschaft“
|
||||
|
||||
Neuer Bereich `/konto/patenschaft` neben „Bestellungen“ und „Wunschliste“.
|
||||
|
||||
### Übersicht
|
||||
|
||||
- alle Patenschaften des Kontos mit Bienenname, Art (einmalig/Abo), Laufzeit
|
||||
und Status (aktiv, abgelaufen, gekündigt)
|
||||
- Medaillenleiste: Patenschafts-Medaillen, aktuelle Stammkunden-Stufe,
|
||||
aktuelle Abo-Stufe oder VIP
|
||||
- bei Abos: nächste Abbuchung, nächste Lieferung, Fortschritt bis zur
|
||||
nächsten Lieferung („2 von 3 Monaten bezahlt“), Kündigungsbutton
|
||||
|
||||
### Detail einer Patenschaft
|
||||
|
||||
- 3D-Ansicht der eigenen Urkunde und der Patenschafts-Medaille (Teilprojekt 2;
|
||||
in Teilprojekt 1 eine statische Ansicht)
|
||||
- Downloads: Urkunde (PDF), Medaille (PNG, SVG), „Alles herunterladen“ (ZIP)
|
||||
- Revisionen sind für Kunden nicht sichtbar. Sie sehen immer die aktuelle
|
||||
Fassung.
|
||||
- Menüpunkt „Übertragen“ (nur Einmal-Patenschaften, Teilprojekt 3)
|
||||
|
||||
### 3D-Ansicht (Teilprojekt 2)
|
||||
|
||||
Ziel: Die Ansicht soll beeindrucken und sich hochwertig anfühlen, ohne die
|
||||
Urkunde zu verfälschen.
|
||||
|
||||
- Technik: three.js mit `@react-three/fiber` und `@react-three/drei`, nur auf
|
||||
dieser Seite und erst im Browser geladen (dynamischer Import), damit der
|
||||
übrige Shop nicht schwerer wird.
|
||||
- Urkunde als Papierblatt mit leichter Wölbung, weichem Schatten und einem
|
||||
langsam wandernden Lichtreflex. Die Textur ist ein hochaufgelöstes Bild
|
||||
(2048 px breit) derselben Revision, aus demselben Layout wie die PDF und
|
||||
ohne Wasserzeichen. Sie wird nur angemeldeten Besitzern ausgeliefert.
|
||||
- Rückseite der Urkunde: Wabenhain-Zeichen und Patenschaftsnummer.
|
||||
- Medaille als Münze mit Rand und erhabener Prägung (SVG-Pfade extrudiert),
|
||||
Metall mit Umgebungsspiegelung. Die Umgebungstextur liegt lokal im Projekt,
|
||||
kein Abruf von fremden Servern.
|
||||
- Bewegung: im Ruhezustand sanftes Schweben und Drehen. Der Mauszeiger neigt
|
||||
das Blatt leicht. Ziehen dreht mit Nachschwung. Doppelklick oder
|
||||
Doppeltippen wendet Urkunde oder Medaille. Zoom per Mausrad oder Zwei-Finger-
|
||||
Geste, begrenzt.
|
||||
- Smartphone: Wischen dreht, Neigen des Geräts bewegt die Szene erst nach
|
||||
einem Tipp auf „Bewegung aktivieren“ (iOS verlangt die Erlaubnis).
|
||||
- `prefers-reduced-motion`: kein Schweben, keine automatische Drehung,
|
||||
Ziehen bleibt möglich.
|
||||
- Ohne WebGL oder bei Fehlern: statisches Bild der Urkunde und der Medaille,
|
||||
Downloads funktionieren unverändert.
|
||||
- Leistung: Pixeldichte höchstens 2, Darstellung pausiert, wenn der Tab im
|
||||
Hintergrund oder die Szene außer Sicht ist. Ziel 60 fps auf einem
|
||||
Mittelklasse-Smartphone.
|
||||
- Bedienbarkeit: Tastatur dreht (Pfeiltasten) und wendet (Leertaste), die
|
||||
Szene hat eine Textbeschreibung für Screenreader, alle Downloads sind
|
||||
normale Links.
|
||||
|
||||
### Erweiterbarkeit
|
||||
|
||||
`Sponsorship` bekommt später eine Medienliste. Die Detailseite ist so
|
||||
aufgebaut, dass ein weiterer Abschnitt („Bilder“) ohne Umbau hinzukommen
|
||||
kann. In diesem Auftrag wird dafür nichts gebaut.
|
||||
|
||||
## Übertragung an Beschenkte (Teilprojekt 3)
|
||||
|
||||
Nur Einmal-Patenschaften lassen sich übertragen.
|
||||
|
||||
1. Der Besitzer wählt im Menü der Patenschaft „Übertragen“.
|
||||
2. Er wählt die Gültigkeit des Links: 24 Stunden, 1 Woche oder 30 Tage.
|
||||
3. Ein Bestätigungsdialog fragt: „Möchtest du den Übertragungslink wirklich
|
||||
erstellen? Jede Person, die diesen Link hat, kann die Patenschaft in ihr
|
||||
Konto übernehmen. Gib ihn nur an die beschenkte Person weiter. Die
|
||||
Weitergabe geschieht auf eigene Verantwortung.“ (Wortlaut rechtlich
|
||||
prüfen.)
|
||||
4. Erst nach Bestätigung entsteht der Link. Er ist einmal nutzbar, enthält ein
|
||||
zufälliges Token mit mindestens 128 Bit, gespeichert wird nur dessen Hash.
|
||||
5. Bis zur Einlösung sieht der Besitzer den offenen Link mit Ablaufzeit und
|
||||
kann ihn widerrufen.
|
||||
6. Die beschenkte Person öffnet den Link, meldet sich an oder registriert sich
|
||||
und bestätigt die Übernahme. Danach gehören Urkunde, Medaille und
|
||||
Downloads ihrem Konto. Beim bisherigen Besitzer verschwindet die
|
||||
Patenschaft aus dem Bereich „Patenschaft“. Bestellung und Rechnung bleiben
|
||||
bei ihm.
|
||||
7. Abgelaufene, widerrufene oder eingelöste Links zeigen eine neutrale Meldung
|
||||
ohne Daten der Patenschaft.
|
||||
8. Jede Übertragung steht im Audit-Log (erstellt, widerrufen, eingelöst, von
|
||||
welchem Konto an welches).
|
||||
|
||||
Eine Übertragung verändert die Urkunde nicht. Die Stammkunden-Stufe zählt den
|
||||
Kauf weiter beim Käufer.
|
||||
|
||||
## Abo (Teilprojekt 4)
|
||||
|
||||
### Abrechnung
|
||||
|
||||
- Stripe Billing: Jedes Abo-Angebot hat einen Stripe-Preis, der beim
|
||||
Speichern im Admin angelegt wird. Eine Preisänderung erzeugt einen neuen
|
||||
Stripe-Preis für neue Abos. Laufende Abos behalten ihren Preis.
|
||||
- `Customer` bekommt eine `stripeCustomerId`.
|
||||
- Der Abschluss läuft über eine Stripe-Checkout-Sitzung im Modus
|
||||
`subscription`.
|
||||
- Neue Webhook-Ereignisse: `customer.subscription.created`,
|
||||
`customer.subscription.updated`, `customer.subscription.deleted`,
|
||||
`invoice.paid`, `invoice.payment_failed`. Jedes Ereignis wird über die
|
||||
Stripe-ID idempotent verarbeitet.
|
||||
- Jede bezahlte Monatsrechnung erzeugt eine Wabenhain-Rechnung im bestehenden
|
||||
Rechnungssystem (Nummernkreis, PDF, E-Rechnung) und eine Mail.
|
||||
- Zahlungsart ändern: über das Stripe-Kundenportal, nur für die Zahlungsart.
|
||||
|
||||
### Schutz vor Verlust: Lieferung erst nach Bezahlung
|
||||
|
||||
Der Kunde kann monatlich kündigen, bekommt aber nie mehr Honig, als er bezahlt
|
||||
hat:
|
||||
|
||||
- Vierteljährlich: Der Anspruch auf eine Lieferung entsteht nach jeweils drei
|
||||
bezahlten Monaten. Wer nach zwei Monaten kündigt, hatte zwei Monate
|
||||
Patenschaft, aber keinen Honig.
|
||||
- Nach der Ernte: Der Inhaber legt im Admin die Erntefenster fest. Geliefert
|
||||
wird im nächsten Fenster, sobald seit der letzten Lieferung mindestens sechs
|
||||
Monate bezahlt sind.
|
||||
- Bezahlt heißt: Stripe meldet die Rechnung als bezahlt, bei SEPA zusätzlich
|
||||
die Regeln unter „SEPA-Lastschrift und Rückbuchungen“.
|
||||
- Fehlgeschlagene Zahlung: Stripe versucht es automatisch erneut. Solange das
|
||||
Abo im Verzug ist, entsteht keine Lieferung. Scheitern alle Versuche, endet
|
||||
das Abo wie bei einer Kündigung.
|
||||
- Die Verkaufsseite und die Abo-Bedingungen sagen klar: „Der Honig wird nach
|
||||
jeweils drei bezahlten Monaten verschickt“ beziehungsweise die
|
||||
entsprechende Regel für die Ernte-Variante.
|
||||
- Widerruf innerhalb von 14 Tagen: Bis dahin ist kein Honig verschickt, es
|
||||
entsteht kein Warenverlust.
|
||||
|
||||
### SEPA-Lastschrift und Rückbuchungen
|
||||
|
||||
Abos lassen sich mit Karte, Apple Pay, Google Pay und SEPA-Lastschrift
|
||||
bezahlen.
|
||||
|
||||
Grenze, die keine Einstellung aufhebt: Bei einer SEPA-Lastschrift kann der
|
||||
Kunde acht Wochen lang ohne Angabe von Gründen bei seiner Bank die Erstattung
|
||||
verlangen, bei einer nicht autorisierten Lastschrift 13 Monate lang. Das ist
|
||||
Bankrecht. Stripe kann es nicht verhindern und solche Rückbuchungen nicht
|
||||
anfechten. Stripe berechnet dafür außerdem eine Gebühr. Der Schutz liegt
|
||||
deshalb in der Lieferlogik von Wabenhain:
|
||||
|
||||
1. Lieferung nur gegen bezahlte Monate (siehe oben). Eine Rückbuchung kann
|
||||
höchstens Honig betreffen, der schon bezahlt erschien.
|
||||
2. Neukunden-Frist: Bei SEPA zählt die erste Abo-Zahlung eines Kontos erst
|
||||
nach einer Frist für den Lieferanspruch. Vorgabe 56 Tage, also die
|
||||
Acht-Wochen-Frist. Die erste Lieferung kommt dadurch bei SEPA etwas später,
|
||||
alle weiteren normal. Die Frist ist im Admin einstellbar (0 schaltet sie
|
||||
ab). Die Verkaufsseite nennt sie bei der Zahlart.
|
||||
3. Rückbuchung erkannt (`charge.dispute.created`, im Webhook schon
|
||||
abonniert): Das Abo geht sofort auf `IM_VERZUG`, offene Lieferungen werden
|
||||
gestoppt und ihre Reservierung freigegeben, die Abo-Stufe ruht. Der Kunde
|
||||
bekommt eine Mail mit der Bitte, den Betrag zu begleichen. Der Fall
|
||||
erscheint in der Aufmerksamkeitsliste.
|
||||
4. Wird der Betrag nicht binnen 14 Tagen bezahlt, endet das Abo wie bei einer
|
||||
Kündigung. Der Anspruch auf den Betrag bleibt bestehen. Ob er eingefordert
|
||||
wird, entscheidet der Inhaber.
|
||||
5. Ein Konto mit einer Rückbuchung kann neue Abos nur noch mit Karte oder
|
||||
Wallet abschließen. Der Admin kann diese Sperre aufheben.
|
||||
|
||||
### Stripe-Einrichtung
|
||||
|
||||
Die Einrichtung erfolgt in Teilprojekt 4, zuerst im Testmodus, dann
|
||||
identisch im Livemodus. Was per API geht, legt ein Einrichtungsskript im Repo
|
||||
an (wiederholbar, ohne Geheimnisse im Code). Was nur im Dashboard geht,
|
||||
steht als Checkliste in `docs/EINRICHTUNG.md`.
|
||||
|
||||
- Zahlarten für Abo-Checkout: Karte, Apple Pay, Google Pay, SEPA-Lastschrift
|
||||
(Mandat wird im Checkout erteilt).
|
||||
- Billing: Smart Retries für fehlgeschlagene Zahlungen, nach dem letzten
|
||||
Versuch Abo kündigen. Stripe-eigene Kundenmails zu Rechnungen aus, weil
|
||||
Wabenhain eigene Rechnungen und Mails schickt.
|
||||
- Kundenportal: nur Zahlungsart ändern. Kündigung und Tarifwechsel im Portal
|
||||
aus, weil die Kündigung über den eigenen Kündigungsbutton läuft.
|
||||
- Webhook-Endpunkt: bestehende Ereignisse plus
|
||||
`customer.subscription.created`, `customer.subscription.updated`,
|
||||
`customer.subscription.deleted`, `invoice.paid`,
|
||||
`invoice.payment_failed`, `charge.dispute.closed`.
|
||||
- Produkte und Preise der Abo-Angebote legt der Admin über Wabenhain an,
|
||||
nicht von Hand im Stripe-Dashboard.
|
||||
- Tests mit Stripe Test Clocks (Abo über mehrere Monate) und
|
||||
SEPA-Testkonten, darunter eines, das eine Rückbuchung auslöst.
|
||||
- Entwicklung und CI in einer eigenen Stripe-Sandbox mit eingeschränktem
|
||||
API-Schlüssel (`rk_`), nicht im Livekonto.
|
||||
|
||||
Ist-Stand Livekonto „Wabenhain“ (gelesen am 2026-10-16, nichts geändert):
|
||||
|
||||
- Zahlarten-Konfiguration „Default“: Karte, Apple Pay, SEPA-Lastschrift,
|
||||
PayPal, Klarna, Link und weitere sind aktiv. Google Pay ist nicht verfügbar
|
||||
und muss im Dashboard unter Zahlungsmethoden geprüft werden. Checkout zeigt
|
||||
im Abo-Modus nur Zahlarten, die wiederkehrende Zahlungen unterstützen.
|
||||
- Ein Webhook-Endpunkt `https://wabenhain.com/api/checkout/webhook` mit den
|
||||
sechs bestehenden Ereignissen. Die Abo-Ereignisse fehlen und kommen mit
|
||||
Teilprojekt 4 dazu.
|
||||
- Kein Kundenportal konfiguriert.
|
||||
- Die Stripe-Anbindung in Claude erreicht nur den Livemodus. Änderungen am
|
||||
Livekonto erfolgen erst nach Abnahme von Teilprojekt 4 und mit Freigabe.
|
||||
|
||||
### Lieferaufträge
|
||||
|
||||
Ein täglicher Lauf im CronJob `wabenhain-certificates` prüft fällige
|
||||
Lieferungen. Ist der Anspruch erfüllt und Bestand reserviert, legt er einen
|
||||
Lieferauftrag als normale Bestellung an (Status `BEZAHLT`, Betrag 0 €, mit
|
||||
Verweis auf das Abo). Er erscheint in der bestehenden Pack- und DHL-Liste. Der
|
||||
Inhaber packt und versendet wie bei jeder Bestellung.
|
||||
|
||||
### Honigbestand und Kontingent
|
||||
|
||||
Kein Abo darf ohne Honig bleiben, weil der Shop zu viele Gläser einzeln
|
||||
verkauft hat:
|
||||
|
||||
- Kontingent: Jedes Abo-Angebot hat eine Höchstzahl aktiver Abos, im Admin
|
||||
pflegbar. Ist sie erreicht, zeigt die Verkaufsseite „Derzeit ausgebucht“
|
||||
mit der bestehenden Benachrichtigung, sobald wieder Plätze frei sind.
|
||||
- Reservierung, vierteljährlich: Für jedes aktive Abo sind die Gläser der
|
||||
nächsten fälligen Lieferung im Bestand des verknüpften Honigprodukts
|
||||
reserviert. Der Shop verkauft einzeln nur den freien Bestand: Bestand minus
|
||||
Abo-Reservierung minus offene Bestellungen.
|
||||
- Reservierung, Ernte-Variante: Der Inhaber trägt je Erntefenster die
|
||||
geplanten Abo-Gläser ein. Sobald die Abfüllung im Bestand ist, wird dieser
|
||||
Anteil reserviert, bevor er in den Freiverkauf geht.
|
||||
- Deckungsanzeige im Admin-Dashboard: „Bestand deckt den Abo-Bedarf der
|
||||
nächsten 2 Lieferungen.“ Unter einer Lieferung erscheint eine Warnung in der
|
||||
Aufmerksamkeitsliste.
|
||||
- Reicht die Deckung für neue Abos nicht, stoppt der Shop neue Abschlüsse
|
||||
automatisch, bis der Inhaber nachlegt.
|
||||
|
||||
### Kündigung
|
||||
|
||||
- Kündigungsbutton nach § 312k BGB: „Verträge hier kündigen“. Im Konto mit
|
||||
einem Klick auf die Bestätigungsseite, zusätzlich öffentlich erreichbar
|
||||
unter `/vertraege-kuendigen` mit Name, E-Mail und Abo-Nummer, nach dem
|
||||
Muster der bestehenden Route `vertrag-widerrufen`. Rechtlich prüfen lassen.
|
||||
- Die Kündigung wirkt zum Ende des bezahlten Monats (`cancel_at_period_end`).
|
||||
Eine Bestätigungsmail geht sofort hinaus.
|
||||
- Wird die Kündigung wirksam:
|
||||
1. Die Urkunde bekommt automatisch eine neue Revision mit „vom … bis …“.
|
||||
Ersteller „System“, Grund „Abo beendet“. Sie bleibt im Konto
|
||||
herunterladbar.
|
||||
2. Die Abo-Stufe und ihre Medaille verschwinden.
|
||||
3. Die Patenschafts-Medaille und alle Downloads bleiben.
|
||||
4. Offene Reservierungen werden freigegeben.
|
||||
|
||||
## Architektur
|
||||
|
||||
### Ein Layout, mehrere Ausgaben
|
||||
|
||||
Vorschau, 3D-Textur und finale PDF müssen identisch umbrechen. Deshalb gibt es
|
||||
genau eine Layout-Berechnung auf dem Server:
|
||||
|
||||
```
|
||||
Personalisierung + Textbausteine + Vorlagenversion
|
||||
│
|
||||
▼
|
||||
composeCertificateText() → aufgelöste Textblöcke (reine Funktion)
|
||||
│
|
||||
▼
|
||||
layoutCertificate() → positionierte Elemente: Zeilen mit x/y,
|
||||
Schriftgröße, Schrift, Pfade (reine Funktion,
|
||||
misst mit fontkit an denselben TTF-Dateien)
|
||||
│
|
||||
├──► renderCertificatePdf() pdfkit, Text als Text
|
||||
├──► renderCertificatePreview() SVG, Glyphen als Pfade, sharp → WebP,
|
||||
│ Wasserzeichen, Bildschirmauflösung
|
||||
└──► renderCertificateTexture() wie Vorschau, ohne Wasserzeichen,
|
||||
2048 px, nur für Besitzer
|
||||
```
|
||||
|
||||
Bild-Ausgaben setzen Glyphen als Pfade aus denselben Schriftdateien an
|
||||
dieselben Positionen. Sie hängen nicht von Browser-Schriften ab. Ein Test
|
||||
vergleicht die Zeilen aller Ausgaben.
|
||||
|
||||
Module unter `src/lib/certificate/`:
|
||||
|
||||
| Modul | Aufgabe |
|
||||
|---|---|
|
||||
| `schema.ts` | zod-Schema der Personalisierung, gemeinsam für Client und Server |
|
||||
| `text.ts` | Bausteine je Sprache, Anlass, eigene/verschenkte Patenschaft, Laufzeitform |
|
||||
| `layout.ts` | Messen, Umbrechen, Schriftstufen, Layoutvarianten |
|
||||
| `templates/` | Vorlagen, je Version eine Datei, alte Versionen bleiben erhalten |
|
||||
| `render-pdf.ts` | pdfkit-Ausgabe |
|
||||
| `render-image.ts` | SVG-Ausgabe, Vorschau und Textur |
|
||||
| `storage.ts` | Ablage der PDFs |
|
||||
| `issue.ts` | Erzeugung nach Zahlung, idempotent, mit Wiederholung |
|
||||
|
||||
Weitere Module: `src/lib/medals/` (Medaillen-SVG, Stufenberechnung),
|
||||
`src/lib/sponsorship-subscription/` (Abo, Lieferanspruch, Reservierung),
|
||||
`src/lib/sponsorship-transfer.ts`.
|
||||
|
||||
### Vorlagenversion
|
||||
|
||||
Jede Vorlage hat eine feste Kennung, etwa `wabe-classic@1`. Eine
|
||||
Designänderung erzeugt eine neue Version, die alte bleibt im Code. Neue
|
||||
Patenschaften nutzen die aktuelle Version. Bestehende behalten ihre Version
|
||||
und ihre gespeicherte PDF. Systemrevisionen (Abo-Ende) nutzen die Version der
|
||||
vorherigen Revision. Medaillen sind ebenso versioniert.
|
||||
|
||||
### Datenmodell (Prisma, beide Provider)
|
||||
|
||||
- `SponsorshipOffer`: Art (`EINMALIG`, `ABO`), Name, Beschreibung,
|
||||
Leistungen, Preis (einmalig) oder Monatspreis, aktiv, Reihenfolge, physisch,
|
||||
verknüpftes Honigprodukt, Gläser je Lieferung, Lieferzyklus
|
||||
(`VIERTELJAEHRLICH`, `ERNTE`), Kontingent, Stripe-Preis-ID,
|
||||
Steueraufteilung, Medaillenstufe
|
||||
- `Sponsorship`: Besitzerkonto, Angebot, Bezug auf `OrderItem` (einmalig)
|
||||
oder `SponsorshipSubscription` (Abo), jeweils eindeutig als
|
||||
Idempotenzschlüssel, Patenschaftsnummer, Start, Ende (leer bei aktivem Abo),
|
||||
Status, aktuelle Revision, Zustellfelder `pdfAttempts`, `nextAttemptAt`,
|
||||
`lastError`, `mailSentAt`, `printedAt`
|
||||
- `SponsorshipRevision`: unveränderlich: Personalisierung (JSON), aufgelöster
|
||||
Text, Vorlagenversion, PDF-Pfad, SHA-256, Ersteller (System, Admin),
|
||||
Grund, Zeitpunkt
|
||||
- `SponsorshipCounter`: fortlaufende Nummer je Jahr
|
||||
- `SponsorshipSubscription`: Konto, Angebot, `stripeSubscriptionId`
|
||||
(eindeutig), Status (`AKTIV`, `IM_VERZUG`, `GEKUENDIGT`, `BEENDET`),
|
||||
Beginn, Kündigung wirksam zum, Ende
|
||||
- `SubscriptionPayment`: Abo, `stripeInvoiceId` (eindeutig), bezahlt am,
|
||||
Betrag, Zahlart, zählt für Lieferung ab (Datum, bei SEPA-Neukunden nach
|
||||
der Frist), zurückgebucht am, Wabenhain-Rechnung
|
||||
- `SubscriptionDelivery`: Abo, fällig am, Gläser, Status, erzeugte Bestellung
|
||||
- `HarvestWindow`: Zeitraum, geplante Abo-Gläser je Angebot
|
||||
- `SponsorshipTransfer`: Patenschaft, Token-Hash, gültig bis, erstellt von,
|
||||
eingelöst von, eingelöst am, widerrufen am
|
||||
- `LoyaltyLevel`: Art (`STAMMKUNDE`, `ABO`), Schwelle, Name, Medaillendesign;
|
||||
VIP als Stufe ohne Zahl
|
||||
- `Customer.stripeCustomerId`, `Customer.sepaBlockedAt` (gesetzt nach einer
|
||||
Rückbuchung)
|
||||
|
||||
Statuswerte der Patenschaft: `AUSSTEHEND`, `FEHLER`, `BEREIT`, `GEDRUCKT`.
|
||||
Aktiv, abgelaufen und gekündigt werden aus Daten berechnet.
|
||||
|
||||
### Warenkorb und Checkout (Einmal-Patenschaft)
|
||||
|
||||
- Patenschaft als Position im bestehenden Warenkorb, Menge immer 1 je
|
||||
Personalisierung.
|
||||
- Die Personalisierung reist mit der Position. Der Checkout prüft sie erneut
|
||||
mit demselben Schema und denselben Layoutregeln und verlangt ein
|
||||
angemeldetes Konto.
|
||||
- Vor dem Hinzufügen bestätigt der Kunde: „Ich habe die Vorschau und die
|
||||
Schreibweise geprüft.“
|
||||
- Beim Anlegen der Bestellung wird die Personalisierung mit der
|
||||
Vorlagenversion an der `OrderItem` gespeichert. Genau dieser Stand wird nach
|
||||
der Zahlung zur ersten Revision.
|
||||
- Reine Digitalbestellungen haben keine Versandkosten. Ob dafür ein neuer
|
||||
`FulfillmentMethod`-Wert `DIGITAL` nötig ist, entscheidet der
|
||||
Umsetzungsplan nach Lesen von Checkout, Rechnung und DHL-Logik.
|
||||
- Physische Pakete laufen über die bestehenden Versandstaffeln je Kategorie
|
||||
mit eigener Staffel für Patenschaftspakete.
|
||||
- Der Honig eines Pakets bucht den Bestand des verknüpften Produkts über die
|
||||
vorhandene Bestandslogik (einschließlich ApiCore-Abgleich), unter
|
||||
Berücksichtigung der Abo-Reservierung.
|
||||
|
||||
### Steuer
|
||||
|
||||
Pakete und Abos enthalten Leistungen mit unterschiedlichen Steuersätzen
|
||||
(Urkunde und Leistung, Honig). Das Angebot speichert deshalb eine Aufteilung:
|
||||
Honiganteil in Cent zum Honig-Satz, Rest zum Regelsatz. Die Rechnung zeigt
|
||||
beide Steuerzeilen über die vorhandene Gruppierung in `lib/vat.ts`. Die
|
||||
Methode muss die Steuerberatung bestätigen. Bei Kleinunternehmerregelung
|
||||
entfällt die Aufteilung wie heute.
|
||||
|
||||
### Ablauf nach der Zahlung (Einmal-Patenschaft)
|
||||
|
||||
1. Der Stripe-Webhook markiert die Bestellung wie heute über den atomaren
|
||||
Claim als bezahlt. Nur dieser Lauf legt die `Sponsorship`-Zeilen an.
|
||||
Ein Duplikat scheitert am eindeutigen `orderItemId` und bricht still ab.
|
||||
2. Danach versucht der Webhook die Erzeugung direkt: Text, Layout, PDF,
|
||||
Ablage, Hash, erste Revision.
|
||||
3. Die Bestellbestätigung verlinkt auf `/konto/patenschaft/<id>`. Der
|
||||
Mailversand wird über `updateMany … where mailSentAt = null` beansprucht,
|
||||
damit doppelte Webhooks keine zweite Mail erzeugen. Erst danach ist der
|
||||
Status `BEREIT`.
|
||||
4. Scheitert die Erzeugung, antwortet der Webhook trotzdem 200 (die Zahlung
|
||||
ist erfolgt). Die Patenschaft bleibt `AUSSTEHEND`. Die Mail sagt: „Deine
|
||||
Urkunde wird gerade erstellt und erscheint in Kürze in deinem Konto.“
|
||||
5. Der CronJob `wabenhain-certificates` (alle 10 Minuten,
|
||||
`concurrencyPolicy: Forbid`, wie die Jobs in `k8s/07-backup-cronjob.yaml`)
|
||||
holt offene Erzeugungen und Mails nach, mit wachsendem Abstand, höchstens
|
||||
8 Versuche, danach `FEHLER` und Hinweis in der Aufmerksamkeitsliste.
|
||||
|
||||
Die finale Urkunde entsteht nie vor bestätigter Zahlung. SEPA-Zahlungen
|
||||
erzeugen sie erst bei `async_payment_succeeded`. Beim Abo entsteht sie mit der
|
||||
ersten bezahlten Rechnung.
|
||||
|
||||
### Ablage und Zugriff
|
||||
|
||||
- PDFs liegen in `CERTIFICATE_DIR`, nicht unter `UPLOAD_DIR`. Die
|
||||
Startprüfung aus `lib/invoice-storage.ts` wird übernommen. Das Verzeichnis
|
||||
kommt auf das gesicherte Volume und in den Sicherungs-CronJob.
|
||||
- Alle Downloads und die 3D-Textur liefern Routen aus, die Anmeldung und
|
||||
Besitz prüfen. Fremde IDs ergeben 404.
|
||||
- Downloads liefern immer die gespeicherte PDF der aktuellen Revision.
|
||||
- Kein QR-Code auf der Urkunde: Er brächte kaum Nutzen und würde die
|
||||
Gestaltung stören.
|
||||
|
||||
### Vorschau
|
||||
|
||||
- `POST /api/patenschaft/vorschau`: prüft die Personalisierung, gibt ein WebP
|
||||
mit Wasserzeichen „Unverbindliche Vorschau“ in Bildschirmauflösung zurück.
|
||||
Rate-Limit je Besucher. Keine Anmeldung nötig.
|
||||
- Der Client fordert sie etwa 400 ms nach der letzten Eingabe an und zeigt bis
|
||||
dahin die letzte gültige Vorschau.
|
||||
|
||||
## Adminbereich
|
||||
|
||||
- Angebote: Einmal- und Abo-Angebote bearbeiten, Kontingent, Erntefenster,
|
||||
Medaillenstufe.
|
||||
- Patenschaften: Liste mit Filtern (ausstehend, Fehler, bereit, zu drucken,
|
||||
gedruckt, Art, Angebot). Detail mit Vorschau, Revisionen, „Druck-PDF
|
||||
öffnen“, „Als gedruckt markieren“, „Erneut erzeugen“, „Mail erneut senden“,
|
||||
Übertragungshistorie.
|
||||
- Abos: Liste mit Status, bezahlten Monaten, nächster Lieferung; Deckung des
|
||||
Honigbedarfs.
|
||||
- Treuestufen: Schwellen und Namen pflegen.
|
||||
- Korrektur: Felder im Kundenformular ändern, Vorschau mit derselben
|
||||
Layoutlogik, Pflichtfeld Änderungsgrund, neue Revision mit neuer PDF, alte
|
||||
bleibt abrufbar, Eintrag über `logAdminAction`, optional Mail an den Kunden.
|
||||
Standardmäßig mit der Vorlagenversion der bisherigen Revision.
|
||||
- Druckablauf: Physische Bestellungen erscheinen nach Zahlung unter „zu
|
||||
drucken“. PDF öffnen, auf festem Papier drucken, als gedruckt markieren,
|
||||
wie gewohnt über DHL versenden.
|
||||
|
||||
## Verkaufsseite
|
||||
|
||||
Route `/patenschaft`, zweisprachig, im Design der Website.
|
||||
|
||||
Im Mittelpunkt:
|
||||
|
||||
- einer Biene symbolisch einen eigenen Namen geben
|
||||
- ein persönlich gestaltetes Geschenk
|
||||
- die regionale Imkerei Wabenhain unterstützen
|
||||
- je nach Angebot eigenen Wabenhain-Honig, einmalig oder regelmäßig
|
||||
|
||||
Aufbau:
|
||||
|
||||
1. Kopfbereich mit großer, echter Urkundenvorschau
|
||||
2. Umschalter „Einmalig“ / „Im Abo“ mit den Angeboten, Preis, Leistungen,
|
||||
Versandkosten beziehungsweise „Versand inklusive“ und den Lieferregeln
|
||||
3. Personalisierung in Schritten: Angebot, für wen und Anlass, Namen, Widmung
|
||||
und Startdatum, Vorschau prüfen
|
||||
4. Ausschnitt aus dem Kontobereich (3D-Urkunde und Medaille als Video oder
|
||||
Bildfolge) mit dem Hinweis, dass der Kauf ein Kundenkonto braucht
|
||||
5. Hinweis zur symbolischen Namensgebung, gut sichtbar
|
||||
6. FAQ
|
||||
|
||||
Smartphone: Vorschau über dem jeweiligen Schritt, ein Tipp vergrößert sie.
|
||||
Eingabefelder mindestens 16 px Schrift, Bedienelemente mindestens 44 px.
|
||||
|
||||
FAQ-Themen: symbolische Namensgebung, Laufzeit (einmalig zwölf Monate, Abo
|
||||
monatlich kündbar), wann der Honig im Abo kommt, warum ein Konto nötig ist,
|
||||
Übertragung an Beschenkte, Versandkosten, Tippfehler (Kontakt, Korrektur
|
||||
durch Wabenhain), was nach Ablauf oder Kündigung bleibt. Keine FAQ verspricht
|
||||
Besuche, Berichte, Fotos oder Umweltwirkungen.
|
||||
|
||||
## Prüfung
|
||||
|
||||
### Layout-Testmatrix
|
||||
|
||||
Automatisierte Tests rendern echte PDFs und prüfen die Layoutdaten (keine
|
||||
Überlappung, alles in der Sicherheitszone, Schrift nie unter Mindestgröße,
|
||||
genau eine Seite) für:
|
||||
|
||||
- sehr kurze Namen („Li“, „Bo“)
|
||||
- maximal lange Namen in beiden Feldern
|
||||
- Doppelnamen („Marie-Luise Schmidt-Habermann“)
|
||||
- Umlaute und Sonderzeichen („Jürgen Weiß“, „Zoë“, „Ñúñez“, „O’Brien“)
|
||||
- mehrere Schenkende („Anna, Ben, Carla und Familie Özdemir“)
|
||||
- ohne Widmung und mit maximal langer Widmung samt allen Zeilenumbrüchen
|
||||
- jeden Anlass, eigene und verschenkte Patenschaft, Deutsch und Englisch
|
||||
- alle drei Laufzeitformen (einmalig, Abo aktiv, Abo beendet)
|
||||
- Vorschau, Textur und PDF ergeben dieselben Zeilen
|
||||
|
||||
Die Matrix legt die endgültigen Eingabelimits fest.
|
||||
|
||||
### Visuelle Kontrolle
|
||||
|
||||
PDFs werden mit 300 dpi gerastert und angesehen: ganze Seite und Ausschnitte
|
||||
in hoher Vergrößerung. Probedruck auf einem Bürodrucker. Medaillen als PNG in
|
||||
Originalgröße. 3D-Ansicht auf Desktop, 390 px mobil, mit
|
||||
`prefers-reduced-motion` und ohne WebGL.
|
||||
|
||||
### Ablauftests
|
||||
|
||||
- doppelter Webhook: eine Patenschaft, eine Mail
|
||||
- PDF-Erzeugung scheitert: Webhook 200, CronJob holt nach
|
||||
- Gastkauf einer Patenschaft wird serverseitig abgewiesen
|
||||
- fremde Patenschaft, fremder Download, fremde Textur: 404
|
||||
- Korrektur: neue Revision, alte unverändert, Audit-Eintrag
|
||||
- neue Vorlagenversion: alte Urkunden unverändert
|
||||
- Übertragung: Link läuft ab, wird widerrufen, wird genau einmal eingelöst
|
||||
- Abo: Lieferung erst nach drei bezahlten Monaten; Kündigung nach zwei
|
||||
Monaten erzeugt keine Lieferung; Zahlungsausfall stoppt Lieferungen;
|
||||
Kündigung erzeugt Von-bis-Revision und entfernt die Abo-Stufe
|
||||
- Bestand: Einzelverkauf kann reservierte Abo-Gläser nicht kaufen;
|
||||
Kontingent voll stoppt neue Abos
|
||||
- doppelte Stripe-Abo-Ereignisse: eine Rechnung, eine Zahlung
|
||||
- SEPA: erste Zahlung zählt erst nach der Neukunden-Frist; Rückbuchung
|
||||
stoppt Lieferungen, setzt das Abo in Verzug, sperrt SEPA für das Konto;
|
||||
ohne Ausgleich endet das Abo nach 14 Tagen
|
||||
- Treuestufen: Erstattung senkt die Stammkunden-Stufe
|
||||
- E2E (Playwright): Einmalkauf mit Stripe-Testkarte bis zur 3D-Ansicht im
|
||||
Konto; Abo-Abschluss mit Stripe-Testuhr (Test Clock) über drei Monate
|
||||
|
||||
Die Repo-Skripte `lint`, `typecheck`, `test` und `build` laufen grün.
|
||||
|
||||
## Abnahme
|
||||
|
||||
Je Teilprojekt gilt: fertig erst nach den passenden Tests, der visuellen
|
||||
Kontrolle und einer Vorführung. Gesamtabnahme:
|
||||
|
||||
1. Verkaufsseite und Personalisierung auf Desktop und 390 px mobil
|
||||
2. die drei Designvarianten und die gewählte Gestaltung
|
||||
3. mehrere echte PDF-Ausgaben mit unterschiedlichen Beispieldaten
|
||||
4. automatischer Ablauf vom Kauf bis zur 3D-Ansicht und zum Download
|
||||
5. Medaillen aller Arten und Stufen
|
||||
6. Übertragung von Konto zu Konto
|
||||
7. Abo über drei Monate mit Test Clock bis zur Lieferung, dann Kündigung
|
||||
8. Druck- und Korrekturablauf im Admin
|
||||
9. offene geschäftliche Konfiguration (Liste unten)
|
||||
|
||||
## Geschäftliche Konfiguration vor Veröffentlichung
|
||||
|
||||
1. Preise kaufmännisch prüfen: Einmalpakete und Abo-Monatspreise mit Honig,
|
||||
Papier, Verpackung, Grußkarte, Versand, Stripe-Gebühren, Arbeitszeit.
|
||||
2. Gläser je Abo-Lieferung, Erntefenster und Kontingente festlegen.
|
||||
3. Steueraufteilung mit der Steuerberatung abstimmen.
|
||||
4. AGB, Abo-Bedingungen und Widerrufsbelehrung: personalisierte Ware
|
||||
(§ 312g Abs. 2 Nr. 1 BGB), digitale Inhalte (§ 356 Abs. 5 BGB),
|
||||
Abo-Laufzeit und Kündigung, Kündigungsbutton (§ 312k BGB), Lieferregel
|
||||
„nach bezahlten Monaten“, Übertragung auf eigene Verantwortung. Rechtlich
|
||||
prüfen lassen.
|
||||
5. Datenschutzerklärung: Namen Dritter, Speicherdauer, Stripe Billing.
|
||||
6. Stripe-Livemodus freigeben: Die Einrichtung (siehe „Stripe-Einrichtung“)
|
||||
läuft erst im Testmodus. Den Livemodus stellt das Skript erst nach
|
||||
ausdrücklicher Freigabe des Inhabers um. Neukunden-Frist für SEPA
|
||||
bestätigen (Vorgabe 56 Tage).
|
||||
7. Versandstaffel für Patenschaftspakete anlegen.
|
||||
8. Logo als SVG oder PNG mit mindestens 300 dpi hochladen.
|
||||
9. Material bevorraten: Urkundenpapier (200–250 g/m², matt, naturweiß),
|
||||
Geschenkverpackung, Grußkarten. Probedruck freigeben.
|
||||
10. Bestellschluss für Weihnachten festlegen.
|
||||
11. Textbausteine und Medaillennamen sprachlich freigeben (de und en).
|
||||
@@ -69,6 +69,29 @@ data:
|
||||
# src/lib/invoice-storage.ts und 04-uploads-pvc.yaml.
|
||||
INVOICE_DIR: "/app/invoices"
|
||||
|
||||
# Urkunden-PDFs der Bienenpatenschaft (src/lib/sponsorship/storage.ts):
|
||||
# /app/invoices/urkunden/2026/WH-P-2026-00042/r1.pdf
|
||||
# Unterordner des Rechnungs-Volumes: ebenso privat (keine oeffentliche Route
|
||||
# zeigt dorthin), ebenso taeglich gesichert (07-backup-cronjob.yaml sichert
|
||||
# das ganze Volume), und kein zweites ReadWriteOnce-Volume am App-Pod. Die
|
||||
# Pfade der Rechnungen beginnen mit dem Jahr, "urkunden" kollidiert nicht.
|
||||
CERTIFICATE_DIR: "/app/invoices/urkunden"
|
||||
|
||||
# Hintergrundaufgaben im App-Prozess (src/lib/background-jobs.ts): Urkunden
|
||||
# nachholen, Abo-Lieferungen anlegen, Verzug nach Rueckbuchung beenden.
|
||||
# Laufen im App-Pod, weil nur er das Volume mit CERTIFICATE_DIR einhaengt.
|
||||
# "off" nur fuer zusaetzliche Instanzen, die keine Aufgaben uebernehmen sollen.
|
||||
BACKGROUND_JOBS: "on"
|
||||
|
||||
# Stripe-Kundenportal fuer "Zahlungsart aendern" im Abo (bpc_..., kein
|
||||
# Geheimnis). Legt scripts/stripe-setup.ts --apply an und gibt die ID aus.
|
||||
# Gesetzt am 2026-10-16 (Livekonto, nur "Zahlungsart aendern"). Leer: dann
|
||||
# sucht die App die Konfiguration ueber ihre Metadaten
|
||||
# (wabenhain=abo-zahlungsart). Gibt es keine, bietet das Konto
|
||||
# "Zahlungsart aendern" nicht an — die Standardkonfiguration von Stripe wird
|
||||
# bewusst nie benutzt, weil sie Kuendigung oder Tarifwechsel erlauben koennte.
|
||||
STRIPE_PORTAL_CONFIGURATION_ID: "bpc_1URCIfEvHaDWQ1U0nD4jVWXc"
|
||||
|
||||
# Umsatzsteuersatz in GANZEN Prozent, der auf der Rechnung ausgewiesen wird.
|
||||
# 7 = ermaessigter Satz (Honig als Lebensmittel, Anlage 2 zum UStG)
|
||||
# 19 = voller Satz
|
||||
@@ -93,6 +116,12 @@ data:
|
||||
VAT_RATE_PERCENT_HONIG: "7"
|
||||
VAT_RATE_PERCENT_KERZEN: "19"
|
||||
VAT_RATE_PERCENT_PROPOLIS: "19"
|
||||
# Weitere Bienenprodukte (Kategorie SONSTIGES, z. B. Salben, Wachstuecher).
|
||||
VAT_RATE_PERCENT_SONSTIGES: "19"
|
||||
# Bienenpatenschaft (Urkunde, Namensgebung, Abo-Monatsbeitrag ohne
|
||||
# Honiganteil): Leistung zum Regelsatz. Vor der Veroeffentlichung mit der
|
||||
# Steuerberatung bestaetigen (Spec, "Geschaeftliche Konfiguration").
|
||||
VAT_RATE_PERCENT_PATENSCHAFT: "19"
|
||||
|
||||
# Threads fuer das Umrechnen hochgeladener Videos (Admin -> Inhalte ->
|
||||
# Hero-Video). NICHT ohne Not erhoehen: ffmpeg teilt sich das Speicherlimit
|
||||
|
||||
@@ -109,6 +109,17 @@ stringData:
|
||||
# Konfigurationsfehler. APICORE_API_URL steht in 01-configmap.yaml.
|
||||
APICORE_API_KEY: ""
|
||||
|
||||
# Secret des ApiCore-Webhooks "stock.changed" (ApiCore -> Automatisierung ->
|
||||
# Webhooks, Ziel https://<shop>/api/apicore/webhook). Damit kommen
|
||||
# Entnahmen aus ApiCore sofort im Shop an; leer = nur der CronJob gleicht
|
||||
# ab (alle 10 Minuten).
|
||||
APICORE_WEBHOOK_SECRET: ""
|
||||
|
||||
# Rechnungsexport fuer ERPNext (GET /api/erp/rechnungen, nur lesend): ERPNext
|
||||
# holt damit die Rechnungen samt PDF ab. Mindestens 32 Zeichen, derselbe
|
||||
# Wert steht in ERPNext als WABENHAIN_ERP_TOKEN. Leer = Export aus.
|
||||
ERP_EXPORT_TOKEN: ""
|
||||
|
||||
# DHL-Versandmarken (Admin -> Bestellung -> "DHL-Versandmarke"), siehe
|
||||
# .env.example fuer die vollstaendige Einrichtung. Leer = der Knopf meldet
|
||||
# "noch nicht konfiguriert", der Rest des Shops ist unberuehrt. Ob Sandbox
|
||||
|
||||
+2
-2
@@ -43,8 +43,8 @@ spec:
|
||||
periodSeconds: 5
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 256Mi
|
||||
cpu: "0"
|
||||
memory: "0"
|
||||
limits:
|
||||
memory: 512Mi
|
||||
volumeClaimTemplates:
|
||||
|
||||
@@ -42,8 +42,8 @@ spec:
|
||||
periodSeconds: 5
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 256Mi
|
||||
cpu: "0"
|
||||
memory: "0"
|
||||
limits:
|
||||
memory: 512Mi
|
||||
volumeClaimTemplates:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# image: unten mit der tatsaechlichen Registry/Tag aus der Gitea-Actions-
|
||||
# Pipeline ersetzen. Kein separater Migrations-Job mehr noetig: der
|
||||
# image: unten auf den Build gepinnt, siehe Kommentar dort. Kein separater
|
||||
# Migrations-Job mehr noetig: der
|
||||
# Container fuehrt "prisma migrate deploy" + "prisma db seed" selbst aus,
|
||||
# BEVOR er den Server startet (siehe Dockerfile-CMD in der runner-Stage) —
|
||||
# beide Schritte sind idempotent, laufen also bei jedem Neustart gefahrlos
|
||||
@@ -72,9 +72,26 @@ spec:
|
||||
# "Uploads lassen sich nicht speichern".
|
||||
securityContext:
|
||||
fsGroup: 1001
|
||||
runAsNonRoot: true
|
||||
runAsUser: 1001
|
||||
runAsGroup: 1001
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: app
|
||||
image: git.encry.de/nick.rosenloecher/wabenhain:latest
|
||||
# Fest auf einen Build gepinnt (Tag sha-<kurzer Commit> aus der
|
||||
# Gitea-Pipeline), nie :latest: ein "rollout restart" holt damit
|
||||
# kein ungeprueftes neues Image. Neuer Build:
|
||||
# kubectl -n wabenhain set image deploy/wabenhain-app app=git.encry.de/nick.rosenloecher/wabenhain:sha-<commit>@sha256:<digest>
|
||||
# und hier nachziehen. Tag plus Digest: der Tag ist lesbar, der
|
||||
# Digest macht das Image unveraenderlich (Tags lassen sich in der
|
||||
# Registry ueberschreiben).
|
||||
image: git.encry.de/nick.rosenloecher/wabenhain:sha-1d88bac@sha256:49dd869c339f476fdb51a79e803f2c3cf8fba308b846cddb314b37d1d0a76731
|
||||
imagePullPolicy: IfNotPresent
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
ports:
|
||||
- containerPort: 3000
|
||||
envFrom:
|
||||
@@ -164,8 +181,8 @@ spec:
|
||||
# Transcode hart drosseln, auch wenn der Knoten gerade frei ist.
|
||||
resources:
|
||||
requests:
|
||||
cpu: 500m
|
||||
memory: 512Mi
|
||||
cpu: "0"
|
||||
memory: "0"
|
||||
limits:
|
||||
memory: 1Gi
|
||||
volumes:
|
||||
|
||||
+8
-1
@@ -72,7 +72,14 @@ metadata:
|
||||
# ports.web.redirectTo.port=websecure), sind diese Zeile UND die
|
||||
# Middleware am Ende der Datei ueberfluessig. Der Namespace-Praefix im
|
||||
# Wert ist Pflicht — Traefik loest den Namen sonst nicht auf.
|
||||
traefik.ingress.kubernetes.io/router.middlewares: wabenhain-redirect-to-https@kubernetescrd
|
||||
#
|
||||
# "cloudflare-only" steht bewusst an erster Stelle: wabenhain.com laeuft
|
||||
# ueber den Cloudflare-Proxy, direkte Zugriffe auf den Origin (an
|
||||
# Cloudflare und damit an WAF und Rate-Limits vorbei) beantwortet Traefik
|
||||
# mit 403. Erlaubt sind nur Cloudflare-IPs und private Netze. Die
|
||||
# Middleware liegt nicht in diesem Repo, sondern in
|
||||
# rke2-cluster/security/cloudflare-only-middlewares.yaml (Stand 2026-10-12).
|
||||
traefik.ingress.kubernetes.io/router.middlewares: wabenhain-cloudflare-only@kubernetescrd,wabenhain-redirect-to-https@kubernetescrd
|
||||
spec:
|
||||
# Muss zur IngressClass der Traefik-Installation passen. Das offizielle
|
||||
# Helm-Chart legt sie als "traefik" an; mit "kubectl get ingressclass"
|
||||
|
||||
+95
-14
@@ -8,9 +8,9 @@
|
||||
# ausserdem einer zehnjaehrigen Aufbewahrungspflicht (§ 147 AO) — ein
|
||||
# Datenverlust ist hier nicht nur aergerlich, sondern ein Rechtsproblem.
|
||||
#
|
||||
# Diese Sicherung liegt bewusst NUR im Cluster. Sie schuetzt gegen
|
||||
# Volume-Verlust und Bedienfehler, nicht gegen den Ausfall des gesamten
|
||||
# Clusters oder Standorts. Fuer eine vollstaendige Absicherung die
|
||||
# Diese Sicherung liegt auf derselben Storage Box wie die Datenbank. Sie
|
||||
# schuetzt gegen Volume-Verlust und Bedienfehler, nicht gegen den Ausfall
|
||||
# der Storage Box oder des Standorts. Fuer eine vollstaendige Absicherung die
|
||||
# erzeugten .sql.gz-Dateien zusaetzlich regelmaessig aus dem Cluster
|
||||
# herausziehen (Beispielbefehl siehe k8s/README.md, Abschnitt "Sicherung
|
||||
# und Wiederherstellung").
|
||||
@@ -20,6 +20,33 @@
|
||||
# pg_dump-Aufruf unten ersetzen durch:
|
||||
# mysqldump -h wabenhain-mysql -u wabenhain -p"$PGPASSWORD" \
|
||||
# --single-transaction --routines wabenhain | gzip -9 > "$file.partial"
|
||||
# Ziel ist die Storage Box wie bei den uebrigen Wabenhain-Volumes. Das PV
|
||||
# zeigt auf den vorhandenen Ordner Customer/Wabenhain; der Unterordner
|
||||
# db-backup entsteht ueber subPath beim ersten Lauf.
|
||||
apiVersion: v1
|
||||
kind: PersistentVolume
|
||||
metadata:
|
||||
name: wabenhain-db-backup
|
||||
spec:
|
||||
capacity:
|
||||
storage: 10Gi
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
persistentVolumeReclaimPolicy: Retain
|
||||
storageClassName: ""
|
||||
mountOptions: ["vers=3.0", "uid=70", "gid=70", "dir_mode=0700", "file_mode=0600", "noperm"]
|
||||
csi:
|
||||
driver: smb.csi.k8s.io
|
||||
volumeHandle: wabenhain-db-backup
|
||||
volumeAttributes:
|
||||
source: //u652065.your-storagebox.de/backup/Server/Disks/Customer/Wabenhain
|
||||
nodeStageSecretRef:
|
||||
name: smb-credentials
|
||||
namespace: wabenhain
|
||||
claimRef:
|
||||
namespace: wabenhain
|
||||
name: wabenhain-db-backup
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
@@ -28,7 +55,8 @@ metadata:
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
# storageClassName: "dein-storage-class"
|
||||
storageClassName: ""
|
||||
volumeName: wabenhain-db-backup
|
||||
resources:
|
||||
requests:
|
||||
# Eine gzip-komprimierte Sicherung dieses Datenbestandes liegt im
|
||||
@@ -129,13 +157,14 @@ spec:
|
||||
ls -lh /backup
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 128Mi
|
||||
cpu: "0"
|
||||
memory: "0"
|
||||
limits:
|
||||
memory: 256Mi
|
||||
volumeMounts:
|
||||
- name: backup
|
||||
mountPath: /backup
|
||||
subPath: db-backup
|
||||
# Nur lesend: dieser Job darf Belege sichern, niemals aendern.
|
||||
- name: invoices
|
||||
mountPath: /invoices
|
||||
@@ -209,17 +238,17 @@ spec:
|
||||
spec:
|
||||
restartPolicy: OnFailure
|
||||
# Gleiche Kennung wie der App-Container (Dockerfile: adduser --uid
|
||||
# 1001 nextjs) — dasselbe Image, derselbe Nutzer.
|
||||
# 1001 nextjs) — beide Images legen denselben Nutzer an.
|
||||
securityContext:
|
||||
runAsUser: 1001
|
||||
runAsGroup: 1001
|
||||
containers:
|
||||
- name: release-stale-orders
|
||||
# DASSELBE Image und derselbe Tag wie in 05-app-deployment.yaml.
|
||||
# Beide zusammen aktualisieren: der Lauf nutzt denselben
|
||||
# Prisma-Client wie die App und muss deshalb zum selben
|
||||
# Datenbankschema passen.
|
||||
image: git.encry.de/nick.rosenloecher/wabenhain:latest
|
||||
# Werkzeug-Image (Dockerfile "AS tools") mit DEMSELBEN Tag wie
|
||||
# das App-Image in 05-app-deployment.yaml. Beide zusammen
|
||||
# aktualisieren: der Lauf nutzt denselben Prisma-Client wie die
|
||||
# App und muss deshalb zum selben Datenbankschema passen.
|
||||
image: git.encry.de/nick.rosenloecher/wabenhain-tools:latest
|
||||
imagePullPolicy: IfNotPresent
|
||||
# Braucht DATABASE_URL, DATABASE_PROVIDER und STRIPE_SECRET_KEY
|
||||
# — die stehen bereits in denselben beiden Quellen wie fuer die
|
||||
@@ -242,9 +271,61 @@ spec:
|
||||
exec tsx scripts/release-stale-orders.ts
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 128Mi
|
||||
cpu: "0"
|
||||
memory: "0"
|
||||
limits:
|
||||
# Derselbe Wert wie beim App-Container: der Lauf laedt
|
||||
# denselben Prisma-Client samt Treiber.
|
||||
memory: 512Mi
|
||||
---
|
||||
# Bestandsabgleich mit ApiCore (scripts/apicore-stock-sync.ts): sendet
|
||||
# liegengebliebene Verkaeufe/Rueckbuchungen an ApiCore und gleicht alle
|
||||
# verknuepften Produkte gegen den ApiCore-Restbestand ab. Sicherheitsnetz
|
||||
# unter dem Sofort-Versand und dem Webhook "stock.changed" — scheitert der
|
||||
# Lauf (ApiCore nicht erreichbar, Buchung abgelehnt), ist der Job rot.
|
||||
apiVersion: batch/v1
|
||||
kind: CronJob
|
||||
metadata:
|
||||
name: wabenhain-apicore-stock
|
||||
namespace: wabenhain
|
||||
spec:
|
||||
schedule: "*/10 * * * *"
|
||||
concurrencyPolicy: Forbid
|
||||
successfulJobsHistoryLimit: 3
|
||||
failedJobsHistoryLimit: 5
|
||||
startingDeadlineSeconds: 300
|
||||
jobTemplate:
|
||||
spec:
|
||||
backoffLimit: 1
|
||||
# Ein Lauf darf den naechsten nicht blockieren.
|
||||
activeDeadlineSeconds: 540
|
||||
template:
|
||||
spec:
|
||||
restartPolicy: OnFailure
|
||||
securityContext:
|
||||
runAsUser: 1001
|
||||
runAsGroup: 1001
|
||||
containers:
|
||||
- name: apicore-stock
|
||||
# Werkzeug-Image mit demselben Tag wie in 05-app-deployment.yaml.
|
||||
image: git.encry.de/nick.rosenloecher/wabenhain-tools:latest
|
||||
imagePullPolicy: IfNotPresent
|
||||
# Braucht DATABASE_URL, DATABASE_PROVIDER, APICORE_API_URL und
|
||||
# APICORE_API_KEY — dieselben Quellen wie die App.
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: wabenhain-config
|
||||
- secretRef:
|
||||
name: wabenhain-secrets
|
||||
command: ["/bin/sh", "-c"]
|
||||
args:
|
||||
- |
|
||||
set -eu
|
||||
node scripts/prisma-provider.mjs
|
||||
exec tsx scripts/apicore-stock-sync.ts
|
||||
resources:
|
||||
requests:
|
||||
cpu: "0"
|
||||
memory: "0"
|
||||
limits:
|
||||
memory: 512Mi
|
||||
+58
-24
@@ -9,9 +9,12 @@ alles laeuft: [../docs/EINRICHTUNG.md](../docs/EINRICHTUNG.md).
|
||||
|
||||
## Einmalige Vorbereitung
|
||||
|
||||
1. **Gitea Actions**: `.gitea/workflows/docker-build.yml` baut bei jedem
|
||||
Push auf `main` das Image `<registry>/<owner>/wabenhain:latest` (+
|
||||
`:sha-<kurzhash>`, `:vX.Y.Z` bei Tags) in der Gitea-Container-Registry.
|
||||
1. **Gitea Actions**: `.gitea/workflows/docker-build.yml` prueft bei jedem
|
||||
Push auf `main` lint, audit, typecheck und test und baut erst danach das
|
||||
Image `<registry>/<owner>/wabenhain:latest` (+ `:sha-<kurzhash>`,
|
||||
`:vX.Y.Z` bei Tags) in der Gitea-Container-Registry. Daneben entsteht
|
||||
mit denselben Tags `wabenhain-tools` fuer die CronJobs in
|
||||
`07-backup-cronjob.yaml`.
|
||||
Ein einzelnes Image reicht fuer `05-app-deployment.yaml` — es traegt
|
||||
sowohl die Next.js-App als auch die Prisma-CLI/tsx und migriert/seedet
|
||||
die Datenbank beim Start selbst (siehe Punkt 2 unten), kein separates
|
||||
@@ -53,8 +56,9 @@ alles laeuft: [../docs/EINRICHTUNG.md](../docs/EINRICHTUNG.md).
|
||||
fuer Produkt- und Erntenfotos.
|
||||
|
||||
6. `image:` in `05-app-deployment.yaml` zeigt bereits auf
|
||||
`git.encry.de/nick.rosenloecher/wabenhain` — nur noch den Tag pruefen
|
||||
(`:latest` passt fuer den jeweils neuesten `main`-Build). Die Domain steht
|
||||
`git.encry.de/nick.rosenloecher/wabenhain` und ist auf einen festen Build
|
||||
gepinnt (`:sha-<commit>@sha256:<digest>`), nie auf `:latest` — siehe
|
||||
„Bei einem neuen Image“ unten. Die Domain steht
|
||||
in `06-ingress.yaml` (`host:` und `tls.hosts`) und in `01-configmap.yaml`
|
||||
(`NEXT_PUBLIC_SITE_URL`) bereits als `wabenhain.com` — beide Stellen
|
||||
muessen uebereinstimmen, sonst zeigen Sitemap, Canonical-Tags und die
|
||||
@@ -91,10 +95,25 @@ der erste Pod bereit ist.
|
||||
|
||||
## Bei einem neuen Image (Redeploy)
|
||||
|
||||
Das Deployment ist auf Tag **und** Digest gepinnt. Ein `rollout restart`
|
||||
holt deshalb kein neues Image, sondern startet nur denselben Build neu (das
|
||||
genuegt nach einer Aenderung an Secret oder ConfigMap). Einen neuen Build
|
||||
rollt man so aus:
|
||||
|
||||
```bash
|
||||
kubectl rollout restart deployment/wabenhain-app -n wabenhain
|
||||
# Digest des gewuenschten Builds aus der Gitea-Registry (Paket "wabenhain",
|
||||
# Tag sha-<kurzer Commit>) uebernehmen:
|
||||
kubectl -n wabenhain set image deploy/wabenhain-app \
|
||||
app=git.encry.de/nick.rosenloecher/wabenhain:sha-<commit>@sha256:<digest>
|
||||
kubectl -n wabenhain rollout status deploy/wabenhain-app
|
||||
```
|
||||
|
||||
Danach dieselbe Zeile in `05-app-deployment.yaml` nachziehen und
|
||||
committen, damit Repo und Cluster nicht auseinanderlaufen. Laufen die
|
||||
CronJobs aus `07-backup-cronjob.yaml`, gehoert ihr `wabenhain-tools`-Image
|
||||
auf denselben Build (sie nutzen denselben Prisma-Client und muessen zum
|
||||
Datenbankschema passen).
|
||||
|
||||
Migrationen + Seed laufen automatisch erneut beim Start jedes neuen Pods
|
||||
(idempotent, siehe oben).
|
||||
|
||||
@@ -114,13 +133,24 @@ Redeploy.
|
||||
Zustand im Prozessspeicher, nicht in einem gemeinsamen Store. Mehrere
|
||||
Replicas wuerden das Limit unbemerkt proportional aufweichen. Fuer
|
||||
horizontale Skalierung zuerst `lib/rate-limit.ts` auf Redis o.ae. umstellen.
|
||||
- Kein `HorizontalPodAutoscaler`, kein `PodDisruptionBudget`, keine
|
||||
`NetworkPolicy` — je nach Cluster/Anforderungen ergaenzen.
|
||||
- Kein `HorizontalPodAutoscaler`, kein `PodDisruptionBudget`. Die
|
||||
`NetworkPolicy`s (`default-deny-ingress`, `allow-same-namespace`,
|
||||
`allow-from-traefik`) und die Traefik-Middleware `cloudflare-only` liegen
|
||||
nicht hier, sondern in den Cluster-Manifesten (Haertung vom 2026-10-12,
|
||||
Ordner `rke2-cluster/`, nicht unter Git).
|
||||
- Repo und Cluster weichen voneinander ab (Stand 2026-10-16): Im Cluster
|
||||
sind `wabenhain-uploads` (5Gi) und `wabenhain-invoices` (50Gi)
|
||||
`ReadWriteMany` auf SMB mit eigenen PersistentVolumes, hier stehen
|
||||
`ReadWriteOnce`-Claims gegen die Default-StorageClass (5Gi/2Gi).
|
||||
`STRIPE_PUBLISHABLE_KEY` liegt im Cluster im Secret, hier in der
|
||||
ConfigMap (beides funktioniert, weil die App beide Quellen per `envFrom`
|
||||
liest). Vor einem `kubectl apply` auf ein bestehendes Cluster die
|
||||
Unterschiede pruefen.
|
||||
- Die Postgres-/MySQL-StatefulSets sind Single-Instance **ohne
|
||||
Replikation**. Eine taegliche Sicherung gibt es inzwischen
|
||||
(`07-backup-cronjob.yaml`, siehe "Sicherung und Wiederherstellung"), sie
|
||||
liegt aber im selben Cluster und ersetzt damit weder Replikation noch
|
||||
eine Auslagerung an einen anderen Ort. Faellt der Knoten aus, ist der
|
||||
liegt aber auf derselben Storage Box wie die Datenbank und ersetzt damit
|
||||
weder Replikation noch eine Auslagerung an einen anderen Ort. Faellt der Knoten aus, ist der
|
||||
Shop bis zur Wiederherstellung offline. Fuer produktiven Betrieb mit
|
||||
hoeherem Anspruch einen Managed-Datenbank-Dienst oder einen dedizierten
|
||||
DB-Operator (z.B. CloudNativePG) in Erwaegung ziehen — `DATABASE_URL` in
|
||||
@@ -263,7 +293,8 @@ PersistentVolume:
|
||||
```yaml
|
||||
spec:
|
||||
mountOptions:
|
||||
- vers=3.0
|
||||
- vers=3.1.1
|
||||
- seal # SMB-Verschluesselung, die Storage Box liegt im Internet
|
||||
- uid=1001 # muss zum Containerbenutzer passen
|
||||
- gid=1001
|
||||
- dir_mode=0770
|
||||
@@ -334,9 +365,14 @@ ffmpeg -i original.mp4 -an -vf "scale='min(1920,iw)':-2" \
|
||||
|
||||
## Sicherung und Wiederherstellung
|
||||
|
||||
`07-backup-cronjob.yaml` legt jede Nacht um 03:15 Uhr eine
|
||||
gzip-komprimierte `pg_dump`-Sicherung auf einem eigenen Volume ab und
|
||||
haelt sie 30 Tage vor. Ohne diese Sicherung liegen Bestellungen,
|
||||
`07-backup-cronjob.yaml` legt jede Nacht um 03:15 Uhr (Zeitzone des
|
||||
Clusters, meist UTC) eine gzip-komprimierte `pg_dump`-Sicherung und ein
|
||||
`rechnungen-<Zeitstempel>.tar.gz` der Rechnungsablage auf einem eigenen
|
||||
Volume ab und haelt beides 30 Tage vor. Das Volume ist ein SMB-PV auf der
|
||||
Storage Box (`//u652065.your-storagebox.de/backup/Server/Disks/Customer/Wabenhain`,
|
||||
Unterordner `db-backup`). Im Cluster ist der Job seit 2026-10-10
|
||||
angelegt; die letzten drei Laeufe waren erfolgreich, zuletzt am 2026-10-16
|
||||
um 03:15 UTC. Ohne diese Sicherung liegen Bestellungen,
|
||||
Rechnungen und Kundenkonten in einem einzelnen PersistentVolume ohne
|
||||
jedes Netz — und Rechnungen unterliegen in Deutschland einer
|
||||
zehnjaehrigen Aufbewahrungspflicht (§ 147 AO).
|
||||
@@ -354,16 +390,14 @@ kubectl logs -n wabenhain -l job-name --tail=50 # Ausgabe des letzten Laufs
|
||||
kubectl create job --from=cronjob/wabenhain-db-backup manuell-$(date +%s) -n wabenhain
|
||||
```
|
||||
|
||||
**Aus dem Cluster herausziehen.** Die Sicherung im Cluster schuetzt gegen
|
||||
Volume-Verlust und Bedienfehler, nicht gegen den Ausfall des gesamten
|
||||
Clusters oder Standorts. Deshalb regelmaessig (oder per eigenem Cron auf
|
||||
einem Rechner ausserhalb) kopieren:
|
||||
|
||||
```bash
|
||||
POD=$(kubectl get pod -n wabenhain -l job-name -o name | head -1)
|
||||
kubectl exec -n wabenhain "$POD" -- ls -1 /backup
|
||||
kubectl cp wabenhain/"${POD#pod/}":/backup/wabenhain-2026-01-31_0315.sql.gz ./wabenhain-2026-01-31.sql.gz
|
||||
```
|
||||
**Aus dem Cluster herausziehen.** Die Sicherung schuetzt gegen
|
||||
Volume-Verlust und Bedienfehler, nicht gegen den Ausfall der Storage Box
|
||||
oder des Standorts. Deshalb regelmaessig (oder per eigenem Cron auf einem
|
||||
Rechner ausserhalb) an einen zweiten Ort kopieren. Die Dateien liegen auf
|
||||
der Storage Box unter `Server/Disks/Customer/Wabenhain/db-backup/` und
|
||||
lassen sich dort direkt abholen (SMB, SFTP oder rsync der Storage Box). Ein
|
||||
`kubectl exec` in den Sicherungs-Pod geht nicht: der Pod ist nach dem Lauf
|
||||
beendet (`Completed`).
|
||||
|
||||
**Wiederherstellen.** Vorher die App anhalten, damit waehrend des
|
||||
Einspielens niemand schreibt — `--clean --if-exists` im Dump loescht die
|
||||
|
||||
+14
-6
@@ -7,6 +7,7 @@
|
||||
"build": "node scripts/generate-prisma-clients.mjs && next build",
|
||||
"start": "node scripts/generate-prisma-clients.mjs && next start",
|
||||
"lint": "eslint",
|
||||
"typecheck": "node scripts/generate-prisma-clients.mjs && next typegen && tsc --noEmit",
|
||||
"postinstall": "node scripts/generate-prisma-clients.mjs",
|
||||
"db:push": "node scripts/prisma-provider.mjs && prisma db push",
|
||||
"db:migrate": "node scripts/prisma-provider.mjs && prisma migrate dev",
|
||||
@@ -19,29 +20,35 @@
|
||||
"test:e2e": "playwright test",
|
||||
"preflight": "tsx scripts/preflight.ts",
|
||||
"places:find": "tsx scripts/find-place-id.ts",
|
||||
"orders:release-stale": "tsx scripts/release-stale-orders.ts"
|
||||
"orders:release-stale": "tsx scripts/release-stale-orders.ts",
|
||||
"stock:apicore-sync": "tsx scripts/apicore-stock-sync.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/adapter-mariadb": "^7.10.0",
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
"@react-three/drei": "10.0.6",
|
||||
"@react-three/fiber": "9.1.2",
|
||||
"@stripe/react-stripe-js": "^6.12.0",
|
||||
"@stripe/stripe-js": "^9.17.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"fflate": "0.8.2",
|
||||
"ffmpeg-static": "^5.3.0",
|
||||
"fontkit": "2.0.4",
|
||||
"jose": "^6.2.8",
|
||||
"mariadb": "^3.5.3",
|
||||
"mariadb": "^3.5.4",
|
||||
"motion": "^13.0.0",
|
||||
"next": "16.3.5",
|
||||
"nodemailer": "^9.1.1",
|
||||
"next": "16.3.8",
|
||||
"nodemailer": "^10.0.10",
|
||||
"otpauth": "^9.5.1",
|
||||
"pdfkit": "^0.19.1",
|
||||
"prisma": "^7.10.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8",
|
||||
"sharp": "^0.35.4",
|
||||
"sharp": "^0.35.5",
|
||||
"stripe": "^22.4.0",
|
||||
"three": "0.170.0",
|
||||
"zod": "^4.4.3",
|
||||
"zustand": "^5.0.14"
|
||||
},
|
||||
@@ -58,10 +65,11 @@
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"@types/three": "0.170.0",
|
||||
"@vitejs/plugin-react": "^6.0.5",
|
||||
"dotenv": "^17.4.2",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.3.5",
|
||||
"eslint-config-next": "16.3.8",
|
||||
"jsdom": "^30.0.1",
|
||||
"tailwindcss": "^4",
|
||||
"tsx": "^4",
|
||||
|
||||
Generated
+687
-201
File diff suppressed because it is too large.
Load diff
+7
-2
@@ -15,8 +15,13 @@ overrides:
|
||||
# lib/db-adapter.ts fuer DATABASE_PROVIDER=mysql) bringt intern eine
|
||||
# eigene, veraltete [email protected] mit, die vom direkten mariadb-Eintrag in
|
||||
# den dependencies (bereits auf ^3.5.3) NICHT ueberschrieben wird — pnpm
|
||||
# haelt dafuer sonst zwei getrennte Kopien vor.
|
||||
mariadb: '>=3.4.6'
|
||||
# haelt dafuer sonst zwei getrennte Kopien vor. Seit 2026-10-14 >= 3.5.4
|
||||
# (neues High-Advisory fuer < 3.5.4, pnpm audit).
|
||||
mariadb: '>=3.5.4'
|
||||
# sharp < 0.35.5 und source-map-js < 1.2.2 (High-Advisories), beide
|
||||
# transitiv ueber next; reine Patch-Spruenge.
|
||||
sharp: '>=0.35.5'
|
||||
source-map-js: '>=1.2.2'
|
||||
# GHSA-rgwj-5xj2-c3m3 u.a.: mysql2 < 3.23.1. Kommt ausschliesslich ueber die
|
||||
# prisma-CLI herein (Migrationen/Generate), nicht ueber den Laufzeitpfad der
|
||||
# Anwendung — die nutzt bei DATABASE_PROVIDER=mysql den mariadb-Treiber
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Abgelehnte Bewertungen werden nicht mehr geloescht, sondern markiert und
|
||||
-- im Archiv unter "Abgelehnt" gefuehrt. null = nicht abgelehnt.
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "reviews" ADD COLUMN "rejectedAt" TIMESTAMP(3);
|
||||
@@ -0,0 +1,56 @@
|
||||
-- Mehrere Ernten derselben Sorte im selben Jahr zulassen.
|
||||
--
|
||||
-- Bisher erzwang "harvests_year_type_key" genau eine Ernte je (Jahr, Sorte).
|
||||
-- Eine Imkerei schleudert dieselbe Sorte aber oft mehrmals im Jahr; der
|
||||
-- ApiCore-Sync scheiterte daran mit P2002. Eindeutig ist ab jetzt nur noch
|
||||
-- der Slug (oeffentliche Adresse /ernten/<slug>).
|
||||
--
|
||||
-- Der Sync erkannte importierte Ernten bisher am Slug "apicore-<ID>". Diese
|
||||
-- ID wandert in eine eigene Spalte, damit der Slug lesbar werden darf.
|
||||
-- Keine Zeile wird geloescht; die Aenderung ist rein additiv bis auf den
|
||||
-- entfernten Unique-Index.
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "harvests" ADD COLUMN "apicoreHarvestId" TEXT;
|
||||
|
||||
-- Backfill: bisherige Sync-Ernten behalten ihre ApiCore-Zuordnung.
|
||||
UPDATE "harvests"
|
||||
SET "apicoreHarvestId" = substring("slug" from 9)
|
||||
WHERE "slug" LIKE 'apicore-%';
|
||||
|
||||
-- Von Hand angelegte Ernten bekamen ihren Slug bisher ohne Umlaut-Behandlung
|
||||
-- ("Frühtracht" 2026 -> "fr-htracht-2026"). Bis jetzt war das unsichtbar;
|
||||
-- ab jetzt ist der Slug die oeffentliche Adresse. Genau diese Form wird auf
|
||||
-- die Schreibweise von lib/slugify.ts gebracht ("fruehtracht-2026") — nur,
|
||||
-- wenn sie sich unterscheidet und die neue Adresse noch frei ist. Sonst
|
||||
-- bleibt der alte Slug: er funktioniert, ist nur weniger schoen.
|
||||
WITH renamed AS (
|
||||
SELECT
|
||||
"id",
|
||||
trim(both '-' from regexp_replace(
|
||||
replace(replace(replace(replace(lower("type"), 'ä', 'ae'), 'ö', 'oe'), 'ü', 'ue'), 'ß', 'ss'),
|
||||
'[^a-z0-9]+', '-', 'g'
|
||||
)) || '-' || "year" AS "newSlug"
|
||||
FROM "harvests"
|
||||
WHERE "apicoreHarvestId" IS NULL
|
||||
AND "slug" = regexp_replace(lower("type"), '[^a-z0-9]+', '-', 'g') || '-' || "year"
|
||||
)
|
||||
UPDATE "harvests" h
|
||||
SET "slug" = r."newSlug"
|
||||
FROM renamed r
|
||||
WHERE h."id" = r."id"
|
||||
AND r."newSlug" <> h."slug"
|
||||
AND r."newSlug" <> ('-' || h."year")
|
||||
AND NOT EXISTS (SELECT 1 FROM "harvests" o WHERE o."slug" = r."newSlug")
|
||||
-- z.B. "Frühtracht" und "Fruehtracht" im selben Jahr: beide ergaeben
|
||||
-- denselben Slug, der Unique-Index liesse die Migration scheitern.
|
||||
AND (SELECT count(*) FROM renamed r2 WHERE r2."newSlug" = r."newSlug") = 1;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "harvests_apicoreHarvestId_key" ON "harvests"("apicoreHarvestId");
|
||||
|
||||
-- DropIndex
|
||||
DROP INDEX "harvests_year_type_key";
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "harvests_year_type_idx" ON "harvests"("year", "type");
|
||||
@@ -0,0 +1,63 @@
|
||||
-- Bestandsabgleich mit ApiCore (ApiCore/docs/superpowers/specs/2026-10-02-bestandsabgleich-design.md):
|
||||
-- ApiCore fuehrt den Restbestand je Charge; Wabenhain meldet bezahlte
|
||||
-- Verkaeufe und Rueckbuchungen ueber eine Warteschlange und gleicht seinen
|
||||
-- Shop-Bestand daran ab. Rein additiv.
|
||||
|
||||
-- AlterEnum
|
||||
ALTER TYPE "ProductCategory" ADD VALUE 'SONSTIGES';
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ApiCoreStockEventKind" AS ENUM ('SALE', 'RETURN');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "products" ADD COLUMN "apicoreProductId" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "order_items" ADD COLUMN "apicoreAllocations" JSONB;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "apicore_stock_events" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kind" "ApiCoreStockEventKind" NOT NULL,
|
||||
"orderItemId" TEXT NOT NULL,
|
||||
"productId" TEXT NOT NULL,
|
||||
"apicoreBottlingId" TEXT,
|
||||
"apicoreProductId" TEXT,
|
||||
"quantity" INTEGER NOT NULL,
|
||||
"reversesEventId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"sentAt" TIMESTAMP(3),
|
||||
"rejectedAt" TIMESTAMP(3),
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"lastError" TEXT,
|
||||
"nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "apicore_stock_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "products_apicoreProductId_key" ON "products"("apicoreProductId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "apicore_stock_events_sentAt_rejectedAt_nextAttemptAt_idx" ON "apicore_stock_events"("sentAt", "rejectedAt", "nextAttemptAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "apicore_stock_events_orderItemId_idx" ON "apicore_stock_events"("orderItemId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "apicore_stock_events_productId_idx" ON "apicore_stock_events"("productId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "apicore_stock_events" ADD CONSTRAINT "apicore_stock_events_orderItemId_fkey" FOREIGN KEY ("orderItemId") REFERENCES "order_items"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "apicore_stock_events" ADD CONSTRAINT "apicore_stock_events_productId_fkey" FOREIGN KEY ("productId") REFERENCES "products"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "apicore_stock_events" ADD CONSTRAINT "apicore_stock_events_reversesEventId_fkey" FOREIGN KEY ("reversesEventId") REFERENCES "apicore_stock_events"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- Genau ein ApiCore-Ziel je Buchung.
|
||||
ALTER TABLE "apicore_stock_events" ADD CONSTRAINT "apicore_stock_events_exactly_one_target"
|
||||
CHECK (("apicoreBottlingId" IS NULL) <> ("apicoreProductId" IS NULL));
|
||||
ALTER TABLE "apicore_stock_events" ADD CONSTRAINT "apicore_stock_events_quantity_positive"
|
||||
CHECK ("quantity" > 0);
|
||||
@@ -0,0 +1,35 @@
|
||||
-- Stornorechnungen: Gegenbeleg mit eigenem Nummernkreis (ST-JJJJ-NNNN) statt
|
||||
-- Loeschen oder Aendern einer Rechnung. Rein additiv.
|
||||
-- CreateTable
|
||||
CREATE TABLE "cancellation_counters" (
|
||||
"year" INTEGER NOT NULL,
|
||||
"lastNumber" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "cancellation_counters_pkey" PRIMARY KEY ("year")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "cancellation_invoices" (
|
||||
"id" TEXT NOT NULL,
|
||||
"invoiceId" TEXT NOT NULL,
|
||||
"number" TEXT NOT NULL,
|
||||
"issuedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"totalCents" INTEGER NOT NULL,
|
||||
"reason" TEXT NOT NULL,
|
||||
"pdfPath" TEXT,
|
||||
|
||||
CONSTRAINT "cancellation_invoices_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "cancellation_invoices_invoiceId_key" ON "cancellation_invoices"("invoiceId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "cancellation_invoices_number_key" ON "cancellation_invoices"("number");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "cancellation_invoices_issuedAt_idx" ON "cancellation_invoices"("issuedAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "cancellation_invoices" ADD CONSTRAINT "cancellation_invoices_invoiceId_fkey" FOREIGN KEY ("invoiceId") REFERENCES "invoices"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
-- Bienenpatenschaft: Angebote, Patenschaften mit Urkunden-Revisionen,
|
||||
-- Uebertragungen, Abos (Stripe Billing) mit Zahlungen und Lieferungen,
|
||||
-- Erntefenster und Treuestufen. Rein additiv; die beiden neuen Enum-Werte
|
||||
-- (PATENSCHAFT, DIGITAL) werden in dieser Migration nicht benutzt, ALTER TYPE
|
||||
-- ADD VALUE ist deshalb auch innerhalb der Migrationstransaktion zulaessig.
|
||||
-- CreateEnum
|
||||
CREATE TYPE "SponsorshipOfferKind" AS ENUM ('EINMALIG', 'ABO');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "SponsorshipCycle" AS ENUM ('VIERTELJAEHRLICH', 'ERNTE');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "MedalTier" AS ENUM ('BRONZE', 'SILBER', 'GOLD', 'ABO');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "SponsorshipStatus" AS ENUM ('AUSSTEHEND', 'FEHLER', 'BEREIT', 'GEDRUCKT');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "SubscriptionStatus" AS ENUM ('AUSSTEHEND', 'AKTIV', 'IM_VERZUG', 'GEKUENDIGT', 'BEENDET');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "DeliveryStatus" AS ENUM ('ANGELEGT', 'ZURUECKGESTELLT');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "LoyaltyKind" AS ENUM ('STAMMKUNDE', 'ABO');
|
||||
|
||||
-- AlterEnum
|
||||
ALTER TYPE "ProductCategory" ADD VALUE 'PATENSCHAFT';
|
||||
|
||||
-- AlterEnum
|
||||
ALTER TYPE "FulfillmentMethod" ADD VALUE 'DIGITAL';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "customers" ADD COLUMN "sepaBlockedAt" TIMESTAMP(3),
|
||||
ADD COLUMN "stripeCustomerId" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "order_items" ADD COLUMN "personalization" JSONB,
|
||||
ADD COLUMN "sponsorshipOfferId" TEXT,
|
||||
ADD COLUMN "sponsorshipRole" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "sponsorship_offers" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"kind" "SponsorshipOfferKind" NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"nameEn" TEXT,
|
||||
"description" TEXT NOT NULL,
|
||||
"descriptionEn" TEXT,
|
||||
"features" JSONB NOT NULL DEFAULT '[]',
|
||||
"featuresEn" JSONB NOT NULL DEFAULT '[]',
|
||||
"priceCents" INTEGER NOT NULL,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"sortOrder" INTEGER NOT NULL DEFAULT 0,
|
||||
"isPhysical" BOOLEAN NOT NULL DEFAULT false,
|
||||
"productId" TEXT,
|
||||
"honeyProductId" TEXT,
|
||||
"honeyJars" INTEGER NOT NULL DEFAULT 0,
|
||||
"honeyShareCentsPerJar" INTEGER NOT NULL DEFAULT 0,
|
||||
"honeyShareCentsPerMonth" INTEGER NOT NULL DEFAULT 0,
|
||||
"cycle" "SponsorshipCycle",
|
||||
"maxActiveSubscriptions" INTEGER,
|
||||
"stripeProductId" TEXT,
|
||||
"stripePriceId" TEXT,
|
||||
"stripePriceAmountCents" INTEGER,
|
||||
"medalTier" "MedalTier" NOT NULL DEFAULT 'BRONZE',
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "sponsorship_offers_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "sponsorships" (
|
||||
"id" TEXT NOT NULL,
|
||||
"number" TEXT NOT NULL,
|
||||
"ownerId" TEXT NOT NULL,
|
||||
"offerId" TEXT NOT NULL,
|
||||
"orderItemId" TEXT,
|
||||
"subscriptionId" TEXT,
|
||||
"locale" TEXT NOT NULL DEFAULT 'de',
|
||||
"startDate" DATE NOT NULL,
|
||||
"endDate" DATE,
|
||||
"status" "SponsorshipStatus" NOT NULL DEFAULT 'AUSSTEHEND',
|
||||
"currentRevision" INTEGER NOT NULL DEFAULT 0,
|
||||
"pdfAttempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"nextAttemptAt" TIMESTAMP(3),
|
||||
"lastError" TEXT,
|
||||
"mailSentAt" TIMESTAMP(3),
|
||||
"printedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "sponsorships_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "sponsorship_revisions" (
|
||||
"id" TEXT NOT NULL,
|
||||
"sponsorshipId" TEXT NOT NULL,
|
||||
"revision" INTEGER NOT NULL,
|
||||
"personalization" JSONB NOT NULL,
|
||||
"term" JSONB NOT NULL,
|
||||
"text" JSONB NOT NULL,
|
||||
"templateVersion" TEXT NOT NULL,
|
||||
"pdfPath" TEXT NOT NULL,
|
||||
"pdfSha256" TEXT NOT NULL,
|
||||
"createdById" TEXT,
|
||||
"createdByLabel" TEXT NOT NULL,
|
||||
"reason" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "sponsorship_revisions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "sponsorship_counters" (
|
||||
"year" INTEGER NOT NULL,
|
||||
"lastNumber" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "sponsorship_counters_pkey" PRIMARY KEY ("year")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "sponsorship_transfers" (
|
||||
"id" TEXT NOT NULL,
|
||||
"sponsorshipId" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"createdById" TEXT NOT NULL,
|
||||
"claimedById" TEXT,
|
||||
"claimedAt" TIMESTAMP(3),
|
||||
"revokedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "sponsorship_transfers_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "sponsorship_subscriptions" (
|
||||
"id" TEXT NOT NULL,
|
||||
"customerId" TEXT NOT NULL,
|
||||
"offerId" TEXT NOT NULL,
|
||||
"status" "SubscriptionStatus" NOT NULL DEFAULT 'AUSSTEHEND',
|
||||
"personalization" JSONB NOT NULL,
|
||||
"locale" TEXT NOT NULL DEFAULT 'de',
|
||||
"stripeCheckoutSessionId" TEXT,
|
||||
"stripeSubscriptionId" TEXT,
|
||||
"startedAt" TIMESTAMP(3),
|
||||
"currentPeriodEnd" TIMESTAMP(3),
|
||||
"cancelAt" TIMESTAMP(3),
|
||||
"endedAt" TIMESTAMP(3),
|
||||
"delinquentSince" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "sponsorship_subscriptions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "subscription_payments" (
|
||||
"id" TEXT NOT NULL,
|
||||
"subscriptionId" TEXT NOT NULL,
|
||||
"stripeInvoiceId" TEXT NOT NULL,
|
||||
"stripePaymentIntentId" TEXT,
|
||||
"paymentMethodType" TEXT,
|
||||
"amountCents" INTEGER NOT NULL,
|
||||
"paidAt" TIMESTAMP(3) NOT NULL,
|
||||
"periodStart" TIMESTAMP(3) NOT NULL,
|
||||
"periodEnd" TIMESTAMP(3) NOT NULL,
|
||||
"countsFrom" TIMESTAMP(3) NOT NULL,
|
||||
"reversedAt" TIMESTAMP(3),
|
||||
"deliveryId" TEXT,
|
||||
"orderId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "subscription_payments_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "subscription_deliveries" (
|
||||
"id" TEXT NOT NULL,
|
||||
"subscriptionId" TEXT NOT NULL,
|
||||
"dueAt" TIMESTAMP(3) NOT NULL,
|
||||
"jars" INTEGER NOT NULL,
|
||||
"status" "DeliveryStatus" NOT NULL,
|
||||
"orderId" TEXT,
|
||||
"note" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "subscription_deliveries_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "harvest_windows" (
|
||||
"id" TEXT NOT NULL,
|
||||
"offerId" TEXT NOT NULL,
|
||||
"startsOn" DATE NOT NULL,
|
||||
"endsOn" DATE NOT NULL,
|
||||
"plannedJars" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "harvest_windows_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "loyalty_levels" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kind" "LoyaltyKind" NOT NULL,
|
||||
"threshold" INTEGER,
|
||||
"name" TEXT NOT NULL,
|
||||
"nameEn" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "loyalty_levels_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "sponsorship_offers_slug_key" ON "sponsorship_offers"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "sponsorship_offers_productId_key" ON "sponsorship_offers"("productId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "sponsorship_offers_kind_isActive_sortOrder_idx" ON "sponsorship_offers"("kind", "isActive", "sortOrder");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "sponsorship_offers_honeyProductId_idx" ON "sponsorship_offers"("honeyProductId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "sponsorships_number_key" ON "sponsorships"("number");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "sponsorships_orderItemId_key" ON "sponsorships"("orderItemId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "sponsorships_subscriptionId_key" ON "sponsorships"("subscriptionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "sponsorships_ownerId_idx" ON "sponsorships"("ownerId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "sponsorships_status_nextAttemptAt_idx" ON "sponsorships"("status", "nextAttemptAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "sponsorships_offerId_idx" ON "sponsorships"("offerId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "sponsorship_revisions_sponsorshipId_revision_key" ON "sponsorship_revisions"("sponsorshipId", "revision");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "sponsorship_transfers_tokenHash_key" ON "sponsorship_transfers"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "sponsorship_transfers_sponsorshipId_idx" ON "sponsorship_transfers"("sponsorshipId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "sponsorship_subscriptions_stripeCheckoutSessionId_key" ON "sponsorship_subscriptions"("stripeCheckoutSessionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "sponsorship_subscriptions_stripeSubscriptionId_key" ON "sponsorship_subscriptions"("stripeSubscriptionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "sponsorship_subscriptions_customerId_idx" ON "sponsorship_subscriptions"("customerId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "sponsorship_subscriptions_offerId_status_idx" ON "sponsorship_subscriptions"("offerId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "subscription_payments_stripeInvoiceId_key" ON "subscription_payments"("stripeInvoiceId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "subscription_payments_orderId_key" ON "subscription_payments"("orderId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "subscription_payments_subscriptionId_paidAt_idx" ON "subscription_payments"("subscriptionId", "paidAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "subscription_deliveries_orderId_key" ON "subscription_deliveries"("orderId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "subscription_deliveries_subscriptionId_dueAt_idx" ON "subscription_deliveries"("subscriptionId", "dueAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "harvest_windows_offerId_startsOn_idx" ON "harvest_windows"("offerId", "startsOn");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "loyalty_levels_kind_threshold_key" ON "loyalty_levels"("kind", "threshold");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "customers_stripeCustomerId_key" ON "customers"("stripeCustomerId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sponsorship_offers" ADD CONSTRAINT "sponsorship_offers_productId_fkey" FOREIGN KEY ("productId") REFERENCES "products"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sponsorship_offers" ADD CONSTRAINT "sponsorship_offers_honeyProductId_fkey" FOREIGN KEY ("honeyProductId") REFERENCES "products"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sponsorships" ADD CONSTRAINT "sponsorships_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sponsorships" ADD CONSTRAINT "sponsorships_offerId_fkey" FOREIGN KEY ("offerId") REFERENCES "sponsorship_offers"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sponsorships" ADD CONSTRAINT "sponsorships_orderItemId_fkey" FOREIGN KEY ("orderItemId") REFERENCES "order_items"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sponsorships" ADD CONSTRAINT "sponsorships_subscriptionId_fkey" FOREIGN KEY ("subscriptionId") REFERENCES "sponsorship_subscriptions"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sponsorship_revisions" ADD CONSTRAINT "sponsorship_revisions_sponsorshipId_fkey" FOREIGN KEY ("sponsorshipId") REFERENCES "sponsorships"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sponsorship_transfers" ADD CONSTRAINT "sponsorship_transfers_sponsorshipId_fkey" FOREIGN KEY ("sponsorshipId") REFERENCES "sponsorships"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sponsorship_subscriptions" ADD CONSTRAINT "sponsorship_subscriptions_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "sponsorship_subscriptions" ADD CONSTRAINT "sponsorship_subscriptions_offerId_fkey" FOREIGN KEY ("offerId") REFERENCES "sponsorship_offers"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "subscription_payments" ADD CONSTRAINT "subscription_payments_subscriptionId_fkey" FOREIGN KEY ("subscriptionId") REFERENCES "sponsorship_subscriptions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "subscription_payments" ADD CONSTRAINT "subscription_payments_deliveryId_fkey" FOREIGN KEY ("deliveryId") REFERENCES "subscription_deliveries"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "subscription_payments" ADD CONSTRAINT "subscription_payments_orderId_fkey" FOREIGN KEY ("orderId") REFERENCES "orders"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "subscription_deliveries" ADD CONSTRAINT "subscription_deliveries_subscriptionId_fkey" FOREIGN KEY ("subscriptionId") REFERENCES "sponsorship_subscriptions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "subscription_deliveries" ADD CONSTRAINT "subscription_deliveries_orderId_fkey" FOREIGN KEY ("orderId") REFERENCES "orders"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "harvest_windows" ADD CONSTRAINT "harvest_windows_offerId_fkey" FOREIGN KEY ("offerId") REFERENCES "sponsorship_offers"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Widerrufene Patenschaft: Einmalkauf storniert oder voll erstattet
|
||||
-- (Stornorechnung ausgestellt). Rein additiv; der neue Wert wird in dieser
|
||||
-- Migration nicht benutzt, ALTER TYPE ADD VALUE ist deshalb auch innerhalb
|
||||
-- der Migrationstransaktion zulaessig.
|
||||
-- AlterEnum
|
||||
ALTER TYPE "SponsorshipStatus" ADD VALUE 'WIDERRUFEN';
|
||||
+484
-3
@@ -76,6 +76,17 @@ model Customer {
|
||||
wishlistItems WishlistItem[]
|
||||
auditLogs AuditLog[]
|
||||
|
||||
/// Stripe-Kunde fuer Abos (Stripe Billing). Erst beim ersten Abo-Abschluss
|
||||
/// angelegt; Einmalkaeufe laufen weiter ohne Stripe-Kunde.
|
||||
stripeCustomerId String? @unique
|
||||
/// Gesetzt nach einer SEPA-Rueckbuchung: neue Abos dieses Kontos nur noch
|
||||
/// mit Karte oder Wallet (siehe lib/sponsorship-subscription). Der Admin
|
||||
/// kann die Sperre aufheben.
|
||||
sepaBlockedAt DateTime?
|
||||
|
||||
sponsorships Sponsorship[]
|
||||
subscriptions SponsorshipSubscription[]
|
||||
|
||||
@@map("customers")
|
||||
}
|
||||
|
||||
@@ -148,9 +159,14 @@ model Address {
|
||||
model Harvest {
|
||||
id String @id @default(cuid())
|
||||
year Int
|
||||
/// z.B. "Fruehtracht", "Sommertracht"
|
||||
/// z.B. "Fruehtracht", "Sommertracht". Bewusst NICHT eindeutig je Jahr:
|
||||
/// dieselbe Sorte wird oft mehrmals im Jahr geerntet.
|
||||
type String
|
||||
/// Oeffentliche Adresse /ernten/<slug> — siehe lib/harvest-slug.ts.
|
||||
slug String @unique
|
||||
/// ID der Ernte in ApiCore; Wiedererkennungs-Schluessel des Syncs
|
||||
/// (admin/actions/apicore-sync.ts). null fuer von Hand angelegte Ernten.
|
||||
apicoreHarvestId String? @unique
|
||||
harvestDate DateTime
|
||||
location String @default("Altenmuenster")
|
||||
description String
|
||||
@@ -170,7 +186,8 @@ model Harvest {
|
||||
batches Batch[]
|
||||
products Product[]
|
||||
|
||||
@@unique([year, type])
|
||||
/// Nur noch fuer die Weiterleitung alter Adressen /ernten/<jahr>/<sorte>.
|
||||
@@index([year, type])
|
||||
@@map("harvests")
|
||||
}
|
||||
|
||||
@@ -206,6 +223,11 @@ enum ProductCategory {
|
||||
HONIG
|
||||
KERZEN
|
||||
PROPOLIS
|
||||
SONSTIGES
|
||||
/// Traegerprodukt einer Einmal-Patenschaft (siehe SponsorshipOffer). Nicht
|
||||
/// im Shop gelistet; es haelt Preis, Steuersatz und Rechnungsposition, damit
|
||||
/// Warenkorb, Checkout und Rechnung keinen Sonderweg brauchen.
|
||||
PATENSCHAFT
|
||||
}
|
||||
|
||||
model Product {
|
||||
@@ -229,6 +251,12 @@ model Product {
|
||||
/// bleiben ("waldhonig-2026"), darf sich also nicht nach einer fremden ID
|
||||
/// richten.
|
||||
apicoreBottlingId String? @unique
|
||||
/// ApiCore-ID des ARTIKELS fuer hergestellte Waren (Kerzen, Propolis-
|
||||
/// Produkte, ...): deren Bestand liegt in ApiCore je Herstellungscharge und
|
||||
/// wird als Summe gefuehrt, ein Shop-Produkt je Artikel. Honig nutzt
|
||||
/// stattdessen apicoreBottlingId. Hoechstens eines von beiden ist gesetzt;
|
||||
/// ist eines gesetzt, kommt der Bestand aus ApiCore (lib/apicore-stock).
|
||||
apicoreProductId String? @unique
|
||||
/// Nur fuer Honig-Produkte gesetzt (Kerzen/Propolis sind keiner Ernte/Charge zugeordnet)
|
||||
harvestId String?
|
||||
batchId String?
|
||||
@@ -274,9 +302,15 @@ model Product {
|
||||
inventory Inventory?
|
||||
orderItems OrderItem[]
|
||||
reviews Review[]
|
||||
apicoreStockEvents ApiCoreStockEvent[]
|
||||
wishlistItems WishlistItem[]
|
||||
stockNotifications StockNotification[]
|
||||
|
||||
/// Einmal-Patenschaft, deren Traegerprodukt dieses Produkt ist.
|
||||
sponsorshipOffer SponsorshipOffer? @relation("SponsorshipOfferProduct")
|
||||
/// Patenschafts-Angebote, deren Honig aus diesem Produkt kommt.
|
||||
sponsorshipHoneyFor SponsorshipOffer[] @relation("SponsorshipOfferHoney")
|
||||
|
||||
@@index([archivedAt])
|
||||
@@map("products")
|
||||
}
|
||||
@@ -326,6 +360,10 @@ model Review {
|
||||
/// Nur freigeschaltete Bewertungen werden auf der Produktseite angezeigt —
|
||||
/// einfache Missbrauchskontrolle durch den Admin vor Veroeffentlichung.
|
||||
isApproved Boolean @default(false)
|
||||
/// Vom Admin abgelehnt: bleibt im Archiv nachvollziehbar statt geloescht zu
|
||||
/// werden. Offen ist eine Bewertung, solange weder isApproved noch
|
||||
/// rejectedAt gesetzt ist (siehe lib/review-status.ts).
|
||||
rejectedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -366,6 +404,9 @@ enum OrderStatus {
|
||||
enum FulfillmentMethod {
|
||||
VERSAND
|
||||
ABHOLUNG
|
||||
/// Nur digitale Leistungen (Patenschaft ohne Paket, Abo-Monatsrechnung):
|
||||
/// nichts zu versenden, nichts abzuholen. Die Rechnungsanschrift bleibt.
|
||||
DIGITAL
|
||||
}
|
||||
|
||||
model Order {
|
||||
@@ -444,6 +485,10 @@ model Order {
|
||||
invoice Invoice?
|
||||
returnRequest ReturnRequest?
|
||||
withdrawalDeclarations WithdrawalDeclaration[]
|
||||
/// Gesetzt, wenn diese Bestellung eine bezahlte Abo-Monatsrechnung abbildet.
|
||||
subscriptionPayment SubscriptionPayment?
|
||||
/// Gesetzt, wenn diese Bestellung eine Abo-Honiglieferung ist (0 €).
|
||||
subscriptionDelivery SubscriptionDelivery?
|
||||
|
||||
/// Bedient sowohl "Meine Bestellungen" (Filter nach customerId, sortiert nach
|
||||
/// createdAt) als auch den reinen customerId-Filter beim Datenexport.
|
||||
@@ -515,9 +560,29 @@ model OrderItem {
|
||||
/// feststellbar ist, welcher Satz gegolten haette.
|
||||
vatRatePercent Int?
|
||||
|
||||
/// Aus welchen ApiCore-Chargen die verkaufte Ware stammt, wie ApiCore sie
|
||||
/// beim Verbuchen zugeordnet hat: [{ lotNumber, quantity }]. Fuer
|
||||
/// Rueckverfolgung und Rueckruf; null, solange der Verkauf noch nicht
|
||||
/// bestaetigt ist oder das Produkt nicht mit ApiCore verknuepft ist.
|
||||
apicoreAllocations Json?
|
||||
|
||||
/// Personalisierung einer Patenschaft, wie sie beim Kauf bestaetigt wurde
|
||||
/// (lib/certificate/schema.ts), samt Vorlagenversion. Nur an der
|
||||
/// Hauptposition (sponsorshipRole "MAIN"); daraus entsteht nach der Zahlung
|
||||
/// die erste Revision der Urkunde.
|
||||
personalization Json?
|
||||
/// Angebot, zu dem diese Position gehoert — an Haupt- UND Honigposition,
|
||||
/// damit Warenkorb, Rechnung und Admin sie als ein Paket zeigen koennen.
|
||||
sponsorshipOfferId String?
|
||||
/// "MAIN" (Patenschaft, Regelsteuersatz) oder "HONEY" (Honiganteil des
|
||||
/// Pakets zum Honig-Satz). Null bei gewoehnlichen Positionen.
|
||||
sponsorshipRole String?
|
||||
|
||||
order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)
|
||||
sponsorship Sponsorship?
|
||||
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
|
||||
batch Batch? @relation(fields: [batchId], references: [id], onDelete: Restrict)
|
||||
apicoreStockEvents ApiCoreStockEvent[]
|
||||
|
||||
/// Wird bei jedem Laden der Positionen einer Bestellung (Konto, Admin,
|
||||
/// Rechnung) ueber die order.items-Relation abgefragt.
|
||||
@@ -541,6 +606,55 @@ model OrderItem {
|
||||
@@map("order_items")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bestandsabgleich mit ApiCore
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
enum ApiCoreStockEventKind {
|
||||
SALE
|
||||
RETURN
|
||||
}
|
||||
|
||||
/// Warteschlange der Bestandsbuchungen an ApiCore (lib/apicore-stock).
|
||||
///
|
||||
/// Geschrieben in DERSELBEN Transaktion wie die ausloesende Statusaenderung
|
||||
/// (bezahlt, storniert, erstattet), gesendet danach — sofort und per
|
||||
/// CronJob nachgereicht. So geht keine Buchung verloren, wenn ApiCore gerade
|
||||
/// nicht erreichbar ist. Die id geht als externalId an ApiCore; ApiCore bucht
|
||||
/// jede id nur einmal, Wiederholungen sind also gefahrlos.
|
||||
model ApiCoreStockEvent {
|
||||
id String @id @default(cuid())
|
||||
kind ApiCoreStockEventKind
|
||||
orderItemId String
|
||||
/// Wabenhain-Produkt, dessen Shop-Bestand von dieser Buchung abhaengt.
|
||||
productId String
|
||||
/// Ziel in ApiCore: eine Abfuellung (Honig) ODER ein Artikel (FIFO ueber
|
||||
/// dessen Herstellungschargen).
|
||||
apicoreBottlingId String?
|
||||
apicoreProductId String?
|
||||
quantity Int
|
||||
/// Bei RETURN: der Verkauf, der zurueckgebucht wird.
|
||||
reversesEventId String?
|
||||
createdAt DateTime @default(now())
|
||||
/// Von ApiCore bestaetigt (neu gebucht oder schon bekannt).
|
||||
sentAt DateTime?
|
||||
/// Von ApiCore abgelehnt — wird nicht wiederholt, das Dashboard zeigt es.
|
||||
rejectedAt DateTime?
|
||||
attempts Int @default(0)
|
||||
lastError String?
|
||||
nextAttemptAt DateTime @default(now())
|
||||
|
||||
orderItem OrderItem @relation(fields: [orderItemId], references: [id], onDelete: Restrict)
|
||||
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
|
||||
reverses ApiCoreStockEvent? @relation("StockEventReversal", fields: [reversesEventId], references: [id], onDelete: Restrict)
|
||||
reversedBy ApiCoreStockEvent[] @relation("StockEventReversal")
|
||||
|
||||
@@index([sentAt, rejectedAt, nextAttemptAt])
|
||||
@@index([orderItemId])
|
||||
@@index([productId])
|
||||
@@map("apicore_stock_events")
|
||||
}
|
||||
|
||||
enum PaymentStatus {
|
||||
PENDING
|
||||
SUCCEEDED
|
||||
@@ -636,11 +750,47 @@ model Invoice {
|
||||
/// einem oeffentlich abrufbaren Pfad.
|
||||
pdfPath String?
|
||||
|
||||
order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)
|
||||
order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)
|
||||
cancellation CancellationInvoice?
|
||||
|
||||
@@map("invoices")
|
||||
}
|
||||
|
||||
/// Eigener fortlaufender Nummernkreis der Stornorechnungen (ST-JJJJ-NNNN),
|
||||
/// je Kalenderjahr — aus demselben Grund eine Zeile mit Sperre wie
|
||||
/// InvoiceCounter.
|
||||
model CancellationCounter {
|
||||
year Int @id
|
||||
lastNumber Int @default(0)
|
||||
|
||||
@@map("cancellation_counters")
|
||||
}
|
||||
|
||||
/// Stornorechnung: hebt eine Rechnung vollstaendig auf. Eine Rechnung wird
|
||||
/// nie geloescht oder geaendert (§ 14 UStG, GoBD); wird die Bestellung
|
||||
/// storniert oder voll erstattet, entsteht stattdessen dieser Gegenbeleg mit
|
||||
/// eigener Nummer und Bezug auf die Rechnung (lib/cancellation-invoice.ts).
|
||||
/// Hoechstens einer je Rechnung. ERPNext uebernimmt ihn als
|
||||
/// Rechnungskorrektur, die Ausgangsrechnung steht dort dann auf
|
||||
/// "Credit Note Issued".
|
||||
model CancellationInvoice {
|
||||
id String @id @default(cuid())
|
||||
invoiceId String @unique
|
||||
number String @unique
|
||||
issuedAt DateTime @default(now())
|
||||
/// Betrag der aufgehobenen Rechnung (brutto, positiv).
|
||||
totalCents Int
|
||||
/// STORNIERUNG (Admin), RETOURE (Retoure erstattet) oder ERSTATTUNG (volle Erstattung bei Stripe).
|
||||
reason String
|
||||
/// Wie Invoice.pdfPath, relativ zu INVOICE_DIR.
|
||||
pdfPath String?
|
||||
|
||||
invoice Invoice @relation(fields: [invoiceId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([issuedAt])
|
||||
@@map("cancellation_invoices")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Marketing / Kontakt
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -841,3 +991,334 @@ model WithdrawalDeclaration {
|
||||
@@index([processedAt])
|
||||
@@map("withdrawal_declarations")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bienenpatenschaft (docs/superpowers/specs/2026-10-16-bienenpatenschaft-design.md)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
enum SponsorshipOfferKind {
|
||||
EINMALIG
|
||||
ABO
|
||||
}
|
||||
|
||||
enum SponsorshipCycle {
|
||||
/// Lieferanspruch nach jeweils drei bezahlten Monaten.
|
||||
VIERTELJAEHRLICH
|
||||
/// Lieferung in den Erntefenstern, frueheste nach sechs bezahlten Monaten
|
||||
/// seit der letzten Lieferung.
|
||||
ERNTE
|
||||
}
|
||||
|
||||
/// Praegung der Patenschafts-Medaille (lib/medals).
|
||||
enum MedalTier {
|
||||
BRONZE
|
||||
SILBER
|
||||
GOLD
|
||||
ABO
|
||||
}
|
||||
|
||||
enum SponsorshipStatus {
|
||||
/// Bezahlt, PDF noch nicht erzeugt oder Mail noch nicht versendet.
|
||||
AUSSTEHEND
|
||||
/// Alle automatischen Versuche aufgebraucht — braucht den Admin.
|
||||
FEHLER
|
||||
/// PDF liegt vor, Mail ist raus.
|
||||
BEREIT
|
||||
/// Nur physische Pakete: Urkunde gedruckt.
|
||||
GEDRUCKT
|
||||
/// Einmalkauf storniert oder voll erstattet (Stornorechnung): keine
|
||||
/// Downloads, keine Uebertragung, keine Ausstellung mehr.
|
||||
WIDERRUFEN
|
||||
}
|
||||
|
||||
enum SubscriptionStatus {
|
||||
/// Checkout gestartet, bei Stripe noch nicht abgeschlossen.
|
||||
AUSSTEHEND
|
||||
AKTIV
|
||||
/// Zahlung offen oder zurueckgebucht — keine Lieferungen, Stufe ruht.
|
||||
IM_VERZUG
|
||||
/// Gekuendigt, laeuft bis zum Ende des bezahlten Monats.
|
||||
GEKUENDIGT
|
||||
BEENDET
|
||||
}
|
||||
|
||||
enum DeliveryStatus {
|
||||
/// Bestellung fuer den Versand angelegt.
|
||||
ANGELEGT
|
||||
/// Faellig, aber ohne Bestand oder Anspruch zurueckgestellt.
|
||||
ZURUECKGESTELLT
|
||||
}
|
||||
|
||||
enum LoyaltyKind {
|
||||
STAMMKUNDE
|
||||
ABO
|
||||
}
|
||||
|
||||
/// Ein im Admin pflegbares Patenschafts-Angebot (Einmalpaket oder Abo).
|
||||
model SponsorshipOffer {
|
||||
id String @id @default(cuid())
|
||||
slug String @unique
|
||||
kind SponsorshipOfferKind
|
||||
name String
|
||||
nameEn String?
|
||||
description String @db.Text
|
||||
descriptionEn String? @db.Text
|
||||
/// Leistungsliste als JSON-Array von Strings (lib/json-array.ts).
|
||||
features Json @default("[]")
|
||||
featuresEn Json @default("[]")
|
||||
/// EINMALIG: Bruttopreis des ganzen Pakets. ABO: Monatspreis brutto.
|
||||
priceCents Int
|
||||
isActive Boolean @default(true)
|
||||
sortOrder Int @default(0)
|
||||
/// Mit gedruckter Urkunde, Honig, Grusskarte und Versand.
|
||||
isPhysical Boolean @default(false)
|
||||
/// Nur EINMALIG: Traegerprodukt (Kategorie PATENSCHAFT) fuer Warenkorb,
|
||||
/// Checkout und Rechnung. Sein Preis ist Paketpreis minus Honiganteil.
|
||||
productId String? @unique
|
||||
/// UNGENUTZT: Pakete und Abos bekommen ihren Honig automatisch (nie cremig,
|
||||
/// neueste Ernte, genug Bestand — lib/sponsorship/honey-selection.ts). Die
|
||||
/// Spalte wird weder gelesen noch geschrieben und bleibt nur stehen, damit
|
||||
/// die laufende Produktion keine Migration braucht; Altwerte sind bedeutungslos.
|
||||
honeyProductId String?
|
||||
/// EINMALIG: Glaeser im Paket. ABO: Glaeser je Lieferung.
|
||||
honeyJars Int @default(0)
|
||||
/// EINMALIG: Honiganteil des Paketpreises je Glas (zum Honig-Steuersatz).
|
||||
honeyShareCentsPerJar Int @default(0)
|
||||
/// ABO: Honiganteil des Monatspreises (zum Honig-Steuersatz).
|
||||
honeyShareCentsPerMonth Int @default(0)
|
||||
/// Nur ABO.
|
||||
cycle SponsorshipCycle?
|
||||
/// Nur ABO: Hoechstzahl aktiver Abos (Kontingent); null = unbegrenzt.
|
||||
maxActiveSubscriptions Int?
|
||||
/// Nur ABO: Stripe-Produkt und der Preis, der priceCents abbildet. Bei einer
|
||||
/// Preisaenderung entsteht ein neuer Stripe-Preis; laufende Abos behalten
|
||||
/// ihren alten.
|
||||
stripeProductId String?
|
||||
stripePriceId String?
|
||||
stripePriceAmountCents Int?
|
||||
medalTier MedalTier @default(BRONZE)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
product Product? @relation("SponsorshipOfferProduct", fields: [productId], references: [id], onDelete: Restrict)
|
||||
honeyProduct Product? @relation("SponsorshipOfferHoney", fields: [honeyProductId], references: [id], onDelete: SetNull)
|
||||
sponsorships Sponsorship[]
|
||||
subscriptions SponsorshipSubscription[]
|
||||
harvestWindows HarvestWindow[]
|
||||
|
||||
@@index([kind, isActive, sortOrder])
|
||||
@@index([honeyProductId])
|
||||
@@map("sponsorship_offers")
|
||||
}
|
||||
|
||||
/// Eine gekaufte Patenschaft (eine Biene, ein Name, eine Urkunde).
|
||||
model Sponsorship {
|
||||
id String @id @default(cuid())
|
||||
/// WH-P-JJJJ-NNNNN, fortlaufend ueber SponsorshipCounter.
|
||||
number String @unique
|
||||
ownerId String
|
||||
offerId String
|
||||
/// Einmalkauf: die Hauptposition der Bestellung. Eindeutig — das ist der
|
||||
/// Idempotenzschluessel gegen doppelt zugestellte Webhooks.
|
||||
orderItemId String? @unique
|
||||
/// Abo: das Abo, aus dem die Patenschaft entstand.
|
||||
subscriptionId String? @unique
|
||||
locale String @default("de")
|
||||
startDate DateTime @db.Date
|
||||
/// Leer bei laufendem Abo.
|
||||
endDate DateTime? @db.Date
|
||||
status SponsorshipStatus @default(AUSSTEHEND)
|
||||
/// Nummer der aktuellen Revision; 0 = noch keine Urkunde erzeugt.
|
||||
currentRevision Int @default(0)
|
||||
pdfAttempts Int @default(0)
|
||||
nextAttemptAt DateTime?
|
||||
lastError String? @db.Text
|
||||
mailSentAt DateTime?
|
||||
printedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
owner Customer @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
offer SponsorshipOffer @relation(fields: [offerId], references: [id], onDelete: Restrict)
|
||||
orderItem OrderItem? @relation(fields: [orderItemId], references: [id], onDelete: SetNull)
|
||||
subscription SponsorshipSubscription? @relation(fields: [subscriptionId], references: [id], onDelete: SetNull)
|
||||
revisions SponsorshipRevision[]
|
||||
transfers SponsorshipTransfer[]
|
||||
|
||||
@@index([ownerId])
|
||||
@@index([status, nextAttemptAt])
|
||||
@@index([offerId])
|
||||
@@map("sponsorships")
|
||||
}
|
||||
|
||||
/// Unveraenderlicher Stand einer Urkunde. Korrekturen und das Abo-Ende
|
||||
/// erzeugen neue Revisionen; alte bleiben samt PDF erhalten.
|
||||
model SponsorshipRevision {
|
||||
id String @id @default(cuid())
|
||||
sponsorshipId String
|
||||
revision Int
|
||||
/// Personalisierung wie bestaetigt (lib/certificate/schema.ts).
|
||||
personalization Json
|
||||
/// Laufzeitform (FIXED/OPEN/ENDED) mit Daten.
|
||||
term Json
|
||||
/// Aufgeloeste Textbausteine — Beleg dessen, was auf der Urkunde steht.
|
||||
text Json
|
||||
templateVersion String
|
||||
/// Relativ zu CERTIFICATE_DIR.
|
||||
pdfPath String
|
||||
pdfSha256 String
|
||||
/// Admin-Konto bei Korrekturen, null bei System-Revisionen.
|
||||
createdById String?
|
||||
/// Lesbarer Ersteller ("System" oder die Admin-Adresse) — bleibt lesbar,
|
||||
/// auch wenn das Admin-Konto spaeter geloescht wird.
|
||||
createdByLabel String
|
||||
reason String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
sponsorship Sponsorship @relation(fields: [sponsorshipId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([sponsorshipId, revision])
|
||||
@@map("sponsorship_revisions")
|
||||
}
|
||||
|
||||
/// Jahreszaehler der Patenschaftsnummern, Muster wie InvoiceCounter.
|
||||
model SponsorshipCounter {
|
||||
year Int @id
|
||||
lastNumber Int @default(0)
|
||||
|
||||
@@map("sponsorship_counters")
|
||||
}
|
||||
|
||||
/// Befristeter, einmal nutzbarer Link zur Uebertragung einer
|
||||
/// Einmal-Patenschaft an ein anderes Konto. Gespeichert wird nur der Hash.
|
||||
model SponsorshipTransfer {
|
||||
id String @id @default(cuid())
|
||||
sponsorshipId String
|
||||
tokenHash String @unique
|
||||
expiresAt DateTime
|
||||
createdById String
|
||||
claimedById String?
|
||||
claimedAt DateTime?
|
||||
revokedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
sponsorship Sponsorship @relation(fields: [sponsorshipId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([sponsorshipId])
|
||||
@@map("sponsorship_transfers")
|
||||
}
|
||||
|
||||
/// Abo-Patenschaft ueber Stripe Billing.
|
||||
model SponsorshipSubscription {
|
||||
id String @id @default(cuid())
|
||||
customerId String
|
||||
offerId String
|
||||
status SubscriptionStatus @default(AUSSTEHEND)
|
||||
/// Personalisierung beim Abschluss bestaetigt; daraus entsteht mit der
|
||||
/// ersten bezahlten Rechnung die Patenschaft.
|
||||
personalization Json
|
||||
locale String @default("de")
|
||||
stripeCheckoutSessionId String? @unique
|
||||
stripeSubscriptionId String? @unique
|
||||
startedAt DateTime?
|
||||
currentPeriodEnd DateTime?
|
||||
/// Gesetzt nach Kuendigung: Ende des bezahlten Zeitraums.
|
||||
cancelAt DateTime?
|
||||
endedAt DateTime?
|
||||
/// Beginn des Verzugs (fehlgeschlagene Zahlung oder Rueckbuchung).
|
||||
delinquentSince DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)
|
||||
offer SponsorshipOffer @relation(fields: [offerId], references: [id], onDelete: Restrict)
|
||||
payments SubscriptionPayment[]
|
||||
deliveries SubscriptionDelivery[]
|
||||
sponsorship Sponsorship?
|
||||
|
||||
@@index([customerId])
|
||||
@@index([offerId, status])
|
||||
@@map("sponsorship_subscriptions")
|
||||
}
|
||||
|
||||
/// Eine bezahlte Abo-Monatsrechnung von Stripe.
|
||||
model SubscriptionPayment {
|
||||
id String @id @default(cuid())
|
||||
subscriptionId String
|
||||
/// Idempotenzschluessel gegen doppelt zugestellte invoice.paid-Ereignisse.
|
||||
stripeInvoiceId String @unique
|
||||
stripePaymentIntentId String?
|
||||
paymentMethodType String?
|
||||
amountCents Int
|
||||
paidAt DateTime
|
||||
periodStart DateTime
|
||||
periodEnd DateTime
|
||||
/// Ab wann diese Zahlung fuer den Lieferanspruch zaehlt (SEPA-Neukunden-
|
||||
/// Frist, siehe lib/sponsorship-subscription/entitlement.ts).
|
||||
countsFrom DateTime
|
||||
/// Zurueckgebucht — zaehlt nie mehr fuer eine Lieferung.
|
||||
reversedAt DateTime?
|
||||
/// Lieferung, die diese Zahlung verbraucht hat.
|
||||
deliveryId String?
|
||||
/// Wabenhain-Bestellung samt Rechnung zu dieser Zahlung.
|
||||
orderId String? @unique
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
subscription SponsorshipSubscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade)
|
||||
delivery SubscriptionDelivery? @relation(fields: [deliveryId], references: [id], onDelete: SetNull)
|
||||
order Order? @relation(fields: [orderId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([subscriptionId, paidAt])
|
||||
@@map("subscription_payments")
|
||||
}
|
||||
|
||||
/// Eine Abo-Honiglieferung (0-€-Bestellung mit Honigpositionen).
|
||||
model SubscriptionDelivery {
|
||||
id String @id @default(cuid())
|
||||
subscriptionId String
|
||||
dueAt DateTime
|
||||
jars Int
|
||||
status DeliveryStatus
|
||||
orderId String? @unique
|
||||
note String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
subscription SponsorshipSubscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade)
|
||||
order Order? @relation(fields: [orderId], references: [id], onDelete: SetNull)
|
||||
payments SubscriptionPayment[]
|
||||
|
||||
@@index([subscriptionId, dueAt])
|
||||
@@map("subscription_deliveries")
|
||||
}
|
||||
|
||||
/// Erntefenster eines Abo-Angebots mit Zyklus ERNTE.
|
||||
model HarvestWindow {
|
||||
id String @id @default(cuid())
|
||||
offerId String
|
||||
startsOn DateTime @db.Date
|
||||
endsOn DateTime @db.Date
|
||||
/// Fuer Abos geplante Glaeser — werden reserviert, bevor sie in den
|
||||
/// Freiverkauf gehen.
|
||||
plannedJars Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
offer SponsorshipOffer @relation(fields: [offerId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([offerId, startsOn])
|
||||
@@map("harvest_windows")
|
||||
}
|
||||
|
||||
/// Treuestufe (Stammkunde nach bezahlten Bestellungen, Abo nach bezahlten
|
||||
/// Monaten). threshold null = VIP (nur ABO, nach der hoechsten Zahl).
|
||||
model LoyaltyLevel {
|
||||
id String @id @default(cuid())
|
||||
kind LoyaltyKind
|
||||
threshold Int?
|
||||
name String
|
||||
nameEn String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([kind, threshold])
|
||||
@@map("loyalty_levels")
|
||||
}
|
||||
+115
@@ -83,6 +83,121 @@ async function main() {
|
||||
"Siehe README, wie ein bestehendes Konto nachtraeglich zu ADMIN befoerdert wird."
|
||||
);
|
||||
}
|
||||
|
||||
await seedSponsorshipDefaults();
|
||||
}
|
||||
|
||||
/**
|
||||
* Startangebote der Bienenpatenschaft und Treuestufen — nur wenn es noch
|
||||
* keine gibt, und die Angebote INAKTIV: dieser Seed laeuft bei jedem
|
||||
* Containerstart auch in Produktion, und Preise, Honig und Rechtstexte muss
|
||||
* der Inhaber vor der Veroeffentlichung pruefen (Spec, "Geschaeftliche
|
||||
* Konfiguration"). Erst das Aktivieren im Admin macht /patenschaft sichtbar.
|
||||
*/
|
||||
async function seedSponsorshipDefaults(): Promise<void> {
|
||||
if ((await prisma.sponsorshipOffer.count()) === 0) {
|
||||
const packages = [
|
||||
{
|
||||
slug: "bienenfreund",
|
||||
name: "Bienenfreund",
|
||||
nameEn: "Bee Friend",
|
||||
priceCents: 1900,
|
||||
isPhysical: false,
|
||||
honeyJars: 0,
|
||||
medalTier: "BRONZE" as const,
|
||||
description: "Symbolische Namensgebung mit individuell gestalteter Urkunde als PDF.",
|
||||
descriptionEn: "Symbolic naming with an individually designed certificate as a PDF.",
|
||||
features: ["Symbolische Namensgebung", "Individuell gestaltete PDF-Urkunde", "Medaille und 3D-Ansicht im Kundenkonto", "Sicherer Download"],
|
||||
featuresEn: ["Symbolic naming", "Individually designed PDF certificate", "Medal and 3D view in your account", "Secure download"],
|
||||
},
|
||||
{
|
||||
slug: "honigfreund",
|
||||
name: "Honigfreund",
|
||||
nameEn: "Honey Friend",
|
||||
priceCents: 3900,
|
||||
isPhysical: true,
|
||||
honeyJars: 1,
|
||||
medalTier: "SILBER" as const,
|
||||
description: "Digitale Leistungen plus gedruckte Urkunde, ein Glas Wabenhain-Honig, Grußkarte und Geschenkverpackung.",
|
||||
descriptionEn: "Digital items plus a printed certificate, a jar of Wabenhain honey, a greeting card and gift wrapping.",
|
||||
features: ["Alle digitalen Leistungen", "Hochwertig gedruckte Urkunde", "1 × 500 g Wabenhain-Honig", "Grußkarte und Geschenkverpackung"],
|
||||
featuresEn: ["All digital items", "High-quality printed certificate", "1 × 500 g Wabenhain honey", "Greeting card and gift wrapping"],
|
||||
},
|
||||
{
|
||||
slug: "wabenfreund",
|
||||
name: "Wabenfreund",
|
||||
nameEn: "Comb Friend",
|
||||
priceCents: 5900,
|
||||
isPhysical: true,
|
||||
honeyJars: 3,
|
||||
medalTier: "GOLD" as const,
|
||||
description: "Digitale Leistungen plus gedruckte Urkunde, drei Gläser Wabenhain-Honig, Grußkarte und Geschenkverpackung.",
|
||||
descriptionEn: "Digital items plus a printed certificate, three jars of Wabenhain honey, a greeting card and gift wrapping.",
|
||||
features: ["Alle digitalen Leistungen", "Hochwertig gedruckte Urkunde", "3 × 500 g Wabenhain-Honig", "Grußkarte und Geschenkverpackung"],
|
||||
featuresEn: ["All digital items", "High-quality printed certificate", "3 × 500 g Wabenhain honey", "Greeting card and gift wrapping"],
|
||||
},
|
||||
];
|
||||
for (const [index, pkg] of packages.entries()) {
|
||||
// Honiganteil als Vorschlag (7 € je Glas) — der Inhaber prueft ihn mit
|
||||
// der Steuerberatung, bevor er das Angebot aktiviert.
|
||||
const honeyShareCentsPerJar = pkg.honeyJars > 0 ? 700 : 0;
|
||||
const product = await prisma.product.create({
|
||||
data: {
|
||||
slug: `patenschaft-${pkg.slug}`,
|
||||
name: `Bienenpatenschaft ${pkg.name}`,
|
||||
category: "PATENSCHAFT",
|
||||
description: pkg.description,
|
||||
weightGrams: 0,
|
||||
priceCents: pkg.priceCents - pkg.honeyJars * honeyShareCentsPerJar,
|
||||
pricePerKgCents: 0,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
await prisma.sponsorshipOffer.create({
|
||||
data: {
|
||||
slug: pkg.slug,
|
||||
kind: "EINMALIG",
|
||||
name: pkg.name,
|
||||
nameEn: pkg.nameEn,
|
||||
description: pkg.description,
|
||||
descriptionEn: pkg.descriptionEn,
|
||||
features: pkg.features,
|
||||
featuresEn: pkg.featuresEn,
|
||||
priceCents: pkg.priceCents,
|
||||
isActive: false,
|
||||
sortOrder: index,
|
||||
isPhysical: pkg.isPhysical,
|
||||
productId: product.id,
|
||||
honeyJars: pkg.honeyJars,
|
||||
honeyShareCentsPerJar,
|
||||
medalTier: pkg.medalTier,
|
||||
},
|
||||
});
|
||||
}
|
||||
console.log("Bienenpatenschaft: drei Startangebote angelegt (inaktiv, bitte im Admin pruefen und aktivieren).");
|
||||
}
|
||||
|
||||
if ((await prisma.loyaltyLevel.count()) === 0) {
|
||||
const regular = [
|
||||
{ threshold: 2, name: "Blütenbesuch", nameEn: "Blossom Visitor" },
|
||||
{ threshold: 5, name: "Wabenbau", nameEn: "Comb Builder" },
|
||||
{ threshold: 10, name: "Honigschatz", nameEn: "Honey Treasure" },
|
||||
{ threshold: 25, name: "Goldwabe", nameEn: "Golden Comb" },
|
||||
];
|
||||
const subscription = Array.from({ length: 24 }, (_, i) => ({
|
||||
threshold: i + 1,
|
||||
name: `Stufe ${i + 1}`,
|
||||
nameEn: `Level ${i + 1}`,
|
||||
}));
|
||||
await prisma.loyaltyLevel.createMany({
|
||||
data: [
|
||||
...regular.map((level) => ({ kind: "STAMMKUNDE" as const, ...level })),
|
||||
...subscription.map((level) => ({ kind: "ABO" as const, ...level })),
|
||||
{ kind: "ABO" as const, threshold: null, name: "VIP", nameEn: "VIP" },
|
||||
],
|
||||
});
|
||||
console.log("Treuestufen angelegt (Stammkunde 2/5/10/25, Abo 1–24 und VIP).");
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Bestandsabgleich mit ApiCore als Sicherheitsnetz unter den Sofort-Wegen.
|
||||
*
|
||||
* Normalerweise geht eine Buchung direkt nach der Zahlung/Stornierung an
|
||||
* ApiCore, und eine Entnahme in ApiCore kommt per Webhook sofort an. Dieser
|
||||
* Lauf faengt alles ab, was dabei liegen blieb: ApiCore war nicht erreichbar,
|
||||
* ein Webhook ging verloren, der Server wurde mitten im Senden neu gestartet.
|
||||
*
|
||||
* 1. offene Buchungen senden (mit Wartezeiten 1, 5, 15, 60 Minuten),
|
||||
* 2. ALLE verknuepften Produkte gegen ApiCore abgleichen.
|
||||
*
|
||||
* Aufruf: pnpm stock:apicore-sync
|
||||
* Im Cluster laeuft er alle 10 Minuten als CronJob (k8s/07-backup-cronjob.yaml).
|
||||
*
|
||||
* Exit-Code 1, wenn ApiCore nicht erreichbar war oder Buchungen abgelehnt
|
||||
* hat: dann soll der Job als fehlgeschlagen sichtbar sein, nicht nur in
|
||||
* einer Logzeile verschwinden.
|
||||
*/
|
||||
import { prisma } from "../src/lib/prisma";
|
||||
import { deliverPendingStockEvents } from "../src/lib/apicore-stock/delivery";
|
||||
import { reconcileApiCoreStock } from "../src/lib/apicore-stock/reconcile";
|
||||
|
||||
async function main(): Promise<number> {
|
||||
const delivered = await deliverPendingStockEvents();
|
||||
console.log(
|
||||
`[apicore-stock] Buchungen: ${delivered.sent} bestaetigt, ${delivered.rejected} abgelehnt, ${delivered.failed} nicht zugestellt${delivered.error ? ` (${delivered.error})` : ""}`
|
||||
);
|
||||
const reconciled = await reconcileApiCoreStock();
|
||||
console.log(
|
||||
`[apicore-stock] Abgleich: ${reconciled.updated} Produkte aktualisiert, ${reconciled.missing} in ApiCore nicht gefunden${reconciled.error ? ` (${reconciled.error})` : ""}`
|
||||
);
|
||||
const failed = delivered.failed > 0 || delivered.rejected > 0 || Boolean(reconciled.error);
|
||||
return failed ? 1 : 0;
|
||||
}
|
||||
|
||||
main()
|
||||
.then(async (code) => {
|
||||
await prisma.$disconnect();
|
||||
process.exit(code);
|
||||
})
|
||||
.catch(async (error: unknown) => {
|
||||
console.error("[apicore-stock] Lauf abgebrochen:", error);
|
||||
await prisma.$disconnect();
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prüft im CI-Job die Grenzen des isolierten Runners (Label ci-isolated,
|
||||
# Runner-Doku im VyCept-Repo, docs/BETRIEB.md 11b; Kopie von dort). Läuft als erster Schritt jedes Prüf-Jobs, damit jeder
|
||||
# Runner bei jedem Lauf geprüft wird. Schlägt fehl, wenn der Job mehr darf als
|
||||
# vorgesehen – oder wenn die Prüfung selbst nichts aussagen würde.
|
||||
set -euo pipefail
|
||||
|
||||
fail() {
|
||||
echo "Runner-Isolation verletzt: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
reachable() {
|
||||
timeout 5 bash -c "exec 3<>/dev/tcp/$1/$2" 2>/dev/null
|
||||
}
|
||||
|
||||
# Namen mit Wiederholung auflösen: Das DNS des Job-Netzes antwortet unter Last
|
||||
# gelegentlich erst beim zweiten Versuch.
|
||||
resolve() {
|
||||
local address=""
|
||||
for _ in 1 2 3 4 5; do
|
||||
address=$(getent hosts "$1" | awk '{ print $1; exit }' || true)
|
||||
if [ -n "$address" ]; then echo "$address"; return 0; fi
|
||||
sleep 2
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# 1. Kein Zugang zum Docker-Daemon über den Socket.
|
||||
[ -z "${DOCKER_HOST:-}" ] || fail "DOCKER_HOST ist gesetzt ($DOCKER_HOST)"
|
||||
for socket in /var/run/docker.sock /run/docker.sock; do
|
||||
[ ! -e "$socket" ] || fail "Docker-Socket $socket ist sichtbar"
|
||||
done
|
||||
|
||||
# 2. Kein Zugang zur Docker-API des Daemons im Runner-Pod (Gateway des Job-Netzes):
|
||||
# 2375 (ohne TLS) zu, 2376 nur mit Client-Zertifikat, das der Job nicht hat.
|
||||
gateway_hex=$(awk '$2 == "00000000" { print $3; exit }' /proc/net/route)
|
||||
[ -n "$gateway_hex" ] || fail "kein Standard-Gateway gefunden – Prüfung wäre wirkungslos"
|
||||
gateway=$(printf '%d.%d.%d.%d' "0x${gateway_hex:6:2}" "0x${gateway_hex:4:2}" "0x${gateway_hex:2:2}" "0x${gateway_hex:0:2}")
|
||||
if reachable "$gateway" 2375; then fail "Docker-API ohne TLS am Gateway $gateway:2375"; fi
|
||||
if curl -sk --max-time 5 "https://$gateway:2376/version" >/dev/null 2>&1; then
|
||||
fail "Docker-API am Gateway $gateway:2376 ohne Client-Zertifikat nutzbar"
|
||||
fi
|
||||
|
||||
# 3. Kein Clusternetz: Kubernetes-API (Service und Knoten) und fremde Namespaces.
|
||||
for target in 10.43.0.1:443 10.50.1.51:6443 10.50.1.52:6443 10.50.1.53:6443; do
|
||||
if reachable "${target%:*}" "${target##*:}"; then fail "$target ist erreichbar"; fi
|
||||
done
|
||||
resolve kubernetes.default.svc.cluster.local >/dev/null || fail "Clusternamen nicht auflösbar – Prüfung wäre wirkungslos"
|
||||
# Fremder Namespace (VyCept-Datenbank) und eigener Namespace (Gitea-Datenbank).
|
||||
for target in vycept-postgres.vycept.svc.cluster.local:5432 gitea-postgres.gitea.svc.cluster.local:5432; do
|
||||
host=${target%:*}
|
||||
address=$(resolve "$host") || fail "$host nicht auflösbar – Prüfung wäre wirkungslos"
|
||||
if reachable "$address" "${target##*:}"; then fail "$host ($address) ist erreichbar"; fi
|
||||
done
|
||||
|
||||
# 4. Internet bleibt erreichbar (npm, GitHub, Images).
|
||||
reachable registry.npmjs.org 443 || fail "Internet (registry.npmjs.org) nicht erreichbar"
|
||||
|
||||
echo "Runner-Isolation in Ordnung (Gateway $gateway, kein Socket, kein Clusternetz)"
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Rendert Beispiel-Urkunden fuer die Sichtpruefung (Spec "Visuelle
|
||||
* Kontrolle"): je Vorlage und Datensatz ein PNG mit 300 dpi (2480 px breit)
|
||||
* und die Druck-PDF, dazu eine Vorschau mit Wasserzeichen.
|
||||
*
|
||||
* Aufruf: pnpm tsx scripts/render-certificate-samples.ts <ausgabeordner> [--templates=a@1,b@1] [--samples=standard,lang]
|
||||
*
|
||||
* Schreibt nur in den angegebenen Ordner; keine Datenbank, keine Uploads.
|
||||
*/
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { layoutCertificate } from "../src/lib/certificate/layout";
|
||||
import { renderCertificateImage } from "../src/lib/certificate/render-image";
|
||||
import { certificatePdfTitle, renderCertificatePdf } from "../src/lib/certificate/render-pdf";
|
||||
import { fixedTermFor, type CertificateTerm, type Personalization } from "../src/lib/certificate/schema";
|
||||
import { listTemplateVersions } from "../src/lib/certificate/templates";
|
||||
import { composeCertificateText } from "../src/lib/certificate/text";
|
||||
import type { Locale } from "../src/i18n/config";
|
||||
|
||||
interface Sample {
|
||||
personalization: Personalization;
|
||||
locale: Locale;
|
||||
term: CertificateTerm;
|
||||
number: string;
|
||||
}
|
||||
|
||||
const START = "2026-12-24";
|
||||
const NUMBER = "WH-P-2026-00042";
|
||||
|
||||
function sample(personalization: Personalization, extra: Partial<Omit<Sample, "personalization">> = {}): Sample {
|
||||
return { personalization, locale: "de", term: fixedTermFor(personalization.startDate), number: NUMBER, ...extra };
|
||||
}
|
||||
|
||||
const MAX_DEDICATION =
|
||||
"Für die Frau, die jeden Garten zum Summen bringt.\nMöge diese kleine Biene dich an all die sonnigen Tage erinnern, die wir gemeinsam zwischen Lavendel und Linden verbracht haben.\n\nIn Liebe und Dankbarkeit,\nAnna, Ben und Carla";
|
||||
|
||||
const SAMPLES: Record<string, Sample> = {
|
||||
// Identische Beispieldaten fuer den Vergleich der drei Varianten.
|
||||
standard: sample({
|
||||
beeName: "Summsi",
|
||||
recipientName: "Marie-Luise Schmidt",
|
||||
giverNames: "Anna und Ben",
|
||||
dedication: "Für die beste Gärtnerin der Welt –\nmögen deine Blüten immer summen.",
|
||||
occasion: "WEIHNACHTEN",
|
||||
startDate: START,
|
||||
}),
|
||||
kurz: sample({ beeName: "Bo", recipientName: "Li", occasion: "SELBST", startDate: START }),
|
||||
lang: sample({
|
||||
beeName: "Hildegard-Wilhelmine",
|
||||
recipientName: "Marie-Luise Schmidt-Habermann von Hohenlinden",
|
||||
giverNames: "Anna, Ben, Carla und Familie Özdemir aus dem Nachbarhaus",
|
||||
dedication: MAX_DEDICATION,
|
||||
occasion: "GEBURTSTAG",
|
||||
startDate: START,
|
||||
}),
|
||||
// An den Eingabelimits (CERTIFICATE_LIMITS): 23/24, 57/60, 80/80, 277/280 Zeichen, 5 Umbrueche.
|
||||
maximal: sample(
|
||||
{
|
||||
beeName: "Wilhelmine-Mümmelwunder",
|
||||
recipientName: "Marie-Luise Schmidt-Habermann von Hohenlinden-Württemberg",
|
||||
giverNames: "Anna, Ben, Carla, Dominik, Emilia, Friedrich und die ganze Familie Özdemir-Lange",
|
||||
dedication: [
|
||||
"Möge diese kleine Biene dich an sonnige Tage im Garten erinnern,",
|
||||
"an Lindenblüten, Lavendel und an den Duft von frischem Honigbrot,",
|
||||
"an lange Abende auf der Bank vor dem Haus und an alle Gespräche.",
|
||||
"Danke für alles, was du für uns getan hast, jeden einzelnen Tag!",
|
||||
"Alles Liebe",
|
||||
"Anna",
|
||||
].join("\n"),
|
||||
occasion: "DANKESCHOEN",
|
||||
startDate: START,
|
||||
},
|
||||
{ locale: "de" }
|
||||
),
|
||||
sonderzeichen: sample(
|
||||
{
|
||||
beeName: "Zoë",
|
||||
recipientName: "Jürgen Weiß & Ñúñez O’Brien",
|
||||
giverNames: "Anna, Ben, Carla und Familie Özdemir",
|
||||
occasion: "DANKESCHOEN",
|
||||
startDate: START,
|
||||
},
|
||||
{ term: { kind: "OPEN", start: START } }
|
||||
),
|
||||
englisch: sample(
|
||||
{
|
||||
beeName: "Honeybell",
|
||||
recipientName: "Charlotte Ashworth-Blake",
|
||||
giverNames: "Oliver and Grace",
|
||||
dedication: "For the kindest gardener we know —\nmay your days always hum with sunshine.",
|
||||
occasion: "GEBURTSTAG",
|
||||
startDate: START,
|
||||
},
|
||||
{ locale: "en" }
|
||||
),
|
||||
beendet: sample(
|
||||
{ beeName: "Lindenblüte", recipientName: "Familie Wagner", occasion: "GESCHENK", startDate: START },
|
||||
{ term: { kind: "ENDED", start: START, end: "2027-05-31" } }
|
||||
),
|
||||
};
|
||||
|
||||
function parseList(flag: string): string[] | null {
|
||||
const arg = process.argv.find((value) => value.startsWith(`--${flag}=`));
|
||||
return arg ? arg.slice(flag.length + 3).split(",").filter(Boolean) : null;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const outDir = process.argv[2];
|
||||
if (!outDir || outDir.startsWith("--")) {
|
||||
throw new Error("Aufruf: pnpm tsx scripts/render-certificate-samples.ts <ausgabeordner> [--templates=…] [--samples=…]");
|
||||
}
|
||||
await mkdir(outDir, { recursive: true });
|
||||
const templates = parseList("templates") ?? listTemplateVersions();
|
||||
const samples = parseList("samples") ?? Object.keys(SAMPLES);
|
||||
|
||||
for (const version of templates) {
|
||||
for (const name of samples) {
|
||||
const data = SAMPLES[name];
|
||||
if (!data) throw new Error(`Unbekannter Datensatz "${name}".`);
|
||||
const text = composeCertificateText(data);
|
||||
const layout = layoutCertificate(text, version);
|
||||
const base = path.join(outDir, `${version.replace("@", "-v")}_${name}`);
|
||||
const [png, pdf] = await Promise.all([
|
||||
renderCertificateImage(layout, { widthPx: 2480, format: "png" }),
|
||||
renderCertificatePdf(layout, { title: certificatePdfTitle(text), creationDate: new Date(`${START}T00:00:00Z`) }),
|
||||
]);
|
||||
await writeFile(`${base}.png`, png);
|
||||
await writeFile(`${base}.pdf`, pdf);
|
||||
if (name === "standard") {
|
||||
const preview = await renderCertificateImage(layout, { widthPx: 1240, format: "png", watermark: data.locale });
|
||||
await writeFile(`${base}_vorschau.png`, preview);
|
||||
}
|
||||
process.stdout.write(`${base}.png / .pdf\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
process.stderr.write(`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Rendert Beispiel-Medaillen aller Arten und Stufen als PNG (und SVG) zur
|
||||
* Sichtpruefung. Aufruf: pnpm tsx scripts/render-medal-samples.ts <Zielordner> [Groesse]
|
||||
*/
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { medalReliefSvg, renderMedalPng, renderMedalSvg, type MedalInput } from "../src/lib/medals";
|
||||
|
||||
const SAMPLES: Array<[string, MedalInput]> = [
|
||||
["patenschaft-bronze", { kind: "PATENSCHAFT", tier: "BRONZE", beeName: "Summsi", year: 2026, number: "WH-P-2026-00042" }],
|
||||
["patenschaft-silber", { kind: "PATENSCHAFT", tier: "SILBER", beeName: "Zoë", year: 2026, number: "WH-P-2026-00043" }],
|
||||
["patenschaft-gold", { kind: "PATENSCHAFT", tier: "GOLD", beeName: "Ñúñez", year: 2026, number: "WH-P-2026-00044" }],
|
||||
["patenschaft-abo", { kind: "PATENSCHAFT", tier: "ABO", beeName: "Hildegard", year: 2026, number: "WH-P-2026-00045" }],
|
||||
["patenschaft-lang-24", { kind: "PATENSCHAFT", tier: "BRONZE", beeName: "Wilhelmine Augusta Maxi", year: 2026, number: "WH-P-2026-00046" }],
|
||||
["patenschaft-lang-ohne-umbruch", { kind: "PATENSCHAFT", tier: "GOLD", beeName: "Bienenköniginwunderbarer", year: 2026, number: "WH-P-2026-00047" }],
|
||||
["patenschaft-abo-lang", { kind: "PATENSCHAFT", tier: "ABO", beeName: "Wilhelmine-Augusta Maxi", year: 2026, number: "WH-P-2026-00048" }],
|
||||
["stammkunde-1", { kind: "STAMMKUNDE", level: 1, name: "Blütenbesuch" }],
|
||||
["stammkunde-2", { kind: "STAMMKUNDE", level: 2, name: "Wabenbau" }],
|
||||
["stammkunde-3", { kind: "STAMMKUNDE", level: 3, name: "Honigschatz" }],
|
||||
["stammkunde-4", { kind: "STAMMKUNDE", level: 4, name: "Goldwabe" }],
|
||||
["abo-1", { kind: "ABO", months: 1 }],
|
||||
["abo-12", { kind: "ABO", months: 12 }],
|
||||
["abo-24", { kind: "ABO", months: 24 }],
|
||||
["vip", { kind: "VIP" }],
|
||||
];
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const target = process.argv[2];
|
||||
if (!target) throw new Error("Zielordner fehlt: pnpm tsx scripts/render-medal-samples.ts <Zielordner> [Groesse]");
|
||||
const size = Number(process.argv[3] ?? 1024);
|
||||
await mkdir(target, { recursive: true });
|
||||
for (const [name, input] of SAMPLES) {
|
||||
await writeFile(path.join(target, `${name}.png`), await renderMedalPng(input, size));
|
||||
await writeFile(path.join(target, `${name}.svg`), renderMedalSvg(input));
|
||||
if (name === "patenschaft-gold") await writeFile(path.join(target, `${name}-relief.svg`), medalReliefSvg(input));
|
||||
}
|
||||
process.stdout.write(`${SAMPLES.length} Medaillen in ${target}\n`);
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Ersteinrichtung der Bienenpatenschaft in einer bestehenden Installation.
|
||||
*
|
||||
* Wiederholbar: legt nur an, was fehlt, und aendert nie ein Angebot, das der
|
||||
* Inhaber schon bearbeitet hat (Felder werden nur gesetzt, wenn sie leer sind).
|
||||
*
|
||||
* - legt die beiden Abo-Angebote INAKTIV an (Testpreise, im Admin pruefen),
|
||||
* - legt fuer jedes Abo-Angebot Stripe-Produkt, Monatspreis und
|
||||
* Traegerprodukt an (syncOfferStripePrice).
|
||||
*
|
||||
* Einen Honig verknuepft das Skript nicht mehr (frueher --honey=<slug>):
|
||||
* Pakete und Abos bekommen ihren Honig automatisch — nie cremig, neueste
|
||||
* Ernte, genug Bestand (lib/sponsorship/honey-selection.ts). Die Spalte
|
||||
* honeyProductId bleibt ungenutzt im Schema; der Probelauf zeigt zur
|
||||
* Kontrolle, welchen Honig die Regel gerade waehlen wuerde.
|
||||
*
|
||||
* Aufruf (Werkzeug-Image, Umgebung wie die App):
|
||||
* tsx scripts/sponsorship-bootstrap.ts (Probelauf)
|
||||
* tsx scripts/sponsorship-bootstrap.ts --apply (ausfuehren)
|
||||
*/
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { syncOfferStripePrice } from "@/lib/sponsorship-subscription/stripe-prices";
|
||||
import { loadHoneyCandidates } from "@/lib/sponsorship/honey-candidates";
|
||||
import { honeyLabel, pickHoneyProduct } from "@/lib/sponsorship/honey-selection";
|
||||
|
||||
interface AboTemplate {
|
||||
slug: string;
|
||||
name: string;
|
||||
nameEn: string;
|
||||
description: string;
|
||||
descriptionEn: string;
|
||||
features: string[];
|
||||
featuresEn: string[];
|
||||
priceCents: number;
|
||||
honeyJars: number;
|
||||
honeyShareCentsPerMonth: number;
|
||||
cycle: "VIERTELJAEHRLICH" | "ERNTE";
|
||||
maxActiveSubscriptions: number;
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
// Kurze Namen: die Verkaufsseite zeigt sie unter "Im Abo", Stripe und die
|
||||
// Rechnung als "Bienenpatenschaft-Abo <Name>".
|
||||
// Testpreise — vor der Aktivierung kaufmaennisch pruefen (Spec, "Geschaeftliche
|
||||
// Konfiguration"). Honiganteil je Monat = Glaeser je Lieferung × 7 € ÷ Monate
|
||||
// je Lieferung, zum Honig-Steuersatz.
|
||||
const ABO_TEMPLATES: AboTemplate[] = [
|
||||
{
|
||||
slug: "abo-vierteljaehrlich",
|
||||
name: "Vierteljährlich",
|
||||
nameEn: "Quarterly",
|
||||
description: "Monatlich zahlen, alle drei bezahlten Monate zwei Gläser Wabenhain-Honig. Versand inklusive, monatlich kündbar.",
|
||||
descriptionEn: "Pay monthly, two jars of Wabenhain honey after every three paid months. Shipping included, cancel monthly.",
|
||||
features: ["Symbolische Namensgebung mit Urkunde", "2 × 500 g Honig nach jeweils 3 bezahlten Monaten", "Versand inklusive", "Monatlich kündbar"],
|
||||
featuresEn: ["Symbolic naming with certificate", "2 × 500 g honey after every 3 paid months", "Shipping included", "Cancel monthly"],
|
||||
priceCents: 1290,
|
||||
honeyJars: 2,
|
||||
honeyShareCentsPerMonth: 467,
|
||||
cycle: "VIERTELJAEHRLICH",
|
||||
maxActiveSubscriptions: 20,
|
||||
sortOrder: 10,
|
||||
},
|
||||
{
|
||||
slug: "abo-ernte",
|
||||
name: "Nach der Ernte",
|
||||
nameEn: "After the harvest",
|
||||
description: "Monatlich zahlen, Honig frisch nach der Ernte: drei Gläser, sobald seit der letzten Lieferung sechs Monate bezahlt sind. Versand inklusive, monatlich kündbar.",
|
||||
descriptionEn: "Pay monthly, honey fresh after the harvest: three jars once six months have been paid since the last delivery. Shipping included, cancel monthly.",
|
||||
features: ["Symbolische Namensgebung mit Urkunde", "3 × 500 g Honig im Erntefenster", "Versand inklusive", "Monatlich kündbar"],
|
||||
featuresEn: ["Symbolic naming with certificate", "3 × 500 g honey in the harvest window", "Shipping included", "Cancel monthly"],
|
||||
priceCents: 990,
|
||||
honeyJars: 3,
|
||||
honeyShareCentsPerMonth: 350,
|
||||
cycle: "ERNTE",
|
||||
maxActiveSubscriptions: 10,
|
||||
sortOrder: 11,
|
||||
},
|
||||
];
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const apply = process.argv.includes("--apply");
|
||||
const honey = pickHoneyProduct(await loadHoneyCandidates(), 1);
|
||||
console.log(
|
||||
`${apply ? "AUSFUEHREN" : "PROBELAUF"} — Honig automatisch, derzeit: ${honey ? honeyLabel(honey) : "kein nicht-cremiger Honig mit freiem Bestand"}`
|
||||
);
|
||||
|
||||
for (const template of ABO_TEMPLATES) {
|
||||
const existing = await prisma.sponsorshipOffer.findUnique({ where: { slug: template.slug }, select: { id: true, stripePriceId: true } });
|
||||
if (existing) {
|
||||
console.log(` Abo ${template.slug}: vorhanden${existing.stripePriceId ? "" : ", Stripe-Preis fehlt"}`);
|
||||
if (apply && !existing.stripePriceId) await syncOfferStripePrice(existing.id);
|
||||
continue;
|
||||
}
|
||||
console.log(` Abo ${template.slug}: anlegen (inaktiv, ${(template.priceCents / 100).toFixed(2)} €/Monat) + Stripe-Preis`);
|
||||
if (!apply) continue;
|
||||
const created = await prisma.sponsorshipOffer.create({
|
||||
data: {
|
||||
...template,
|
||||
kind: "ABO",
|
||||
isActive: false,
|
||||
isPhysical: true,
|
||||
medalTier: "ABO",
|
||||
},
|
||||
});
|
||||
await syncOfferStripePrice(created.id);
|
||||
}
|
||||
|
||||
const offers = await prisma.sponsorshipOffer.findMany({
|
||||
orderBy: { sortOrder: "asc" },
|
||||
select: { slug: true, kind: true, isActive: true, priceCents: true, honeyJars: true, stripePriceId: true, productId: true },
|
||||
});
|
||||
console.table(offers);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* Stripe-Einrichtung fuer das Abo der Bienenpatenschaft (Spec
|
||||
* "Stripe-Einrichtung", docs/EINRICHTUNG.md).
|
||||
*
|
||||
* Wiederholbar und ohne Geheimnisse im Code: liest STRIPE_SECRET_KEY aus der
|
||||
* Umgebung (.env), vergleicht den Ist-Stand mit dem Soll und zeigt, was es
|
||||
* aendern wuerde. Ohne --apply wird NICHTS geschrieben.
|
||||
*
|
||||
* pnpm tsx scripts/stripe-setup.ts # Probelauf (Standard)
|
||||
* pnpm tsx scripts/stripe-setup.ts --apply # Aenderungen schreiben
|
||||
* pnpm tsx scripts/stripe-setup.ts --base-url=https://wabenhain.com
|
||||
*
|
||||
* Gegen ein Livekonto (sk_live_/rk_live_) schreibt es nur mit dem
|
||||
* zusaetzlichen Schalter --live-ok — erst nach ausdruecklicher Freigabe des
|
||||
* Inhabers.
|
||||
*
|
||||
* Was es einrichtet:
|
||||
* 1. Webhook-Endpunkt <BASE_URL>/api/checkout/webhook mit allen Ereignissen
|
||||
* (die bestehenden sechs plus die Abo-Ereignisse). Bestehende Ereignisse
|
||||
* bleiben, es wird nur ergaenzt.
|
||||
* 2. Kundenportal-Konfiguration, die NUR das Aendern der Zahlungsart erlaubt
|
||||
* (keine Kuendigung, kein Tarifwechsel, keine Kundendaten, keine
|
||||
* Stripe-Rechnungen). Die App findet sie ueber ihre Metadaten.
|
||||
* Was nur im Dashboard geht, gibt es am Ende als Checkliste aus.
|
||||
*/
|
||||
import "dotenv/config";
|
||||
import Stripe from "stripe";
|
||||
|
||||
const REQUIRED_EVENTS = [
|
||||
// bestehend (Einmalbestellungen)
|
||||
"checkout.session.completed",
|
||||
"checkout.session.async_payment_succeeded",
|
||||
"checkout.session.async_payment_failed",
|
||||
"checkout.session.expired",
|
||||
"charge.refunded",
|
||||
"charge.dispute.created",
|
||||
// Abo
|
||||
"customer.subscription.created",
|
||||
"customer.subscription.updated",
|
||||
"customer.subscription.deleted",
|
||||
"invoice.paid",
|
||||
"invoice.payment_failed",
|
||||
"charge.dispute.closed",
|
||||
] as const satisfies readonly Stripe.WebhookEndpointCreateParams.EnabledEvent[];
|
||||
|
||||
/** Muss zu PORTAL_METADATA_VALUE in src/lib/sponsorship-subscription/cancellation.ts passen. */
|
||||
const PORTAL_METADATA = { wabenhain: "abo-zahlungsart" } as const;
|
||||
|
||||
const PORTAL_FEATURES = {
|
||||
payment_method_update: { enabled: true },
|
||||
subscription_cancel: { enabled: false },
|
||||
subscription_update: { enabled: false },
|
||||
customer_update: { enabled: false },
|
||||
invoice_history: { enabled: false },
|
||||
} as const;
|
||||
|
||||
interface Options {
|
||||
apply: boolean;
|
||||
liveOk: boolean;
|
||||
baseUrl: string;
|
||||
}
|
||||
|
||||
function parseOptions(argv: string[]): Options {
|
||||
const baseArg = argv.find((arg) => arg.startsWith("--base-url="))?.slice("--base-url=".length);
|
||||
const baseUrl = (baseArg || process.env.NEXT_PUBLIC_SITE_URL || "https://wabenhain.com").replace(/\/+$/, "");
|
||||
return { apply: argv.includes("--apply"), liveOk: argv.includes("--live-ok"), baseUrl };
|
||||
}
|
||||
|
||||
function log(line: string): void {
|
||||
process.stdout.write(`${line}\n`);
|
||||
}
|
||||
|
||||
async function ensureWebhook(stripe: Stripe, options: Options): Promise<void> {
|
||||
const url = `${options.baseUrl}/api/checkout/webhook`;
|
||||
const endpoints = await stripe.webhookEndpoints.list({ limit: 100 });
|
||||
const existing = endpoints.data.find((endpoint) => endpoint.url === url);
|
||||
|
||||
if (!existing) {
|
||||
log(`Webhook: kein Endpunkt fuer ${url} — ${options.apply ? "wird angelegt" : "wuerde angelegt"} mit ${REQUIRED_EVENTS.length} Ereignissen.`);
|
||||
if (!options.apply) return;
|
||||
const created = await stripe.webhookEndpoints.create({
|
||||
url,
|
||||
enabled_events: [...REQUIRED_EVENTS],
|
||||
description: "Wabenhain Shop (Bestellungen und Abos)",
|
||||
});
|
||||
log(` angelegt: ${created.id}. Das Signatur-Geheimnis steht NUR in dieser Antwort und im Dashboard:`);
|
||||
log(" im Dashboard unter Entwickler → Webhooks → Endpunkt → Signaturgeheimnis anzeigen, als STRIPE_WEBHOOK_SECRET setzen.");
|
||||
return;
|
||||
}
|
||||
|
||||
const enabled = new Set<string>(existing.enabled_events);
|
||||
if (enabled.has("*")) {
|
||||
log(`Webhook ${existing.id}: empfaengt alle Ereignisse ("*") — nichts zu tun.`);
|
||||
return;
|
||||
}
|
||||
const missing = REQUIRED_EVENTS.filter((event) => !enabled.has(event));
|
||||
if (missing.length === 0) {
|
||||
log(`Webhook ${existing.id}: alle ${REQUIRED_EVENTS.length} Ereignisse abonniert — nichts zu tun.`);
|
||||
return;
|
||||
}
|
||||
log(`Webhook ${existing.id}: ${missing.length} Ereignisse fehlen — ${options.apply ? "werden ergaenzt" : "wuerden ergaenzt"}:`);
|
||||
for (const event of missing) log(` + ${event}`);
|
||||
if (existing.status !== "enabled") log(` Hinweis: Endpunkt ist "${existing.status}".`);
|
||||
if (!options.apply) return;
|
||||
await stripe.webhookEndpoints.update(existing.id, {
|
||||
enabled_events: [...existing.enabled_events, ...missing] as Stripe.WebhookEndpointUpdateParams.EnabledEvent[],
|
||||
});
|
||||
log(" ergaenzt.");
|
||||
}
|
||||
|
||||
function portalDeviations(config: Stripe.BillingPortal.Configuration): string[] {
|
||||
const features = config.features;
|
||||
const actual: Record<keyof typeof PORTAL_FEATURES, boolean> = {
|
||||
payment_method_update: features.payment_method_update.enabled,
|
||||
subscription_cancel: features.subscription_cancel.enabled,
|
||||
subscription_update: features.subscription_update.enabled,
|
||||
customer_update: features.customer_update.enabled,
|
||||
invoice_history: features.invoice_history.enabled,
|
||||
};
|
||||
return (Object.keys(PORTAL_FEATURES) as (keyof typeof PORTAL_FEATURES)[])
|
||||
.filter((key) => actual[key] !== PORTAL_FEATURES[key].enabled)
|
||||
.map((key) => `${key}: ${actual[key]} → ${PORTAL_FEATURES[key].enabled}`);
|
||||
}
|
||||
|
||||
async function ensurePortal(stripe: Stripe, options: Options): Promise<void> {
|
||||
const configs = await stripe.billingPortal.configurations.list({ active: true, limit: 100 });
|
||||
const existing = configs.data.find((config) => config.metadata?.wabenhain === PORTAL_METADATA.wabenhain);
|
||||
const defaultReturnUrl = `${options.baseUrl}/konto/patenschaft`;
|
||||
|
||||
if (!existing) {
|
||||
log(`Kundenportal: keine Wabenhain-Konfiguration — ${options.apply ? "wird angelegt" : "wuerde angelegt"} (nur Zahlungsart aendern).`);
|
||||
if (!options.apply) return;
|
||||
const created = await stripe.billingPortal.configurations.create({
|
||||
name: "Wabenhain Abo – nur Zahlungsart",
|
||||
features: PORTAL_FEATURES,
|
||||
default_return_url: defaultReturnUrl,
|
||||
metadata: PORTAL_METADATA,
|
||||
});
|
||||
log(` angelegt: ${created.id} (die App findet sie ueber die Metadaten; optional STRIPE_PORTAL_CONFIGURATION_ID=${created.id}).`);
|
||||
return;
|
||||
}
|
||||
|
||||
const deviations = portalDeviations(existing);
|
||||
if (deviations.length === 0) {
|
||||
log(`Kundenportal ${existing.id}: erlaubt nur das Aendern der Zahlungsart — nichts zu tun.`);
|
||||
return;
|
||||
}
|
||||
log(`Kundenportal ${existing.id}: weicht ab — ${options.apply ? "wird korrigiert" : "wuerde korrigiert"}:`);
|
||||
for (const deviation of deviations) log(` ~ ${deviation}`);
|
||||
if (!options.apply) return;
|
||||
await stripe.billingPortal.configurations.update(existing.id, { features: PORTAL_FEATURES, default_return_url: defaultReturnUrl });
|
||||
log(" korrigiert.");
|
||||
}
|
||||
|
||||
function printDashboardChecklist(): void {
|
||||
log("");
|
||||
log("Nur im Stripe-Dashboard einstellbar (siehe docs/EINRICHTUNG.md):");
|
||||
log(" [ ] Billing → Einstellungen → Abos und E-Mails → Fehlgeschlagene Zahlungen: Smart Retries an.");
|
||||
log(" [ ] … nach dem letzten erfolglosen Versuch: Abo kuendigen (nicht 'als unbezahlt markieren').");
|
||||
log(" [ ] … Kunden-E-Mails: Rechnungen/Belege fuer erfolgreiche Zahlungen, bevorstehende Verlaengerungen und");
|
||||
log(" fehlgeschlagene Zahlungen AUS — Wabenhain verschickt eigene Rechnungen und Mails.");
|
||||
log(" [ ] Einstellungen → Zahlungsmethoden: Karte, Apple Pay, Google Pay, SEPA-Lastschrift aktiv (Google Pay pruefen).");
|
||||
log(" [ ] Apple Pay / Google Pay im eingebetteten Checkout: Domain wabenhain.com unter Zahlungsmethoden-Domains registrieren.");
|
||||
log(" [ ] Stripe Tax nur mit aktiver Registrierung einschalten — sonst bleibt es aus (Preise sind Bruttopreise).");
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const options = parseOptions(process.argv.slice(2));
|
||||
const key = process.env.STRIPE_SECRET_KEY?.trim();
|
||||
if (!key) throw new Error("STRIPE_SECRET_KEY ist nicht gesetzt.");
|
||||
const live = /^(sk|rk)_live_/.test(key);
|
||||
if (live && options.apply && !options.liveOk) {
|
||||
throw new Error("Livekonto: --apply schreibt hier nur zusammen mit --live-ok (nach Freigabe des Inhabers).");
|
||||
}
|
||||
|
||||
log(`Stripe-Einrichtung (${live ? "LIVEMODUS" : "Testmodus"}, ${options.apply ? "SCHREIBT" : "Probelauf, schreibt nichts"})`);
|
||||
log(`Basis-URL: ${options.baseUrl}`);
|
||||
log("");
|
||||
const stripe = new Stripe(key);
|
||||
await ensureWebhook(stripe, options);
|
||||
await ensurePortal(stripe, options);
|
||||
printDashboardChecklist();
|
||||
if (!options.apply) log("\nProbelauf beendet. Mit --apply schreiben.");
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
process.stderr.write(`Fehler: ${error instanceof Error ? error.message : String(error)}\n`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -15,3 +15,8 @@ export * from "./actions/content";
|
||||
export * from "./actions/apicore-sync";
|
||||
export * from "./actions/dhl";
|
||||
export * from "./actions/archive";
|
||||
export * from "./actions/sponsorship";
|
||||
export * from "./actions/sponsorship-offers";
|
||||
export * from "./actions/sponsorship-harvest";
|
||||
export * from "./actions/sponsorship-subscriptions";
|
||||
export * from "./actions/sponsorship-loyalty";
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
getApiCoreConnection,
|
||||
fetchApiCoreShopData,
|
||||
isSellableStatus,
|
||||
isManufactured,
|
||||
ApiCoreConfigError,
|
||||
ApiCoreRequestError,
|
||||
type ApiCoreShopData,
|
||||
@@ -15,16 +16,22 @@ import {
|
||||
type ApiCoreProduct,
|
||||
type ApiCoreBottlingBatchWithHarvestId,
|
||||
} from "@/lib/apicore-client";
|
||||
import { harvestSlugCandidates, writeWithFreeSlug } from "@/lib/harvest-slug";
|
||||
import { findTakenHarvestSlugs } from "@/lib/harvest-slug-db";
|
||||
import {
|
||||
slugForApiCoreSource,
|
||||
hasLegacyApiCoreSlug,
|
||||
buildHarvestDescription,
|
||||
buildProductDescription,
|
||||
deriveJarWeightGrams,
|
||||
productSlugCandidates,
|
||||
slugifyProductName,
|
||||
harvestFactChanges,
|
||||
batchFactChanges,
|
||||
} from "@/lib/apicore-mapping";
|
||||
import { requireAdmin } from "./_shared";
|
||||
import { deliverPendingStockEvents } from "@/lib/apicore-stock/delivery";
|
||||
import { reconcileApiCoreStock } from "@/lib/apicore-stock/reconcile";
|
||||
import type { ProductCategory } from "@/generated/prisma/client";
|
||||
|
||||
/**
|
||||
* Uebernimmt Stammdaten aus ApiCore (separates Imkerei-Verwaltungssystem) in
|
||||
@@ -59,8 +66,10 @@ import { requireAdmin } from "./_shared";
|
||||
* der Losnummer — die kann in ApiCore korrigiert werden.
|
||||
*
|
||||
* Idempotent ist das alles ueber einen stabilen Schluessel je Datensatz:
|
||||
* "apicore-<ApiCore-ID>" als Harvest.slug, und die ApiCore-ID der Abfuellung
|
||||
* als Batch.apicoreBottlingId bzw. Product.apicoreBottlingId.
|
||||
* die ApiCore-ID der Ernte als Harvest.apicoreHarvestId, und die ApiCore-ID
|
||||
* der Abfuellung als Batch.apicoreBottlingId bzw. Product.apicoreBottlingId.
|
||||
* Mehrere Ernten derselben Sorte im selben Jahr sind ausdruecklich erlaubt;
|
||||
* sie unterscheiden sich im Slug am Erntedatum (lib/harvest-slug.ts).
|
||||
*
|
||||
* Wabenhains "type" bei Ernten (Erntesaison, z.B. "Sommertracht") und
|
||||
* ApiCores "honeyType" (Honigsorte, z.B. "Lindenhonig") sind KEINE
|
||||
@@ -101,6 +110,21 @@ async function wasEditedByAdmin(harvestId: string): Promise<boolean> {
|
||||
return entries > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ernten aus der Zeit, als der Slug "apicore-<ID>" der Sync-Schluessel war,
|
||||
* bekommen eine lesbare Adresse. Gefahrlos auch fuer veroeffentlichte
|
||||
* Ernten: oeffentlich verlinkt war bis dahin /ernten/<jahr>/<sorte>, nie der
|
||||
* Slug. Gibt zurueck, ob umbenannt wurde.
|
||||
*/
|
||||
async function replaceLegacySlug(harvest: { id: string; slug: string; type: string; harvestDate: Date }): Promise<boolean> {
|
||||
if (!hasLegacyApiCoreSlug(harvest.slug)) return false;
|
||||
await writeWithFreeSlug(harvestSlugCandidates(harvest.type, harvest.harvestDate), (slug) =>
|
||||
prisma.harvest.update({ where: { id: harvest.id }, data: { slug } }),
|
||||
findTakenHarvestSlugs
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Produkte kennen bewusst kein "updated" — sie werden nur neu angelegt,
|
||||
* siehe syncProducts().
|
||||
@@ -132,7 +156,6 @@ async function syncHarvests(sources: ApiCoreHarvest[]): Promise<HarvestSyncCount
|
||||
const counts: HarvestSyncCounts = { created: 0, updated: 0, skipped: 0, failed: 0, protectedDrafts: 0 };
|
||||
|
||||
for (const source of sources) {
|
||||
const slug = slugForApiCoreSource(source.id);
|
||||
const date = new Date(source.date);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
counts.failed++;
|
||||
@@ -142,17 +165,19 @@ async function syncHarvests(sources: ApiCoreHarvest[]): Promise<HarvestSyncCount
|
||||
const type = source.honeyType?.trim() || `Ernte ${source.id.slice(0, 8)}`;
|
||||
|
||||
try {
|
||||
const existing = await prisma.harvest.findUnique({ where: { slug } });
|
||||
const existing = await prisma.harvest.findUnique({ where: { apicoreHarvestId: source.id } });
|
||||
const shopOwned = existing && (existing.isPublished || (await wasEditedByAdmin(existing.id)));
|
||||
if (existing && shopOwned) {
|
||||
// Nur die ApiCore-eigenen Fakten; Sorte, Ort und Text gehoeren jetzt dem Shop.
|
||||
const facts = harvestFactChanges(existing, date);
|
||||
if (!existing.isPublished) counts.protectedDrafts++;
|
||||
const renamed = await replaceLegacySlug(existing);
|
||||
if (Object.keys(facts).length === 0) {
|
||||
counts.skipped++;
|
||||
if (renamed) counts.updated++;
|
||||
else counts.skipped++;
|
||||
continue;
|
||||
}
|
||||
await prisma.harvest.update({ where: { slug }, data: facts });
|
||||
await prisma.harvest.update({ where: { id: existing.id }, data: facts });
|
||||
counts.updated++;
|
||||
continue;
|
||||
}
|
||||
@@ -166,17 +191,23 @@ async function syncHarvests(sources: ApiCoreHarvest[]): Promise<HarvestSyncCount
|
||||
};
|
||||
|
||||
if (existing) {
|
||||
await prisma.harvest.update({ where: { slug }, data });
|
||||
await prisma.harvest.update({ where: { id: existing.id }, data });
|
||||
await replaceLegacySlug({ ...existing, ...data });
|
||||
counts.updated++;
|
||||
} else {
|
||||
await prisma.harvest.create({ data: { ...data, slug, isPublished: false } });
|
||||
// Der Slug ist die oeffentliche Adresse und wird aus Sorte und Datum
|
||||
// gebildet; mehrere Ernten derselben Sorte im selben Jahr bekommen
|
||||
// ueber das Erntedatum je eine eigene (lib/harvest-slug.ts).
|
||||
await writeWithFreeSlug(harvestSlugCandidates(type, date), (slug) =>
|
||||
prisma.harvest.create({ data: { ...data, slug, apicoreHarvestId: source.id, isPublished: false } }),
|
||||
findTakenHarvestSlugs
|
||||
);
|
||||
counts.created++;
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
counts.failed++;
|
||||
// z.B. P2002 (unique constraint year+type), falls zwei ApiCore-Ernten
|
||||
// im selben Jahr denselben honeyType tragen — bewusst nicht fatal fuer
|
||||
// den gesamten Sync-Lauf, siehe Kommentar oben zur Taxonomie-Kollision.
|
||||
// Bewusst nicht fatal fuer den gesamten Sync-Lauf: die uebrigen Ernten
|
||||
// werden weiter verarbeitet, der Fehler steht im Server-Log.
|
||||
console.error(`[apicore-sync] Ernte ${source.id} konnte nicht importiert werden: ${describeError(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -337,6 +368,73 @@ async function syncProducts(
|
||||
* niemandem etwas, und der Fall bedeutet ohnehin, dass hier jemand
|
||||
* hinschauen muss.
|
||||
*/
|
||||
const SHOP_CATEGORIES: readonly ProductCategory[] = ["HONIG", "KERZEN", "PROPOLIS", "SONSTIGES"];
|
||||
|
||||
function shopCategoryOf(article: ApiCoreProduct): ProductCategory {
|
||||
const category = article.shopCategory as ProductCategory | undefined;
|
||||
return category && SHOP_CATEGORIES.includes(category) && category !== "HONIG" ? category : "SONSTIGES";
|
||||
}
|
||||
|
||||
/**
|
||||
* Hergestellte Waren (Kerzen, Propolis-Tinkturen, Salben, ...): EIN
|
||||
* Shop-Produkt je ApiCore-Artikel, nicht je Charge wie beim Honig. Kundinnen
|
||||
* kaufen "Bienenwachskerze klein", nicht eine bestimmte Charge — welche Charge
|
||||
* verkauft wird, entscheidet ApiCore (aelteste zuerst) und meldet es zurueck.
|
||||
*
|
||||
* Gleiche Regeln wie bei Honig-Entwuerfen: deaktiviert, ohne Preis, nie
|
||||
* aktualisiert. Ein schon in Wabenhain gepflegtes Produkt verknuepft man
|
||||
* im Admin ("ApiCore-Artikel verknuepfen") statt es neu anlegen zu lassen.
|
||||
*/
|
||||
async function syncManufacturedProducts(articles: ApiCoreProduct[]): Promise<ProductSyncCounts> {
|
||||
const counts: ProductSyncCounts = { created: 0, skipped: 0, failed: 0, pending: 0, discontinued: 0 };
|
||||
for (const article of articles.filter(isManufactured)) {
|
||||
try {
|
||||
const linked = await prisma.product.findUnique({
|
||||
where: { apicoreProductId: article.id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (linked) {
|
||||
counts.skipped++;
|
||||
continue;
|
||||
}
|
||||
if (!isSellableStatus(article.status)) {
|
||||
counts.discontinued++;
|
||||
continue;
|
||||
}
|
||||
const base = slugifyProductName(article.name) || "produkt";
|
||||
const sku = slugifyProductName(article.sku ?? "");
|
||||
const slug = await firstFreeSlug(sku ? [base, `${base}-${sku}`] : [base]);
|
||||
if (!slug) {
|
||||
counts.failed++;
|
||||
console.error(
|
||||
`[apicore-sync] Für "${article.name}" ist keine freie Adresse frei — Produkt bitte von Hand anlegen und verknüpfen.`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
await prisma.product.create({
|
||||
data: {
|
||||
slug,
|
||||
apicoreProductId: article.id,
|
||||
name: article.name,
|
||||
description: buildProductDescription(article),
|
||||
weightGrams: deriveJarWeightGrams(null, article),
|
||||
category: shopCategoryOf(article),
|
||||
priceCents: 0,
|
||||
pricePerKgCents: 0,
|
||||
isActive: false,
|
||||
// Der Bestand kommt im Abgleich direkt danach aus ApiCore.
|
||||
inventory: { create: { quantity: 0 } },
|
||||
},
|
||||
});
|
||||
counts.created++;
|
||||
} catch (error: unknown) {
|
||||
counts.failed++;
|
||||
console.error(`[apicore-sync] Artikel "${article.name}" konnte nicht als Produkt importiert werden: ${describeError(error)}`);
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
async function firstFreeSlug(candidates: string[]): Promise<string | null> {
|
||||
for (const slug of candidates) {
|
||||
const taken = await prisma.product.findUnique({ where: { slug }, select: { id: true } });
|
||||
@@ -407,7 +505,7 @@ async function syncBatches(sources: ApiCoreBottlingBatchWithHarvestId[]): Promis
|
||||
continue;
|
||||
}
|
||||
const harvest = await prisma.harvest.findUnique({
|
||||
where: { slug: slugForApiCoreSource(source.harvestSourceId) },
|
||||
where: { apicoreHarvestId: source.harvestSourceId },
|
||||
});
|
||||
if (!harvest) {
|
||||
counts.failed++;
|
||||
@@ -505,8 +603,16 @@ export async function syncApiCoreAction(formData: FormData): Promise<void> {
|
||||
`${batches.stockConflicts} Bestandskonflikte, ${batches.failed} fehlgeschlagen`,
|
||||
});
|
||||
|
||||
// 3. Produkte — je Abfuellung ein Jahrgang, jetzt mit vorhandenen Chargen.
|
||||
const products = await syncProducts(source.products, source.bottlings);
|
||||
// 3. Produkte — Honig je Abfuellung ein Jahrgang, hergestellte Waren je Artikel.
|
||||
const honeyProducts = await syncProducts(source.products, source.bottlings);
|
||||
const manufacturedProducts = await syncManufacturedProducts(source.products);
|
||||
const products: ProductSyncCounts = {
|
||||
created: honeyProducts.created + manufacturedProducts.created,
|
||||
skipped: honeyProducts.skipped + manufacturedProducts.skipped,
|
||||
failed: honeyProducts.failed + manufacturedProducts.failed,
|
||||
pending: honeyProducts.pending,
|
||||
discontinued: honeyProducts.discontinued + manufacturedProducts.discontinued,
|
||||
};
|
||||
await logAdminAction(admin, {
|
||||
action: "product.sync_apicore",
|
||||
entityType: "Product",
|
||||
@@ -515,6 +621,23 @@ export async function syncApiCoreAction(formData: FormData): Promise<void> {
|
||||
`${products.pending} warten auf die Charge, ${products.discontinued} in ApiCore ausgelaufen`,
|
||||
});
|
||||
|
||||
// 4. Bestand — offene Buchungen senden, dann alle verknuepften Produkte
|
||||
// auf den ApiCore-Rest setzen. Scheitert das, bleibt der Sync trotzdem
|
||||
// gueltig; der CronJob holt den Abgleich nach.
|
||||
try {
|
||||
const delivered = await deliverPendingStockEvents();
|
||||
const reconciled = await reconcileApiCoreStock();
|
||||
await logAdminAction(admin, {
|
||||
action: "stock.sync_apicore",
|
||||
entityType: "Inventory",
|
||||
detail:
|
||||
`${delivered.sent} Buchungen bestätigt, ${delivered.rejected} abgelehnt, ${delivered.failed} offen; ` +
|
||||
`${reconciled.updated} Bestände abgeglichen, ${reconciled.missing} in ApiCore nicht gefunden`,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error(`[apicore-sync] Bestandsabgleich fehlgeschlagen: ${describeError(error)}`);
|
||||
}
|
||||
|
||||
revalidatePath("/admin/ernten");
|
||||
revalidatePath("/admin/chargen");
|
||||
revalidatePath("/admin/produkte");
|
||||
|
||||
@@ -9,6 +9,7 @@ import { requireAdmin } from "./_shared";
|
||||
import { fail, succeed } from "@/lib/flash";
|
||||
import { normalizeContactEmail } from "@/lib/contact-email";
|
||||
import { settingsPathForGroup } from "@/lib/settings-tabs";
|
||||
import { INVOICE_COPY_KEY } from "@/lib/invoice-mail";
|
||||
|
||||
const COMPANY_EMAIL_KEY = "company.email";
|
||||
|
||||
@@ -64,7 +65,17 @@ export async function updateSiteContentAction(formData: FormData): Promise<void>
|
||||
"Die Firmen-E-Mail ergibt keine gültige Adresse. Möglich sind z. B. [email protected], info [at] wabenhain.com oder info [á] wabenhain.com."
|
||||
);
|
||||
}
|
||||
updates.push({ key: def.key, valueDe: def.key === COMPANY_EMAIL_KEY ? valueDe.trim() : valueDe, valueEn: null });
|
||||
// Die Rechnungskopie geht an genau diese Adresse: leer (keine Kopie) oder
|
||||
// eine echte Adresse, sonst verschwaenden die Kopien stillschweigend.
|
||||
// Genau eine Adresse: "[email protected], [email protected]" waere fuer nodemailer eine Liste.
|
||||
if (def.key === INVOICE_COPY_KEY && valueDe.trim() !== "" && !/^[^,;]+$/.test(normalizeContactEmail(valueDe) ?? "")) {
|
||||
return fail(
|
||||
settingsPathForGroup(group),
|
||||
"„Rechnungskopie an“ ist keine gültige E-Mail-Adresse. Bitte z. B. [email protected] eintragen oder das Feld leer lassen."
|
||||
);
|
||||
}
|
||||
const trimmed = def.key === COMPANY_EMAIL_KEY || def.key === INVOICE_COPY_KEY;
|
||||
updates.push({ key: def.key, valueDe: trimmed ? valueDe.trim() : valueDe, valueEn: null });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ import { logAdminAction } from "@/lib/audit-log";
|
||||
import { adminCreateCustomerSchema, adminUpdateCustomerSchema } from "@/lib/validation";
|
||||
import { requireAdmin, fail, isLastAdmin, str } from "./_shared";
|
||||
import { setFlash, succeed, MAIL_FAILED_HINT } from "@/lib/flash";
|
||||
import { certificateDirsOfCustomer, hasBlockingSubscription, removeCertificateDirs } from "@/lib/sponsorship/customer-deletion";
|
||||
import { discardPendingCheckouts } from "@/lib/sponsorship-subscription/pending";
|
||||
|
||||
export async function createCustomerAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
@@ -176,8 +178,19 @@ export async function deleteCustomerAction(formData: FormData): Promise<void> {
|
||||
if (await isLastAdmin(id)) {
|
||||
return fail("/admin/benutzer", "Der letzte Admin-Account kann nicht gelöscht werden.");
|
||||
}
|
||||
// Laufendes Abo: erst kuendigen bzw. bei Stripe beenden — sonst zoege
|
||||
// Stripe weiter ab, ohne dass es ein Konto gibt (lib/sponsorship/customer-deletion.ts).
|
||||
if (await hasBlockingSubscription(id)) {
|
||||
return fail(
|
||||
"/admin/benutzer",
|
||||
"Dieses Konto hat ein laufendes Patenschafts-Abo. Bitte das Abo zuerst kündigen und sein Ende abwarten (oder bei Stripe beenden) — erst danach lässt sich das Konto löschen."
|
||||
);
|
||||
}
|
||||
|
||||
const certificateDirs = await certificateDirsOfCustomer(id);
|
||||
await discardPendingCheckouts(id);
|
||||
const deleted = await prisma.customer.delete({ where: { id } });
|
||||
await removeCertificateDirs(certificateDirs);
|
||||
await logAdminAction(admin, { action: "customer.delete", entityType: "Customer", entityId: id, detail: deleted.email });
|
||||
revalidatePath("/admin/benutzer");
|
||||
return succeed("/admin/benutzer", `Konto ${deleted.email} wurde gelöscht.`);
|
||||
|
||||
@@ -6,6 +6,8 @@ import { logAdminAction } from "@/lib/audit-log";
|
||||
import { isValidUploadPath } from "@/lib/uploads";
|
||||
import { requireAdmin, fail, str, num, strArraySlots } from "./_shared";
|
||||
import { succeed } from "@/lib/flash";
|
||||
import { harvestSlugCandidates, writeWithFreeSlug } from "@/lib/harvest-slug";
|
||||
import { findTakenHarvestSlugs } from "@/lib/harvest-slug-db";
|
||||
|
||||
/**
|
||||
* Bildslots fuer Ernte und Charge. Die Position entscheidet, WELCHE Kachel
|
||||
@@ -26,25 +28,33 @@ export async function createHarvestAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const year = num(formData, "year");
|
||||
const type = str(formData, "type");
|
||||
const slug = `${type.toLowerCase().replace(/[^a-z0-9]+/g, "-")}-${year}`;
|
||||
const harvestDate = new Date(str(formData, "harvestDate"));
|
||||
if (!type || !Number.isInteger(year) || year < 1 || Number.isNaN(harvestDate.getTime())) {
|
||||
return fail("/admin/ernten", "Bitte Sorte, Jahr und ein gültiges Erntedatum angeben.");
|
||||
}
|
||||
// Checkbox: nur in formData vorhanden, wenn angehakt — fehlt sie ganz
|
||||
// (kein Feld im Formular), gilt "veroeffentlicht" als sicherer Default fuer
|
||||
// manuell im Admin-Bereich angelegte Ernten (bisheriges Verhalten vor
|
||||
// Einfuehrung von isPublished).
|
||||
const isPublished = !formData.has("isPublished") || formData.get("isPublished") === "on";
|
||||
|
||||
const harvest = await prisma.harvest.create({
|
||||
data: {
|
||||
year,
|
||||
type,
|
||||
slug,
|
||||
harvestDate: new Date(str(formData, "harvestDate")),
|
||||
location: str(formData, "location") || "Altenmünster",
|
||||
description: str(formData, "description"),
|
||||
images: imageSlots(formData),
|
||||
isPublished,
|
||||
},
|
||||
});
|
||||
// Dieselbe Sorte darf mehrmals im Jahr geerntet werden; die zweite bekommt
|
||||
// eine Adresse mit Erntedatum statt eines Fehlers (lib/harvest-slug.ts).
|
||||
const harvest = await writeWithFreeSlug(harvestSlugCandidates(type, harvestDate), (slug) =>
|
||||
prisma.harvest.create({
|
||||
data: {
|
||||
year,
|
||||
type,
|
||||
slug,
|
||||
harvestDate,
|
||||
location: str(formData, "location") || "Altenmünster",
|
||||
description: str(formData, "description"),
|
||||
images: imageSlots(formData),
|
||||
isPublished,
|
||||
},
|
||||
}),
|
||||
findTakenHarvestSlugs
|
||||
);
|
||||
|
||||
await logAdminAction(admin, {
|
||||
action: "harvest.create",
|
||||
|
||||
@@ -5,16 +5,17 @@ import { prisma } from "@/lib/prisma";
|
||||
import { logAdminAction } from "@/lib/audit-log";
|
||||
import { requireAdmin, str, fail } from "./_shared";
|
||||
import { setFlash } from "@/lib/flash";
|
||||
import { isInquiryStatus } from "@/lib/inquiry-status";
|
||||
|
||||
export async function updateBusinessInquiryStatusAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
const status = str(formData, "status");
|
||||
if (!["NEU", "IN_BEARBEITUNG", "ABGESCHLOSSEN", "ABGELEHNT"].includes(status)) return fail("/admin/anfragen", "Ungültiger Status.");
|
||||
if (!isInquiryStatus(status)) return fail("/admin/anfragen", "Ungültiger Status.");
|
||||
|
||||
await prisma.businessInquiry.update({
|
||||
where: { id },
|
||||
data: { status: status as "NEU" | "IN_BEARBEITUNG" | "ABGESCHLOSSEN" | "ABGELEHNT" },
|
||||
data: { status },
|
||||
});
|
||||
|
||||
await logAdminAction(admin, {
|
||||
|
||||
@@ -19,6 +19,9 @@ import { getStripeClient } from "@/lib/stripe";
|
||||
import { isLocale, defaultLocale } from "@/i18n/config";
|
||||
import type { OrderStatus, PaymentStatus } from "@/generated/prisma/client";
|
||||
import { requireAdmin, str, strOrNull, fail } from "./_shared";
|
||||
import { recordOrderReturn, recordOrderSale } from "@/lib/apicore-stock/stock-events";
|
||||
import { issueCancellationInvoice } from "@/lib/cancellation-invoice";
|
||||
import { scheduleApiCoreStockSync } from "@/lib/apicore-stock/schedule";
|
||||
import { setFlash, succeed, MAIL_FAILED_HINT } from "@/lib/flash";
|
||||
|
||||
const ORDER_STATUSES = [
|
||||
@@ -63,14 +66,15 @@ async function settleCancelledOrder(order: {
|
||||
orderNumber: string;
|
||||
previousStatus: OrderStatus;
|
||||
stripeCheckoutSessionId: string | null;
|
||||
payment: { status: PaymentStatus; stripePaymentIntentId: string | null } | null;
|
||||
payment: { status: PaymentStatus; stripePaymentIntentId: string | null; amountCents: number } | null;
|
||||
}): Promise<string[]> {
|
||||
const warnings: string[] = [];
|
||||
|
||||
// Nur eine tatsaechlich eingezogene Zahlung wird erstattet. "FAILED" gab es
|
||||
// nie zu erstatten, "REFUNDED" waere eine zweite Erstattung desselben
|
||||
// Betrags, und "PENDING" ist noch gar nicht abgeschlossen.
|
||||
if (order.payment?.status === "SUCCEEDED") {
|
||||
// 0-€-Zahlungen (Abo-Honiglieferung, Provider "abo") haben nichts zu erstatten.
|
||||
if (order.payment?.status === "SUCCEEDED" && order.payment.amountCents > 0) {
|
||||
const paymentIntentId = order.payment.stripePaymentIntentId;
|
||||
if (!paymentIntentId) {
|
||||
warnings.push(
|
||||
@@ -146,9 +150,10 @@ export async function updateOrderStatusAction(formData: FormData): Promise<void>
|
||||
firstName: true,
|
||||
locale: true,
|
||||
stripeCheckoutSessionId: true,
|
||||
payment: { select: { status: true, stripePaymentIntentId: true } },
|
||||
items: { select: { productId: true, quantity: true, productName: true } },
|
||||
payment: { select: { status: true, stripePaymentIntentId: true, amountCents: true } },
|
||||
items: { select: { productId: true, quantity: true, productName: true, product: { select: { category: true } } } },
|
||||
returnRequest: { select: { status: true } },
|
||||
invoice: { select: { cancellation: { select: { number: true } } } },
|
||||
},
|
||||
});
|
||||
if (!previous) return null;
|
||||
@@ -157,6 +162,12 @@ export async function updateOrderStatusAction(formData: FormData): Promise<void>
|
||||
// Bestaetigung aus dem Formular (siehe needsConfirmToChangeStatus). Ohne
|
||||
// sie wird nichts veraendert.
|
||||
const reopening = needsConfirmToChangeStatus(previous.status, status);
|
||||
// Mit Stornorechnung ist die Rechnung aufgehoben und das Geld erstattet;
|
||||
// ein Wiederoeffnen waere ein Verkauf ohne Rechnung. Dann bitte eine neue
|
||||
// Bestellung anlegen.
|
||||
if (reopening && previous.invoice?.cancellation) {
|
||||
return { ...previous, shipment: null, cancelledNow: false, blocked: "cancellation-invoice" as const };
|
||||
}
|
||||
if (reopening && !confirmedReopen) {
|
||||
return { ...previous, shipment: null, cancelledNow: false, blocked: "needs-confirm" as const };
|
||||
}
|
||||
@@ -185,6 +196,10 @@ export async function updateOrderStatusAction(formData: FormData): Promise<void>
|
||||
if (needsRestockOnCancel(previous.returnRequest?.status ?? null)) {
|
||||
await restockOrderItems(tx, previous.items);
|
||||
}
|
||||
// War die Bestellung bezahlt, steht ein Verkauf in ApiCore — der
|
||||
// wird zurueckgebucht. Unbezahlte Bestellungen haben keinen, dann
|
||||
// passiert hier nichts.
|
||||
await recordOrderReturn(tx, orderId);
|
||||
}
|
||||
} else if (reopening) {
|
||||
// Gegenbuchung zur Stornierung: die dabei zurueckgebuchte Ware wird
|
||||
@@ -202,6 +217,10 @@ export async function updateOrderStatusAction(formData: FormData): Promise<void>
|
||||
// Wirft InsufficientStockError, wenn die Ware inzwischen verkauft ist —
|
||||
// die Transaktion nimmt dann auch den Statuswechsel zurueck.
|
||||
await reserveOrderItems(tx, previous.items);
|
||||
// Eine bezahlte Bestellung ist damit wieder verkauft.
|
||||
if (previous.payment?.status === "SUCCEEDED") {
|
||||
await recordOrderSale(tx, orderId);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Atomar gegen den aktuellen Zeilenstand: hat ein zweiter Tab die
|
||||
@@ -245,6 +264,10 @@ export async function updateOrderStatusAction(formData: FormData): Promise<void>
|
||||
throw error;
|
||||
});
|
||||
|
||||
if (result && !("insufficientStock" in result)) {
|
||||
scheduleApiCoreStockSync(result.items.map((item) => item.productId));
|
||||
}
|
||||
|
||||
if (result && "insufficientStock" in result) {
|
||||
return fail(
|
||||
detailPath,
|
||||
@@ -264,6 +287,12 @@ export async function updateOrderStatusAction(formData: FormData): Promise<void>
|
||||
if (result.blocked === "changed") {
|
||||
return fail(detailPath, "Die Bestellung wurde zwischenzeitlich geändert. Bitte die Seite neu laden und erneut versuchen.");
|
||||
}
|
||||
if (result.blocked === "cancellation-invoice") {
|
||||
return fail(
|
||||
detailPath,
|
||||
`Zu dieser Bestellung gibt es die Stornorechnung ${result.invoice?.cancellation?.number}. Sie kann nicht wieder geöffnet werden — bitte eine neue Bestellung anlegen.`
|
||||
);
|
||||
}
|
||||
|
||||
// undefined = keine E-Mail faellig; false = faellig, aber nicht versendet.
|
||||
let mailSent: boolean | undefined;
|
||||
@@ -293,6 +322,15 @@ export async function updateOrderStatusAction(formData: FormData): Promise<void>
|
||||
stripeCheckoutSessionId: result.stripeCheckoutSessionId,
|
||||
payment: result.payment,
|
||||
});
|
||||
// Hatte die Bestellung eine Rechnung, wird sie durch eine
|
||||
// Stornorechnung aufgehoben (nie geloescht) — auch wenn die Erstattung
|
||||
// oben scheiterte: verkauft ist dann trotzdem nichts mehr.
|
||||
try {
|
||||
await issueCancellationInvoice(orderId, "STORNIERUNG");
|
||||
} catch (error: unknown) {
|
||||
console.error(`[order-cancel] Stornorechnung fuer ${result.orderNumber} fehlgeschlagen:`, error);
|
||||
stornoWarnings.push("Die Stornorechnung konnte nicht erstellt werden. Sie entsteht spätestens mit der Stripe-Erstattung; sonst bitte den Support informieren.");
|
||||
}
|
||||
|
||||
if (stornoWarnings.length > 0) {
|
||||
await logAdminAction(admin, {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { planInventoryEdit } from "@/lib/inventory";
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { requireAdmin, fail, str, strOrNull, strArray } from "./_shared";
|
||||
import { succeed } from "@/lib/flash";
|
||||
import { scheduleApiCoreStockSync } from "@/lib/apicore-stock/schedule";
|
||||
|
||||
/**
|
||||
* Ein Produkt darf nicht aktiv geschaltet werden, solange kein Preis
|
||||
@@ -213,7 +214,25 @@ export async function updateProductAction(formData: FormData): Promise<void> {
|
||||
const isActive = formData.get("isActive") === "on";
|
||||
await assertPricedIfActive(`/admin/produkte/${id}`, isActive, numbers.priceCents);
|
||||
|
||||
const inventoryPlan = planInventoryEdit({ loaded: str(formData, "quantityLoaded"), submitted: numbers.quantity });
|
||||
const current = await prisma.product.findUnique({
|
||||
where: { id },
|
||||
select: { apicoreBottlingId: true, apicoreProductId: true },
|
||||
});
|
||||
if (!current) return fail("/admin/produkte", "Produkt nicht gefunden.");
|
||||
|
||||
// Verknuepfung mit einem ApiCore-Artikel (nur hergestellte Waren; Honig
|
||||
// haengt fest an seiner Abfuellung). Feld fehlt = unveraendert lassen.
|
||||
const requestedLink = formData.has("apicoreProductId") ? strOrNull(formData, "apicoreProductId") : undefined;
|
||||
const apicoreProductId = current.apicoreBottlingId ? current.apicoreProductId : requestedLink;
|
||||
const linkChanged = apicoreProductId !== undefined && apicoreProductId !== current.apicoreProductId;
|
||||
const stockFromApiCore = Boolean(current.apicoreBottlingId || (apicoreProductId ?? current.apicoreProductId));
|
||||
|
||||
// Bei verknuepften Produkten gehoert der Bestand ApiCore: ein Wert aus dem
|
||||
// Formular wird nie geschrieben, auch wenn jemand das gesperrte Feld per
|
||||
// Entwicklerwerkzeug aendert.
|
||||
const inventoryPlan = stockFromApiCore
|
||||
? ({ kind: "keep" } as const)
|
||||
: planInventoryEdit({ loaded: str(formData, "quantityLoaded"), submitted: numbers.quantity });
|
||||
if (inventoryPlan.kind === "reload") {
|
||||
return fail(
|
||||
`/admin/produkte/${id}`,
|
||||
@@ -244,10 +263,27 @@ export async function updateProductAction(formData: FormData): Promise<void> {
|
||||
vatRatePercent: numbers.vatRatePercent,
|
||||
images: strArray(formData, "images").filter(isValidUploadPath),
|
||||
isActive,
|
||||
...(linkChanged ? { apicoreProductId } : {}),
|
||||
},
|
||||
});
|
||||
}).catch((error: unknown) => {
|
||||
if (typeof error === "object" && error !== null && "code" in error && error.code === "P2002") {
|
||||
return "link-taken" as const;
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
|
||||
if (product === "link-taken") {
|
||||
return fail(
|
||||
`/admin/produkte/${id}`,
|
||||
"Dieser ApiCore-Artikel ist bereits mit einem anderen Produkt verknüpft. Nichts wurde gespeichert."
|
||||
);
|
||||
}
|
||||
if (linkChanged && apicoreProductId) {
|
||||
// Bestand sofort aus ApiCore holen, nicht erst beim naechsten CronJob.
|
||||
scheduleApiCoreStockSync([id]);
|
||||
}
|
||||
|
||||
if (!product) {
|
||||
const current = await prisma.inventory.findUnique({ where: { productId: id }, select: { quantity: true } });
|
||||
return fail(
|
||||
|
||||
@@ -12,7 +12,7 @@ export async function approveReviewAction(formData: FormData): Promise<void> {
|
||||
|
||||
const review = await prisma.review.update({
|
||||
where: { id },
|
||||
data: { isApproved: true },
|
||||
data: { isApproved: true, rejectedAt: null },
|
||||
select: { product: { select: { slug: true, name: true } } },
|
||||
});
|
||||
|
||||
@@ -28,6 +28,33 @@ export async function approveReviewAction(formData: FormData): Promise<void> {
|
||||
await setFlash("success", "Bewertung freigegeben — sie ist jetzt im Shop sichtbar.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Lehnt eine Bewertung ab, statt sie zu loeschen: sie verschwindet aus dem
|
||||
* Shop (falls sie dort war) und steht im Archiv unter "Abgelehnt", damit die
|
||||
* Entscheidung nachvollziehbar bleibt und sich rueckgaengig machen laesst.
|
||||
*/
|
||||
export async function rejectReviewAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
|
||||
const review = await prisma.review.update({
|
||||
where: { id },
|
||||
data: { isApproved: false, rejectedAt: new Date() },
|
||||
select: { product: { select: { slug: true, name: true } } },
|
||||
});
|
||||
|
||||
await logAdminAction(admin, {
|
||||
action: "review.reject",
|
||||
entityType: "Review",
|
||||
entityId: id,
|
||||
detail: review.product.name,
|
||||
});
|
||||
|
||||
revalidatePath("/admin/bewertungen");
|
||||
revalidatePath(`/honig/${review.product.slug}`);
|
||||
await setFlash("success", "Bewertung abgelehnt — sie steht jetzt im Archiv.");
|
||||
}
|
||||
|
||||
export async function deleteReviewAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { logAdminAction } from "@/lib/audit-log";
|
||||
import { isIsoDate } from "@/lib/certificate/schema";
|
||||
import { requireAdmin, fail, succeed, str } from "./_shared";
|
||||
|
||||
const windowSchema = z
|
||||
.object({
|
||||
startsOn: z.string().refine(isIsoDate, "Bitte ein gültiges Beginndatum angeben."),
|
||||
endsOn: z.string().refine(isIsoDate, "Bitte ein gültiges Enddatum angeben."),
|
||||
plannedJars: z.coerce
|
||||
.number({ error: "Geplante Gläser: bitte eine ganze Zahl." })
|
||||
.int("Geplante Gläser: bitte eine ganze Zahl.")
|
||||
.min(0, "Geplante Gläser: mindestens 0.")
|
||||
.max(100_000, "Geplante Gläser: höchstens 100000."),
|
||||
})
|
||||
.refine((value) => value.endsOn >= value.startsOn, "Das Ende darf nicht vor dem Beginn liegen.");
|
||||
|
||||
function windowPath(offerId: string): string {
|
||||
return `/admin/patenschaften/angebote/${offerId}/erntefenster`;
|
||||
}
|
||||
|
||||
function toDate(isoDate: string): Date {
|
||||
return new Date(`${isoDate}T00:00:00.000Z`);
|
||||
}
|
||||
|
||||
/** Erntefenster gibt es nur fuer Abo-Angebote mit Zyklus ERNTE. */
|
||||
async function loadHarvestOffer(offerId: string) {
|
||||
const offer = await prisma.sponsorshipOffer.findUnique({ where: { id: offerId }, select: { id: true, name: true, kind: true, cycle: true } });
|
||||
return offer && offer.kind === "ABO" && offer.cycle === "ERNTE" ? offer : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fenster desselben Angebots duerfen sich nicht ueberschneiden: sonst waere
|
||||
* unklar, in welchem Fenster eine Lieferung faellig wird, und die geplanten
|
||||
* Glaeser wuerden doppelt reserviert.
|
||||
*/
|
||||
async function overlaps(offerId: string, startsOn: Date, endsOn: Date, exceptId?: string): Promise<boolean> {
|
||||
const count = await prisma.harvestWindow.count({
|
||||
where: {
|
||||
offerId,
|
||||
...(exceptId ? { id: { not: exceptId } } : {}),
|
||||
startsOn: { lte: endsOn },
|
||||
endsOn: { gte: startsOn },
|
||||
},
|
||||
});
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
function parseWindow(formData: FormData) {
|
||||
return windowSchema.safeParse({
|
||||
startsOn: str(formData, "startsOn"),
|
||||
endsOn: str(formData, "endsOn"),
|
||||
plannedJars: str(formData, "plannedJars") || "0",
|
||||
});
|
||||
}
|
||||
|
||||
export async function createHarvestWindowAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const offer = await loadHarvestOffer(str(formData, "offerId"));
|
||||
if (!offer) return fail("/admin/patenschaften/angebote", "Erntefenster gibt es nur für Abo-Angebote mit dem Zyklus „Nach der Ernte“.");
|
||||
const back = windowPath(offer.id);
|
||||
const parsed = parseWindow(formData);
|
||||
if (!parsed.success) return fail(back, parsed.error.issues[0]?.message ?? "Ungültige Eingabe.");
|
||||
const startsOn = toDate(parsed.data.startsOn);
|
||||
const endsOn = toDate(parsed.data.endsOn);
|
||||
if (await overlaps(offer.id, startsOn, endsOn)) return fail(back, "Das Fenster überschneidet sich mit einem bestehenden Erntefenster.");
|
||||
|
||||
const window = await prisma.harvestWindow.create({
|
||||
data: { offerId: offer.id, startsOn, endsOn, plannedJars: parsed.data.plannedJars },
|
||||
});
|
||||
await logAdminAction(admin, {
|
||||
action: "harvest_window.create",
|
||||
entityType: "HarvestWindow",
|
||||
entityId: window.id,
|
||||
detail: `${offer.name}: ${parsed.data.startsOn} – ${parsed.data.endsOn}, ${parsed.data.plannedJars} Gläser`,
|
||||
});
|
||||
revalidatePath(back);
|
||||
return succeed(back, "Erntefenster angelegt.");
|
||||
}
|
||||
|
||||
export async function updateHarvestWindowAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
const existing = await prisma.harvestWindow.findUnique({ where: { id }, select: { offerId: true } });
|
||||
const offer = existing ? await loadHarvestOffer(existing.offerId) : null;
|
||||
if (!existing || !offer) return fail("/admin/patenschaften/angebote", "Das Erntefenster wurde nicht gefunden.");
|
||||
const back = windowPath(offer.id);
|
||||
const parsed = parseWindow(formData);
|
||||
if (!parsed.success) return fail(back, parsed.error.issues[0]?.message ?? "Ungültige Eingabe.");
|
||||
const startsOn = toDate(parsed.data.startsOn);
|
||||
const endsOn = toDate(parsed.data.endsOn);
|
||||
if (await overlaps(offer.id, startsOn, endsOn, id)) return fail(back, "Das Fenster überschneidet sich mit einem bestehenden Erntefenster.");
|
||||
|
||||
await prisma.harvestWindow.update({ where: { id }, data: { startsOn, endsOn, plannedJars: parsed.data.plannedJars } });
|
||||
await logAdminAction(admin, {
|
||||
action: "harvest_window.update",
|
||||
entityType: "HarvestWindow",
|
||||
entityId: id,
|
||||
detail: `${offer.name}: ${parsed.data.startsOn} – ${parsed.data.endsOn}, ${parsed.data.plannedJars} Gläser`,
|
||||
});
|
||||
revalidatePath(back);
|
||||
return succeed(back, "Erntefenster gespeichert.");
|
||||
}
|
||||
|
||||
export async function deleteHarvestWindowAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
const existing = await prisma.harvestWindow.findUnique({ where: { id }, include: { offer: { select: { name: true } } } });
|
||||
if (!existing) return fail("/admin/patenschaften/angebote", "Das Erntefenster wurde nicht gefunden — möglicherweise bereits gelöscht.");
|
||||
const back = windowPath(existing.offerId);
|
||||
await prisma.harvestWindow.deleteMany({ where: { id } });
|
||||
await logAdminAction(admin, {
|
||||
action: "harvest_window.delete",
|
||||
entityType: "HarvestWindow",
|
||||
entityId: id,
|
||||
detail: `${existing.offer.name}: ${existing.startsOn.toISOString().slice(0, 10)} – ${existing.endsOn.toISOString().slice(0, 10)}`,
|
||||
});
|
||||
revalidatePath(back);
|
||||
return succeed(back, "Erntefenster gelöscht.");
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { logAdminAction } from "@/lib/audit-log";
|
||||
import { requireAdmin, fail, succeed, str } from "./_shared";
|
||||
import { isUniqueViolation } from "./sponsorship-shared";
|
||||
|
||||
const LOYALTY_PATH = "/admin/patenschaften/treuestufen";
|
||||
|
||||
const nameFields = {
|
||||
name: z.string().trim().min(1, "Bitte einen Namen angeben.").max(60, "Name: höchstens 60 Zeichen."),
|
||||
nameEn: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(60, "Name (Englisch): höchstens 60 Zeichen.")
|
||||
.transform((value) => (value === "" ? null : value)),
|
||||
};
|
||||
|
||||
const thresholdField = z.coerce
|
||||
.number({ error: "Schwelle: bitte eine ganze Zahl." })
|
||||
.int("Schwelle: bitte eine ganze Zahl.")
|
||||
.min(1, "Schwelle: mindestens 1.")
|
||||
.max(1000, "Schwelle: höchstens 1000.");
|
||||
|
||||
const levelSchema = z.object({ ...nameFields, threshold: thresholdField });
|
||||
const newLevelSchema = levelSchema.extend({ kind: z.enum(["STAMMKUNDE", "ABO"], { error: "Unbekannte Stufenart." }) });
|
||||
|
||||
function readLevel(formData: FormData) {
|
||||
return {
|
||||
name: str(formData, "name"),
|
||||
nameEn: str(formData, "nameEn"),
|
||||
threshold: str(formData, "threshold"),
|
||||
};
|
||||
}
|
||||
|
||||
const DUPLICATE_THRESHOLD = "Für diese Schwelle gibt es bereits eine Stufe.";
|
||||
|
||||
export async function createLoyaltyLevelAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const parsed = newLevelSchema.safeParse({ ...readLevel(formData), kind: str(formData, "kind") });
|
||||
if (!parsed.success) return fail(LOYALTY_PATH, parsed.error.issues[0]?.message ?? "Ungültige Eingabe.");
|
||||
try {
|
||||
const level = await prisma.loyaltyLevel.create({ data: parsed.data });
|
||||
await logAdminAction(admin, {
|
||||
action: "loyalty_level.create",
|
||||
entityType: "LoyaltyLevel",
|
||||
entityId: level.id,
|
||||
detail: `${level.kind} ab ${level.threshold}: ${level.name}`,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (isUniqueViolation(error)) return fail(LOYALTY_PATH, DUPLICATE_THRESHOLD);
|
||||
throw error;
|
||||
}
|
||||
revalidatePath(LOYALTY_PATH);
|
||||
return succeed(LOYALTY_PATH, "Stufe angelegt.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Speichert Namen und Schwelle einer Stufe. Die VIP-Stufe (Abo, ohne
|
||||
* Schwelle) behaelt ihre fehlende Schwelle — sie folgt immer nach der
|
||||
* hoechsten Zahl, nur ihr Name ist pflegbar.
|
||||
*/
|
||||
export async function updateLoyaltyLevelAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
const existing = await prisma.loyaltyLevel.findUnique({ where: { id } });
|
||||
if (!existing) return fail(LOYALTY_PATH, "Die Stufe wurde nicht gefunden.");
|
||||
const isVip = existing.threshold === null;
|
||||
|
||||
const parsed = isVip
|
||||
? z.object(nameFields).safeParse(readLevel(formData))
|
||||
: levelSchema.safeParse(readLevel(formData));
|
||||
if (!parsed.success) return fail(LOYALTY_PATH, parsed.error.issues[0]?.message ?? "Ungültige Eingabe.");
|
||||
|
||||
try {
|
||||
await prisma.loyaltyLevel.update({ where: { id }, data: parsed.data });
|
||||
} catch (error: unknown) {
|
||||
if (isUniqueViolation(error)) return fail(LOYALTY_PATH, DUPLICATE_THRESHOLD);
|
||||
throw error;
|
||||
}
|
||||
const threshold = "threshold" in parsed.data ? parsed.data.threshold : null;
|
||||
await logAdminAction(admin, {
|
||||
action: "loyalty_level.update",
|
||||
entityType: "LoyaltyLevel",
|
||||
entityId: id,
|
||||
detail: `${existing.kind} ${existing.threshold ?? "VIP"} → ${threshold ?? "VIP"}: ${existing.name} → ${parsed.data.name}`,
|
||||
});
|
||||
revalidatePath(LOYALTY_PATH);
|
||||
return succeed(LOYALTY_PATH, "Stufe gespeichert.");
|
||||
}
|
||||
|
||||
export async function deleteLoyaltyLevelAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
const existing = await prisma.loyaltyLevel.findUnique({ where: { id } });
|
||||
if (!existing) return fail(LOYALTY_PATH, "Die Stufe wurde nicht gefunden — möglicherweise bereits gelöscht.");
|
||||
if (existing.threshold === null) return fail(LOYALTY_PATH, "Die VIP-Stufe kann nicht gelöscht werden.");
|
||||
|
||||
await prisma.loyaltyLevel.deleteMany({ where: { id, threshold: { not: null } } });
|
||||
await logAdminAction(admin, {
|
||||
action: "loyalty_level.delete",
|
||||
entityType: "LoyaltyLevel",
|
||||
entityId: id,
|
||||
detail: `${existing.kind} ab ${existing.threshold}: ${existing.name}`,
|
||||
});
|
||||
revalidatePath(LOYALTY_PATH);
|
||||
return succeed(LOYALTY_PATH, "Stufe gelöscht.");
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { logAdminAction } from "@/lib/audit-log";
|
||||
import { formatPrice } from "@/lib/format";
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { carrierPriceCents, parseOfferForm, type OfferFormValues } from "@/app/admin/patenschaften/_lib/offer-schema";
|
||||
import { setFlash } from "@/lib/flash";
|
||||
import { loadHoneyCandidates } from "@/lib/sponsorship/honey-candidates";
|
||||
import { pickHoneyProduct } from "@/lib/sponsorship/honey-selection";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireAdmin, fail, succeed, str } from "./_shared";
|
||||
import { isUniqueViolation, syncStripePriceSafely } from "./sponsorship-shared";
|
||||
|
||||
const OFFERS_PATH = "/admin/patenschaften/angebote";
|
||||
|
||||
function carrierSlug(slug: string): string {
|
||||
return `patenschaft-${slug}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Traegerprodukt einer Einmal-Patenschaft (Kategorie PATENSCHAFT): haelt
|
||||
* Preis, Steuersatz und Rechnungsposition, damit Warenkorb, Checkout und
|
||||
* Rechnung keinen Sonderweg brauchen. Sein Preis ist Paketpreis minus
|
||||
* Honiganteil — der Honig wird im Checkout als eigene Position zum
|
||||
* Honig-Steuersatz angelegt.
|
||||
*/
|
||||
function carrierProductData(values: OfferFormValues) {
|
||||
return {
|
||||
name: `Bienenpatenschaft ${values.name}`,
|
||||
slug: carrierSlug(values.slug),
|
||||
category: "PATENSCHAFT" as const,
|
||||
description: values.description,
|
||||
weightGrams: 0,
|
||||
priceCents: carrierPriceCents(values),
|
||||
pricePerKgCents: 0,
|
||||
isActive: true,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* honeyProductId wird bewusst nicht geschrieben: der Honig wird automatisch
|
||||
* gewaehlt (lib/sponsorship/honey-selection.ts). Die Spalte bleibt nur im
|
||||
* Schema stehen, damit die laufende Produktion keine Migration braucht; ein
|
||||
* dort noch stehender Altwert wird nirgends mehr gelesen.
|
||||
*/
|
||||
function offerData(values: OfferFormValues) {
|
||||
return {
|
||||
slug: values.slug,
|
||||
name: values.name,
|
||||
nameEn: values.nameEn,
|
||||
description: values.description,
|
||||
descriptionEn: values.descriptionEn,
|
||||
features: values.features,
|
||||
featuresEn: values.featuresEn,
|
||||
priceCents: values.priceCents,
|
||||
isActive: values.isActive,
|
||||
sortOrder: values.sortOrder,
|
||||
isPhysical: values.isPhysical,
|
||||
honeyJars: values.honeyJars,
|
||||
honeyShareCentsPerJar: values.honeyShareCentsPerJar,
|
||||
honeyShareCentsPerMonth: values.honeyShareCentsPerMonth,
|
||||
cycle: values.cycle,
|
||||
maxActiveSubscriptions: values.maxActiveSubscriptions,
|
||||
medalTier: values.medalTier,
|
||||
} satisfies Prisma.SponsorshipOfferUncheckedUpdateInput;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pruefungen gegen die Datenbank: eindeutige Adressen. Den Honig prueft
|
||||
* honeyWarning() — er sperrt das Aktivieren nicht mehr, weil er sich mit
|
||||
* jeder Bestellung und jeder neuen Ernte aendert.
|
||||
*/
|
||||
async function findConflict(
|
||||
values: OfferFormValues,
|
||||
existing: { id: string; productId: string | null } | null
|
||||
): Promise<string | null> {
|
||||
const slugOwner = await prisma.sponsorshipOffer.findUnique({ where: { slug: values.slug }, select: { id: true } });
|
||||
if (slugOwner && slugOwner.id !== existing?.id) return `Die Adresse "${values.slug}" hat bereits ein anderes Angebot.`;
|
||||
|
||||
if (values.kind === "EINMALIG") {
|
||||
const product = await prisma.product.findUnique({ where: { slug: carrierSlug(values.slug) }, select: { id: true } });
|
||||
if (product && product.id !== existing?.productId) {
|
||||
return `Die Produktadresse "${carrierSlug(values.slug)}" ist bereits vergeben. Bitte eine andere Adresse wählen.`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function auditDetail(values: OfferFormValues): string {
|
||||
const state = values.isActive ? "aktiv" : "inaktiv";
|
||||
return `${values.name} (${values.kind}, ${formatPrice(values.priceCents)}, ${state})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aktivierungsregel fuer Angebote mit Honig: es muss einen Honig geben, den
|
||||
* die automatische Wahl nehmen darf (nicht cremig, genug freier Bestand fuer
|
||||
* die Glaeser). Fehlt er, wird trotzdem gespeichert — das Angebot steht dann
|
||||
* auf der Verkaufsseite als nicht bestellbar (isOfferAvailable), bis
|
||||
* fluessiger Honig nachgelegt ist —, aber der Admin bekommt einen Hinweis,
|
||||
* statt sich ueber ein "ausverkauftes" neues Angebot zu wundern.
|
||||
*/
|
||||
async function honeyWarning(values: OfferFormValues): Promise<string | null> {
|
||||
if (!values.isActive || values.honeyJars <= 0) return null;
|
||||
if (pickHoneyProduct(await loadHoneyCandidates(), values.honeyJars)) return null;
|
||||
return "Hinweis: Derzeit gibt es keinen nicht-cremigen Honig mit genug freiem Bestand – bestellbar erst, wenn flüssiger Honig nachgelegt ist.";
|
||||
}
|
||||
|
||||
/** Nach dem Speichern: Stripe-Preis eines Abo-Angebots nachziehen, Honig pruefen und passend melden. */
|
||||
async function finishSave(offerId: string, values: OfferFormValues, message: string): Promise<never> {
|
||||
revalidatePath(OFFERS_PATH);
|
||||
revalidatePath("/patenschaft");
|
||||
const target = `${OFFERS_PATH}/${offerId}`;
|
||||
if (values.kind === "ABO") {
|
||||
const stripeError = await syncStripePriceSafely(offerId);
|
||||
if (stripeError) {
|
||||
return fail(target, `${message} Der Stripe-Preis konnte aber nicht angelegt werden (${stripeError}). Bitte später erneut speichern.`);
|
||||
}
|
||||
}
|
||||
const warning = await honeyWarning(values);
|
||||
if (warning) {
|
||||
await setFlash("info", `${message} ${warning}`);
|
||||
redirect(target);
|
||||
}
|
||||
return succeed(target, message);
|
||||
}
|
||||
|
||||
export async function createSponsorshipOfferAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const back = `${OFFERS_PATH}/neu`;
|
||||
const parsed = parseOfferForm(formData);
|
||||
if (!parsed.ok) return fail(back, parsed.message);
|
||||
const values = parsed.value;
|
||||
|
||||
const conflict = await findConflict(values, null);
|
||||
if (conflict) return fail(back, conflict);
|
||||
|
||||
let offerId: string;
|
||||
try {
|
||||
offerId = await prisma.$transaction(async (tx) => {
|
||||
const productId = values.kind === "EINMALIG" ? (await tx.product.create({ data: carrierProductData(values) })).id : null;
|
||||
const offer = await tx.sponsorshipOffer.create({ data: { ...offerData(values), kind: values.kind, productId } });
|
||||
return offer.id;
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (isUniqueViolation(error)) return fail(back, "Adresse bereits vergeben — bitte eine andere wählen.");
|
||||
throw error;
|
||||
}
|
||||
|
||||
await logAdminAction(admin, {
|
||||
action: "sponsorship_offer.create",
|
||||
entityType: "SponsorshipOffer",
|
||||
entityId: offerId,
|
||||
detail: auditDetail(values),
|
||||
});
|
||||
return finishSave(offerId, values, "Angebot angelegt.");
|
||||
}
|
||||
|
||||
export async function updateSponsorshipOfferAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
const existing = await prisma.sponsorshipOffer.findUnique({
|
||||
where: { id },
|
||||
select: { id: true, kind: true, productId: true, isActive: true, priceCents: true },
|
||||
});
|
||||
if (!existing) return fail(OFFERS_PATH, "Das Angebot wurde nicht gefunden.");
|
||||
const back = `${OFFERS_PATH}/${id}`;
|
||||
|
||||
const parsed = parseOfferForm(formData, existing.kind);
|
||||
if (!parsed.ok) return fail(back, parsed.message);
|
||||
const values = parsed.value;
|
||||
|
||||
const conflict = await findConflict(values, existing);
|
||||
if (conflict) return fail(back, conflict);
|
||||
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
let productId = existing.productId;
|
||||
if (values.kind === "EINMALIG") {
|
||||
// Fehlt das Traegerprodukt (Altbestand), wird es hier nachgeholt —
|
||||
// ohne Produkt ist eine Einmal-Patenschaft nicht bestellbar.
|
||||
productId = productId
|
||||
? (await tx.product.update({ where: { id: productId }, data: carrierProductData(values) })).id
|
||||
: (await tx.product.create({ data: carrierProductData(values) })).id;
|
||||
}
|
||||
await tx.sponsorshipOffer.update({ where: { id }, data: { ...offerData(values), productId } });
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (isUniqueViolation(error)) return fail(back, "Adresse bereits vergeben — bitte eine andere wählen.");
|
||||
throw error;
|
||||
}
|
||||
|
||||
const changes = [
|
||||
existing.isActive !== values.isActive ? (values.isActive ? "aktiviert" : "deaktiviert") : null,
|
||||
existing.priceCents !== values.priceCents ? `Preis ${formatPrice(existing.priceCents)} → ${formatPrice(values.priceCents)}` : null,
|
||||
].filter(Boolean);
|
||||
await logAdminAction(admin, {
|
||||
action: "sponsorship_offer.update",
|
||||
entityType: "SponsorshipOffer",
|
||||
entityId: id,
|
||||
detail: `${auditDetail(values)}${changes.length > 0 ? `; ${changes.join(", ")}` : ""}`,
|
||||
});
|
||||
return finishSave(id, values, "Angebot gespeichert.");
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { syncOfferStripePrice } from "@/lib/sponsorship-subscription/stripe-prices";
|
||||
|
||||
/**
|
||||
* Gemeinsame Helfer der Patenschafts-Actions (bewusst ohne "use server":
|
||||
* hier liegen keine aufrufbaren Endpunkte, nur Bausteine).
|
||||
*/
|
||||
|
||||
/** Prisma-Fehler P2002: eindeutiger Wert (Slug, Schwelle) bereits vergeben, etwa durch einen parallelen Speichervorgang. */
|
||||
export function isUniqueViolation(error: unknown): boolean {
|
||||
return typeof error === "object" && error !== null && (error as { code?: unknown }).code === "P2002";
|
||||
}
|
||||
|
||||
export function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt Stripe-Produkt und -Preis eines Abo-Angebots an bzw. zieht sie nach.
|
||||
* Scheitert das (Stripe nicht erreichbar, kein Schluessel), bleibt das
|
||||
* Angebot gespeichert — der Admin bekommt eine klare Meldung und kann erneut
|
||||
* speichern; syncOfferStripePrice ist idempotent. Gibt die Fehlermeldung
|
||||
* zurueck oder null.
|
||||
*/
|
||||
export async function syncStripePriceSafely(offerId: string): Promise<string | null> {
|
||||
try {
|
||||
await syncOfferStripePrice(offerId);
|
||||
return null;
|
||||
} catch (error: unknown) {
|
||||
const message = errorMessage(error);
|
||||
console.error(`[patenschaft] Stripe-Preis fuer Angebot ${offerId} nicht synchronisiert: ${message}`);
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
/** Ganze Zahl aus einem Formularfeld, sonst null (leer, Komma, Buchstaben). */
|
||||
export function intOrNull(value: string): number | null {
|
||||
return /^\d+$/.test(value.trim()) ? Number(value.trim()) : null;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { logAdminAction } from "@/lib/audit-log";
|
||||
import { MAX_SEPA_HOLD_DAYS, SEPA_HOLD_DAYS_KEY, getSepaHoldDays } from "@/lib/sponsorship/settings";
|
||||
import { requireAdmin, fail, succeed, str } from "./_shared";
|
||||
import { intOrNull } from "./sponsorship-shared";
|
||||
|
||||
const SUBSCRIPTIONS_PATH = "/admin/patenschaften/abos";
|
||||
|
||||
/**
|
||||
* Hebt die SEPA-Sperre eines Kontos auf (gesetzt nach einer Rueckbuchung).
|
||||
* Danach kann das Konto neue Abos wieder per Lastschrift abschliessen.
|
||||
*/
|
||||
export async function liftSepaBlockAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const customerId = str(formData, "customerId");
|
||||
const customer = await prisma.customer.findUnique({ where: { id: customerId }, select: { email: true, sepaBlockedAt: true } });
|
||||
if (!customer) return fail(SUBSCRIPTIONS_PATH, "Das Konto wurde nicht gefunden.");
|
||||
if (!customer.sepaBlockedAt) return succeed(SUBSCRIPTIONS_PATH, "Für dieses Konto besteht keine SEPA-Sperre.");
|
||||
|
||||
await prisma.customer.update({ where: { id: customerId }, data: { sepaBlockedAt: null } });
|
||||
await logAdminAction(admin, {
|
||||
action: "customer.sepa_unblock",
|
||||
entityType: "Customer",
|
||||
entityId: customerId,
|
||||
detail: `${customer.email} (gesperrt seit ${customer.sepaBlockedAt.toISOString().slice(0, 10)})`,
|
||||
});
|
||||
revalidatePath(SUBSCRIPTIONS_PATH);
|
||||
return succeed(SUBSCRIPTIONS_PATH, `SEPA-Sperre für ${customer.email} aufgehoben.`);
|
||||
}
|
||||
|
||||
export async function updateSepaHoldDaysAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const days = intOrNull(str(formData, "sepaHoldDays"));
|
||||
if (days === null || days > MAX_SEPA_HOLD_DAYS) {
|
||||
return fail(SUBSCRIPTIONS_PATH, `Bitte eine ganze Zahl von 0 bis ${MAX_SEPA_HOLD_DAYS} Tagen angeben.`);
|
||||
}
|
||||
const previous = await getSepaHoldDays();
|
||||
await prisma.siteContent.upsert({
|
||||
where: { key: SEPA_HOLD_DAYS_KEY },
|
||||
create: { key: SEPA_HOLD_DAYS_KEY, valueDe: String(days) },
|
||||
update: { valueDe: String(days) },
|
||||
});
|
||||
await logAdminAction(admin, {
|
||||
action: "sponsorship.sepa_hold_days",
|
||||
entityType: "SiteContent",
|
||||
entityId: SEPA_HOLD_DAYS_KEY,
|
||||
detail: `${previous} → ${days} Tage`,
|
||||
});
|
||||
revalidatePath(SUBSCRIPTIONS_PATH);
|
||||
return succeed(SUBSCRIPTIONS_PATH, days === 0 ? "SEPA-Neukunden-Frist abgeschaltet." : `SEPA-Neukunden-Frist auf ${days} Tage gesetzt.`);
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { logAdminAction } from "@/lib/audit-log";
|
||||
import { sendMail } from "@/lib/mail";
|
||||
import { MAIL_FAILED_HINT } from "@/lib/flash";
|
||||
import { getBaseUrl } from "@/lib/url";
|
||||
import { defaultLocale, isLocale } from "@/i18n/config";
|
||||
import { processSponsorship, resetSponsorshipForRetry, type ProcessResult } from "@/lib/sponsorship/issue";
|
||||
import { sponsorshipReadyEmail } from "@/lib/sponsorship/emails";
|
||||
import { reviseSponsorship, type ReviseSponsorshipError } from "@/lib/sponsorship/revise";
|
||||
import { beeNameFromJson } from "@/app/admin/patenschaften/_lib/revision-data";
|
||||
import { requireAdmin, fail, succeed, str } from "./_shared";
|
||||
|
||||
const LIST_PATH = "/admin/patenschaften";
|
||||
|
||||
function detailPath(id: string): string {
|
||||
return `${LIST_PATH}/${id}`;
|
||||
}
|
||||
|
||||
export async function markSponsorshipPrintedAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
// Atomar an den Zustand gebunden: ein Doppelklick oder ein zweiter Tab
|
||||
// setzt printedAt nicht ein zweites Mal neu.
|
||||
const updated = await prisma.sponsorship.updateMany({
|
||||
where: { id, status: "BEREIT", printedAt: null, offer: { isPhysical: true } },
|
||||
data: { status: "GEDRUCKT", printedAt: new Date() },
|
||||
});
|
||||
if (updated.count === 0) {
|
||||
return fail(detailPath(id), "Nur bereite, noch nicht gedruckte Urkunden physischer Pakete lassen sich als gedruckt markieren.");
|
||||
}
|
||||
const sponsorship = await prisma.sponsorship.findUnique({ where: { id }, select: { number: true } });
|
||||
await logAdminAction(admin, {
|
||||
action: "sponsorship.mark_printed",
|
||||
entityType: "Sponsorship",
|
||||
entityId: id,
|
||||
detail: sponsorship?.number,
|
||||
});
|
||||
revalidatePath(LIST_PATH);
|
||||
return succeed(detailPath(id), "Als gedruckt markiert.");
|
||||
}
|
||||
|
||||
const PROCESS_MESSAGES: Record<ProcessResult, string> = {
|
||||
ready: "Urkunde erzeugt und Mail versendet.",
|
||||
retry: "Der Versuch ist fehlgeschlagen. Der nächste automatische Versuch ist eingeplant — Fehler siehe unten.",
|
||||
failed: "Der Versuch ist fehlgeschlagen. Alle automatischen Versuche sind aufgebraucht — Fehler siehe unten.",
|
||||
missing: "Die Patenschaft wurde nicht gefunden.",
|
||||
revoked: "Die Patenschaft ist widerrufen (Bestellung storniert oder erstattet) und wird nicht mehr ausgestellt.",
|
||||
};
|
||||
|
||||
/**
|
||||
* "Erneut erzeugen": bei FEHLER werden die Versuche zurueckgesetzt, bei
|
||||
* AUSSTEHEND wird nur sofort ein Versuch gestartet, statt auf den CronJob zu
|
||||
* warten. Beides laeuft ueber processSponsorship — Revision 1 entsteht dort
|
||||
* nur, solange es noch keine gibt, eine Wiederholung erzeugt also nie eine
|
||||
* zweite Urkunde.
|
||||
*/
|
||||
export async function retrySponsorshipAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
const sponsorship = await prisma.sponsorship.findUnique({ where: { id }, select: { number: true, status: true } });
|
||||
if (!sponsorship) return fail(LIST_PATH, "Die Patenschaft wurde nicht gefunden.");
|
||||
if (sponsorship.status !== "FEHLER" && sponsorship.status !== "AUSSTEHEND") {
|
||||
return fail(detailPath(id), "Die Urkunde ist bereits erzeugt.");
|
||||
}
|
||||
if (sponsorship.status === "FEHLER") await resetSponsorshipForRetry(id);
|
||||
const result = await processSponsorship(id);
|
||||
await logAdminAction(admin, {
|
||||
action: "sponsorship.retry",
|
||||
entityType: "Sponsorship",
|
||||
entityId: id,
|
||||
detail: `${sponsorship.number}: ${sponsorship.status} → ${result}`,
|
||||
});
|
||||
revalidatePath(LIST_PATH);
|
||||
if (result !== "ready") return fail(detailPath(id), PROCESS_MESSAGES[result]);
|
||||
return succeed(detailPath(id), PROCESS_MESSAGES.ready);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Mail erneut senden" — nur der Versand, sonst nichts. Bewusst NICHT ueber
|
||||
* processSponsorship: das bricht bei BEREIT/GEDRUCKT sofort ab, und den
|
||||
* Status dafuer zurueckzusetzen wuerde einen gedruckten Stand verlieren.
|
||||
* Revisionen werden hier weder gelesen noch angelegt, ausser zum Auslesen
|
||||
* des aktuellen Bienennamens.
|
||||
*/
|
||||
export async function resendSponsorshipMailAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
const sponsorship = await prisma.sponsorship.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
id: true,
|
||||
number: true,
|
||||
status: true,
|
||||
locale: true,
|
||||
currentRevision: true,
|
||||
owner: { select: { email: true, firstName: true } },
|
||||
},
|
||||
});
|
||||
if (!sponsorship) return fail(LIST_PATH, "Die Patenschaft wurde nicht gefunden.");
|
||||
if ((sponsorship.status !== "BEREIT" && sponsorship.status !== "GEDRUCKT") || sponsorship.currentRevision === 0) {
|
||||
return fail(detailPath(id), "Die Mail lässt sich erst erneut senden, wenn die Urkunde zugestellt wurde.");
|
||||
}
|
||||
const revision = await prisma.sponsorshipRevision.findUnique({
|
||||
where: { sponsorshipId_revision: { sponsorshipId: id, revision: sponsorship.currentRevision } },
|
||||
select: { personalization: true },
|
||||
});
|
||||
const locale = isLocale(sponsorship.locale) ? sponsorship.locale : defaultLocale;
|
||||
const { subject, html, text } = await sponsorshipReadyEmail({
|
||||
locale,
|
||||
firstName: sponsorship.owner.firstName,
|
||||
beeName: beeNameFromJson(revision?.personalization) ?? "",
|
||||
number: sponsorship.number,
|
||||
accountUrl: `${getBaseUrl()}/konto/patenschaft/${sponsorship.id}`,
|
||||
});
|
||||
const sent = await sendMail({ to: sponsorship.owner.email, subject, html, text });
|
||||
if (!sent) return fail(detailPath(id), MAIL_FAILED_HINT);
|
||||
|
||||
await prisma.sponsorship.update({ where: { id }, data: { mailSentAt: new Date() } });
|
||||
await logAdminAction(admin, {
|
||||
action: "sponsorship.resend_mail",
|
||||
entityType: "Sponsorship",
|
||||
entityId: id,
|
||||
detail: `${sponsorship.number} an ${sponsorship.owner.email}`,
|
||||
});
|
||||
return succeed(detailPath(id), `Mail erneut an ${sponsorship.owner.email} gesendet.`);
|
||||
}
|
||||
|
||||
const FIELD_LABELS: Record<string, string> = {
|
||||
beeName: "Name der Patenbiene",
|
||||
recipientName: "Name auf der Urkunde",
|
||||
giverNames: "Schenkende",
|
||||
dedication: "Widmung",
|
||||
occasion: "Anlass",
|
||||
startDate: "Startdatum",
|
||||
layout: "Gesamtlayout",
|
||||
};
|
||||
|
||||
const SCHEMA_MESSAGES: Record<string, string> = {
|
||||
required: "ist ein Pflichtfeld",
|
||||
too_short: "ist zu kurz",
|
||||
too_long: "ist zu lang",
|
||||
too_many_line_breaks: "hat zu viele Zeilenumbrüche",
|
||||
no_letter: "braucht mindestens einen Buchstaben",
|
||||
invalid_date: "ist kein gültiges Datum",
|
||||
};
|
||||
|
||||
function revisionErrorMessage(error: ReviseSponsorshipError): string {
|
||||
switch (error.code) {
|
||||
case "not_found":
|
||||
return "Die Patenschaft wurde nicht gefunden.";
|
||||
case "no_revision":
|
||||
return "Die Urkunde wurde noch nicht erzeugt — korrigieren lässt sich erst eine bestehende Urkunde.";
|
||||
case "revoked":
|
||||
return "Die Patenschaft ist widerrufen (Bestellung storniert oder erstattet) und lässt sich nicht mehr korrigieren.";
|
||||
case "reason":
|
||||
return `Bitte einen Änderungsgrund angeben (${error.min}–${error.max} Zeichen).`;
|
||||
case "unknown_template":
|
||||
return "Unbekannte Vorlagenversion.";
|
||||
case "unchanged":
|
||||
return "Keine Änderung gegenüber der aktuellen Revision.";
|
||||
case "start_date_out_of_range":
|
||||
return `Das Startdatum muss zwischen ${error.min} und ${error.max} liegen.`;
|
||||
case "invalid": {
|
||||
const label = error.field ? FIELD_LABELS[error.field] : "Eingabe";
|
||||
return `${label} ${SCHEMA_MESSAGES[error.message] ?? "ist ungültig"}.`;
|
||||
}
|
||||
case "glyphs":
|
||||
return `${FIELD_LABELS[error.field] ?? "Text"}: diese Zeichen kann die Urkunde nicht drucken: ${error.characters.join(" ")}`;
|
||||
case "fit":
|
||||
return `${FIELD_LABELS[error.field] ?? "Text"} passt so nicht auf die Urkunde — bitte kürzen.`;
|
||||
case "conflict":
|
||||
return "Die Urkunde wurde gerade von jemand anderem korrigiert. Bitte die Seite neu laden und erneut prüfen.";
|
||||
}
|
||||
}
|
||||
|
||||
export async function reviseSponsorshipAction(formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin();
|
||||
const id = str(formData, "id");
|
||||
const back = `${detailPath(id)}/korrigieren`;
|
||||
const result = await reviseSponsorship({
|
||||
sponsorshipId: id,
|
||||
personalization: {
|
||||
beeName: String(formData.get("beeName") ?? ""),
|
||||
recipientName: String(formData.get("recipientName") ?? ""),
|
||||
giverNames: String(formData.get("giverNames") ?? ""),
|
||||
dedication: String(formData.get("dedication") ?? ""),
|
||||
occasion: str(formData, "occasion"),
|
||||
startDate: str(formData, "startDate"),
|
||||
},
|
||||
reason: String(formData.get("reason") ?? ""),
|
||||
templateVersion: str(formData, "templateVersion") || null,
|
||||
notifyCustomer: formData.get("notifyCustomer") === "on",
|
||||
admin,
|
||||
});
|
||||
if (!result.ok) return fail(back, revisionErrorMessage(result.error));
|
||||
|
||||
revalidatePath(LIST_PATH);
|
||||
const message = `Revision ${result.revision} gespeichert.`;
|
||||
if (result.mailSent === false) return fail(detailPath(id), `${message} ${MAIL_FAILED_HINT}`);
|
||||
return succeed(detailPath(id), result.mailSent ? `${message} Kunde benachrichtigt.` : message);
|
||||
}
|
||||
@@ -9,6 +9,9 @@ import {
|
||||
AdminSearchForm,
|
||||
type AdminBadgeTone,
|
||||
} from "@/components/admin-list";
|
||||
import { AdminArchiveTabs } from "@/components/admin-archive";
|
||||
import { isArchiveView } from "@/lib/archive";
|
||||
import { inquiryViewWhere } from "@/lib/inquiry-status";
|
||||
import { updateBusinessInquiryStatusAction } from "../actions";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getDictionary } from "@/i18n/get-dictionary";
|
||||
@@ -28,35 +31,57 @@ export default async function AdminInquiriesPage(props: PageProps<"/admin/anfrag
|
||||
ABGESCHLOSSEN: t.adminInquiriesPage.statusCompleted,
|
||||
ABGELEHNT: t.adminInquiriesPage.statusRejected,
|
||||
};
|
||||
const { q } = await props.searchParams;
|
||||
const { q, ansicht } = await props.searchParams;
|
||||
const query = typeof q === "string" ? q.trim() : "";
|
||||
const isArchive = isArchiveView(ansicht);
|
||||
|
||||
const inquiries = await prisma.businessInquiry.findMany({
|
||||
where: query
|
||||
? {
|
||||
OR: [
|
||||
{ companyName: insensitiveContains(query) },
|
||||
{ contactPerson: insensitiveContains(query) },
|
||||
{ email: insensitiveContains(query) },
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 100,
|
||||
});
|
||||
const filterWhere = query
|
||||
? {
|
||||
OR: [
|
||||
{ companyName: insensitiveContains(query) },
|
||||
{ contactPerson: insensitiveContains(query) },
|
||||
{ email: insensitiveContains(query) },
|
||||
],
|
||||
}
|
||||
: {};
|
||||
|
||||
const [inquiries, activeCount, archivedCount] = await Promise.all([
|
||||
prisma.businessInquiry.findMany({
|
||||
where: { ...filterWhere, ...inquiryViewWhere(isArchive) },
|
||||
// Aktiv: zuletzt eingegangen oben. Archiv: zuletzt erledigt oben.
|
||||
orderBy: isArchive ? { updatedAt: "desc" } : { createdAt: "desc" },
|
||||
take: 100,
|
||||
}),
|
||||
prisma.businessInquiry.count({ where: { ...filterWhere, ...inquiryViewWhere(false) } }),
|
||||
prisma.businessInquiry.count({ where: { ...filterWhere, ...inquiryViewWhere(true) } }),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<BackLink href="/admin" label={t.adminInquiriesPage.backToDashboard} />
|
||||
<AdminPageHeader title={t.adminInquiriesPage.title} />
|
||||
|
||||
<AdminArchiveTabs
|
||||
basePath="/admin/anfragen"
|
||||
isArchive={isArchive}
|
||||
counts={{ active: activeCount, archived: archivedCount }}
|
||||
keepParams={{ q: query }}
|
||||
labels={{
|
||||
ariaLabel: t.adminArchive.tabsAriaLabel,
|
||||
active: t.adminArchive.tabActive,
|
||||
archive: t.adminArchive.tabArchive,
|
||||
}}
|
||||
/>
|
||||
{isArchive ? <p className="mb-6 text-xs text-ink/60 max-w-2xl">{t.adminArchive.autoRuleInquiries}</p> : null}
|
||||
|
||||
<AdminSearchForm
|
||||
query={query}
|
||||
label={t.adminInquiriesPage.searchLabel}
|
||||
placeholder={t.adminInquiriesPage.searchPlaceholder}
|
||||
submitLabel={t.adminInquiriesPage.filterButton}
|
||||
resetHref="/admin/anfragen"
|
||||
resetHref={isArchive ? "/admin/anfragen?ansicht=archiv" : "/admin/anfragen"}
|
||||
resetLabel={t.adminInquiriesPage.resetFilter}
|
||||
hiddenFields={isArchive ? { ansicht: "archiv" } : {}}
|
||||
/>
|
||||
<div className="space-y-4">
|
||||
{inquiries.map((inquiry) => (
|
||||
@@ -119,7 +144,15 @@ export default async function AdminInquiriesPage(props: PageProps<"/admin/anfrag
|
||||
{inquiries.length === 0 ? (
|
||||
<AdminEmptyState
|
||||
bordered
|
||||
message={query ? t.adminInquiriesPage.noResultsFiltered : t.adminInquiriesPage.noInquiriesYet}
|
||||
message={
|
||||
query
|
||||
? t.adminInquiriesPage.noResultsFiltered
|
||||
: isArchive
|
||||
? t.adminArchive.emptyArchive
|
||||
: archivedCount > 0
|
||||
? t.adminInquiriesPage.noOpenInquiries
|
||||
: t.adminInquiriesPage.noInquiriesYet
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -17,25 +17,36 @@ import { getDictionary } from "@/i18n/get-dictionary";
|
||||
import { isDhlConfigured } from "@/lib/dhl";
|
||||
import { OrderStatusBadge, OrderStatusTimeline } from "@/components/account-ui";
|
||||
import { Button } from "@/components/ui";
|
||||
import { getSponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
|
||||
export default async function AdminOrderDetailPage(props: PageProps<"/admin/bestellungen/[id]">) {
|
||||
const t = getDictionary(await getLocale());
|
||||
const locale = await getLocale();
|
||||
const t = getDictionary(locale);
|
||||
const statusLabels = t.orderStatusBadge;
|
||||
const { id } = await props.params;
|
||||
const order = await prisma.order.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
items: { include: { product: { select: { slug: true } }, batch: { select: { code: true } } } },
|
||||
items: {
|
||||
include: {
|
||||
product: { select: { slug: true } },
|
||||
batch: { select: { code: true } },
|
||||
sponsorship: { select: { number: true, status: true } },
|
||||
},
|
||||
},
|
||||
payment: true,
|
||||
shipment: true,
|
||||
pickup: true,
|
||||
invoice: true,
|
||||
invoice: { include: { cancellation: { select: { number: true } } } },
|
||||
customer: { select: { email: true, firstName: true, lastName: true } },
|
||||
discountCode: { select: { code: true } },
|
||||
},
|
||||
});
|
||||
if (!order) notFound();
|
||||
const dhlConfigured = isDhlConfigured();
|
||||
// Storno/Erstattung widerruft Patenschaften (lib/sponsorship/revoke.ts);
|
||||
// ein Wiederoeffnen stellt sie bewusst nicht von selbst wieder her.
|
||||
const revokedNumbers = order.items.flatMap((item) => (item.sponsorship?.status === "WIDERRUFEN" ? [item.sponsorship.number] : []));
|
||||
// Dieselbe Regel, die deleteOrderAction serverseitig durchsetzt — geteilt
|
||||
// ueber lib/order-delete.ts, damit Anzeige und Durchsetzung nicht
|
||||
// auseinanderlaufen koennen.
|
||||
@@ -88,6 +99,12 @@ export default async function AdminOrderDetailPage(props: PageProps<"/admin/best
|
||||
/>
|
||||
</div>
|
||||
|
||||
{revokedNumbers.length > 0 ? (
|
||||
<p role="note" className="mb-8 border border-ink/20 bg-ink/[0.03] px-6 py-4 text-sm text-ink/80">
|
||||
{getSponsorshipAdminStrings(locale).order.revokedNote(revokedNumbers.join(", "))}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{order.giftMessage ? (
|
||||
<div className="bg-honey/10 border border-honey-dark/30 p-6 mb-8">
|
||||
<h2 className="text-xs tracking-wide-caps text-honey-dark mb-3">{t.adminOrderDetailPage.giftHeading}</h2>
|
||||
@@ -211,7 +228,7 @@ export default async function AdminOrderDetailPage(props: PageProps<"/admin/best
|
||||
<Link href={`/admin/produkte/${item.productId}`} className="text-heading underline">
|
||||
{item.productName}
|
||||
</Link>{" "}
|
||||
<span className="text-ink/65">({item.weightGrams} g)</span>
|
||||
{item.weightGrams > 0 ? <span className="text-ink/65">({item.weightGrams} g)</span> : null}
|
||||
</td>
|
||||
<td className="py-2 text-ink/70">{item.batch?.code ?? "—"}</td>
|
||||
<td className="py-2 text-right">{item.quantity}</td>
|
||||
@@ -279,6 +296,19 @@ export default async function AdminOrderDetailPage(props: PageProps<"/admin/best
|
||||
>
|
||||
{t.adminOrderDetailPage.downloadPdf}
|
||||
</a>
|
||||
{order.invoice.cancellation && (
|
||||
<>
|
||||
<span className="mt-3">
|
||||
{t.invoicePage.cancellationTitle} {order.invoice.cancellation.number}
|
||||
</span>
|
||||
<a
|
||||
href={`/rechnung/${order.invoice.cancellation.number}/pdf`}
|
||||
className="link-draw text-sm text-heading"
|
||||
>
|
||||
{t.adminOrderDetailPage.downloadPdf}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-ink/65">{t.adminOrderDetailPage.noInvoiceYet}</p>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Link from "next/link";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { BackLink } from "@/components/back-link";
|
||||
import { ConfirmForm } from "@/components/confirm-form";
|
||||
import { formatDate } from "@/lib/format";
|
||||
@@ -12,114 +13,234 @@ import {
|
||||
AdminRowActions,
|
||||
AdminSearchForm,
|
||||
} from "@/components/admin-list";
|
||||
import { AdminArchiveTabs } from "@/components/admin-archive";
|
||||
import { insensitiveContains } from "@/lib/prisma-search";
|
||||
import { approveReviewAction, deleteReviewAction } from "../actions";
|
||||
import { isArchiveView } from "@/lib/archive";
|
||||
import { approvedReviewWhere, pendingReviewWhere, rejectedReviewWhere } from "@/lib/review-status";
|
||||
import { approveReviewAction, deleteReviewAction, rejectReviewAction } from "../actions";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getDictionary } from "@/i18n/get-dictionary";
|
||||
import type { Dictionary } from "@/i18n/dictionary-type";
|
||||
|
||||
const MAX_ROWS = 100;
|
||||
const BASE_PATH = "/admin/bewertungen";
|
||||
|
||||
const REVIEW_INCLUDE = {
|
||||
product: { select: { name: true, slug: true } },
|
||||
customer: { select: { firstName: true, lastName: true } },
|
||||
} satisfies Prisma.ReviewInclude;
|
||||
|
||||
type AdminReview = Prisma.ReviewGetPayload<{ include: typeof REVIEW_INCLUDE }>;
|
||||
type ReviewTexts = Dictionary["adminReviewsPage"];
|
||||
|
||||
function searchWhere(query: string): Prisma.ReviewWhereInput {
|
||||
if (!query) return {};
|
||||
return {
|
||||
OR: [
|
||||
{ product: { name: insensitiveContains(query) } },
|
||||
{ customer: { firstName: insensitiveContains(query) } },
|
||||
{ customer: { lastName: insensitiveContains(query) } },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export default async function AdminBewertungenPage(props: PageProps<"/admin/bewertungen">) {
|
||||
const t = getDictionary(await getLocale());
|
||||
const { q } = await props.searchParams;
|
||||
const s = t.adminReviewsPage;
|
||||
const { q, ansicht } = await props.searchParams;
|
||||
const query = typeof q === "string" ? q.trim() : "";
|
||||
const isArchive = isArchiveView(ansicht);
|
||||
const filter = searchWhere(query);
|
||||
|
||||
const reviews = await prisma.review.findMany({
|
||||
where: query
|
||||
? {
|
||||
OR: [
|
||||
{ product: { name: insensitiveContains(query) } },
|
||||
{ customer: { firstName: insensitiveContains(query) } },
|
||||
{ customer: { lastName: insensitiveContains(query) } },
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
include: {
|
||||
product: { select: { name: true, slug: true } },
|
||||
customer: { select: { firstName: true, lastName: true } },
|
||||
},
|
||||
orderBy: [{ isApproved: "asc" }, { createdAt: "desc" }],
|
||||
take: 100,
|
||||
});
|
||||
const findReviews = (where: Prisma.ReviewWhereInput, orderBy: Prisma.ReviewOrderByWithRelationInput) =>
|
||||
prisma.review.findMany({ where: { ...filter, ...where }, include: REVIEW_INCLUDE, orderBy, take: MAX_ROWS });
|
||||
|
||||
// Offene: aelteste zuerst, sie warten am laengsten. Archiv: zuletzt entschiedene oben.
|
||||
const [pending, approved, rejected, pendingCount, decidedCount] = await Promise.all([
|
||||
isArchive ? Promise.resolve([]) : findReviews(pendingReviewWhere(), { createdAt: "asc" }),
|
||||
isArchive ? findReviews(approvedReviewWhere(), { updatedAt: "desc" }) : Promise.resolve([]),
|
||||
isArchive ? findReviews(rejectedReviewWhere(), { rejectedAt: "desc" }) : Promise.resolve([]),
|
||||
prisma.review.count({ where: { ...filter, ...pendingReviewWhere() } }),
|
||||
prisma.review.count({ where: { ...filter, NOT: pendingReviewWhere() } }),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<BackLink href="/admin" label={t.adminReviewsPage.backToDashboard} />
|
||||
<AdminPageHeader title={t.adminReviewsPage.title} />
|
||||
<BackLink href="/admin" label={s.backToDashboard} />
|
||||
<AdminPageHeader title={s.title} />
|
||||
|
||||
<AdminArchiveTabs
|
||||
basePath={BASE_PATH}
|
||||
isArchive={isArchive}
|
||||
counts={{ active: pendingCount, archived: decidedCount }}
|
||||
keepParams={{ q: query }}
|
||||
labels={{
|
||||
ariaLabel: t.adminArchive.tabsAriaLabel,
|
||||
active: t.adminArchive.tabActive,
|
||||
archive: t.adminArchive.tabArchive,
|
||||
}}
|
||||
/>
|
||||
{isArchive ? <p className="mb-6 text-xs text-ink/60 max-w-2xl">{t.adminArchive.autoRuleReviews}</p> : null}
|
||||
|
||||
<AdminSearchForm
|
||||
query={query}
|
||||
label={t.adminReviewsPage.searchLabel}
|
||||
placeholder={t.adminReviewsPage.searchPlaceholder}
|
||||
submitLabel={t.adminReviewsPage.filterButton}
|
||||
resetHref="/admin/bewertungen"
|
||||
resetLabel={t.adminReviewsPage.resetFilter}
|
||||
label={s.searchLabel}
|
||||
placeholder={s.searchPlaceholder}
|
||||
submitLabel={s.filterButton}
|
||||
resetHref={isArchive ? `${BASE_PATH}?ansicht=archiv` : BASE_PATH}
|
||||
resetLabel={s.resetFilter}
|
||||
hiddenFields={isArchive ? { ansicht: "archiv" } : {}}
|
||||
/>
|
||||
|
||||
<div className="overflow-x-auto bg-background border border-ink/10">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-left text-ink/65 border-b border-ink/10">
|
||||
<tr>
|
||||
<th className="p-4">{t.adminReviewsPage.colProduct}</th>
|
||||
<th className="p-4">{t.adminReviewsPage.colCustomer}</th>
|
||||
<th className="p-4">{t.adminReviewsPage.colRating}</th>
|
||||
<th className="p-4">{t.adminReviewsPage.colComment}</th>
|
||||
<th className="p-4">{t.adminReviewsPage.colDate}</th>
|
||||
<th className="p-4">{t.adminReviewsPage.colStatus}</th>
|
||||
<th className="p-4" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-ink/10">
|
||||
{reviews.map((review) => (
|
||||
<tr key={review.id} className="transition-colors hover:bg-ink/[0.03]">
|
||||
<td className="p-4">
|
||||
<Link href={`/honig/${review.product.slug}`} className="link-draw text-heading">
|
||||
{review.product.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="p-4">
|
||||
{review.customer.firstName} {review.customer.lastName}
|
||||
</td>
|
||||
<td className="p-4 whitespace-nowrap">
|
||||
<StarRating value={review.rating} />
|
||||
<span className="sr-only">{review.rating} / 5</span>
|
||||
</td>
|
||||
<td className="p-4 max-w-xs">{review.comment ?? "—"}</td>
|
||||
<td className="p-4 whitespace-nowrap">{formatDate(review.createdAt)}</td>
|
||||
<td className="p-4">
|
||||
{review.isApproved ? (
|
||||
<AdminBadge tone="positive">{t.adminReviewsPage.statusPublished}</AdminBadge>
|
||||
) : (
|
||||
<AdminBadge tone="pending" pulse>
|
||||
{t.adminReviewsPage.statusPending}
|
||||
</AdminBadge>
|
||||
)}
|
||||
</td>
|
||||
<td className="p-4">
|
||||
<AdminRowActions>
|
||||
{!review.isApproved ? (
|
||||
<form action={approveReviewAction}>
|
||||
<input type="hidden" name="id" value={review.id} />
|
||||
<AdminActionButton>{t.adminReviewsPage.approve}</AdminActionButton>
|
||||
</form>
|
||||
) : null}
|
||||
<ConfirmForm
|
||||
action={deleteReviewAction}
|
||||
confirmMessage={t.adminReviewsPage.deleteConfirm}
|
||||
>
|
||||
<input type="hidden" name="id" value={review.id} />
|
||||
<AdminActionButton tone="danger">{t.adminReviewsPage.delete}</AdminActionButton>
|
||||
</ConfirmForm>
|
||||
</AdminRowActions>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{reviews.length === 0 ? (
|
||||
<AdminEmptyState
|
||||
message={query ? t.adminReviewsPage.noResultsFiltered : t.adminReviewsPage.noReviewsYet}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
{isArchive ? (
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<DecidedColumn title={s.columnApproved} reviews={approved} decision="approved" s={s} />
|
||||
<DecidedColumn title={s.columnRejected} reviews={rejected} decision="rejected" s={s} />
|
||||
</div>
|
||||
) : (
|
||||
<PendingTable reviews={pending} query={query} s={s} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PendingTable({ reviews, query, s }: { reviews: AdminReview[]; query: string; s: ReviewTexts }) {
|
||||
return (
|
||||
<div className="overflow-x-auto bg-background border border-ink/10">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-left text-ink/65 border-b border-ink/10">
|
||||
<tr>
|
||||
<th className="p-4">{s.colProduct}</th>
|
||||
<th className="p-4">{s.colCustomer}</th>
|
||||
<th className="p-4">{s.colRating}</th>
|
||||
<th className="p-4">{s.colComment}</th>
|
||||
<th className="p-4">{s.colDate}</th>
|
||||
<th className="p-4">{s.colStatus}</th>
|
||||
<th className="p-4" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-ink/10">
|
||||
{reviews.map((review) => (
|
||||
<tr key={review.id} className="transition-colors hover:bg-ink/[0.03]">
|
||||
<td className="p-4">
|
||||
<ProductLink review={review} />
|
||||
</td>
|
||||
<td className="p-4">
|
||||
{review.customer.firstName} {review.customer.lastName}
|
||||
</td>
|
||||
<td className="p-4 whitespace-nowrap">
|
||||
<Stars rating={review.rating} />
|
||||
</td>
|
||||
<td className="p-4 max-w-xs">{review.comment ?? "—"}</td>
|
||||
<td className="p-4 whitespace-nowrap">{formatDate(review.createdAt)}</td>
|
||||
<td className="p-4">
|
||||
<AdminBadge tone="pending" pulse>
|
||||
{s.statusPending}
|
||||
</AdminBadge>
|
||||
</td>
|
||||
<td className="p-4">
|
||||
<ReviewActions review={review} decision="pending" s={s} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{reviews.length === 0 ? (
|
||||
<AdminEmptyState message={query ? s.noResultsFiltered : s.noPendingReviews} />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DecidedColumn({
|
||||
title,
|
||||
reviews,
|
||||
decision,
|
||||
s,
|
||||
}: {
|
||||
title: string;
|
||||
reviews: AdminReview[];
|
||||
decision: "approved" | "rejected";
|
||||
s: ReviewTexts;
|
||||
}) {
|
||||
return (
|
||||
<section aria-label={title} className="bg-background border border-ink/10">
|
||||
<h2 className="flex items-center justify-between gap-3 border-b border-ink/10 px-5 py-3 text-heading">
|
||||
{title}
|
||||
<AdminBadge tone={decision === "approved" ? "positive" : "neutral"}>{reviews.length}</AdminBadge>
|
||||
</h2>
|
||||
{reviews.length === 0 ? (
|
||||
<p className="px-5 py-6 text-sm text-ink/60">{s.emptyColumn}</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-ink/10">
|
||||
{reviews.map((review) => (
|
||||
<li key={review.id} className="space-y-2 px-5 py-4 text-sm">
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<ProductLink review={review} />
|
||||
<Stars rating={review.rating} />
|
||||
</div>
|
||||
<p className="text-ink/70">
|
||||
{review.customer.firstName} {review.customer.lastName} ·{" "}
|
||||
<span className="tabular-nums">{formatDate(review.createdAt)}</span>
|
||||
</p>
|
||||
{review.comment ? <p className="text-ink/80">{review.comment}</p> : null}
|
||||
{decision === "rejected" && review.rejectedAt ? (
|
||||
<p className="text-xs text-ink/55">{s.rejectedOn(formatDate(review.rejectedAt))}</p>
|
||||
) : null}
|
||||
<ReviewActions review={review} decision={decision} s={s} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function ProductLink({ review }: { review: AdminReview }) {
|
||||
return (
|
||||
<Link href={`/honig/${review.product.slug}`} className="link-draw text-heading">
|
||||
{review.product.name}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function Stars({ rating }: { rating: number }) {
|
||||
return (
|
||||
<span className="whitespace-nowrap">
|
||||
<StarRating value={rating} />
|
||||
<span className="sr-only">{rating} / 5</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Freischalten und Ablehnen jeweils nur dort, wo es den Stand aendert; Loeschen immer. */
|
||||
function ReviewActions({
|
||||
review,
|
||||
decision,
|
||||
s,
|
||||
}: {
|
||||
review: AdminReview;
|
||||
decision: "pending" | "approved" | "rejected";
|
||||
s: ReviewTexts;
|
||||
}) {
|
||||
return (
|
||||
<AdminRowActions>
|
||||
{decision !== "approved" ? (
|
||||
<form action={approveReviewAction}>
|
||||
<input type="hidden" name="id" value={review.id} />
|
||||
<AdminActionButton>{s.approve}</AdminActionButton>
|
||||
</form>
|
||||
) : null}
|
||||
{decision !== "rejected" ? (
|
||||
<ConfirmForm action={rejectReviewAction} confirmMessage={s.rejectConfirm}>
|
||||
<input type="hidden" name="id" value={review.id} />
|
||||
<AdminActionButton>{s.reject}</AdminActionButton>
|
||||
</ConfirmForm>
|
||||
) : null}
|
||||
<ConfirmForm action={deleteReviewAction} confirmMessage={s.deleteConfirm}>
|
||||
<input type="hidden" name="id" value={review.id} />
|
||||
<AdminActionButton tone="danger">{s.delete}</AdminActionButton>
|
||||
</ConfirmForm>
|
||||
</AdminRowActions>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { redirect } from "next/navigation";
|
||||
import { noticeUrl } from "@/lib/notice";
|
||||
import { getCurrentAdmin } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { pendingReviewWhere } from "@/lib/review-status";
|
||||
import { logoutAction } from "@/app/konto/actions";
|
||||
import { AdminShell } from "@/components/admin-shell";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
@@ -54,11 +55,16 @@ export default async function AdminLayout({ children }: LayoutProps<"/admin">) {
|
||||
const themeChoice = parseThemeChoice((await cookies()).get(THEME_COOKIE)?.value);
|
||||
const [openOrders, openReturns, openWithdrawals, pendingReviews, newInquiries] = await Promise.all([
|
||||
prisma.order.count({
|
||||
where: { status: { in: ["BEZAHLT", "IN_VORBEREITUNG", "VERSANDBEREIT", "ABHOLBEREIT"] }, archivedAt: null },
|
||||
// DIGITAL (nur Patenschaften, Abo-Monatsrechnungen): nichts zu packen.
|
||||
where: {
|
||||
status: { in: ["BEZAHLT", "IN_VORBEREITUNG", "VERSANDBEREIT", "ABHOLBEREIT"] },
|
||||
archivedAt: null,
|
||||
fulfillmentMethod: { not: "DIGITAL" },
|
||||
},
|
||||
}),
|
||||
prisma.returnRequest.count({ where: { status: "ANGEFRAGT" } }),
|
||||
prisma.withdrawalDeclaration.count({ where: { processedAt: null } }),
|
||||
prisma.review.count({ where: { isApproved: false } }),
|
||||
prisma.review.count({ where: pendingReviewWhere() }),
|
||||
prisma.businessInquiry.count({ where: { status: "NEU" } }),
|
||||
]);
|
||||
|
||||
|
||||
+35
-8
@@ -1,7 +1,9 @@
|
||||
import Link from "next/link";
|
||||
import { ApiCoreSyncPanel, ApiCoreSyncResult } from "@/components/apicore-sync-panel";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { COUNTED_SALE_WHERE } from "@/lib/sales";
|
||||
import { pendingReviewWhere } from "@/lib/review-status";
|
||||
import { countApiCoreStockIssues } from "@/lib/apicore-stock/dashboard";
|
||||
import { COUNTED_SALE_WHERE, SHOP_SALE_WHERE } from "@/lib/sales";
|
||||
import { formatPrice } from "@/lib/format";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getDictionary } from "@/i18n/get-dictionary";
|
||||
@@ -9,6 +11,7 @@ import { checkUploadFiles } from "@/lib/upload-health";
|
||||
import { checkUploadVolume } from "@/lib/uploads";
|
||||
import { getCurrentAdmin } from "@/lib/auth";
|
||||
import { HexMark } from "@/components/honeycomb";
|
||||
import { getSponsorshipAttentionItems } from "@/app/admin/patenschaften/_lib/attention";
|
||||
|
||||
const DASHBOARD_ICON_PROPS = {
|
||||
width: 20,
|
||||
@@ -127,14 +130,20 @@ export default async function AdminDashboardPage(props: PageProps<"/admin">) {
|
||||
where: { createdAt: { gte: startOfMonth() }, ...COUNTED_SALE_WHERE },
|
||||
}),
|
||||
prisma.order.count({
|
||||
where: { status: { notIn: ["VERSENDET", "ABGEHOLT", "STORNIERT"] } },
|
||||
where: { status: { notIn: ["VERSENDET", "ABGEHOLT", "STORNIERT"] }, fulfillmentMethod: { not: "DIGITAL" } },
|
||||
}),
|
||||
prisma.inventory.aggregate({ _sum: { quantity: true } }),
|
||||
prisma.orderItem.aggregate({ _sum: { quantity: true }, where: { order: COUNTED_SALE_WHERE } }),
|
||||
// Glaeser: Patenschafts-Positionen (Urkunde, Abo-Monatszeilen) sind keine.
|
||||
prisma.orderItem.aggregate({
|
||||
_sum: { quantity: true },
|
||||
where: { order: COUNTED_SALE_WHERE, product: { category: { not: "PATENSCHAFT" } } },
|
||||
}),
|
||||
// Warenkorbwert nur aus echten Shop-Bestellungen: Abo-Monatsrechnungen
|
||||
// und 0-€-Abo-Lieferungen sind keine Warenkoerbe.
|
||||
prisma.order.aggregate({
|
||||
_avg: { totalCents: true },
|
||||
_count: true,
|
||||
where: COUNTED_SALE_WHERE,
|
||||
where: SHOP_SALE_WHERE,
|
||||
}),
|
||||
// Summiert wird in der DATENBANK, nicht hier. Frueher lud diese Abfrage
|
||||
// JEDE Bestellposition, die es je gab, samt Produkt-Join in den Speicher,
|
||||
@@ -165,7 +174,7 @@ export default async function AdminDashboardPage(props: PageProps<"/admin">) {
|
||||
// machen — mit der Begruendung, Prisma koenne kein HAVING. Es kann.
|
||||
prisma.order.groupBy({
|
||||
by: ["customerId"],
|
||||
where: { customerId: { not: null }, ...COUNTED_SALE_WHERE },
|
||||
where: { customerId: { not: null }, ...SHOP_SALE_WHERE },
|
||||
having: { customerId: { _count: { gt: 1 } } },
|
||||
}),
|
||||
prisma.discountCode.findMany({
|
||||
@@ -258,20 +267,38 @@ export default async function AdminDashboardPage(props: PageProps<"/admin">) {
|
||||
const revenueTrend = [...revenueByDay.entries()];
|
||||
const maxDailyRevenue = Math.max(1, ...revenueTrend.map(([, v]) => v));
|
||||
|
||||
const [admin, waitingOrders, waitingReturns, waitingReviews, waitingInquiries] = await Promise.all([
|
||||
// Bestandsabgleich mit ApiCore (nur wenn eingerichtet).
|
||||
const stockIssues = await countApiCoreStockIssues();
|
||||
const stockOverdue = stockIssues.overdue;
|
||||
const stockRejected = stockIssues.rejected;
|
||||
const unlinkedProducts = stockIssues.unlinked;
|
||||
|
||||
const [admin, waitingOrders, waitingReturns, waitingReviews, waitingInquiries, sponsorshipItems] = await Promise.all([
|
||||
getCurrentAdmin(),
|
||||
prisma.order.count({
|
||||
where: { status: { in: ["BEZAHLT", "IN_VORBEREITUNG", "VERSANDBEREIT", "ABHOLBEREIT"] }, archivedAt: null },
|
||||
// DIGITAL (nur Patenschaften, Abo-Monatsrechnungen): nichts zu packen.
|
||||
where: {
|
||||
status: { in: ["BEZAHLT", "IN_VORBEREITUNG", "VERSANDBEREIT", "ABHOLBEREIT"] },
|
||||
archivedAt: null,
|
||||
fulfillmentMethod: { not: "DIGITAL" },
|
||||
},
|
||||
}),
|
||||
prisma.returnRequest.count({ where: { status: "ANGEFRAGT" } }),
|
||||
prisma.review.count({ where: { isApproved: false } }),
|
||||
prisma.review.count({ where: pendingReviewWhere() }),
|
||||
prisma.businessInquiry.count({ where: { status: "NEU" } }),
|
||||
// Bienenpatenschaft: gescheiterte Ausstellung, liegengebliebener Druck,
|
||||
// Honigdeckung der Abos, Abos im Verzug (siehe patenschaften/_lib/attention.ts).
|
||||
getSponsorshipAttentionItems(locale),
|
||||
]);
|
||||
const toDo = [
|
||||
{ count: waitingOrders, href: "/admin/bestellungen", label: t.adminDashboardPage.toDoOrders(waitingOrders) },
|
||||
{ count: waitingReturns, href: "/admin/retouren", label: t.adminDashboardPage.toDoReturns(waitingReturns) },
|
||||
{ count: waitingReviews, href: "/admin/bewertungen", label: t.adminDashboardPage.toDoReviews(waitingReviews) },
|
||||
{ count: waitingInquiries, href: "/admin/anfragen", label: t.adminDashboardPage.toDoInquiries(waitingInquiries) },
|
||||
{ count: stockRejected, href: "/admin/bestellungen", label: t.adminDashboardPage.toDoStockRejected(stockRejected) },
|
||||
{ count: stockOverdue, href: "/admin", label: t.adminDashboardPage.toDoStockOverdue(stockOverdue) },
|
||||
{ count: unlinkedProducts, href: "/admin/produkte", label: t.adminDashboardPage.toDoUnlinkedProducts(unlinkedProducts) },
|
||||
...sponsorshipItems,
|
||||
].filter((item) => item.count > 0);
|
||||
|
||||
// Begruessung nach Tageszeit in Berliner Zeit (der Server laeuft in UTC).
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { defaultLocale, isLocale } from "@/i18n/config";
|
||||
import { personalizationSchema } from "@/lib/certificate/schema";
|
||||
import { checkCertificateFits } from "@/lib/certificate/layout";
|
||||
import { listTemplateVersions } from "@/lib/certificate/templates";
|
||||
import { renderCertificateDocumentImage } from "@/lib/sponsorship/certificate-document";
|
||||
import { REVISABLE_FIELDS, revisionTerm } from "@/lib/sponsorship/revise";
|
||||
import { getAuthorizedAdmin, notFoundResponse } from "../../_lib/admin-guard";
|
||||
|
||||
const PREVIEW_WIDTH_PX = 900;
|
||||
const WATERMARK = "Korrekturvorschau";
|
||||
/** Ein Korrekturformular ist klein; alles darueber ist kein legitimer Aufruf. */
|
||||
const MAX_BODY_BYTES = 8 * 1024;
|
||||
|
||||
function invalid(body: Record<string, unknown>): Response {
|
||||
return Response.json(body, { status: 422, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Live-Vorschau der Korrektur: dieselbe Pruefung (Schema, Glyphen, Platz)
|
||||
* und dieselbe Laufzeitregel wie reviseSponsorship, gerendert mit dem
|
||||
* Wasserzeichen "Korrekturvorschau". Ungueltige Eingaben ergeben 422 mit
|
||||
* Feld und Fehlercode, damit das Formular die Stelle markieren kann.
|
||||
* Nur fuer Admins mit 2FA, sonst 404.
|
||||
*/
|
||||
export async function POST(request: Request, ctx: RouteContext<"/admin/patenschaften/[id]/korrekturvorschau">): Promise<Response> {
|
||||
if (!(await getAuthorizedAdmin())) return notFoundResponse();
|
||||
const { id } = await ctx.params;
|
||||
const sponsorship = await prisma.sponsorship.findUnique({
|
||||
where: { id },
|
||||
select: { number: true, locale: true, startDate: true, endDate: true, subscriptionId: true, currentRevision: true },
|
||||
});
|
||||
if (!sponsorship || sponsorship.currentRevision === 0) return notFoundResponse();
|
||||
|
||||
const raw = await request.text();
|
||||
if (raw.length > MAX_BODY_BYTES) return invalid({ code: "too_large" });
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
const parsedBody: unknown = JSON.parse(raw);
|
||||
body = parsedBody && typeof parsedBody === "object" ? (parsedBody as Record<string, unknown>) : {};
|
||||
} catch {
|
||||
return invalid({ code: "bad_json" });
|
||||
}
|
||||
|
||||
const isSubscription = sponsorship.subscriptionId !== null;
|
||||
const startDate = sponsorship.startDate.toISOString().slice(0, 10);
|
||||
const parsed = personalizationSchema.safeParse(isSubscription ? { ...body, startDate } : body);
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
const field = REVISABLE_FIELDS.find((name) => name === issue?.path[0]) ?? null;
|
||||
return invalid({ field, code: issue?.message ?? "invalid" });
|
||||
}
|
||||
const templateVersion = typeof body.templateVersion === "string" ? body.templateVersion : "";
|
||||
if (!listTemplateVersions().includes(templateVersion)) return invalid({ field: null, code: "unknown_template" });
|
||||
|
||||
const locale = isLocale(sponsorship.locale) ? sponsorship.locale : defaultLocale;
|
||||
const term = revisionTerm({
|
||||
isSubscription,
|
||||
personalization: parsed.data,
|
||||
startDate: sponsorship.startDate,
|
||||
endDate: sponsorship.endDate,
|
||||
});
|
||||
const fit = checkCertificateFits(parsed.data, locale, { term, templateVersion, number: sponsorship.number });
|
||||
if (!fit.ok) {
|
||||
return invalid({ field: fit.field, code: fit.reason, characters: fit.reason === "glyphs" ? fit.characters : [] });
|
||||
}
|
||||
|
||||
const image = await renderCertificateDocumentImage(
|
||||
{ personalization: parsed.data, locale, term, number: sponsorship.number, templateVersion },
|
||||
{ widthPx: PREVIEW_WIDTH_PX, format: "webp", watermark: WATERMARK }
|
||||
);
|
||||
return new Response(new Uint8Array(image), {
|
||||
headers: { "Content-Type": "image/webp", "Cache-Control": "private, no-store" },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { BackLink } from "@/components/back-link";
|
||||
import { startDateRange } from "@/lib/certificate/schema";
|
||||
import { CURRENT_TEMPLATE_VERSION } from "@/lib/certificate/templates";
|
||||
import { parseStoredPersonalization, toIsoDate } from "@/lib/sponsorship/certificate-document";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getSponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { reviseSponsorshipAction } from "@/app/admin/actions";
|
||||
import { CorrectionForm } from "../../_components/correction-form";
|
||||
|
||||
export default async function AdminSponsorshipCorrectionPage(props: PageProps<"/admin/patenschaften/[id]/korrigieren">) {
|
||||
const locale = await getLocale();
|
||||
const t = getSponsorshipAdminStrings(locale).correction;
|
||||
const { id } = await props.params;
|
||||
const sponsorship = await prisma.sponsorship.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
id: true,
|
||||
number: true,
|
||||
currentRevision: true,
|
||||
subscriptionId: true,
|
||||
createdAt: true,
|
||||
orderItem: { select: { order: { select: { createdAt: true } } } },
|
||||
},
|
||||
});
|
||||
if (!sponsorship || sponsorship.currentRevision === 0) notFound();
|
||||
const revision = await prisma.sponsorshipRevision.findUnique({
|
||||
where: { sponsorshipId_revision: { sponsorshipId: id, revision: sponsorship.currentRevision } },
|
||||
select: { personalization: true, templateVersion: true },
|
||||
});
|
||||
if (!revision) notFound();
|
||||
|
||||
const current = parseStoredPersonalization({ personalization: revision.personalization, templateVersion: revision.templateVersion });
|
||||
const isSubscription = sponsorship.subscriptionId !== null;
|
||||
// Dasselbe Fenster wie beim Kauf, gerechnet ab dem Bestelltag (reviseSponsorship prueft es erneut).
|
||||
const orderDate = toIsoDate(sponsorship.orderItem?.order.createdAt ?? sponsorship.createdAt);
|
||||
const templateOptions = [
|
||||
{ value: current.templateVersion, label: t.templatePrevious(current.templateVersion) },
|
||||
...(current.templateVersion !== CURRENT_TEMPLATE_VERSION
|
||||
? [{ value: CURRENT_TEMPLATE_VERSION, label: t.templateLatest(CURRENT_TEMPLATE_VERSION) }]
|
||||
: []),
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl">
|
||||
<BackLink href={`/admin/patenschaften/${id}`} label={t.backToDetail} />
|
||||
<h1 className="mb-2 text-2xl text-heading">{t.title(sponsorship.number)}</h1>
|
||||
<p className="mb-8 max-w-2xl text-sm text-ink/70">{t.intro}</p>
|
||||
<CorrectionForm
|
||||
sponsorshipId={id}
|
||||
locale={locale}
|
||||
action={reviseSponsorshipAction}
|
||||
isSubscription={isSubscription}
|
||||
startRange={isSubscription ? null : startDateRange(orderDate)}
|
||||
templateOptions={templateOptions}
|
||||
initial={{
|
||||
beeName: current.personalization.beeName,
|
||||
recipientName: current.personalization.recipientName,
|
||||
giverNames: current.personalization.giverNames ?? "",
|
||||
dedication: current.personalization.dedication ?? "",
|
||||
occasion: current.personalization.occasion,
|
||||
startDate: current.personalization.startDate,
|
||||
templateVersion: current.templateVersion,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import type { ReactNode } from "react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { BackLink } from "@/components/back-link";
|
||||
import { AdminBadge } from "@/components/admin-list";
|
||||
import { formatDate, formatDateTime } from "@/lib/format";
|
||||
import { MAX_ISSUE_ATTEMPTS } from "@/lib/sponsorship/issue";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getSponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { SponsorshipStatusBadge } from "../_components/status-badge";
|
||||
import { SponsorshipActions } from "../_components/sponsorship-actions";
|
||||
import { RevisionTable, TransferTable } from "../_components/history-tables";
|
||||
import { beeNameFromJson } from "../_lib/revision-data";
|
||||
|
||||
// A4 hochkant: 595.28 × 841.89 pt — die Vorschau wird in 900 px Breite gerendert.
|
||||
const PREVIEW_WIDTH = 900;
|
||||
const PREVIEW_HEIGHT = Math.round((PREVIEW_WIDTH * 841.89) / 595.28);
|
||||
|
||||
function Panel({ title, children }: { title: string; children: ReactNode }) {
|
||||
return (
|
||||
<section className="border border-ink/10 bg-background p-6">
|
||||
<h2 className="mb-3 text-xs tracking-wide-caps text-ink/65">{title}</h2>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function AdminSponsorshipDetailPage(props: PageProps<"/admin/patenschaften/[id]">) {
|
||||
const locale = await getLocale();
|
||||
const t = getSponsorshipAdminStrings(locale);
|
||||
const td = t.detail;
|
||||
const { id } = await props.params;
|
||||
const sponsorship = await prisma.sponsorship.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
owner: { select: { id: true, email: true, firstName: true, lastName: true } },
|
||||
offer: { select: { id: true, name: true, kind: true, isPhysical: true } },
|
||||
orderItem: { select: { order: { select: { id: true, orderNumber: true } } } },
|
||||
subscription: { select: { id: true, status: true } },
|
||||
revisions: { orderBy: { revision: "desc" } },
|
||||
transfers: { orderBy: { createdAt: "desc" } },
|
||||
},
|
||||
});
|
||||
if (!sponsorship) notFound();
|
||||
|
||||
const accountIds = [...new Set(sponsorship.transfers.flatMap((row) => [row.createdById, row.claimedById ?? ""]).filter(Boolean))];
|
||||
const accounts =
|
||||
accountIds.length > 0
|
||||
? await prisma.customer.findMany({ where: { id: { in: accountIds } }, select: { id: true, email: true } })
|
||||
: [];
|
||||
const emailOf = new Map(accounts.map((account) => [account.id, account.email]));
|
||||
const current = sponsorship.revisions.find((row) => row.revision === sponsorship.currentRevision) ?? null;
|
||||
const beeName = beeNameFromJson(current?.personalization) ?? "—";
|
||||
const start = formatDate(sponsorship.startDate, locale);
|
||||
const order = sponsorship.orderItem?.order ?? null;
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl">
|
||||
<BackLink href="/admin/patenschaften" label={td.backToList} />
|
||||
<div className="mb-8 flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<p className="font-mono text-xs text-ink/60">{sponsorship.number}</p>
|
||||
<h1 className="mt-1 font-serif text-3xl text-heading">{beeName}</h1>
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
<SponsorshipStatusBadge status={sponsorship.status} label={t.statuses[sponsorship.status]} />
|
||||
<AdminBadge tone="neutral">{t.kinds[sponsorship.offer.kind]}</AdminBadge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Panel title={td.ownerHeading}>
|
||||
<p>
|
||||
{sponsorship.owner.firstName} {sponsorship.owner.lastName}
|
||||
</p>
|
||||
<p className="break-all text-sm text-ink/70">{sponsorship.owner.email}</p>
|
||||
<Link href={`/admin/benutzer/${sponsorship.owner.id}`} className="link-draw mt-2 inline-block text-sm text-heading">
|
||||
{td.openAccount}
|
||||
</Link>
|
||||
</Panel>
|
||||
<Panel title={td.sourceHeading}>
|
||||
{order ? (
|
||||
<Link href={`/admin/bestellungen/${order.id}`} className="link-draw text-heading">
|
||||
{td.order(order.orderNumber)}
|
||||
</Link>
|
||||
) : sponsorship.subscription ? (
|
||||
<Link href="/admin/patenschaften/abos" className="link-draw text-heading">
|
||||
{td.subscription} · {t.subscriptionStatuses[sponsorship.subscription.status]}
|
||||
</Link>
|
||||
) : (
|
||||
<p className="text-sm text-ink/65">{td.noSource}</p>
|
||||
)}
|
||||
</Panel>
|
||||
<Panel title={td.offerHeading}>
|
||||
<Link href={`/admin/patenschaften/angebote/${sponsorship.offer.id}`} className="link-draw text-heading">
|
||||
{sponsorship.offer.name}
|
||||
</Link>
|
||||
<p className="mt-1 text-sm text-ink/65">{sponsorship.offer.isPhysical ? td.physical : td.digital}</p>
|
||||
</Panel>
|
||||
<Panel title={td.termHeading}>
|
||||
<p className="tabular-nums">
|
||||
{sponsorship.endDate ? t.common.range(start, formatDate(sponsorship.endDate, locale)) : td.termOpen(start)}
|
||||
</p>
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
<div className="mb-8 grid gap-6 lg:grid-cols-5">
|
||||
<section className="border border-ink/10 bg-background p-6 lg:col-span-2">
|
||||
<h2 className="mb-4 text-xs tracking-wide-caps text-ink/65">{td.previewHeading}</h2>
|
||||
{current ? (
|
||||
<Image
|
||||
src={`/admin/patenschaften/${sponsorship.id}/vorschau.webp?r=${sponsorship.currentRevision}`}
|
||||
alt={td.previewAlt(beeName, sponsorship.currentRevision)}
|
||||
width={PREVIEW_WIDTH}
|
||||
height={PREVIEW_HEIGHT}
|
||||
unoptimized
|
||||
className="h-auto w-full border border-ink/10 shadow-[0_18px_40px_-28px_rgba(36,53,43,0.6)]"
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm text-ink/65">{td.noRevision}</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<div className="flex flex-col gap-6 lg:col-span-3">
|
||||
<Panel title={td.actionsHeading}>
|
||||
<SponsorshipActions
|
||||
id={sponsorship.id}
|
||||
status={sponsorship.status}
|
||||
currentRevision={sponsorship.currentRevision}
|
||||
isPhysical={sponsorship.offer.isPhysical}
|
||||
printed={sponsorship.printedAt !== null}
|
||||
ownerEmail={sponsorship.owner.email}
|
||||
t={td}
|
||||
/>
|
||||
</Panel>
|
||||
<Panel title={td.deliveryHeading}>
|
||||
<ul className="space-y-1 text-sm">
|
||||
<li className="tabular-nums">{td.attempts(sponsorship.pdfAttempts, MAX_ISSUE_ATTEMPTS)}</li>
|
||||
{sponsorship.nextAttemptAt ? <li>{td.nextAttempt(formatDateTime(sponsorship.nextAttemptAt, locale))}</li> : null}
|
||||
<li>{sponsorship.mailSentAt ? td.mailSent(formatDateTime(sponsorship.mailSentAt, locale)) : td.mailNotSent}</li>
|
||||
{sponsorship.offer.isPhysical ? (
|
||||
<li>{sponsorship.printedAt ? td.printed(formatDateTime(sponsorship.printedAt, locale)) : td.notPrinted}</li>
|
||||
) : null}
|
||||
</ul>
|
||||
{sponsorship.lastError ? (
|
||||
<div className="mt-4 border border-red-200 bg-red-50 p-3">
|
||||
<p className="text-xs tracking-wide-caps text-red-700">{td.lastError}</p>
|
||||
<p className="mt-1 whitespace-pre-wrap break-words font-mono text-xs text-red-800">{sponsorship.lastError}</p>
|
||||
</div>
|
||||
) : null}
|
||||
</Panel>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-8">
|
||||
<Panel title={td.revisionsHeading}>
|
||||
<RevisionTable
|
||||
sponsorshipId={sponsorship.id}
|
||||
revisions={sponsorship.revisions}
|
||||
currentRevision={sponsorship.currentRevision}
|
||||
locale={locale}
|
||||
t={td}
|
||||
/>
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
<Panel title={td.transfersHeading}>
|
||||
<TransferTable
|
||||
now={new Date()}
|
||||
locale={locale}
|
||||
t={td}
|
||||
transfers={sponsorship.transfers.map((row) => ({
|
||||
id: row.id,
|
||||
createdAt: row.createdAt,
|
||||
expiresAt: row.expiresAt,
|
||||
createdBy: emailOf.get(row.createdById) ?? row.createdById,
|
||||
claimedBy: row.claimedById ? (emailOf.get(row.claimedById) ?? row.claimedById) : null,
|
||||
claimedAt: row.claimedAt,
|
||||
revokedAt: row.revokedAt,
|
||||
}))}
|
||||
/>
|
||||
</Panel>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { readCertificatePdf } from "@/lib/sponsorship/storage";
|
||||
import { getAuthorizedAdmin, notFoundResponse } from "../../../_lib/admin-guard";
|
||||
|
||||
/**
|
||||
* Gespeicherte PDF einer Revision (/admin/patenschaften/<id>/revision/3.pdf).
|
||||
* Ausgeliefert wird immer die abgelegte Datei, nie ein Neu-Rendering — sie
|
||||
* ist der Beleg dessen, was die Kundschaft bekommen hat bzw. was gedruckt
|
||||
* wird. ?inline=1 oeffnet sie im Browser (Druck-PDF), sonst Download.
|
||||
* Nur fuer Admins mit 2FA, sonst 404.
|
||||
*/
|
||||
export async function GET(request: NextRequest, ctx: RouteContext<"/admin/patenschaften/[id]/revision/[rev]">): Promise<Response> {
|
||||
if (!(await getAuthorizedAdmin())) return notFoundResponse();
|
||||
const { id, rev } = await ctx.params;
|
||||
const match = /^(\d{1,6})(?:\.pdf)?$/.exec(rev);
|
||||
if (!match) return notFoundResponse();
|
||||
const revision = await prisma.sponsorshipRevision.findUnique({
|
||||
where: { sponsorshipId_revision: { sponsorshipId: id, revision: Number(match[1]) } },
|
||||
select: { revision: true, pdfPath: true, sponsorship: { select: { number: true } } },
|
||||
});
|
||||
if (!revision) return notFoundResponse();
|
||||
const pdf = await readCertificatePdf(revision.pdfPath);
|
||||
if (!pdf) return notFoundResponse();
|
||||
|
||||
const filename = `${revision.sponsorship.number}-r${revision.revision}.pdf`;
|
||||
const disposition = request.nextUrl.searchParams.get("inline") === "1" ? "inline" : "attachment";
|
||||
return new Response(new Uint8Array(pdf), {
|
||||
headers: {
|
||||
"Content-Type": "application/pdf",
|
||||
"Content-Disposition": `${disposition}; filename="${filename}"`,
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { renderCertificateDocumentImage } from "@/lib/sponsorship/certificate-document";
|
||||
import { getAuthorizedAdmin, notFoundResponse } from "../../_lib/admin-guard";
|
||||
import { loadRevisionDocument } from "../../_lib/revision-data";
|
||||
|
||||
const PREVIEW_WIDTH_PX = 900;
|
||||
|
||||
/**
|
||||
* Bild der aktuellen Revision fuer die Admin-Detailseite. Gerendert aus den
|
||||
* gespeicherten Revisionsdaten ueber dieselben Helfer wie PDF und Vorschau —
|
||||
* ohne Wasserzeichen, weil es die tatsaechlich ausgestellte Urkunde zeigt.
|
||||
* Nur fuer Admins mit 2FA, sonst 404.
|
||||
*/
|
||||
export async function GET(_request: Request, ctx: RouteContext<"/admin/patenschaften/[id]/vorschau.webp">): Promise<Response> {
|
||||
if (!(await getAuthorizedAdmin())) return notFoundResponse();
|
||||
const { id } = await ctx.params;
|
||||
const document = await loadRevisionDocument(id);
|
||||
if (!document) return notFoundResponse();
|
||||
|
||||
const image = await renderCertificateDocumentImage(document.input, { widthPx: PREVIEW_WIDTH_PX, format: "webp" });
|
||||
return new Response(new Uint8Array(image), {
|
||||
headers: {
|
||||
"Content-Type": "image/webp",
|
||||
// Personenbezogen (Namen, Widmung): nie in geteilten Caches ablegen.
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState, type ChangeEvent } from "react";
|
||||
import { CERTIFICATE_LIMITS, OCCASIONS, countCharacters, type Occasion } from "@/lib/certificate/schema";
|
||||
import type { Locale } from "@/i18n/config";
|
||||
import { getSponsorshipAdminStrings, type SponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
|
||||
export interface CorrectionValues {
|
||||
beeName: string;
|
||||
recipientName: string;
|
||||
giverNames: string;
|
||||
dedication: string;
|
||||
occasion: Occasion;
|
||||
startDate: string;
|
||||
templateVersion: string;
|
||||
}
|
||||
|
||||
type FieldName = keyof CorrectionValues;
|
||||
|
||||
interface PreviewError {
|
||||
field: FieldName | "layout" | null;
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface CorrectionFormProps {
|
||||
sponsorshipId: string;
|
||||
initial: CorrectionValues;
|
||||
isSubscription: boolean;
|
||||
startRange: { min: string; max: string } | null;
|
||||
templateOptions: { value: string; label: string }[];
|
||||
action: (formData: FormData) => void | Promise<void>;
|
||||
/** Texte werden hier geholt statt als Prop gereicht: sie enthalten Funktionen, die nicht ueber die Server-Client-Grenze gehen. */
|
||||
locale: Locale;
|
||||
}
|
||||
|
||||
const PREVIEW_DEBOUNCE_MS = 400;
|
||||
const inputClass = "mt-1 w-full border border-ink/20 bg-background px-3 py-2";
|
||||
|
||||
function errorText(code: string, characters: string[], t: SponsorshipAdminStrings["correction"]): string {
|
||||
if (code === "glyphs") return t.errors.glyphs(characters.join(" "));
|
||||
const known = t.errors[code as Exclude<keyof typeof t.errors, "glyphs">];
|
||||
return typeof known === "string" ? known : t.previewFailed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Korrekturformular mit Live-Vorschau. Die Vorschau kommt vom Server
|
||||
* (/admin/patenschaften/<id>/korrekturvorschau) und nutzt dieselbe
|
||||
* Layoutlogik wie die spaetere PDF. Bis eine neue gueltige Vorschau da ist,
|
||||
* bleibt die letzte sichtbar — gedimmt, damit klar ist, dass sie nicht mehr
|
||||
* dem Formular entspricht.
|
||||
*/
|
||||
export function CorrectionForm({
|
||||
sponsorshipId,
|
||||
initial,
|
||||
isSubscription,
|
||||
startRange,
|
||||
templateOptions,
|
||||
action,
|
||||
locale,
|
||||
}: CorrectionFormProps) {
|
||||
const strings = getSponsorshipAdminStrings(locale);
|
||||
const t = strings.correction;
|
||||
const occasionLabels = strings.occasions;
|
||||
const [values, setValues] = useState<CorrectionValues>(initial);
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
||||
const [isStale, setIsStale] = useState(true);
|
||||
const [error, setError] = useState<PreviewError | null>(null);
|
||||
const urlRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(async () => {
|
||||
setIsStale(true);
|
||||
try {
|
||||
const response = await fetch(`/admin/patenschaften/${sponsorshipId}/korrekturvorschau`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(values),
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.status === 422) {
|
||||
const body = (await response.json()) as { field?: PreviewError["field"]; code?: string; characters?: string[] };
|
||||
setError({ field: body.field ?? null, message: errorText(body.code ?? "", body.characters ?? [], t) });
|
||||
return;
|
||||
}
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const url = URL.createObjectURL(await response.blob());
|
||||
if (urlRef.current) URL.revokeObjectURL(urlRef.current);
|
||||
urlRef.current = url;
|
||||
setPreviewUrl(url);
|
||||
setError(null);
|
||||
setIsStale(false);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof DOMException && cause.name === "AbortError") return;
|
||||
setError({ field: null, message: t.previewFailed });
|
||||
}
|
||||
}, PREVIEW_DEBOUNCE_MS);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [values, sponsorshipId, t]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (urlRef.current) URL.revokeObjectURL(urlRef.current);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const update = (field: FieldName) => (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
|
||||
const value = event.target.value;
|
||||
setValues((previous) => ({ ...previous, [field]: value }));
|
||||
};
|
||||
|
||||
const fieldError = (field: FieldName) =>
|
||||
error?.field === field ? (
|
||||
<span role="alert" className="mt-1 block text-xs text-red-700">
|
||||
{error.message}
|
||||
</span>
|
||||
) : null;
|
||||
|
||||
const counter = (value: string, max: number) => (
|
||||
<span className={`mt-1 block text-right text-xs tabular-nums ${countCharacters(value) > max ? "text-red-700" : "text-ink/55"}`}>
|
||||
{t.counter(countCharacters(value), max)}
|
||||
</span>
|
||||
);
|
||||
|
||||
const showGivers = values.occasion !== "SELBST";
|
||||
|
||||
return (
|
||||
<div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(0,26rem)]">
|
||||
<form action={action} className="space-y-8 border border-ink/10 bg-background p-6 sm:p-8">
|
||||
<input type="hidden" name="id" value={sponsorshipId} />
|
||||
<fieldset className="space-y-4 border-b border-ink/10 pb-8">
|
||||
<legend className="mb-4 font-serif text-xl text-heading">{t.sectionText}</legend>
|
||||
<label className="block text-sm">
|
||||
<span className="text-ink/70">{t.beeName}</span>
|
||||
<input name="beeName" value={values.beeName} onChange={update("beeName")} required className={inputClass} />
|
||||
{counter(values.beeName, CERTIFICATE_LIMITS.beeName.max)}
|
||||
{fieldError("beeName")}
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
<span className="text-ink/70">{t.recipientName}</span>
|
||||
<input name="recipientName" value={values.recipientName} onChange={update("recipientName")} required className={inputClass} />
|
||||
{counter(values.recipientName, CERTIFICATE_LIMITS.recipientName.max)}
|
||||
{fieldError("recipientName")}
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
<span className="text-ink/70">{t.occasion}</span>
|
||||
<select name="occasion" value={values.occasion} onChange={update("occasion")} className={inputClass}>
|
||||
{OCCASIONS.map((occasion) => (
|
||||
<option key={occasion} value={occasion}>
|
||||
{occasionLabels[occasion]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldError("occasion")}
|
||||
</label>
|
||||
{showGivers ? (
|
||||
<label className="block text-sm">
|
||||
<span className="text-ink/70">{t.giverNames}</span>
|
||||
<input name="giverNames" value={values.giverNames} onChange={update("giverNames")} className={inputClass} />
|
||||
{counter(values.giverNames, CERTIFICATE_LIMITS.giverNames.max)}
|
||||
{fieldError("giverNames")}
|
||||
</label>
|
||||
) : null}
|
||||
<label className="block text-sm">
|
||||
<span className="text-ink/70">{t.dedication}</span>
|
||||
<textarea name="dedication" value={values.dedication} onChange={update("dedication")} rows={5} className={inputClass} />
|
||||
{counter(values.dedication, CERTIFICATE_LIMITS.dedication.max)}
|
||||
{fieldError("dedication")}
|
||||
</label>
|
||||
{isSubscription || !startRange ? (
|
||||
<div className="text-sm">
|
||||
<span className="text-ink/70">{t.startDate}</span>
|
||||
<p className="mt-1 tabular-nums">{values.startDate}</p>
|
||||
<input type="hidden" name="startDate" value={values.startDate} />
|
||||
<p className="mt-1 text-xs text-ink/65">{t.startDateSubscription}</p>
|
||||
</div>
|
||||
) : (
|
||||
<label className="block text-sm">
|
||||
<span className="text-ink/70">{t.startDate}</span>
|
||||
<input
|
||||
type="date"
|
||||
name="startDate"
|
||||
value={values.startDate}
|
||||
min={startRange.min}
|
||||
max={startRange.max}
|
||||
onChange={update("startDate")}
|
||||
required
|
||||
className={inputClass}
|
||||
/>
|
||||
<span className="mt-1 block text-xs text-ink/65">{t.startDateHint(startRange.min, startRange.max)}</span>
|
||||
{fieldError("startDate")}
|
||||
</label>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="space-y-4 border-b border-ink/10 pb-8">
|
||||
<legend className="mb-4 font-serif text-xl text-heading">{t.sectionTemplate}</legend>
|
||||
<label className="block text-sm">
|
||||
<span className="text-ink/70">{t.templateLabel}</span>
|
||||
<select name="templateVersion" value={values.templateVersion} onChange={update("templateVersion")} className={inputClass}>
|
||||
{templateOptions.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="space-y-4">
|
||||
<legend className="mb-4 font-serif text-xl text-heading">{t.sectionReason}</legend>
|
||||
<label className="block text-sm">
|
||||
<span className="text-ink/70">{t.reasonLabel}</span>
|
||||
<textarea name="reason" required minLength={3} maxLength={500} rows={3} className={inputClass} />
|
||||
<span className="mt-1 block text-xs text-ink/65">{t.reasonHint}</span>
|
||||
</label>
|
||||
<label className="inline-flex cursor-pointer items-center gap-3 text-sm text-ink/80">
|
||||
<input type="checkbox" name="notifyCustomer" className="h-4 w-4 accent-[var(--color-forest)]" />
|
||||
{t.notifyLabel}
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<div className="flex justify-end border-t border-ink/10 pt-6">
|
||||
<button
|
||||
type="submit"
|
||||
className="inline-flex items-center justify-center border border-heading bg-forest px-7 py-3 text-sm tracking-wide-caps text-cream transition-colors hover:bg-honey-deep"
|
||||
>
|
||||
{t.submit}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<aside className="lg:sticky lg:top-6 lg:self-start">
|
||||
<h2 className="mb-3 text-xs tracking-wide-caps text-ink/65">{t.previewHeading}</h2>
|
||||
<div className="relative border border-ink/10 bg-background p-3" aria-live="polite">
|
||||
{previewUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element -- Blob-URL der Live-Vorschau, next/image kann sie nicht optimieren
|
||||
<img
|
||||
src={previewUrl}
|
||||
alt={t.previewAlt}
|
||||
className={`h-auto w-full transition-opacity duration-300 ${isStale ? "opacity-50" : "opacity-100"}`}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex aspect-[595/842] items-center justify-center text-sm text-ink/60">{t.previewLoading}</div>
|
||||
)}
|
||||
{error && (error.field === null || error.field === "layout") ? (
|
||||
<p role="alert" className="mt-3 text-sm text-red-700">
|
||||
{error.message}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import type { Locale } from "@/i18n/config";
|
||||
import type { SponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
|
||||
interface RevisionRow {
|
||||
revision: number;
|
||||
createdAt: Date;
|
||||
createdByLabel: string;
|
||||
reason: string | null;
|
||||
templateVersion: string;
|
||||
pdfSha256: string;
|
||||
}
|
||||
|
||||
const thClass = "p-3 font-normal";
|
||||
|
||||
/** Alle Revisionen, neueste zuerst; jede mit eigener PDF (alte bleiben abrufbar). */
|
||||
export function RevisionTable({
|
||||
sponsorshipId,
|
||||
revisions,
|
||||
currentRevision,
|
||||
locale,
|
||||
t,
|
||||
}: {
|
||||
sponsorshipId: string;
|
||||
revisions: RevisionRow[];
|
||||
currentRevision: number;
|
||||
locale: Locale;
|
||||
t: SponsorshipAdminStrings["detail"];
|
||||
}) {
|
||||
if (revisions.length === 0) return <p className="text-sm text-ink/65">{t.noRevision}</p>;
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b border-ink/10 text-left text-xs text-ink/65">
|
||||
<tr>
|
||||
<th className={thClass}>{t.colRevision}</th>
|
||||
<th className={thClass}>{t.colCreatedAt}</th>
|
||||
<th className={thClass}>{t.colCreatedBy}</th>
|
||||
<th className={thClass}>{t.colReason}</th>
|
||||
<th className={thClass}>{t.colTemplate}</th>
|
||||
<th className={thClass}>{t.colChecksum}</th>
|
||||
<th className={thClass} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-ink/10">
|
||||
{revisions.map((row) => (
|
||||
<tr key={row.revision}>
|
||||
<td className="whitespace-nowrap p-3 tabular-nums text-heading">
|
||||
r{row.revision}
|
||||
{row.revision === currentRevision ? <span className="ml-2 text-xs text-honey-dark">{t.current}</span> : null}
|
||||
</td>
|
||||
<td className="whitespace-nowrap p-3 tabular-nums text-ink/70">{formatDateTime(row.createdAt, locale)}</td>
|
||||
<td className="p-3">{row.createdByLabel}</td>
|
||||
<td className="max-w-xs p-3 text-ink/80">{row.reason ?? "—"}</td>
|
||||
<td className="whitespace-nowrap p-3 font-mono text-xs">{row.templateVersion}</td>
|
||||
<td className="p-3 font-mono text-xs text-ink/60" title={row.pdfSha256}>
|
||||
{row.pdfSha256.slice(0, 12)}…
|
||||
</td>
|
||||
<td className="p-3 text-right">
|
||||
<a href={`/admin/patenschaften/${sponsorshipId}/revision/${row.revision}.pdf`} className="link-draw text-heading">
|
||||
{t.download}
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface TransferRow {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
expiresAt: Date;
|
||||
createdBy: string;
|
||||
claimedBy: string | null;
|
||||
claimedAt: Date | null;
|
||||
revokedAt: Date | null;
|
||||
}
|
||||
|
||||
/** Uebertragungshistorie, nur lesend (Uebertragungen steuert die Kundschaft im Konto). */
|
||||
export function TransferTable({ transfers, now, locale, t }: { transfers: TransferRow[]; now: Date; locale: Locale; t: SponsorshipAdminStrings["detail"] }) {
|
||||
if (transfers.length === 0) return <p className="text-sm text-ink/65">{t.noTransfers}</p>;
|
||||
const statusOf = (row: TransferRow): string => {
|
||||
if (row.claimedAt) return t.transferClaimed(row.claimedBy ?? "—", formatDateTime(row.claimedAt, locale));
|
||||
if (row.revokedAt) return t.transferRevoked(formatDateTime(row.revokedAt, locale));
|
||||
return row.expiresAt < now ? t.transferExpired : t.transferOpen;
|
||||
};
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b border-ink/10 text-left text-xs text-ink/65">
|
||||
<tr>
|
||||
<th className={thClass}>{t.colTransferCreated}</th>
|
||||
<th className={thClass}>{t.colTransferBy}</th>
|
||||
<th className={thClass}>{t.colExpires}</th>
|
||||
<th className={thClass}>{t.colTransferStatus}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-ink/10">
|
||||
{transfers.map((row) => (
|
||||
<tr key={row.id}>
|
||||
<td className="whitespace-nowrap p-3 tabular-nums text-ink/70">{formatDateTime(row.createdAt, locale)}</td>
|
||||
<td className="p-3">{row.createdBy}</td>
|
||||
<td className="whitespace-nowrap p-3 tabular-nums text-ink/70">{formatDateTime(row.expiresAt, locale)}</td>
|
||||
<td className="p-3">{statusOf(row)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { Button } from "@/components/ui";
|
||||
import {
|
||||
AdminField,
|
||||
AdminFieldset,
|
||||
AdminFormPanel,
|
||||
AdminHint,
|
||||
AdminSelect,
|
||||
AdminSwitch,
|
||||
AdminTextarea,
|
||||
} from "@/components/admin-form";
|
||||
import { formatPrice } from "@/lib/format";
|
||||
import type { MedalTier, SponsorshipCycle, SponsorshipOfferKind } from "@/generated/prisma/client";
|
||||
import type { SponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { MEDAL_TIERS, OFFER_CYCLES, OFFER_KINDS, centsToEuroInput } from "../_lib/offer-schema";
|
||||
|
||||
export interface OfferFormDefaults {
|
||||
id?: string;
|
||||
kind: SponsorshipOfferKind;
|
||||
name: string;
|
||||
nameEn: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
descriptionEn: string;
|
||||
features: string[];
|
||||
featuresEn: string[];
|
||||
priceCents: number;
|
||||
honeyShareCentsPerJar: number;
|
||||
honeyShareCentsPerMonth: number;
|
||||
isActive: boolean;
|
||||
isPhysical: boolean;
|
||||
sortOrder: number;
|
||||
honeyJars: number;
|
||||
cycle: SponsorshipCycle | null;
|
||||
maxActiveSubscriptions: number | null;
|
||||
medalTier: MedalTier;
|
||||
}
|
||||
|
||||
export const EMPTY_OFFER: OfferFormDefaults = {
|
||||
kind: "EINMALIG",
|
||||
name: "",
|
||||
nameEn: "",
|
||||
slug: "",
|
||||
description: "",
|
||||
descriptionEn: "",
|
||||
features: [],
|
||||
featuresEn: [],
|
||||
priceCents: 0,
|
||||
honeyShareCentsPerJar: 0,
|
||||
honeyShareCentsPerMonth: 0,
|
||||
isActive: false,
|
||||
isPhysical: false,
|
||||
sortOrder: 0,
|
||||
honeyJars: 0,
|
||||
cycle: null,
|
||||
maxActiveSubscriptions: null,
|
||||
medalTier: "BRONZE",
|
||||
};
|
||||
|
||||
interface OfferFormProps {
|
||||
defaults: OfferFormDefaults;
|
||||
/** Beim Bearbeiten ist die Art fest. */
|
||||
isNew: boolean;
|
||||
/** "<Name> <Jahr>" des Honigs, den die automatische Wahl gerade nimmt; null = keiner reicht. */
|
||||
currentHoneyLabel: string | null;
|
||||
action: (formData: FormData) => void | Promise<void>;
|
||||
t: SponsorshipAdminStrings;
|
||||
}
|
||||
|
||||
const euroOrEmpty = (cents: number): string => (cents > 0 ? centsToEuroInput(cents) : "");
|
||||
|
||||
/**
|
||||
* Ein Formular fuer Einmal- und Abo-Angebote. Felder der jeweils anderen Art
|
||||
* stehen mit "(nur Einmalig)" bzw. "(nur Abo)" da und werden beim Speichern
|
||||
* geleert (offer-schema.ts) — so bleibt das Formular ohne Client-Logik.
|
||||
*/
|
||||
export function OfferForm({ defaults, isNew, currentHoneyLabel, action, t }: OfferFormProps) {
|
||||
const tf = t.offerForm;
|
||||
return (
|
||||
<AdminFormPanel action={action} actions={<Button type="submit">{isNew ? tf.create : tf.save}</Button>}>
|
||||
{defaults.id ? <input type="hidden" name="id" value={defaults.id} /> : null}
|
||||
<AdminFieldset legend={tf.sectionBasics}>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<AdminField name="name" label={tf.name} defaultValue={defaults.name} required />
|
||||
<AdminField name="nameEn" label={tf.nameEn} defaultValue={defaults.nameEn} />
|
||||
</div>
|
||||
<AdminField name="slug" label={tf.slug} defaultValue={defaults.slug} required hint={tf.slugHint} />
|
||||
{isNew ? (
|
||||
<AdminSelect name="kind" label={tf.kind} defaultValue={defaults.kind} hint={tf.kindFixed}>
|
||||
{OFFER_KINDS.map((kind) => (
|
||||
<option key={kind} value={kind}>
|
||||
{t.kinds[kind]}
|
||||
</option>
|
||||
))}
|
||||
</AdminSelect>
|
||||
) : (
|
||||
<AdminField name="kindDisplay" label={tf.kind} defaultValue={t.kinds[defaults.kind]} readOnly hint={tf.kindFixed} />
|
||||
)}
|
||||
</AdminFieldset>
|
||||
|
||||
<AdminFieldset legend={tf.sectionTexts}>
|
||||
<AdminTextarea name="description" label={tf.description} defaultValue={defaults.description} required rows={3} />
|
||||
<AdminTextarea name="descriptionEn" label={tf.descriptionEn} defaultValue={defaults.descriptionEn} rows={3} />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<AdminTextarea name="features" label={tf.features} defaultValue={defaults.features.join("\n")} rows={5} />
|
||||
<AdminTextarea name="featuresEn" label={tf.featuresEn} defaultValue={defaults.featuresEn.join("\n")} rows={5} />
|
||||
</div>
|
||||
</AdminFieldset>
|
||||
|
||||
<AdminFieldset legend={tf.sectionPrice}>
|
||||
<AdminField name="price" label={tf.price} defaultValue={euroOrEmpty(defaults.priceCents)} placeholder="39,00" required />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<AdminField name="honeySharePerJar" label={tf.shareJar} defaultValue={euroOrEmpty(defaults.honeyShareCentsPerJar)} placeholder="7,00" />
|
||||
<AdminField name="honeySharePerMonth" label={tf.shareMonth} defaultValue={euroOrEmpty(defaults.honeyShareCentsPerMonth)} placeholder="4,00" />
|
||||
</div>
|
||||
{!isNew && defaults.kind === "EINMALIG" ? (
|
||||
<AdminHint>
|
||||
{tf.carrierPrice(formatPrice(defaults.priceCents - defaults.honeyJars * defaults.honeyShareCentsPerJar))}
|
||||
</AdminHint>
|
||||
) : null}
|
||||
</AdminFieldset>
|
||||
|
||||
<AdminFieldset legend={tf.sectionHoney}>
|
||||
<AdminSwitch name="isPhysical" label={tf.isPhysical} defaultChecked={defaults.isPhysical} />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{/* Keine Auswahl mehr: Pakete und Abos bekommen den Honig automatisch
|
||||
(lib/sponsorship/honey-selection.ts). Nur Anzeige, wird nicht gespeichert. */}
|
||||
<AdminField
|
||||
name="honeyDisplay"
|
||||
label={tf.honey}
|
||||
defaultValue={tf.honeyAuto(currentHoneyLabel)}
|
||||
readOnly
|
||||
hint={tf.honeyAutoHint}
|
||||
/>
|
||||
<AdminField name="honeyJars" label={tf.honeyJars} type="number" min={0} defaultValue={String(defaults.honeyJars)} />
|
||||
</div>
|
||||
</AdminFieldset>
|
||||
|
||||
<AdminFieldset legend={tf.sectionAbo}>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<AdminSelect name="cycle" label={tf.cycle} defaultValue={defaults.cycle ?? ""}>
|
||||
<option value="">{tf.cycleNone}</option>
|
||||
{OFFER_CYCLES.map((cycle) => (
|
||||
<option key={cycle} value={cycle}>
|
||||
{t.cycles[cycle]}
|
||||
</option>
|
||||
))}
|
||||
</AdminSelect>
|
||||
<AdminField
|
||||
name="maxActiveSubscriptions"
|
||||
label={tf.maxActive}
|
||||
type="number"
|
||||
min={1}
|
||||
defaultValue={defaults.maxActiveSubscriptions !== null ? String(defaults.maxActiveSubscriptions) : ""}
|
||||
/>
|
||||
</div>
|
||||
<AdminHint>{tf.stripeHint}</AdminHint>
|
||||
</AdminFieldset>
|
||||
|
||||
<AdminFieldset legend={tf.sectionDisplay} last>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<AdminSelect name="medalTier" label={tf.medalTier} defaultValue={defaults.medalTier}>
|
||||
{MEDAL_TIERS.map((tier) => (
|
||||
<option key={tier} value={tier}>
|
||||
{t.medals[tier]}
|
||||
</option>
|
||||
))}
|
||||
</AdminSelect>
|
||||
<AdminField name="sortOrder" label={tf.sortOrder} type="number" min={0} defaultValue={String(defaults.sortOrder)} />
|
||||
</div>
|
||||
<AdminSwitch name="isActive" label={tf.isActive} defaultChecked={defaults.isActive} />
|
||||
</AdminFieldset>
|
||||
</AdminFormPanel>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import Link from "next/link";
|
||||
|
||||
interface PaginationProps {
|
||||
page: number;
|
||||
totalPages: number;
|
||||
hrefFor: (page: number) => string;
|
||||
labels: { previous: string; next: string; pageOf: (page: number, total: number) => string };
|
||||
}
|
||||
|
||||
/** Blaettern unter einer Admin-Liste; erscheint erst ab der zweiten Seite. */
|
||||
export function Pagination({ page, totalPages, hrefFor, labels }: PaginationProps) {
|
||||
if (totalPages <= 1) return null;
|
||||
const linkClass = "link-draw text-heading";
|
||||
return (
|
||||
<nav aria-label={labels.pageOf(page, totalPages)} className="mt-4 flex items-center justify-between gap-4 text-sm">
|
||||
{page > 1 ? (
|
||||
<Link href={hrefFor(page - 1)} className={linkClass} rel="prev">
|
||||
{labels.previous}
|
||||
</Link>
|
||||
) : (
|
||||
<span aria-hidden="true" />
|
||||
)}
|
||||
<span className="tabular-nums text-ink/65">{labels.pageOf(page, totalPages)}</span>
|
||||
{page < totalPages ? (
|
||||
<Link href={hrefFor(page + 1)} className={linkClass} rel="next">
|
||||
{labels.next}
|
||||
</Link>
|
||||
) : (
|
||||
<span aria-hidden="true" />
|
||||
)}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import Link from "next/link";
|
||||
import { ConfirmForm } from "@/components/confirm-form";
|
||||
import { Button } from "@/components/ui";
|
||||
import { AdminActionNote } from "@/components/admin-list";
|
||||
import type { SponsorshipStatus } from "@/generated/prisma/client";
|
||||
import type { SponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { markSponsorshipPrintedAction, resendSponsorshipMailAction, retrySponsorshipAction } from "@/app/admin/actions";
|
||||
|
||||
interface SponsorshipActionsProps {
|
||||
id: string;
|
||||
status: SponsorshipStatus;
|
||||
currentRevision: number;
|
||||
isPhysical: boolean;
|
||||
printed: boolean;
|
||||
ownerEmail: string;
|
||||
t: SponsorshipAdminStrings["detail"];
|
||||
}
|
||||
|
||||
const buttonClass = "px-4 py-2 text-xs";
|
||||
|
||||
/**
|
||||
* Aktionen einer Patenschaft. Jede Aktion steht nur da, wo sie im aktuellen
|
||||
* Zustand Sinn ergibt; fehlt eine, sagt eine kurze Notiz warum. Die Server
|
||||
* Actions pruefen denselben Zustand noch einmal — die Anzeige ist keine
|
||||
* Sicherheitsgrenze.
|
||||
*/
|
||||
export function SponsorshipActions({ id, status, currentRevision, isPhysical, printed, ownerEmail, t }: SponsorshipActionsProps) {
|
||||
const issued = currentRevision > 0;
|
||||
const delivered = status === "BEREIT" || status === "GEDRUCKT";
|
||||
// Widerrufen (Storno/Erstattung): nur noch das Druck-PDF zur Ansicht, keine
|
||||
// Aktion, die der Kundschaft wieder etwas zustellen oder aendern wuerde.
|
||||
if (status === "WIDERRUFEN") {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{issued ? (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<a
|
||||
href={`/admin/patenschaften/${id}/revision/${currentRevision}.pdf?inline=1`}
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
className="inline-flex items-center justify-center border border-ink/20 px-4 py-2 text-xs tracking-wide-caps text-ink transition-colors hover:border-ink"
|
||||
>
|
||||
{t.openPrintPdf}
|
||||
</a>
|
||||
</div>
|
||||
) : null}
|
||||
<AdminActionNote>{t.noteRevoked}</AdminActionNote>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{issued ? (
|
||||
<a
|
||||
href={`/admin/patenschaften/${id}/revision/${currentRevision}.pdf?inline=1`}
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
className="inline-flex items-center justify-center border border-heading bg-forest px-4 py-2 text-xs tracking-wide-caps text-cream transition-colors hover:bg-honey-deep"
|
||||
>
|
||||
{t.openPrintPdf}
|
||||
</a>
|
||||
) : null}
|
||||
{isPhysical && status === "BEREIT" && !printed ? (
|
||||
<ConfirmForm action={markSponsorshipPrintedAction} confirmMessage={t.markPrintedConfirm}>
|
||||
<input type="hidden" name="id" value={id} />
|
||||
<Button type="submit" variant="secondary" className={buttonClass}>
|
||||
{t.markPrinted}
|
||||
</Button>
|
||||
</ConfirmForm>
|
||||
) : null}
|
||||
{status === "FEHLER" || status === "AUSSTEHEND" ? (
|
||||
<ConfirmForm action={retrySponsorshipAction} confirmMessage={t.retryConfirm}>
|
||||
<input type="hidden" name="id" value={id} />
|
||||
<Button type="submit" variant="secondary" className={buttonClass}>
|
||||
{status === "FEHLER" ? t.retry : t.retryNow}
|
||||
</Button>
|
||||
</ConfirmForm>
|
||||
) : null}
|
||||
{delivered && issued ? (
|
||||
<ConfirmForm action={resendSponsorshipMailAction} confirmMessage={t.resendConfirm(ownerEmail)}>
|
||||
<input type="hidden" name="id" value={id} />
|
||||
<Button type="submit" variant="ghost" className={buttonClass}>
|
||||
{t.resendMail}
|
||||
</Button>
|
||||
</ConfirmForm>
|
||||
) : null}
|
||||
{issued ? (
|
||||
<Link
|
||||
href={`/admin/patenschaften/${id}/korrigieren`}
|
||||
className="inline-flex items-center justify-center border border-ink/20 px-4 py-2 text-xs tracking-wide-caps text-ink transition-colors hover:border-ink"
|
||||
>
|
||||
{t.correct}
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
{!isPhysical ? <AdminActionNote>{t.notePrintPhysical}</AdminActionNote> : null}
|
||||
{isPhysical && !delivered ? <AdminActionNote>{t.notePrintReady}</AdminActionNote> : null}
|
||||
{!delivered ? <AdminActionNote>{t.noteMailReady}</AdminActionNote> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import Link from "next/link";
|
||||
import type { SponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
|
||||
export type SponsorshipSection = "overview" | "offers" | "subscriptions" | "loyalty";
|
||||
|
||||
const SECTIONS: { key: SponsorshipSection; href: string }[] = [
|
||||
{ key: "overview", href: "/admin/patenschaften" },
|
||||
{ key: "offers", href: "/admin/patenschaften/angebote" },
|
||||
{ key: "subscriptions", href: "/admin/patenschaften/abos" },
|
||||
{ key: "loyalty", href: "/admin/patenschaften/treuestufen" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Unternavigation des Bereichs. Die Seitenleiste fuehrt mit einem Eintrag
|
||||
* "Patenschaften" hierher; die vier Teile liegen als Reiter darunter — so
|
||||
* bleibt die Seitenleiste kurz, und es gibt dort nie zwei aktive Eintraege.
|
||||
*/
|
||||
export function SponsorshipTabs({ active, labels }: { active: SponsorshipSection; labels: SponsorshipAdminStrings["tabs"] }) {
|
||||
return (
|
||||
<nav aria-label={labels.ariaLabel} className="mb-6 flex gap-1 overflow-x-auto border-b border-ink/10">
|
||||
{SECTIONS.map((section) => {
|
||||
const selected = section.key === active;
|
||||
return (
|
||||
<Link
|
||||
key={section.key}
|
||||
href={section.href}
|
||||
aria-current={selected ? "page" : undefined}
|
||||
className={`-mb-px whitespace-nowrap border-b-2 px-4 py-2 text-sm transition-colors ${
|
||||
selected ? "border-heading text-heading" : "border-transparent text-ink/60 hover:text-heading"
|
||||
}`}
|
||||
>
|
||||
{labels[section.key]}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { AdminBadge, type AdminBadgeTone } from "@/components/admin-list";
|
||||
import type { SponsorshipStatus, SubscriptionStatus } from "@/generated/prisma/client";
|
||||
|
||||
const SPONSORSHIP_TONES: Record<SponsorshipStatus, AdminBadgeTone> = {
|
||||
AUSSTEHEND: "pending",
|
||||
FEHLER: "danger",
|
||||
BEREIT: "positive",
|
||||
GEDRUCKT: "neutral",
|
||||
WIDERRUFEN: "danger",
|
||||
};
|
||||
|
||||
const SUBSCRIPTION_TONES: Record<SubscriptionStatus, AdminBadgeTone> = {
|
||||
AUSSTEHEND: "neutral",
|
||||
AKTIV: "positive",
|
||||
IM_VERZUG: "danger",
|
||||
GEKUENDIGT: "pending",
|
||||
BEENDET: "neutral",
|
||||
};
|
||||
|
||||
export function SponsorshipStatusBadge({ status, label }: { status: SponsorshipStatus; label: string }) {
|
||||
return (
|
||||
<AdminBadge tone={SPONSORSHIP_TONES[status]} pulse={status === "FEHLER"}>
|
||||
{label}
|
||||
</AdminBadge>
|
||||
);
|
||||
}
|
||||
|
||||
export function SubscriptionStatusBadge({ status, label }: { status: SubscriptionStatus; label: string }) {
|
||||
return <AdminBadge tone={SUBSCRIPTION_TONES[status]}>{label}</AdminBadge>;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { ConfirmForm } from "@/components/confirm-form";
|
||||
import { AdminActionButton, AdminBadge } from "@/components/admin-list";
|
||||
import type { SponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { liftSepaBlockAction, updateSepaHoldDaysAction } from "@/app/admin/actions";
|
||||
import { MAX_SEPA_HOLD_DAYS } from "@/lib/sponsorship/settings";
|
||||
import type { HoneyCoverage } from "../_lib/coverage";
|
||||
|
||||
type Strings = SponsorshipAdminStrings["subscriptions"];
|
||||
|
||||
export function SepaBlockButton({ customerId, confirmMessage, label }: { customerId: string; confirmMessage: string; label: string }) {
|
||||
return (
|
||||
<ConfirmForm action={liftSepaBlockAction} confirmMessage={confirmMessage}>
|
||||
<input type="hidden" name="customerId" value={customerId} />
|
||||
<AdminActionButton>{label}</AdminActionButton>
|
||||
</ConfirmForm>
|
||||
);
|
||||
}
|
||||
|
||||
/** Deckung der Abos durch den automatisch gewaehlten (nicht-cremigen) Honig; unter einer Lieferrunde rot markiert (auch in der Aufmerksamkeitsliste). */
|
||||
export function CoveragePanel({ coverage, t }: { coverage: HoneyCoverage; t: Strings }) {
|
||||
return (
|
||||
<section id="deckung" className="border border-ink/10 bg-background p-6">
|
||||
<h2 className="mb-2 font-serif text-xl text-heading">{t.coverageHeading}</h2>
|
||||
<p className="mb-4 text-xs text-ink/65">{t.coverageIntro}</p>
|
||||
{coverage.rows.length === 0 ? (
|
||||
<p className="text-sm text-ink/65">{t.noCoverage}</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b border-ink/10 text-left text-xs text-ink/65">
|
||||
<tr>
|
||||
<th className="p-3 font-normal">{t.colProduct}</th>
|
||||
<th className="p-3 text-right font-normal">{t.colYear}</th>
|
||||
<th className="p-3 text-right font-normal">{t.colStock}</th>
|
||||
<th className="p-3 text-right font-normal">{t.colReserved}</th>
|
||||
<th className="p-3 text-right font-normal">{t.colFree}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-ink/10">
|
||||
{coverage.rows.map((row) => (
|
||||
<tr key={row.productId}>
|
||||
<td className="p-3">{row.productName}</td>
|
||||
<td className="p-3 text-right tabular-nums">{row.harvestYear}</td>
|
||||
<td className="p-3 text-right tabular-nums">{row.stock}</td>
|
||||
<td className="p-3 text-right tabular-nums">{row.reserved}</td>
|
||||
<td className="p-3 text-right tabular-nums">{row.free}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{coverage.deliveriesCovered !== null ? (
|
||||
<p className="mt-4 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-ink/75">
|
||||
<span className="tabular-nums">{t.perDelivery(coverage.jarsPerDelivery)}</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>{t.coversLabel}:</span>
|
||||
{coverage.deliveriesCovered < 1 ? (
|
||||
<AdminBadge tone="danger" pulse>
|
||||
{t.coverageWarning}
|
||||
</AdminBadge>
|
||||
) : (
|
||||
<span className="tabular-nums text-heading">{t.covers(coverage.deliveriesCovered)}</span>
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function SepaSettingsPanel({ holdDays, t }: { holdDays: number; t: Strings }) {
|
||||
return (
|
||||
<section className="border border-ink/10 bg-background p-6">
|
||||
<h2 className="mb-2 font-serif text-xl text-heading">{t.sepaHeading}</h2>
|
||||
<p className="mb-4 text-xs text-ink/65">{t.sepaIntro}</p>
|
||||
<form action={updateSepaHoldDaysAction} className="flex flex-wrap items-end gap-3">
|
||||
<label className="block text-sm">
|
||||
<span className="text-xs text-ink/65">{t.sepaLabel}</span>
|
||||
<input
|
||||
type="number"
|
||||
name="sepaHoldDays"
|
||||
min={0}
|
||||
max={MAX_SEPA_HOLD_DAYS}
|
||||
defaultValue={String(holdDays)}
|
||||
required
|
||||
className="mt-1 w-28 border border-ink/20 bg-background px-3 py-2 text-sm tabular-nums"
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="border border-heading px-4 py-2 text-sm text-heading transition-colors hover:bg-forest hover:text-cream">
|
||||
{t.sepaSave}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-3 text-xs text-ink/65">{t.sepaCurrent(holdDays)}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { getCurrentAdmin } from "@/lib/auth";
|
||||
|
||||
/**
|
||||
* Pruefung fuer die Route Handler unter /admin/patenschaften (Vorschau,
|
||||
* Revisions-PDFs). Route Handler laufen nicht durch das Admin-Layout, also
|
||||
* gilt hier dieselbe Regel wie in requireAdmin(): Admin-Rolle laut Datenbank
|
||||
* UND aktive Zwei-Faktor-Authentifizierung. Die Aufrufer antworten bei null
|
||||
* mit 404, damit von aussen nicht einmal die Existenz einer Patenschaft
|
||||
* erkennbar ist.
|
||||
*/
|
||||
export async function getAuthorizedAdmin(): Promise<{ id: string; email: string } | null> {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin || !admin.twoFactorEnabled) return null;
|
||||
return { id: admin.id, email: admin.email };
|
||||
}
|
||||
|
||||
export function notFoundResponse(): Response {
|
||||
return new Response("Nicht gefunden.", { status: 404, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { Locale } from "@/i18n/config";
|
||||
import { getSponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { countUndercovered, getHoneyCoverage } from "./coverage";
|
||||
import { TO_PRINT_FILTER } from "./sponsorship-filters";
|
||||
|
||||
export interface AttentionItem {
|
||||
count: number;
|
||||
href: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** Ab wann eine druckbereite Urkunde als liegengeblieben gilt. */
|
||||
const PRINT_GRACE_MS = 2 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Eintraege der Patenschaft fuer die Aufmerksamkeitsliste im Dashboard:
|
||||
* Ausstellung endgueltig gescheitert, Urkunden, die seit ueber zwei Tagen
|
||||
* auf den Druck warten, Honig, der keine Abo-Lieferung mehr deckt, und Abos
|
||||
* im Verzug. Nur Eintraege mit count > 0.
|
||||
*/
|
||||
export async function getSponsorshipAttentionItems(locale: Locale, now: Date = new Date()): Promise<AttentionItem[]> {
|
||||
const t = getSponsorshipAdminStrings(locale).attention;
|
||||
// Honigdeckung zaehlt hoechstens 1: Abos haben keinen festen Honig mehr,
|
||||
// gedeckt wird aus allem nicht-cremigen Honig zusammen (coverage.ts).
|
||||
const [failed, overdueToPrint, delinquent, coverage] = await Promise.all([
|
||||
prisma.sponsorship.count({ where: { status: "FEHLER" } }),
|
||||
// mailSentAt ist der Moment, in dem die Patenschaft BEREIT wurde (die
|
||||
// Mail ist der letzte Schritt der Ausstellung).
|
||||
prisma.sponsorship.count({
|
||||
where: { ...TO_PRINT_FILTER, mailSentAt: { lte: new Date(now.getTime() - PRINT_GRACE_MS) } },
|
||||
}),
|
||||
prisma.sponsorshipSubscription.count({ where: { status: "IM_VERZUG" } }),
|
||||
getHoneyCoverage(now),
|
||||
]);
|
||||
const undercovered = countUndercovered(coverage);
|
||||
return [
|
||||
{ count: failed, href: "/admin/patenschaften?status=FEHLER", label: t.failed(failed) },
|
||||
{ count: overdueToPrint, href: "/admin/patenschaften?status=ZU_DRUCKEN", label: t.toPrint(overdueToPrint) },
|
||||
{ count: undercovered, href: "/admin/patenschaften/abos#deckung", label: t.coverage },
|
||||
{ count: delinquent, href: "/admin/patenschaften/abos?status=IM_VERZUG", label: t.delinquent(delinquent) },
|
||||
].filter((item) => item.count > 0);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { freeStock, subscriptionReservationByProduct } from "@/lib/sponsorship-subscription/reservation";
|
||||
import { loadHoneyStock } from "@/lib/sponsorship/honey-stock";
|
||||
import { rankHoneyCandidates, type HoneyCandidate } from "@/lib/sponsorship/honey-selection";
|
||||
|
||||
/**
|
||||
* Honigbestand und Abo-Deckung fuer den Admin (Spec, "Honigbestand und
|
||||
* Kontingent"). Pakete und Abos bekommen automatisch nicht-cremigen Honig
|
||||
* (lib/sponsorship/honey-selection.ts) — gezeigt wird deshalb genau dieser
|
||||
* Honig, in der Rangfolge der automatischen Wahl. Reserviert wird in
|
||||
* lib/sponsorship-subscription/reservation.ts berechnet; hier wird nur
|
||||
* zusammengestellt und angezeigt.
|
||||
*/
|
||||
|
||||
/** Abos, deren naechste Lieferung noch Honig braucht (wie in reservation.ts). */
|
||||
const DEMANDING_STATUSES = ["AKTIV", "IM_VERZUG", "GEKUENDIGT"] as const;
|
||||
|
||||
export interface HoneyStock {
|
||||
stock: number;
|
||||
reserved: number;
|
||||
free: number;
|
||||
}
|
||||
|
||||
export interface EligibleHoneyRow extends HoneyStock {
|
||||
productId: string;
|
||||
productName: string;
|
||||
weightGrams: number;
|
||||
harvestYear: number;
|
||||
consistency: string;
|
||||
}
|
||||
|
||||
export interface HoneyCoverage {
|
||||
/** Nicht-cremiger, aktiver Honig in der Rangfolge der automatischen Wahl. */
|
||||
rows: EligibleHoneyRow[];
|
||||
/** Glaeser, die eine vierteljaehrliche Lieferrunde aller laufenden Abos braucht. */
|
||||
jarsPerDelivery: number;
|
||||
/** Wie viele Lieferrunden der gesamte passende Bestand bedient; null = kein vierteljaehrlicher Bedarf. */
|
||||
deliveriesCovered: number | null;
|
||||
}
|
||||
|
||||
/** Ganze Lieferrunden, die ein Bestand deckt; null, wenn es keinen Bedarf gibt. */
|
||||
export function deliveriesCovered(stock: number, jarsPerDelivery: number): number | null {
|
||||
if (jarsPerDelivery <= 0) return null;
|
||||
return Math.floor(Math.max(0, stock) / jarsPerDelivery);
|
||||
}
|
||||
|
||||
/**
|
||||
* Passender Honig (aktiv, nicht cremig) mit Bestand, Abo-Reservierung und
|
||||
* freiem Bestand, in der Rangfolge der automatischen Wahl (bei gleicher Ernte
|
||||
* nach freiem Bestand). Eine Abfrage-Runde fuer alle Produkte.
|
||||
*/
|
||||
export async function getEligibleHoneyStock(now: Date = new Date()): Promise<EligibleHoneyRow[]> {
|
||||
const stock = await loadHoneyStock();
|
||||
const reserved = await subscriptionReservationByProduct(now, prisma, stock);
|
||||
const withFree = stock.map((candidate) => ({
|
||||
...candidate,
|
||||
freeStock: freeStock(candidate.inventory, reserved.get(candidate.id) ?? 0),
|
||||
}));
|
||||
return rankHoneyCandidates(withFree).map((candidate) => ({
|
||||
productId: candidate.id,
|
||||
productName: candidate.name,
|
||||
weightGrams: candidate.weightGrams,
|
||||
harvestYear: candidate.harvestYear,
|
||||
consistency: candidate.consistency,
|
||||
stock: candidate.inventory,
|
||||
reserved: reserved.get(candidate.id) ?? 0,
|
||||
free: candidate.freeStock,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Zeilen zurueck in Kandidaten der automatischen Wahl (freier Bestand). */
|
||||
export function toHoneyCandidates(rows: readonly EligibleHoneyRow[]): HoneyCandidate[] {
|
||||
return rows.map((row) => ({
|
||||
id: row.productId,
|
||||
name: row.productName,
|
||||
weightGrams: row.weightGrams,
|
||||
harvestYear: row.harvestYear,
|
||||
consistency: row.consistency,
|
||||
inventory: row.stock,
|
||||
freeStock: row.free,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Deckung der Abos durch den passenden Honig insgesamt. */
|
||||
export async function getHoneyCoverage(now: Date = new Date()): Promise<HoneyCoverage> {
|
||||
const [rows, subscriptions] = await Promise.all([
|
||||
getEligibleHoneyStock(now),
|
||||
prisma.sponsorshipSubscription.findMany({
|
||||
where: { status: { in: [...DEMANDING_STATUSES] }, offer: { cycle: "VIERTELJAEHRLICH", honeyJars: { gt: 0 } } },
|
||||
select: { offer: { select: { honeyJars: true } } },
|
||||
}),
|
||||
]);
|
||||
const jarsPerDelivery = subscriptions.reduce((sum, { offer }) => sum + offer.honeyJars, 0);
|
||||
const totalStock = rows.reduce((sum, row) => sum + row.stock, 0);
|
||||
return { rows, jarsPerDelivery, deliveriesCovered: deliveriesCovered(totalStock, jarsPerDelivery) };
|
||||
}
|
||||
|
||||
/** Fuer die Aufmerksamkeitsliste: 1, wenn der passende Honig keine volle Lieferrunde mehr deckt. */
|
||||
export function countUndercovered(coverage: Pick<HoneyCoverage, "deliveriesCovered">): number {
|
||||
return coverage.deliveriesCovered !== null && coverage.deliveriesCovered < 1 ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { isOfferAvailable } from "@/lib/sponsorship/offers";
|
||||
import { honeyLabel, pickHoneyProduct } from "@/lib/sponsorship/honey-selection";
|
||||
import { getEligibleHoneyStock, toHoneyCandidates, type EligibleHoneyRow, type HoneyStock } from "./coverage";
|
||||
|
||||
/** Abos, die einen Platz im Kontingent belegen (wie lib/sponsorship/offers.ts). */
|
||||
const QUOTA_STATUSES = ["AKTIV", "IM_VERZUG", "GEKUENDIGT"] as const;
|
||||
|
||||
async function loadOffers(where: { id?: string }) {
|
||||
return prisma.sponsorshipOffer.findMany({
|
||||
where,
|
||||
include: { product: { select: { id: true, priceCents: true } } },
|
||||
orderBy: [{ kind: "asc" }, { sortOrder: "asc" }, { createdAt: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
export type OfferRow = Awaited<ReturnType<typeof loadOffers>>[number];
|
||||
|
||||
/** Der Honig, den die automatische Wahl gerade fuer ein Angebot nimmt. */
|
||||
export interface CurrentHoney extends HoneyStock {
|
||||
productId: string;
|
||||
/** "<Name> <Jahr>" */
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface OfferOverviewRow {
|
||||
offer: OfferRow;
|
||||
/** Live: dieselbe Entscheidung wie auf der Verkaufsseite. */
|
||||
isAvailable: boolean;
|
||||
activeSubscriptions: number;
|
||||
/** null bei Angeboten ohne Glaeser oder wenn kein passender Honig reicht. */
|
||||
currentHoney: CurrentHoney | null;
|
||||
}
|
||||
|
||||
export interface OfferOverview {
|
||||
rows: OfferOverviewRow[];
|
||||
/** Passender Honig (nicht cremig) in der Rangfolge der automatischen Wahl. */
|
||||
eligibleHoney: EligibleHoneyRow[];
|
||||
}
|
||||
|
||||
/** Die automatische Wahl fuer `jars` Glaeser als Anzeige-Datensatz — oder null. */
|
||||
export function currentHoneyFor(eligibleHoney: readonly EligibleHoneyRow[], jars: number): CurrentHoney | null {
|
||||
if (jars <= 0) return null;
|
||||
const picked = pickHoneyProduct(toHoneyCandidates(eligibleHoney), jars);
|
||||
const row = picked ? eligibleHoney.find((candidate) => candidate.productId === picked.id) : undefined;
|
||||
if (!row) return null;
|
||||
return {
|
||||
productId: row.productId,
|
||||
label: honeyLabel({ name: row.productName, harvestYear: row.harvestYear }),
|
||||
stock: row.stock,
|
||||
reserved: row.reserved,
|
||||
free: row.free,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Angebote samt Live-Verfuegbarkeit und automatisch gewaehltem Honig. Fuer
|
||||
* ALLE Angebote, auch inaktive — getActiveOffers() aus
|
||||
* lib/sponsorship/offers.ts kennt nur aktive, der Admin will aber sehen, ob
|
||||
* ein Angebot nach dem Aktivieren ueberhaupt bestellbar waere. Die
|
||||
* Entscheidung selbst bleibt isOfferAvailable.
|
||||
*/
|
||||
export async function getOfferOverview(offerId?: string): Promise<OfferOverview> {
|
||||
const offers = await loadOffers(offerId ? { id: offerId } : {});
|
||||
const [eligibleHoney, groups] = await Promise.all([
|
||||
getEligibleHoneyStock(),
|
||||
prisma.sponsorshipSubscription.groupBy({
|
||||
by: ["offerId"],
|
||||
where: { offerId: { in: offers.map((offer) => offer.id) }, status: { in: [...QUOTA_STATUSES] } },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
]);
|
||||
const subscriptionCounts = new Map(groups.map((group) => [group.offerId, group._count._all]));
|
||||
|
||||
const rows = offers.map((offer) => {
|
||||
const currentHoney = currentHoneyFor(eligibleHoney, offer.honeyJars);
|
||||
const activeSubscriptions = subscriptionCounts.get(offer.id) ?? 0;
|
||||
return {
|
||||
offer,
|
||||
activeSubscriptions,
|
||||
currentHoney,
|
||||
isAvailable: isOfferAvailable({
|
||||
isActive: offer.isActive,
|
||||
kind: offer.kind,
|
||||
hasCarrierProduct: offer.productId !== null,
|
||||
honeyJars: offer.honeyJars,
|
||||
hasEligibleHoney: currentHoney !== null,
|
||||
maxActiveSubscriptions: offer.maxActiveSubscriptions,
|
||||
activeSubscriptions,
|
||||
}),
|
||||
};
|
||||
});
|
||||
return { rows, eligibleHoney };
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { carrierPriceCents, centsToEuroInput, parseEuroToCents, parseOfferForm } from "./offer-schema";
|
||||
|
||||
function form(values: Record<string, string>): FormData {
|
||||
const data = new FormData();
|
||||
for (const [key, value] of Object.entries(values)) data.set(key, value);
|
||||
return data;
|
||||
}
|
||||
|
||||
const oneTime = {
|
||||
kind: "EINMALIG",
|
||||
name: "Honigfreund",
|
||||
slug: "honigfreund",
|
||||
description: "Gedruckte Urkunde und ein Glas Honig.",
|
||||
features: "Gedruckte Urkunde\n\n1 × 500 g Honig\n",
|
||||
price: "39,00",
|
||||
honeySharePerJar: "7",
|
||||
isPhysical: "on",
|
||||
honeyJars: "1",
|
||||
medalTier: "SILBER",
|
||||
};
|
||||
|
||||
const subscription = {
|
||||
kind: "ABO",
|
||||
name: "Abo vierteljährlich",
|
||||
slug: "abo-vierteljaehrlich",
|
||||
description: "Monatlich bezahlt, Honig nach drei Monaten.",
|
||||
price: "12,50",
|
||||
honeySharePerMonth: "4",
|
||||
isPhysical: "on",
|
||||
honeyJars: "2",
|
||||
cycle: "VIERTELJAEHRLICH",
|
||||
medalTier: "ABO",
|
||||
};
|
||||
|
||||
describe("parseEuroToCents", () => {
|
||||
it("versteht deutsche und englische Schreibweisen", () => {
|
||||
expect(parseEuroToCents("19")).toBe(1900);
|
||||
expect(parseEuroToCents("19,9")).toBe(1990);
|
||||
expect(parseEuroToCents("19.90 €")).toBe(1990);
|
||||
expect(parseEuroToCents("1.234,56")).toBe(123456);
|
||||
});
|
||||
|
||||
it("lehnt Unklares ab", () => {
|
||||
expect(parseEuroToCents("")).toBeNull();
|
||||
expect(parseEuroToCents("19,999")).toBeNull();
|
||||
expect(parseEuroToCents("-5")).toBeNull();
|
||||
expect(parseEuroToCents("abc")).toBeNull();
|
||||
});
|
||||
|
||||
it("wandelt Cent zurueck ins Formularformat", () => {
|
||||
expect(centsToEuroInput(1990)).toBe("19,90");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseOfferForm", () => {
|
||||
it("liest ein gueltiges Einmal-Angebot und raeumt Abo-Felder ab", () => {
|
||||
const result = parseOfferForm(form({ ...oneTime, cycle: "ERNTE", honeySharePerMonth: "3" }));
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value).toMatchObject({
|
||||
kind: "EINMALIG",
|
||||
priceCents: 3900,
|
||||
honeyShareCentsPerJar: 700,
|
||||
honeyShareCentsPerMonth: 0,
|
||||
cycle: null,
|
||||
features: ["Gedruckte Urkunde", "1 × 500 g Honig"],
|
||||
nameEn: null,
|
||||
isActive: false,
|
||||
});
|
||||
expect(carrierPriceCents(result.value)).toBe(3200);
|
||||
});
|
||||
|
||||
it("verlangt Honiganteil × Gläser kleiner als den Paketpreis", () => {
|
||||
const result = parseOfferForm(form({ ...oneTime, honeyJars: "3", honeySharePerJar: "13" }));
|
||||
expect(result).toEqual({ ok: false, message: "Honiganteil × Gläser muss kleiner als der Paketpreis sein." });
|
||||
});
|
||||
|
||||
it("verlangt bei Glaesern im Paket einen Honiganteil", () => {
|
||||
const result = parseOfferForm(form({ ...oneTime, honeySharePerJar: "" }));
|
||||
expect(result).toEqual({ ok: false, message: "Bei Gläsern im Paket bitte den Honiganteil je Glas angeben." });
|
||||
});
|
||||
|
||||
it("verlangt fuer physische Angebote mindestens ein Glas", () => {
|
||||
const result = parseOfferForm(form({ ...oneTime, honeyJars: "0", honeySharePerJar: "" }));
|
||||
expect(result).toEqual({ ok: false, message: "Ein physisches Angebot braucht mindestens ein Glas Honig." });
|
||||
});
|
||||
|
||||
it("nimmt kein festes Honigprodukt mehr an — der Honig wird automatisch gewaehlt", () => {
|
||||
const result = parseOfferForm(form({ ...oneTime, honeyProductId: "prod_1" }));
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) expect(result.value).not.toHaveProperty("honeyProductId");
|
||||
});
|
||||
|
||||
it("erlaubt ein rein digitales Angebot ohne Honig", () => {
|
||||
const result = parseOfferForm(
|
||||
form({ ...oneTime, isPhysical: "", honeyJars: "0", honeySharePerJar: "", price: "19" })
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) expect(carrierPriceCents(result.value)).toBe(1900);
|
||||
});
|
||||
|
||||
it("verlangt beim Abo einen Zyklus und einen Monatsanteil unter dem Monatspreis", () => {
|
||||
expect(parseOfferForm(form({ ...subscription, cycle: "" }))).toEqual({
|
||||
ok: false,
|
||||
message: "Ein Abo braucht einen Lieferzyklus.",
|
||||
});
|
||||
expect(parseOfferForm(form({ ...subscription, honeySharePerMonth: "12,50" }))).toEqual({
|
||||
ok: false,
|
||||
message: "Der Honiganteil je Monat muss kleiner als der Monatspreis sein.",
|
||||
});
|
||||
});
|
||||
|
||||
it("liest ein Abo mit Kontingent und leert den Glasanteil", () => {
|
||||
const result = parseOfferForm(form({ ...subscription, maxActiveSubscriptions: "40", honeySharePerJar: "5" }));
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.value).toMatchObject({ priceCents: 1250, honeyShareCentsPerMonth: 400, honeyShareCentsPerJar: 0, maxActiveSubscriptions: 40 });
|
||||
}
|
||||
});
|
||||
|
||||
it("setzt beim Bearbeiten die gespeicherte Art durch", () => {
|
||||
const result = parseOfferForm(form({ ...subscription, kind: "EINMALIG" }), "ABO");
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) expect(result.value.kind).toBe("ABO");
|
||||
});
|
||||
|
||||
it("prueft Slug und Preis", () => {
|
||||
expect(parseOfferForm(form({ ...oneTime, slug: "Honig Freund" }))).toEqual({
|
||||
ok: false,
|
||||
message: "Adresse: nur Kleinbuchstaben, Ziffern und einzelne Bindestriche.",
|
||||
});
|
||||
expect(parseOfferForm(form({ ...oneTime, price: "abc" }))).toEqual({
|
||||
ok: false,
|
||||
message: "Preis: bitte einen Betrag in Euro angeben, z. B. 19,90.",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { z } from "zod";
|
||||
import type { MedalTier, SponsorshipCycle, SponsorshipOfferKind } from "@/generated/prisma/client";
|
||||
|
||||
/**
|
||||
* Formularpruefung der Patenschafts-Angebote. Rein (ohne Datenbank), damit
|
||||
* die Geschaeftsregeln — vor allem die Steueraufteilung — testbar bleiben.
|
||||
* Meldungen auf Deutsch, sie erscheinen unveraendert als Flash-Meldung.
|
||||
*/
|
||||
|
||||
export const OFFER_KINDS = ["EINMALIG", "ABO"] as const satisfies readonly SponsorshipOfferKind[];
|
||||
export const OFFER_CYCLES = ["VIERTELJAEHRLICH", "ERNTE"] as const satisfies readonly SponsorshipCycle[];
|
||||
export const MEDAL_TIERS = ["BRONZE", "SILBER", "GOLD", "ABO"] as const satisfies readonly MedalTier[];
|
||||
|
||||
const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
const MAX_PRICE_CENTS = 1_000_000;
|
||||
const MAX_FEATURES = 12;
|
||||
const MAX_FEATURE_LENGTH = 120;
|
||||
|
||||
/**
|
||||
* Euro-Eingabe in Cent: "19", "19,9", "19,90", "19.90" und "1.234,56".
|
||||
* null bei allem anderen — lieber ablehnen als einen Preis raten.
|
||||
*/
|
||||
export function parseEuroToCents(value: string): number | null {
|
||||
let text = value.replace(/[\s€]/g, "");
|
||||
if (text === "") return null;
|
||||
if (text.includes(",") && text.includes(".")) text = text.replace(/\./g, "");
|
||||
text = text.replace(",", ".");
|
||||
if (!/^\d+(\.\d{1,2})?$/.test(text)) return null;
|
||||
return Math.round(Number(text) * 100);
|
||||
}
|
||||
|
||||
/** Cent als Formularwert, z.B. 1990 → "19,90". */
|
||||
export function centsToEuroInput(cents: number): string {
|
||||
return (cents / 100).toFixed(2).replace(".", ",");
|
||||
}
|
||||
|
||||
function euro(label: string, { optional }: { optional: boolean }) {
|
||||
return z.string().transform((value, ctx) => {
|
||||
if (optional && value.trim() === "") return 0;
|
||||
const cents = parseEuroToCents(value);
|
||||
if (cents === null || cents > MAX_PRICE_CENTS) {
|
||||
ctx.addIssue({ code: "custom", message: `${label}: bitte einen Betrag in Euro angeben, z. B. 19,90.` });
|
||||
return z.NEVER;
|
||||
}
|
||||
return cents;
|
||||
});
|
||||
}
|
||||
|
||||
function optionalText(max: number, label: string) {
|
||||
return z
|
||||
.string()
|
||||
.trim()
|
||||
.max(max, `${label}: höchstens ${max} Zeichen.`)
|
||||
.transform((value) => (value === "" ? null : value));
|
||||
}
|
||||
|
||||
/** Eine Leistung je Zeile; leere Zeilen fallen weg. */
|
||||
function featureLines(label: string) {
|
||||
return z
|
||||
.string()
|
||||
.transform((value) => value.split(/\r?\n/).map((line) => line.trim()).filter(Boolean))
|
||||
.pipe(
|
||||
z
|
||||
.array(z.string().max(MAX_FEATURE_LENGTH, `${label}: jede Zeile höchstens ${MAX_FEATURE_LENGTH} Zeichen.`))
|
||||
.max(MAX_FEATURES, `${label}: höchstens ${MAX_FEATURES} Zeilen.`)
|
||||
);
|
||||
}
|
||||
|
||||
function intField(label: string, min: number, max: number) {
|
||||
return z.coerce
|
||||
.number({ error: `${label}: bitte eine ganze Zahl angeben.` })
|
||||
.int(`${label}: bitte eine ganze Zahl angeben.`)
|
||||
.min(min, `${label}: mindestens ${min}.`)
|
||||
.max(max, `${label}: höchstens ${max}.`);
|
||||
}
|
||||
|
||||
const offerFormSchema = z
|
||||
.object({
|
||||
kind: z.enum(OFFER_KINDS, { error: "Bitte die Art des Angebots wählen." }),
|
||||
name: z.string().trim().min(2, "Bitte einen Namen angeben.").max(80, "Name: höchstens 80 Zeichen."),
|
||||
nameEn: optionalText(80, "Name (Englisch)"),
|
||||
slug: z
|
||||
.string()
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.min(2, "Bitte eine Adresse (Slug) angeben.")
|
||||
.max(60, "Adresse: höchstens 60 Zeichen.")
|
||||
.regex(SLUG, "Adresse: nur Kleinbuchstaben, Ziffern und einzelne Bindestriche."),
|
||||
description: z.string().trim().min(1, "Bitte eine Beschreibung angeben.").max(2000, "Beschreibung: höchstens 2000 Zeichen."),
|
||||
descriptionEn: optionalText(2000, "Beschreibung (Englisch)"),
|
||||
features: featureLines("Leistungen"),
|
||||
featuresEn: featureLines("Leistungen (Englisch)"),
|
||||
priceCents: euro("Preis", { optional: false }),
|
||||
honeyShareCentsPerJar: euro("Honiganteil je Glas", { optional: true }),
|
||||
honeyShareCentsPerMonth: euro("Honiganteil je Monat", { optional: true }),
|
||||
isActive: z.boolean(),
|
||||
isPhysical: z.boolean(),
|
||||
sortOrder: intField("Reihenfolge", 0, 9999),
|
||||
honeyJars: intField("Gläser", 0, 24),
|
||||
cycle: z.union([z.enum(OFFER_CYCLES), z.literal("")]).transform((value) => (value === "" ? null : value)),
|
||||
maxActiveSubscriptions: z.union([z.literal(""), intField("Höchstzahl aktiver Abos", 1, 100_000)]).transform((value) =>
|
||||
value === "" ? null : value
|
||||
),
|
||||
medalTier: z.enum(MEDAL_TIERS, { error: "Bitte eine Medaillenstufe wählen." }),
|
||||
})
|
||||
.superRefine((offer, ctx) => {
|
||||
const issue = (message: string) => ctx.addIssue({ code: "custom", message });
|
||||
if (offer.priceCents <= 0) issue("Der Preis muss größer als 0 € sein.");
|
||||
// Welcher Honig, waehlt das System automatisch (nie cremig, neueste
|
||||
// Ernte — lib/sponsorship/honey-selection.ts); hier geht es nur um die
|
||||
// Menge. Ein festes Honigprodukt nimmt das Formular nicht mehr an.
|
||||
if (offer.isPhysical && offer.honeyJars < 1) issue("Ein physisches Angebot braucht mindestens ein Glas Honig.");
|
||||
if (offer.kind === "EINMALIG") {
|
||||
// Der Rest nach Abzug des Honiganteils ist der Preis des Traegerprodukts
|
||||
// (Urkunde und Leistung zum Regelsatz) — er muss positiv bleiben.
|
||||
if (offer.honeyJars * offer.honeyShareCentsPerJar >= offer.priceCents) {
|
||||
issue("Honiganteil × Gläser muss kleiner als der Paketpreis sein.");
|
||||
}
|
||||
// Die Honigposition im Checkout kostet genau den Honiganteil je Glas;
|
||||
// eine 0-€-Position wuerde den Honig steuerlich verschwinden lassen.
|
||||
if (offer.honeyJars > 0 && offer.honeyShareCentsPerJar <= 0) {
|
||||
issue("Bei Gläsern im Paket bitte den Honiganteil je Glas angeben.");
|
||||
}
|
||||
} else {
|
||||
if (offer.honeyShareCentsPerMonth >= offer.priceCents) issue("Der Honiganteil je Monat muss kleiner als der Monatspreis sein.");
|
||||
if (!offer.cycle) issue("Ein Abo braucht einen Lieferzyklus.");
|
||||
}
|
||||
})
|
||||
// Felder, die zur jeweils anderen Art gehoeren, werden geleert — sonst
|
||||
// blieben z.B. ein Lieferzyklus oder ein Monatsanteil an einem
|
||||
// Einmal-Angebot haengen, die nirgends angezeigt, aber gespeichert waeren.
|
||||
.transform((offer) =>
|
||||
offer.kind === "EINMALIG"
|
||||
? { ...offer, honeyShareCentsPerMonth: 0, cycle: null, maxActiveSubscriptions: null }
|
||||
: { ...offer, honeyShareCentsPerJar: 0 }
|
||||
);
|
||||
|
||||
export type OfferFormValues = z.output<typeof offerFormSchema>;
|
||||
|
||||
function field(formData: FormData, key: string): string {
|
||||
return String(formData.get(key) ?? "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Liest und prueft das Angebotsformular. `fixedKind` setzt beim Bearbeiten
|
||||
* die gespeicherte Art durch — die Art ist nach dem Anlegen unveraenderlich,
|
||||
* ein manipuliertes Formularfeld darf daran nichts aendern.
|
||||
*/
|
||||
export function parseOfferForm(
|
||||
formData: FormData,
|
||||
fixedKind?: SponsorshipOfferKind
|
||||
): { ok: true; value: OfferFormValues } | { ok: false; message: string } {
|
||||
const parsed = offerFormSchema.safeParse({
|
||||
kind: fixedKind ?? field(formData, "kind"),
|
||||
name: field(formData, "name"),
|
||||
nameEn: field(formData, "nameEn"),
|
||||
slug: field(formData, "slug"),
|
||||
description: field(formData, "description"),
|
||||
descriptionEn: field(formData, "descriptionEn"),
|
||||
features: field(formData, "features"),
|
||||
featuresEn: field(formData, "featuresEn"),
|
||||
priceCents: field(formData, "price"),
|
||||
honeyShareCentsPerJar: field(formData, "honeySharePerJar"),
|
||||
honeyShareCentsPerMonth: field(formData, "honeySharePerMonth"),
|
||||
isActive: formData.get("isActive") === "on",
|
||||
isPhysical: formData.get("isPhysical") === "on",
|
||||
sortOrder: field(formData, "sortOrder") || "0",
|
||||
honeyJars: field(formData, "honeyJars") || "0",
|
||||
cycle: field(formData, "cycle"),
|
||||
maxActiveSubscriptions: field(formData, "maxActiveSubscriptions").trim(),
|
||||
medalTier: field(formData, "medalTier"),
|
||||
});
|
||||
if (!parsed.success) return { ok: false, message: parsed.error.issues[0]?.message ?? "Ungültige Eingabe." };
|
||||
return { ok: true, value: parsed.data };
|
||||
}
|
||||
|
||||
/** Preis des Traegerprodukts einer Einmal-Patenschaft: Paketpreis minus Honiganteil. */
|
||||
export function carrierPriceCents(offer: Pick<OfferFormValues, "priceCents" | "honeyJars" | "honeyShareCentsPerJar">): number {
|
||||
return offer.priceCents - offer.honeyJars * offer.honeyShareCentsPerJar;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { defaultLocale, isLocale } from "@/i18n/config";
|
||||
import type { CertificateTerm } from "@/lib/certificate/schema";
|
||||
import { parseStoredPersonalization, type CertificateDocumentInput } from "@/lib/sponsorship/certificate-document";
|
||||
|
||||
const termSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("FIXED"), start: z.string(), end: z.string() }),
|
||||
z.object({ kind: z.literal("OPEN"), start: z.string() }),
|
||||
z.object({ kind: z.literal("ENDED"), start: z.string(), end: z.string() }),
|
||||
]);
|
||||
|
||||
/** Laufzeit einer gespeicherten Revision; wirft bei einem unerwarteten Format statt still falsch zu rendern. */
|
||||
export function parseStoredTerm(value: unknown): CertificateTerm {
|
||||
return termSchema.parse(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bienenname aus einem gespeicherten Personalisierungs-JSON — entweder direkt
|
||||
* (Revision: { beeName, … }) oder verpackt (Bestellposition/Abo:
|
||||
* { personalization: { beeName, … }, templateVersion }). Nur fuer Anzeige
|
||||
* und Suche, deshalb ohne Schema-Pruefung.
|
||||
*/
|
||||
export function beeNameFromJson(value: unknown): string | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const record = value as { beeName?: unknown; personalization?: unknown };
|
||||
if (typeof record.beeName === "string") return record.beeName;
|
||||
return beeNameFromJson(record.personalization);
|
||||
}
|
||||
|
||||
export interface RevisionDocument {
|
||||
input: CertificateDocumentInput;
|
||||
revision: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Daten einer gespeicherten Revision so, wie die Urkunden-Helfer sie zum
|
||||
* Rendern brauchen. Ohne `revision` die aktuelle. null, wenn es die
|
||||
* Patenschaft oder die Revision nicht gibt.
|
||||
*/
|
||||
export async function loadRevisionDocument(sponsorshipId: string, revision?: number): Promise<RevisionDocument | null> {
|
||||
const sponsorship = await prisma.sponsorship.findUnique({
|
||||
where: { id: sponsorshipId },
|
||||
select: { number: true, locale: true, currentRevision: true },
|
||||
});
|
||||
if (!sponsorship) return null;
|
||||
const wanted = revision ?? sponsorship.currentRevision;
|
||||
if (wanted < 1) return null;
|
||||
const row = await prisma.sponsorshipRevision.findUnique({
|
||||
where: { sponsorshipId_revision: { sponsorshipId, revision: wanted } },
|
||||
select: { personalization: true, term: true, templateVersion: true },
|
||||
});
|
||||
if (!row) return null;
|
||||
const stored = parseStoredPersonalization({ personalization: row.personalization, templateVersion: row.templateVersion });
|
||||
return {
|
||||
revision: wanted,
|
||||
input: {
|
||||
personalization: stored.personalization,
|
||||
templateVersion: stored.templateVersion,
|
||||
term: parseStoredTerm(row.term),
|
||||
number: sponsorship.number,
|
||||
locale: isLocale(sponsorship.locale) ? sponsorship.locale : defaultLocale,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { insensitiveContains } from "@/lib/prisma-search";
|
||||
import type { Prisma, SponsorshipOfferKind } from "@/generated/prisma/client";
|
||||
import { beeNameFromJson } from "./revision-data";
|
||||
|
||||
/**
|
||||
* Filter der Patenschaftsliste. "ZU_DRUCKEN" ist kein gespeicherter Status,
|
||||
* sondern die Arbeitsliste des Druckablaufs: physisches Paket, Urkunde
|
||||
* bereit, noch nicht gedruckt.
|
||||
*/
|
||||
export const LIST_STATUSES = ["AUSSTEHEND", "FEHLER", "BEREIT", "GEDRUCKT", "WIDERRUFEN", "ZU_DRUCKEN"] as const;
|
||||
export type ListStatus = (typeof LIST_STATUSES)[number];
|
||||
|
||||
export const TO_PRINT_FILTER = {
|
||||
status: "BEREIT",
|
||||
printedAt: null,
|
||||
offer: { isPhysical: true },
|
||||
} satisfies Prisma.SponsorshipWhereInput;
|
||||
|
||||
export const PAGE_SIZE = 50;
|
||||
|
||||
/** Obergrenze der Zeilen, die fuer die Bienennamen-Suche gelesen werden (siehe sponsorshipIdsByBeeName). */
|
||||
const BEE_SEARCH_LIMIT = 5000;
|
||||
|
||||
export interface SponsorshipListFilters {
|
||||
query: string;
|
||||
status: ListStatus | null;
|
||||
kind: SponsorshipOfferKind | null;
|
||||
offerId: string | null;
|
||||
page: number;
|
||||
}
|
||||
|
||||
type SearchParams = Record<string, string | string[] | undefined>;
|
||||
|
||||
function single(params: SearchParams, key: string): string {
|
||||
const value = params[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
export function parseListFilters(params: SearchParams): SponsorshipListFilters {
|
||||
const status = single(params, "status");
|
||||
const kind = single(params, "art");
|
||||
const page = Number.parseInt(single(params, "seite"), 10);
|
||||
return {
|
||||
query: single(params, "q").slice(0, 100),
|
||||
status: (LIST_STATUSES as readonly string[]).includes(status) ? (status as ListStatus) : null,
|
||||
kind: kind === "EINMALIG" || kind === "ABO" ? kind : null,
|
||||
offerId: single(params, "angebot") || null,
|
||||
page: Number.isFinite(page) && page > 1 ? page : 1,
|
||||
};
|
||||
}
|
||||
|
||||
/** URL der Liste mit den aktuellen Filtern; `page` ueberschreibt die Seite. */
|
||||
export function listHref(filters: SponsorshipListFilters, page: number): string {
|
||||
const params = new URLSearchParams();
|
||||
if (filters.query) params.set("q", filters.query);
|
||||
if (filters.status) params.set("status", filters.status);
|
||||
if (filters.kind) params.set("art", filters.kind);
|
||||
if (filters.offerId) params.set("angebot", filters.offerId);
|
||||
if (page > 1) params.set("seite", String(page));
|
||||
const query = params.toString();
|
||||
return query ? `/admin/patenschaften?${query}` : "/admin/patenschaften";
|
||||
}
|
||||
|
||||
/**
|
||||
* Der Bienenname steht nur im JSON der Personalisierung (Revision,
|
||||
* Bestellposition, Abo). JSON-Pfadfilter sind zwischen Postgres und MySQL
|
||||
* nicht gleich formuliert und im generierten Client verschieden typisiert —
|
||||
* deshalb wird hier im Speicher gesucht. Bei der Groesse einer Imkerei ist
|
||||
* das billig; die Obergrenze verhindert, dass es je unbemerkt teuer wird.
|
||||
* Gefunden werden auch fruehere Namen (vor einer Korrektur).
|
||||
*/
|
||||
async function sponsorshipIdsByBeeName(query: string): Promise<string[]> {
|
||||
const needle = query.toLocaleLowerCase("de");
|
||||
const matches = (value: unknown) => beeNameFromJson(value)?.toLocaleLowerCase("de").includes(needle) ?? false;
|
||||
const notIssued = { sponsorship: { is: { currentRevision: 0 } } };
|
||||
const [revisions, orderItems, subscriptions] = await Promise.all([
|
||||
prisma.sponsorshipRevision.findMany({
|
||||
select: { sponsorshipId: true, personalization: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: BEE_SEARCH_LIMIT,
|
||||
}),
|
||||
prisma.orderItem.findMany({
|
||||
where: notIssued,
|
||||
select: { personalization: true, sponsorship: { select: { id: true } } },
|
||||
take: BEE_SEARCH_LIMIT,
|
||||
}),
|
||||
prisma.sponsorshipSubscription.findMany({
|
||||
where: notIssued,
|
||||
select: { personalization: true, sponsorship: { select: { id: true } } },
|
||||
take: BEE_SEARCH_LIMIT,
|
||||
}),
|
||||
]);
|
||||
const ids = new Set<string>();
|
||||
for (const row of revisions) if (matches(row.personalization)) ids.add(row.sponsorshipId);
|
||||
for (const row of [...orderItems, ...subscriptions]) {
|
||||
if (row.sponsorship && matches(row.personalization)) ids.add(row.sponsorship.id);
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
export async function buildSponsorshipWhere(filters: SponsorshipListFilters): Promise<Prisma.SponsorshipWhereInput> {
|
||||
const and: Prisma.SponsorshipWhereInput[] = [];
|
||||
if (filters.status === "ZU_DRUCKEN") and.push(TO_PRINT_FILTER);
|
||||
else if (filters.status) and.push({ status: filters.status });
|
||||
if (filters.kind) and.push({ offer: { kind: filters.kind } });
|
||||
if (filters.offerId) and.push({ offerId: filters.offerId });
|
||||
if (filters.query) {
|
||||
const beeIds = await sponsorshipIdsByBeeName(filters.query);
|
||||
and.push({
|
||||
OR: [
|
||||
{ number: insensitiveContains(filters.query) },
|
||||
{ owner: { email: insensitiveContains(filters.query) } },
|
||||
...(beeIds.length > 0 ? [{ id: { in: beeIds } }] : []),
|
||||
],
|
||||
});
|
||||
}
|
||||
return and.length > 0 ? { AND: and } : {};
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/lib/prisma", () => ({ prisma: {} }));
|
||||
|
||||
import { nextDeliveryView } from "./subscription-view";
|
||||
import { countUndercovered, deliveriesCovered } from "./coverage";
|
||||
|
||||
describe("nextDeliveryView", () => {
|
||||
it("vierteljaehrlich: zaehlt die fehlenden bezahlten Monate", () => {
|
||||
expect(nextDeliveryView({ cycle: "VIERTELJAEHRLICH", countingPaidMonths: 0, nextWindowStart: null })).toEqual({
|
||||
kind: "quarterly",
|
||||
remaining: 3,
|
||||
});
|
||||
expect(nextDeliveryView({ cycle: "VIERTELJAEHRLICH", countingPaidMonths: 2, nextWindowStart: null })).toEqual({
|
||||
kind: "quarterly",
|
||||
remaining: 1,
|
||||
});
|
||||
expect(nextDeliveryView({ cycle: "VIERTELJAEHRLICH", countingPaidMonths: 5, nextWindowStart: null })).toEqual({
|
||||
kind: "quarterly",
|
||||
remaining: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("Ernte: naechstes Fenster und Fortschritt bis sechs Monate", () => {
|
||||
const start = new Date("2027-07-01T00:00:00Z");
|
||||
expect(nextDeliveryView({ cycle: "ERNTE", countingPaidMonths: 8, nextWindowStart: start })).toEqual({
|
||||
kind: "harvest",
|
||||
windowStart: start,
|
||||
paid: 6,
|
||||
needed: 6,
|
||||
});
|
||||
});
|
||||
|
||||
it("ohne Zyklus keine Angabe", () => {
|
||||
expect(nextDeliveryView({ cycle: null, countingPaidMonths: 4, nextWindowStart: null })).toEqual({ kind: "none" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Honigdeckung", () => {
|
||||
it("rechnet ganze Lieferrunden und ignoriert fehlenden Bedarf", () => {
|
||||
expect(deliveriesCovered(10, 4)).toBe(2);
|
||||
expect(deliveriesCovered(3, 4)).toBe(0);
|
||||
expect(deliveriesCovered(-2, 4)).toBe(0);
|
||||
expect(deliveriesCovered(10, 0)).toBeNull();
|
||||
});
|
||||
|
||||
it("meldet hoechstens einen Eintrag: wenn der passende Honig zusammen keine Lieferrunde mehr deckt", () => {
|
||||
expect(countUndercovered({ deliveriesCovered: 0 })).toBe(1);
|
||||
expect(countUndercovered({ deliveriesCovered: 1 })).toBe(0);
|
||||
expect(countUndercovered({ deliveriesCovered: null })).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { SponsorshipCycle } from "@/generated/prisma/client";
|
||||
|
||||
/**
|
||||
* Anzeige "naechste Lieferung" in der Abo-Liste. Nur eine Lesehilfe fuer den
|
||||
* Admin — verbindlich entscheidet der taegliche Lieferlauf
|
||||
* (lib/sponsorship-subscription). Die Regeln stammen aus der Spec ("Schutz
|
||||
* vor Verlust: Lieferung erst nach Bezahlung").
|
||||
*/
|
||||
|
||||
/** Vierteljaehrlich: Anspruch nach jeweils drei bezahlten Monaten. */
|
||||
export const QUARTERLY_PAID_MONTHS = 3;
|
||||
/** Ernte: frueheste Lieferung nach sechs bezahlten Monaten seit der letzten. */
|
||||
export const HARVEST_PAID_MONTHS = 6;
|
||||
|
||||
export type NextDeliveryView =
|
||||
| { kind: "quarterly"; remaining: number }
|
||||
| { kind: "harvest"; windowStart: Date | null; paid: number; needed: number }
|
||||
| { kind: "none" };
|
||||
|
||||
/**
|
||||
* @param countingPaidMonths bezahlte, nicht zurueckgebuchte Monate, die schon
|
||||
* fuer eine Lieferung zaehlen (SEPA-Frist abgelaufen) und noch keiner
|
||||
* Lieferung zugeordnet sind.
|
||||
*/
|
||||
export function nextDeliveryView(input: {
|
||||
cycle: SponsorshipCycle | null;
|
||||
countingPaidMonths: number;
|
||||
nextWindowStart: Date | null;
|
||||
}): NextDeliveryView {
|
||||
const paid = Math.max(0, input.countingPaidMonths);
|
||||
if (input.cycle === "VIERTELJAEHRLICH") {
|
||||
return { kind: "quarterly", remaining: Math.max(0, QUARTERLY_PAID_MONTHS - paid) };
|
||||
}
|
||||
if (input.cycle === "ERNTE") {
|
||||
return { kind: "harvest", windowStart: input.nextWindowStart, paid: Math.min(paid, HARVEST_PAID_MONTHS), needed: HARVEST_PAID_MONTHS };
|
||||
}
|
||||
return { kind: "none" };
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import Link from "next/link";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { BackLink } from "@/components/back-link";
|
||||
import { AdminBadge, AdminEmptyState, AdminPageHeader } from "@/components/admin-list";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import type { SubscriptionStatus } from "@/generated/prisma/client";
|
||||
import type { Locale } from "@/i18n/config";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getSponsorshipAdminStrings, type SponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { SponsorshipTabs } from "../_components/sponsorship-tabs";
|
||||
import { SubscriptionStatusBadge } from "../_components/status-badge";
|
||||
import { CoveragePanel, SepaSettingsPanel, SepaBlockButton } from "../_components/subscription-panels";
|
||||
import { getHoneyCoverage } from "../_lib/coverage";
|
||||
import { nextDeliveryView, type NextDeliveryView } from "../_lib/subscription-view";
|
||||
import { getSepaHoldDays } from "@/lib/sponsorship/settings";
|
||||
|
||||
const SUBSCRIPTION_STATUSES = ["AUSSTEHEND", "AKTIV", "IM_VERZUG", "GEKUENDIGT", "BEENDET"] as const satisfies readonly SubscriptionStatus[];
|
||||
const LIST_LIMIT = 200;
|
||||
|
||||
function describeNextDelivery(view: NextDeliveryView, ts: SponsorshipAdminStrings["subscriptions"], locale: Locale): string {
|
||||
if (view.kind === "quarterly") return ts.nextQuarterly(view.remaining);
|
||||
if (view.kind === "harvest") {
|
||||
return view.windowStart ? ts.nextHarvest(formatDate(view.windowStart, locale), view.paid, view.needed) : ts.noHarvestWindow;
|
||||
}
|
||||
return "—";
|
||||
}
|
||||
|
||||
export default async function AdminSponsorshipSubscriptionsPage(props: PageProps<"/admin/patenschaften/abos">) {
|
||||
const locale = await getLocale();
|
||||
const t = getSponsorshipAdminStrings(locale);
|
||||
const ts = t.subscriptions;
|
||||
const { status } = await props.searchParams;
|
||||
const statusFilter = (SUBSCRIPTION_STATUSES as readonly string[]).includes(String(status)) ? (status as SubscriptionStatus) : null;
|
||||
const now = new Date();
|
||||
const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
||||
|
||||
const [subscriptions, windows, coverage, holdDays, blockedCustomers] = await Promise.all([
|
||||
prisma.sponsorshipSubscription.findMany({
|
||||
where: statusFilter ? { status: statusFilter } : {},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: LIST_LIMIT,
|
||||
include: {
|
||||
customer: { select: { id: true, email: true, firstName: true, lastName: true, sepaBlockedAt: true } },
|
||||
offer: { select: { id: true, name: true, cycle: true } },
|
||||
sponsorship: { select: { id: true, number: true } },
|
||||
payments: { select: { reversedAt: true, deliveryId: true, countsFrom: true } },
|
||||
deliveries: { orderBy: { dueAt: "desc" }, take: 1, select: { dueAt: true } },
|
||||
},
|
||||
}),
|
||||
prisma.harvestWindow.findMany({ where: { endsOn: { gte: today } }, orderBy: { startsOn: "asc" }, select: { offerId: true, startsOn: true } }),
|
||||
getHoneyCoverage(now),
|
||||
getSepaHoldDays(),
|
||||
prisma.customer.findMany({
|
||||
where: { sepaBlockedAt: { not: null } },
|
||||
orderBy: { sepaBlockedAt: "desc" },
|
||||
select: { id: true, email: true, firstName: true, lastName: true, sepaBlockedAt: true },
|
||||
}),
|
||||
]);
|
||||
const nextWindowByOffer = new Map<string, Date>();
|
||||
for (const window of windows) if (!nextWindowByOffer.has(window.offerId)) nextWindowByOffer.set(window.offerId, window.startsOn);
|
||||
|
||||
const selectClass = "border border-ink/20 bg-background px-3 py-2 text-sm";
|
||||
|
||||
return (
|
||||
<div>
|
||||
<BackLink href="/admin" label={t.common.backToDashboard} />
|
||||
<AdminPageHeader title={ts.title} intro={ts.intro} />
|
||||
<SponsorshipTabs active="subscriptions" labels={t.tabs} />
|
||||
|
||||
<form method="GET" className="mb-6 flex flex-wrap items-end gap-3">
|
||||
<label className="text-sm">
|
||||
<span className="mb-1 block text-xs text-ink/65">{ts.statusLabel}</span>
|
||||
<select name="status" defaultValue={statusFilter ?? ""} className={selectClass}>
|
||||
<option value="">{ts.statusAll}</option>
|
||||
{SUBSCRIPTION_STATUSES.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{t.subscriptionStatuses[value]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button type="submit" className="border border-heading px-4 py-2 text-sm text-heading transition-colors hover:bg-forest hover:text-cream">
|
||||
{t.common.filter}
|
||||
</button>
|
||||
{statusFilter ? (
|
||||
<Link href="/admin/patenschaften/abos" className="link-draw py-2 text-sm text-ink/65">
|
||||
{t.common.resetFilter}
|
||||
</Link>
|
||||
) : null}
|
||||
</form>
|
||||
|
||||
<div className="overflow-x-auto border border-ink/10 bg-background">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b border-ink/10 text-left text-ink/65">
|
||||
<tr>
|
||||
<th className="p-4">{ts.colSubscription}</th>
|
||||
<th className="p-4">{ts.colCustomer}</th>
|
||||
<th className="p-4">{ts.colOffer}</th>
|
||||
<th className="p-4">{ts.colStatus}</th>
|
||||
<th className="p-4 text-right">{ts.colPaid}</th>
|
||||
<th className="p-4">{ts.colNextDelivery}</th>
|
||||
<th className="p-4">{ts.colDelinquency}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-ink/10">
|
||||
{subscriptions.map((subscription) => {
|
||||
const paid = subscription.payments.filter((payment) => !payment.reversedAt);
|
||||
const counting = paid.filter((payment) => !payment.deliveryId && payment.countsFrom <= now).length;
|
||||
const next = nextDeliveryView({
|
||||
cycle: subscription.offer.cycle,
|
||||
countingPaidMonths: counting,
|
||||
nextWindowStart: nextWindowByOffer.get(subscription.offer.id) ?? null,
|
||||
});
|
||||
const lastDelivery = subscription.deliveries[0]?.dueAt;
|
||||
return (
|
||||
<tr key={subscription.id} className="align-top transition-colors hover:bg-ink/[0.03]">
|
||||
<td className="whitespace-nowrap p-4 font-mono text-xs">
|
||||
{subscription.sponsorship ? (
|
||||
<Link href={`/admin/patenschaften/${subscription.sponsorship.id}`} className="link-draw text-heading">
|
||||
{subscription.sponsorship.number}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-ink/60">{ts.noSponsorship}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="p-4">
|
||||
{subscription.customer.firstName} {subscription.customer.lastName}
|
||||
<br />
|
||||
<span className="text-xs text-ink/65">{subscription.customer.email}</span>
|
||||
{subscription.customer.sepaBlockedAt ? (
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
<AdminBadge tone="danger">{ts.sepaBlocked}</AdminBadge>
|
||||
<SepaBlockButton customerId={subscription.customer.id} confirmMessage={ts.liftSepaConfirm(subscription.customer.email)} label={ts.liftSepa} />
|
||||
</div>
|
||||
) : null}
|
||||
</td>
|
||||
<td className="p-4">
|
||||
{subscription.offer.name}
|
||||
{subscription.offer.cycle ? <span className="block text-xs text-ink/65">{t.cycles[subscription.offer.cycle]}</span> : null}
|
||||
</td>
|
||||
<td className="p-4">
|
||||
<SubscriptionStatusBadge status={subscription.status} label={t.subscriptionStatuses[subscription.status]} />
|
||||
{subscription.cancelAt ? <span className="mt-1 block text-xs text-ink/65">{ts.cancelAt(formatDate(subscription.cancelAt, locale))}</span> : null}
|
||||
</td>
|
||||
<td className="p-4 text-right tabular-nums">{paid.length}</td>
|
||||
<td className="p-4">
|
||||
{subscription.status === "BEENDET" ? "—" : describeNextDelivery(next, ts, locale)}
|
||||
{lastDelivery ? <span className="mt-1 block text-xs text-ink/65">{ts.lastDelivery(formatDate(lastDelivery, locale))}</span> : null}
|
||||
</td>
|
||||
<td className="whitespace-nowrap p-4 text-xs">
|
||||
{subscription.delinquentSince ? (
|
||||
<span className="text-red-700">{t.common.since(formatDate(subscription.delinquentSince, locale))}</span>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
{subscriptions.length === 0 ? <AdminEmptyState message={statusFilter ? ts.emptyFiltered : ts.empty} /> : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-10 grid gap-6 lg:grid-cols-5">
|
||||
<div className="lg:col-span-3">
|
||||
<CoveragePanel coverage={coverage} t={ts} />
|
||||
</div>
|
||||
<div className="flex flex-col gap-6 lg:col-span-2">
|
||||
<SepaSettingsPanel holdDays={holdDays} t={ts} />
|
||||
<section className="border border-ink/10 bg-background p-6">
|
||||
<h2 className="mb-2 font-serif text-xl text-heading">{ts.blockedHeading}</h2>
|
||||
<p className="mb-4 text-xs text-ink/65">{ts.blockedIntro}</p>
|
||||
{blockedCustomers.length === 0 ? (
|
||||
<p className="text-sm text-ink/65">{ts.noBlocked}</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-ink/10">
|
||||
{blockedCustomers.map((customer) => (
|
||||
<li key={customer.id} className="flex flex-wrap items-center justify-between gap-3 py-3 text-sm">
|
||||
<span>
|
||||
{customer.firstName} {customer.lastName}
|
||||
<span className="block text-xs text-ink/65">{customer.email}</span>
|
||||
{customer.sepaBlockedAt ? (
|
||||
<span className="block text-xs text-ink/65">{ts.blockedSince(formatDate(customer.sepaBlockedAt, locale))}</span>
|
||||
) : null}
|
||||
</span>
|
||||
<SepaBlockButton customerId={customer.id} confirmMessage={ts.liftSepaConfirm(customer.email)} label={ts.liftSepa} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { BackLink } from "@/components/back-link";
|
||||
import { ConfirmForm } from "@/components/confirm-form";
|
||||
import { AdminActionButton, AdminEmptyState } from "@/components/admin-list";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getSponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { createHarvestWindowAction, deleteHarvestWindowAction, updateHarvestWindowAction } from "@/app/admin/actions";
|
||||
|
||||
const inputClass = "mt-1 w-full border border-ink/20 bg-background px-3 py-2 text-sm";
|
||||
|
||||
function isoDate(date: Date): string {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function WindowFields({ startsOn, endsOn, plannedJars, labels }: {
|
||||
startsOn: string;
|
||||
endsOn: string;
|
||||
plannedJars: number;
|
||||
labels: { startsOn: string; endsOn: string; plannedJars: string };
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<label className="block text-sm">
|
||||
<span className="text-xs text-ink/65">{labels.startsOn}</span>
|
||||
<input type="date" name="startsOn" defaultValue={startsOn} required className={inputClass} />
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
<span className="text-xs text-ink/65">{labels.endsOn}</span>
|
||||
<input type="date" name="endsOn" defaultValue={endsOn} required className={inputClass} />
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
<span className="text-xs text-ink/65">{labels.plannedJars}</span>
|
||||
<input type="number" name="plannedJars" min={0} defaultValue={String(plannedJars)} className={inputClass} />
|
||||
</label>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function AdminHarvestWindowsPage(props: PageProps<"/admin/patenschaften/angebote/[id]/erntefenster">) {
|
||||
const t = getSponsorshipAdminStrings(await getLocale());
|
||||
const th = t.harvest;
|
||||
const { id } = await props.params;
|
||||
const offer = await prisma.sponsorshipOffer.findUnique({
|
||||
where: { id },
|
||||
select: { id: true, name: true, kind: true, cycle: true, harvestWindows: { orderBy: { startsOn: "asc" } } },
|
||||
});
|
||||
if (!offer) notFound();
|
||||
const back = <BackLink href={`/admin/patenschaften/angebote/${offer.id}`} label={th.backToOffer} />;
|
||||
|
||||
if (offer.kind !== "ABO" || offer.cycle !== "ERNTE") {
|
||||
return (
|
||||
<div className="max-w-3xl">
|
||||
{back}
|
||||
<h1 className="mb-4 text-2xl text-heading">{th.title(offer.name)}</h1>
|
||||
<AdminEmptyState message={th.notHarvest} bordered />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const today = isoDate(new Date());
|
||||
return (
|
||||
<div className="max-w-3xl">
|
||||
{back}
|
||||
<h1 className="mb-2 text-2xl text-heading">{th.title(offer.name)}</h1>
|
||||
<p className="mb-8 max-w-2xl text-sm text-ink/70">{th.intro}</p>
|
||||
|
||||
<div className="mb-10 space-y-3">
|
||||
{offer.harvestWindows.length === 0 ? <AdminEmptyState message={th.empty} bordered /> : null}
|
||||
{offer.harvestWindows.map((window) => {
|
||||
const isPast = isoDate(window.endsOn) < today;
|
||||
return (
|
||||
<div key={window.id} className={`flex flex-wrap items-end gap-4 border border-ink/10 bg-background p-4 ${isPast ? "opacity-70" : ""}`}>
|
||||
<form action={updateHarvestWindowAction} className="grid flex-1 grid-cols-1 items-end gap-3 sm:grid-cols-[1fr_1fr_1fr_auto]">
|
||||
<input type="hidden" name="id" value={window.id} />
|
||||
<WindowFields startsOn={isoDate(window.startsOn)} endsOn={isoDate(window.endsOn)} plannedJars={window.plannedJars} labels={th} />
|
||||
<button type="submit" className="border border-heading px-4 py-2 text-sm text-heading transition-colors hover:bg-forest hover:text-cream">
|
||||
{t.common.save}
|
||||
</button>
|
||||
</form>
|
||||
<div className="flex items-center gap-3 pb-2">
|
||||
{isPast ? <span className="text-xs text-ink/60">{th.past}</span> : null}
|
||||
<ConfirmForm action={deleteHarvestWindowAction} confirmMessage={th.deleteConfirm}>
|
||||
<input type="hidden" name="id" value={window.id} />
|
||||
<AdminActionButton tone="danger">{t.common.delete}</AdminActionButton>
|
||||
</ConfirmForm>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<section className="border border-ink/10 bg-background p-6">
|
||||
<h2 className="mb-4 font-serif text-xl text-heading">{th.newHeading}</h2>
|
||||
<form action={createHarvestWindowAction} className="grid grid-cols-1 items-end gap-3 sm:grid-cols-[1fr_1fr_1fr_auto]">
|
||||
<input type="hidden" name="offerId" value={offer.id} />
|
||||
<WindowFields startsOn="" endsOn="" plannedJars={0} labels={th} />
|
||||
<button type="submit" className="border border-heading bg-forest px-4 py-2 text-sm text-cream transition-colors hover:bg-honey-deep">
|
||||
{th.add}
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { BackLink } from "@/components/back-link";
|
||||
import { AdminBadge } from "@/components/admin-list";
|
||||
import { asStringArray } from "@/lib/json-array";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getSponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { updateSponsorshipOfferAction } from "@/app/admin/actions";
|
||||
import { OfferForm } from "../../_components/offer-form";
|
||||
import { getOfferOverview } from "../../_lib/offer-overview";
|
||||
|
||||
export default async function AdminSponsorshipOfferEditPage(props: PageProps<"/admin/patenschaften/angebote/[id]">) {
|
||||
const t = getSponsorshipAdminStrings(await getLocale());
|
||||
const tf = t.offerForm;
|
||||
const { id } = await props.params;
|
||||
const {
|
||||
rows: [row],
|
||||
} = await getOfferOverview(id);
|
||||
if (!row) notFound();
|
||||
const { offer, isAvailable, currentHoney, activeSubscriptions } = row;
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl">
|
||||
<BackLink href="/admin/patenschaften/angebote" label={tf.backToOffers} />
|
||||
<h1 className="mb-6 text-2xl text-heading">{tf.editTitle(offer.name)}</h1>
|
||||
|
||||
{/* Live-Verfuegbarkeit: dieselbe Entscheidung wie auf der Verkaufsseite. */}
|
||||
<section className="mb-8 border border-ink/10 bg-background p-6">
|
||||
<h2 className="mb-3 text-xs tracking-wide-caps text-ink/65">{tf.availabilityHeading}</h2>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<AdminBadge tone={isAvailable ? "positive" : "pending"}>{isAvailable ? t.offers.available : t.offers.unavailable}</AdminBadge>
|
||||
<span className="text-sm text-ink/75">{isAvailable ? tf.availableNow : tf.unavailableNow}</span>
|
||||
</div>
|
||||
{currentHoney ? (
|
||||
<p className="mt-3 text-sm tabular-nums text-ink/75">
|
||||
{tf.stockLine(currentHoney.label, currentHoney.stock, currentHoney.reserved, currentHoney.free)}
|
||||
</p>
|
||||
) : offer.honeyJars > 0 ? (
|
||||
<p className="mt-3 text-sm text-ink/75">{tf.noEligibleHoney}</p>
|
||||
) : null}
|
||||
{offer.kind === "ABO" ? (
|
||||
<p className="mt-1 text-sm tabular-nums text-ink/75">{tf.activeSubscriptions(activeSubscriptions, offer.maxActiveSubscriptions)}</p>
|
||||
) : null}
|
||||
{offer.kind === "ABO" && offer.cycle === "ERNTE" ? (
|
||||
<Link href={`/admin/patenschaften/angebote/${offer.id}/erntefenster`} className="link-draw mt-3 inline-block text-sm text-heading">
|
||||
{t.offers.harvestWindows} →
|
||||
</Link>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<OfferForm
|
||||
isNew={false}
|
||||
currentHoneyLabel={currentHoney?.label ?? null}
|
||||
action={updateSponsorshipOfferAction}
|
||||
t={t}
|
||||
defaults={{
|
||||
id: offer.id,
|
||||
kind: offer.kind,
|
||||
name: offer.name,
|
||||
nameEn: offer.nameEn ?? "",
|
||||
slug: offer.slug,
|
||||
description: offer.description,
|
||||
descriptionEn: offer.descriptionEn ?? "",
|
||||
features: asStringArray(offer.features),
|
||||
featuresEn: asStringArray(offer.featuresEn),
|
||||
priceCents: offer.priceCents,
|
||||
honeyShareCentsPerJar: offer.honeyShareCentsPerJar,
|
||||
honeyShareCentsPerMonth: offer.honeyShareCentsPerMonth,
|
||||
isActive: offer.isActive,
|
||||
isPhysical: offer.isPhysical,
|
||||
sortOrder: offer.sortOrder,
|
||||
honeyJars: offer.honeyJars,
|
||||
cycle: offer.cycle,
|
||||
maxActiveSubscriptions: offer.maxActiveSubscriptions,
|
||||
medalTier: offer.medalTier,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { BackLink } from "@/components/back-link";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getSponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { createSponsorshipOfferAction } from "@/app/admin/actions";
|
||||
import { EMPTY_OFFER, OfferForm } from "../../_components/offer-form";
|
||||
import { currentHoneyFor } from "../../_lib/offer-overview";
|
||||
import { getEligibleHoneyStock } from "../../_lib/coverage";
|
||||
|
||||
export default async function AdminSponsorshipOfferNewPage() {
|
||||
const t = getSponsorshipAdminStrings(await getLocale());
|
||||
// Vorschau der automatischen Wahl fuer ein Glas — die echte Wahl richtet
|
||||
// sich nach den Glaesern des Angebots und faellt bei jeder Bestellung neu.
|
||||
const currentHoney = currentHoneyFor(await getEligibleHoneyStock(), 1);
|
||||
return (
|
||||
<div className="max-w-3xl">
|
||||
<BackLink href="/admin/patenschaften/angebote" label={t.offerForm.backToOffers} />
|
||||
<h1 className="mb-8 text-2xl text-heading">{t.offerForm.newTitle}</h1>
|
||||
<OfferForm defaults={EMPTY_OFFER} isNew currentHoneyLabel={currentHoney?.label ?? null} action={createSponsorshipOfferAction} t={t} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { BackLink } from "@/components/back-link";
|
||||
import {
|
||||
AdminActionLink,
|
||||
AdminBadge,
|
||||
AdminEmptyState,
|
||||
AdminPageHeader,
|
||||
AdminRowActions,
|
||||
} from "@/components/admin-list";
|
||||
import { formatPrice } from "@/lib/format";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getSponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { SponsorshipTabs } from "../_components/sponsorship-tabs";
|
||||
import { getOfferOverview } from "../_lib/offer-overview";
|
||||
|
||||
export default async function AdminSponsorshipOffersPage() {
|
||||
const t = getSponsorshipAdminStrings(await getLocale());
|
||||
const to = t.offers;
|
||||
// Honig waehlt das System automatisch (nie cremig, neueste Ernte); gezeigt
|
||||
// wird hier der passende Honig in der Rangfolge der Wahl.
|
||||
const { rows, eligibleHoney } = await getOfferOverview();
|
||||
// "Erste Wahl" = der Honig, den ein Paket mit einem Glas gerade bekaeme.
|
||||
const firstChoiceId = eligibleHoney.find((row) => row.free > 0)?.productId;
|
||||
const newOffer = { href: "/admin/patenschaften/angebote/neu", label: to.newOffer };
|
||||
|
||||
return (
|
||||
<div>
|
||||
<BackLink href="/admin" label={t.common.backToDashboard} />
|
||||
<AdminPageHeader title={to.title} intro={to.intro} action={newOffer} />
|
||||
<SponsorshipTabs active="offers" labels={t.tabs} />
|
||||
|
||||
<div className="overflow-x-auto border border-ink/10 bg-background">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b border-ink/10 text-left text-ink/65">
|
||||
<tr>
|
||||
<th className="p-4">{to.colName}</th>
|
||||
<th className="p-4">{to.colKind}</th>
|
||||
<th className="p-4">{to.colPrice}</th>
|
||||
<th className="p-4">{to.colHoney}</th>
|
||||
<th className="p-4">{to.colMedal}</th>
|
||||
<th className="p-4">{to.colStatus}</th>
|
||||
<th className="p-4">{to.colAvailability}</th>
|
||||
<th className="p-4" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-ink/10">
|
||||
{rows.map(({ offer, isAvailable, currentHoney }) => (
|
||||
<tr key={offer.id} className="transition-colors hover:bg-ink/[0.03]">
|
||||
<td className="p-4">
|
||||
<span className="text-heading">{offer.name}</span>
|
||||
<br />
|
||||
<span className="font-mono text-xs text-ink/60">{offer.slug}</span>
|
||||
</td>
|
||||
<td className="p-4">
|
||||
{t.kinds[offer.kind]}
|
||||
{offer.cycle ? <span className="block text-xs text-ink/65">{t.cycles[offer.cycle]}</span> : null}
|
||||
</td>
|
||||
<td className="whitespace-nowrap p-4 tabular-nums">
|
||||
{formatPrice(offer.priceCents)}
|
||||
{offer.kind === "ABO" ? <span className="text-ink/65"> {to.perMonth}</span> : null}
|
||||
</td>
|
||||
<td className="p-4">
|
||||
{offer.honeyJars > 0 ? (
|
||||
to.honeyAuto(offer.honeyJars, currentHoney?.label ?? null)
|
||||
) : (
|
||||
<span className="text-ink/60">{to.noHoney}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="p-4">{t.medals[offer.medalTier]}</td>
|
||||
<td className="p-4">
|
||||
<AdminBadge tone={offer.isActive ? "positive" : "neutral"}>{offer.isActive ? to.active : to.inactive}</AdminBadge>
|
||||
</td>
|
||||
<td className="p-4">
|
||||
<AdminBadge tone={isAvailable ? "positive" : "pending"}>{isAvailable ? to.available : to.unavailable}</AdminBadge>
|
||||
</td>
|
||||
<td className="p-4">
|
||||
<AdminRowActions>
|
||||
{offer.kind === "ABO" && offer.cycle === "ERNTE" ? (
|
||||
<AdminActionLink href={`/admin/patenschaften/angebote/${offer.id}/erntefenster`}>{to.harvestWindows}</AdminActionLink>
|
||||
) : null}
|
||||
<AdminActionLink href={`/admin/patenschaften/angebote/${offer.id}`}>{to.edit}</AdminActionLink>
|
||||
</AdminRowActions>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{rows.length === 0 ? <AdminEmptyState message={to.empty} action={newOffer} /> : null}
|
||||
</div>
|
||||
|
||||
<section className="mt-10">
|
||||
<h2 className="mb-1 text-lg text-heading">{to.stockHeading}</h2>
|
||||
<p className="mb-3 max-w-prose text-xs text-ink/65">{to.stockIntro}</p>
|
||||
{eligibleHoney.length === 0 ? (
|
||||
<p className="text-sm text-ink/65">{to.noEligibleHoney}</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto border border-ink/10 bg-background">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b border-ink/10 text-left text-ink/65">
|
||||
<tr>
|
||||
<th className="p-4">{to.colProduct}</th>
|
||||
<th className="p-4 text-right">{to.colYear}</th>
|
||||
<th className="p-4">{to.colConsistency}</th>
|
||||
<th className="p-4 text-right">{to.colStock}</th>
|
||||
<th className="p-4 text-right">{to.colReserved}</th>
|
||||
<th className="p-4 text-right">{to.colFree}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-ink/10">
|
||||
{eligibleHoney.map((row) => (
|
||||
<tr key={row.productId}>
|
||||
<td className="p-4">
|
||||
{row.productName}
|
||||
{row.productId === firstChoiceId ? (
|
||||
<span className="ml-2">
|
||||
<AdminBadge tone="positive">{to.firstChoice}</AdminBadge>
|
||||
</span>
|
||||
) : null}
|
||||
</td>
|
||||
<td className="p-4 text-right tabular-nums">{row.harvestYear}</td>
|
||||
<td className="p-4">{row.consistency}</td>
|
||||
<td className="p-4 text-right tabular-nums">{row.stock}</td>
|
||||
<td className="p-4 text-right tabular-nums">{row.reserved}</td>
|
||||
<td className="p-4 text-right tabular-nums text-heading">{row.free}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import Link from "next/link";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { BackLink } from "@/components/back-link";
|
||||
import { AdminBadge, AdminEmptyState, AdminPageHeader, AdminSearchForm } from "@/components/admin-list";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getSponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { SponsorshipTabs } from "./_components/sponsorship-tabs";
|
||||
import { SponsorshipStatusBadge } from "./_components/status-badge";
|
||||
import { Pagination } from "./_components/pagination";
|
||||
import { beeNameFromJson } from "./_lib/revision-data";
|
||||
import { LIST_STATUSES, PAGE_SIZE, buildSponsorshipWhere, listHref, parseListFilters } from "./_lib/sponsorship-filters";
|
||||
|
||||
const selectClass = "border border-ink/20 bg-background px-3 py-2 text-sm";
|
||||
|
||||
export default async function AdminSponsorshipsPage(props: PageProps<"/admin/patenschaften">) {
|
||||
const locale = await getLocale();
|
||||
const t = getSponsorshipAdminStrings(locale);
|
||||
const filters = parseListFilters(await props.searchParams);
|
||||
const where = await buildSponsorshipWhere(filters);
|
||||
|
||||
const [total, offers] = await Promise.all([
|
||||
prisma.sponsorship.count({ where }),
|
||||
prisma.sponsorshipOffer.findMany({ select: { id: true, name: true }, orderBy: [{ kind: "asc" }, { sortOrder: "asc" }] }),
|
||||
]);
|
||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
const page = Math.min(filters.page, totalPages);
|
||||
const sponsorships = await prisma.sponsorship.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: "desc" },
|
||||
skip: (page - 1) * PAGE_SIZE,
|
||||
take: PAGE_SIZE,
|
||||
include: {
|
||||
owner: { select: { email: true, firstName: true, lastName: true } },
|
||||
offer: { select: { name: true, kind: true, isPhysical: true } },
|
||||
revisions: { orderBy: { revision: "desc" }, take: 1, select: { personalization: true } },
|
||||
orderItem: { select: { personalization: true } },
|
||||
subscription: { select: { personalization: true } },
|
||||
},
|
||||
});
|
||||
const isFiltered = Boolean(filters.query || filters.status || filters.kind || filters.offerId);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<BackLink href="/admin" label={t.common.backToDashboard} />
|
||||
<AdminPageHeader title={t.list.title} intro={t.list.intro} />
|
||||
<SponsorshipTabs active="overview" labels={t.tabs} />
|
||||
|
||||
<AdminSearchForm
|
||||
query={filters.query}
|
||||
label={t.list.searchLabel}
|
||||
placeholder={t.list.searchPlaceholder}
|
||||
submitLabel={t.common.filter}
|
||||
resetHref="/admin/patenschaften"
|
||||
resetLabel={t.common.resetFilter}
|
||||
isFiltered={isFiltered}
|
||||
>
|
||||
<label className="text-sm">
|
||||
<span className="mb-1 block text-xs text-ink/65">{t.list.statusLabel}</span>
|
||||
<select name="status" defaultValue={filters.status ?? ""} className={selectClass}>
|
||||
<option value="">{t.list.statusAll}</option>
|
||||
{LIST_STATUSES.map((status) => (
|
||||
<option key={status} value={status}>
|
||||
{status === "ZU_DRUCKEN" ? t.list.toPrint : t.statuses[status]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="mb-1 block text-xs text-ink/65">{t.list.kindLabel}</span>
|
||||
<select name="art" defaultValue={filters.kind ?? ""} className={selectClass}>
|
||||
<option value="">{t.list.kindAll}</option>
|
||||
<option value="EINMALIG">{t.kinds.EINMALIG}</option>
|
||||
<option value="ABO">{t.kinds.ABO}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="mb-1 block text-xs text-ink/65">{t.list.offerLabel}</span>
|
||||
<select name="angebot" defaultValue={filters.offerId ?? ""} className={selectClass}>
|
||||
<option value="">{t.list.offerAll}</option>
|
||||
{offers.map((offer) => (
|
||||
<option key={offer.id} value={offer.id}>
|
||||
{offer.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</AdminSearchForm>
|
||||
|
||||
<p className="mb-3 text-xs text-ink/60">{t.list.resultCount(total)}</p>
|
||||
<div className="overflow-x-auto border border-ink/10 bg-background">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b border-ink/10 text-left text-ink/65">
|
||||
<tr>
|
||||
<th className="p-4">{t.list.colNumber}</th>
|
||||
<th className="p-4">{t.list.colBee}</th>
|
||||
<th className="p-4">{t.list.colOwner}</th>
|
||||
<th className="p-4">{t.list.colOffer}</th>
|
||||
<th className="p-4">{t.list.colTerm}</th>
|
||||
<th className="p-4">{t.list.colStatus}</th>
|
||||
<th className="p-4">{t.list.colCreated}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-ink/10">
|
||||
{sponsorships.map((sponsorship) => {
|
||||
const beeName =
|
||||
beeNameFromJson(sponsorship.revisions[0]?.personalization) ??
|
||||
beeNameFromJson(sponsorship.orderItem?.personalization ?? sponsorship.subscription?.personalization);
|
||||
const toPrint = sponsorship.offer.isPhysical && sponsorship.status === "BEREIT" && !sponsorship.printedAt;
|
||||
const start = formatDate(sponsorship.startDate, locale);
|
||||
return (
|
||||
<tr key={sponsorship.id} className="transition-colors hover:bg-ink/[0.03]">
|
||||
<td className="whitespace-nowrap p-4 font-mono text-xs text-heading">
|
||||
<Link href={`/admin/patenschaften/${sponsorship.id}`} className="link-draw">
|
||||
{sponsorship.number}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="p-4 font-serif text-base text-heading">{beeName ?? t.common.none}</td>
|
||||
<td className="p-4">
|
||||
{sponsorship.owner.firstName} {sponsorship.owner.lastName}
|
||||
<br />
|
||||
<span className="text-xs text-ink/65">{sponsorship.owner.email}</span>
|
||||
</td>
|
||||
<td className="p-4">
|
||||
{sponsorship.offer.name}
|
||||
<br />
|
||||
<span className="text-xs text-ink/65">{t.kinds[sponsorship.offer.kind]}</span>
|
||||
</td>
|
||||
<td className="whitespace-nowrap p-4 tabular-nums">
|
||||
{sponsorship.endDate ? t.common.range(start, formatDate(sponsorship.endDate, locale)) : t.common.since(start)}
|
||||
</td>
|
||||
<td className="p-4">
|
||||
<div className="flex flex-col items-start gap-1.5">
|
||||
<SponsorshipStatusBadge status={sponsorship.status} label={t.statuses[sponsorship.status]} />
|
||||
{toPrint ? (
|
||||
<AdminBadge tone="pending" pulse>
|
||||
{t.list.toPrintBadge}
|
||||
</AdminBadge>
|
||||
) : null}
|
||||
</div>
|
||||
</td>
|
||||
<td className="whitespace-nowrap p-4 tabular-nums text-ink/70">{formatDate(sponsorship.createdAt, locale)}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
{sponsorships.length === 0 ? <AdminEmptyState message={isFiltered ? t.list.emptyFiltered : t.list.empty} /> : null}
|
||||
</div>
|
||||
<Pagination page={page} totalPages={totalPages} hrefFor={(target) => listHref(filters, target)} labels={t.common} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { BackLink } from "@/components/back-link";
|
||||
import { ConfirmForm } from "@/components/confirm-form";
|
||||
import { AdminActionButton, AdminActionNote, AdminEmptyState, AdminPageHeader } from "@/components/admin-list";
|
||||
import type { LoyaltyKind } from "@/generated/prisma/client";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getSponsorshipAdminStrings, type SponsorshipAdminStrings } from "@/i18n/sponsorship/admin";
|
||||
import { createLoyaltyLevelAction, deleteLoyaltyLevelAction, updateLoyaltyLevelAction } from "@/app/admin/actions";
|
||||
import { SponsorshipTabs } from "../_components/sponsorship-tabs";
|
||||
|
||||
const inputClass = "mt-1 w-full border border-ink/20 bg-background px-3 py-2 text-sm";
|
||||
const saveClass = "border border-heading px-4 py-2 text-sm text-heading transition-colors hover:bg-forest hover:text-cream";
|
||||
|
||||
interface Level {
|
||||
id: string;
|
||||
kind: LoyaltyKind;
|
||||
threshold: number | null;
|
||||
name: string;
|
||||
nameEn: string | null;
|
||||
}
|
||||
|
||||
function LevelRow({ level, t, common }: { level: Level; t: SponsorshipAdminStrings["loyalty"]; common: SponsorshipAdminStrings["common"] }) {
|
||||
const isVip = level.threshold === null;
|
||||
return (
|
||||
<div className="flex flex-wrap items-end gap-4 py-3">
|
||||
<form action={updateLoyaltyLevelAction} className="grid flex-1 grid-cols-1 items-end gap-3 sm:grid-cols-[7rem_1fr_1fr_auto]">
|
||||
<input type="hidden" name="id" value={level.id} />
|
||||
{isVip ? (
|
||||
<div className="text-sm">
|
||||
<span className="text-xs text-ink/65">{t.threshold}</span>
|
||||
<p className="mt-1 py-2 text-xs text-honey-dark">{t.vip}</p>
|
||||
</div>
|
||||
) : (
|
||||
<label className="block text-sm">
|
||||
<span className="text-xs text-ink/65">{t.threshold}</span>
|
||||
<input type="number" name="threshold" min={1} defaultValue={String(level.threshold)} required className={`${inputClass} tabular-nums`} />
|
||||
</label>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
<span className="text-xs text-ink/65">{t.name}</span>
|
||||
<input name="name" defaultValue={level.name} required className={inputClass} />
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
<span className="text-xs text-ink/65">{t.nameEn}</span>
|
||||
<input name="nameEn" defaultValue={level.nameEn ?? ""} className={inputClass} />
|
||||
</label>
|
||||
<button type="submit" className={saveClass}>
|
||||
{common.save}
|
||||
</button>
|
||||
</form>
|
||||
<div className="w-28 pb-2">
|
||||
{isVip ? (
|
||||
<AdminActionNote>{t.vipNotDeletable}</AdminActionNote>
|
||||
) : (
|
||||
<ConfirmForm action={deleteLoyaltyLevelAction} confirmMessage={t.deleteConfirm(level.name)}>
|
||||
<input type="hidden" name="id" value={level.id} />
|
||||
<AdminActionButton tone="danger">{common.delete}</AdminActionButton>
|
||||
</ConfirmForm>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LevelSection({ kind, heading, hint, levels, t, common }: {
|
||||
kind: LoyaltyKind;
|
||||
heading: string;
|
||||
hint: string;
|
||||
levels: Level[];
|
||||
t: SponsorshipAdminStrings["loyalty"];
|
||||
common: SponsorshipAdminStrings["common"];
|
||||
}) {
|
||||
return (
|
||||
<section className="border border-ink/10 bg-background p-6">
|
||||
<h2 className="font-serif text-xl text-heading">{heading}</h2>
|
||||
<p className="mb-4 mt-1 text-xs text-ink/65">{hint}</p>
|
||||
{levels.length === 0 ? <AdminEmptyState message={t.empty} /> : null}
|
||||
<div className="divide-y divide-ink/10">
|
||||
{levels.map((level) => (
|
||||
<LevelRow key={level.id} level={level} t={t} common={common} />
|
||||
))}
|
||||
</div>
|
||||
<form action={createLoyaltyLevelAction} className="mt-6 grid grid-cols-1 items-end gap-3 border-t border-ink/10 pt-6 sm:grid-cols-[7rem_1fr_1fr_auto]">
|
||||
<input type="hidden" name="kind" value={kind} />
|
||||
<label className="block text-sm">
|
||||
<span className="text-xs text-ink/65">{t.threshold}</span>
|
||||
<input type="number" name="threshold" min={1} required className={`${inputClass} tabular-nums`} />
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
<span className="text-xs text-ink/65">{t.name}</span>
|
||||
<input name="name" required className={inputClass} />
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
<span className="text-xs text-ink/65">{t.nameEn}</span>
|
||||
<input name="nameEn" className={inputClass} />
|
||||
</label>
|
||||
<button type="submit" className="border border-heading bg-forest px-4 py-2 text-sm text-cream transition-colors hover:bg-honey-deep">
|
||||
{t.add}
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Schwellen aufsteigend, VIP (ohne Schwelle) immer zuletzt. */
|
||||
function byThreshold(a: Level, b: Level): number {
|
||||
return (a.threshold ?? Number.POSITIVE_INFINITY) - (b.threshold ?? Number.POSITIVE_INFINITY);
|
||||
}
|
||||
|
||||
export default async function AdminLoyaltyLevelsPage() {
|
||||
const t = getSponsorshipAdminStrings(await getLocale());
|
||||
const tl = t.loyalty;
|
||||
const levels = await prisma.loyaltyLevel.findMany({ select: { id: true, kind: true, threshold: true, name: true, nameEn: true } });
|
||||
const regular = levels.filter((level) => level.kind === "STAMMKUNDE").sort(byThreshold);
|
||||
const subscription = levels.filter((level) => level.kind === "ABO").sort(byThreshold);
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl">
|
||||
<BackLink href="/admin" label={t.common.backToDashboard} />
|
||||
<AdminPageHeader title={tl.title} intro={tl.intro} />
|
||||
<SponsorshipTabs active="loyalty" labels={t.tabs} />
|
||||
<div className="space-y-8">
|
||||
<LevelSection kind="STAMMKUNDE" heading={tl.regularHeading} hint={tl.regularHint} levels={regular} t={tl} common={t.common} />
|
||||
<LevelSection kind="ABO" heading={tl.aboHeading} hint={tl.aboHint} levels={subscription} t={tl} common={t.common} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,9 +9,41 @@ import {
|
||||
AdminFieldset,
|
||||
AdminFormPanel,
|
||||
AdminHint,
|
||||
AdminSelect,
|
||||
AdminSwitch,
|
||||
AdminTextarea,
|
||||
} from "@/components/admin-form";
|
||||
import {
|
||||
fetchApiCoreShopData,
|
||||
getApiCoreConnection,
|
||||
isManufactured,
|
||||
type ApiCoreProduct,
|
||||
} from "@/lib/apicore-client";
|
||||
|
||||
/**
|
||||
* ApiCore-Artikel, mit denen sich dieses Produkt verknuepfen laesst: nur
|
||||
* hergestellte Waren (Honig haengt an der Abfuellung) und nur solche, die
|
||||
* kein anderes Produkt schon belegt. Ist ApiCore nicht erreichbar, bleibt
|
||||
* die Verknuepfung, wie sie ist — die Seite selbst funktioniert weiter.
|
||||
*/
|
||||
async function linkableApiCoreArticles(
|
||||
productId: string
|
||||
): Promise<{ articles: ApiCoreProduct[]; error: string | null }> {
|
||||
try {
|
||||
const feed = await fetchApiCoreShopData(getApiCoreConnection());
|
||||
const taken = await prisma.product.findMany({
|
||||
where: { apicoreProductId: { not: null }, NOT: { id: productId } },
|
||||
select: { apicoreProductId: true },
|
||||
});
|
||||
const takenIds = new Set(taken.map((row) => row.apicoreProductId));
|
||||
return {
|
||||
articles: feed.products.filter((article) => isManufactured(article) && !takenIds.has(article.id)),
|
||||
error: null,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { articles: [], error: error instanceof Error ? error.message : "Unbekannter Fehler" };
|
||||
}
|
||||
}
|
||||
import { updateProductAction } from "../../actions";
|
||||
import { getLocale } from "@/i18n/locale";
|
||||
import { getDictionary } from "@/i18n/get-dictionary";
|
||||
@@ -30,6 +62,8 @@ export default async function AdminProductEditPage(props: PageProps<"/admin/prod
|
||||
tasteTags: asStringArray(rawProduct.tasteTags),
|
||||
images: asStringArray(rawProduct.images),
|
||||
};
|
||||
const stockFromApiCore = Boolean(product.apicoreBottlingId || product.apicoreProductId);
|
||||
const linkable = product.apicoreBottlingId ? null : await linkableApiCoreArticles(product.id);
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl">
|
||||
@@ -93,8 +127,37 @@ export default async function AdminProductEditPage(props: PageProps<"/admin/prod
|
||||
type="number"
|
||||
defaultValue={String(product.inventory?.quantity ?? 0)}
|
||||
required
|
||||
readOnly={stockFromApiCore}
|
||||
hint={stockFromApiCore ? te.stockFromApiCoreHint : undefined}
|
||||
/>
|
||||
</div>
|
||||
{product.apicoreBottlingId ? (
|
||||
<AdminHint>{te.apicoreHoneyLinked(product.apicoreBottlingId)}</AdminHint>
|
||||
) : linkable?.error ? (
|
||||
<>
|
||||
<input type="hidden" name="apicoreProductId" value={product.apicoreProductId ?? ""} />
|
||||
<AdminHint>{te.apicoreUnavailable(linkable.error)}</AdminHint>
|
||||
</>
|
||||
) : (
|
||||
<AdminSelect
|
||||
name="apicoreProductId"
|
||||
label={te.apicoreLinkLabel}
|
||||
defaultValue={product.apicoreProductId ?? ""}
|
||||
hint={te.apicoreLinkHint}
|
||||
>
|
||||
<option value="">{te.apicoreNotLinked}</option>
|
||||
{(linkable?.articles ?? []).map((article) => (
|
||||
<option key={article.id} value={article.id}>
|
||||
{article.name}
|
||||
{article.sku ? ` (${article.sku})` : ""}
|
||||
</option>
|
||||
))}
|
||||
{product.apicoreProductId &&
|
||||
!(linkable?.articles ?? []).some((article) => article.id === product.apicoreProductId) ? (
|
||||
<option value={product.apicoreProductId}>{product.apicoreProductId}</option>
|
||||
) : null}
|
||||
</AdminSelect>
|
||||
)}
|
||||
<div className="grid grid-cols-2 items-end gap-4">
|
||||
<AdminField
|
||||
name="priceCents"
|
||||
|
||||
Loaded 100 of 397 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user