Admin komplett, Rollen und Rechte, Zahlungsarten, Docker-Setup

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SvuGvHpbAQ4syfuLuRvutL
This commit is contained in:
Claude 2026-10-19 13:24:29 +00:00
parent 6c784e8a30
commit f377a14f79
No known key found for this signature in database
47 changed files with 2133 additions and 11 deletions

5
.dockerignore Normal file
View file

@ -0,0 +1,5 @@
node_modules
.next
.env
uploads
.git

31
Dockerfile Normal file
View file

@ -0,0 +1,31 @@
# Sanamare Shop – Produktions-Image
FROM node:22-alpine AS deps
WORKDIR /app
RUN apk add --no-cache openssl
COPY package.json package-lock.json ./
COPY prisma ./prisma
RUN npm ci
FROM node:22-alpine AS build
WORKDIR /app
RUN apk add --no-cache openssl
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npx prisma generate && npm run build
FROM node:22-alpine AS run
WORKDIR /app
RUN apk add --no-cache openssl && addgroup -S app && adduser -S app -G app
ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0 UPLOAD_DIR=/app/uploads
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
COPY --from=build /app/prisma ./prisma
COPY --from=build /app/src/lib/permissions.ts ./src/lib/permissions.ts
COPY --from=build /app/src/lib/payments/catalog.ts ./src/lib/payments/catalog.ts
COPY --from=deps /app/node_modules ./node_modules
COPY docker/entrypoint.sh /entrypoint.sh
RUN mkdir -p /app/uploads && chown -R app:app /app/uploads && chmod +x /entrypoint.sh
USER app
EXPOSE 3000
ENTRYPOINT ["/entrypoint.sh"]

46
README.md Normal file
View file

@ -0,0 +1,46 @@
# Sanamare – Online-Shop
Pilates-Shop mit Admin-Dashboard, frei konfigurierbaren Rollen und Rechten und im Admin einstellbaren Zahlungsarten. Gestaltung nach dem Design System „Sanamare“ (`design/`).
**Technik:** Next.js 15 (App Router, Server Actions) · TypeScript · PostgreSQL mit Prisma · reines CSS auf den Design-Tokens · Docker.
## Was drin ist
**Shop:** Startseite (alle Texte im Admin änderbar), Produktliste mit Kategorien und Sortierung, Suche, Produktseite mit Galerie und Varianten, Warenkorb mit Gutscheinen, Kasse in vier Schritten (Adresse → Versand → Zahlung → Prüfen) mit Gastbestellung, Kundenkonto mit Bestellübersicht, frei anlegbare Textseiten (Impressum, AGB …), Newsletter-Anmeldung, Wartungsmodus.
**Admin (`/admin`):** Übersicht mit Umsatz, Diagramm, Einrichtungs-Checkliste und niedrigem Bestand · Bestellungen (Filter, Status, Sendungsnummer, Verlauf, Storno/Erstattung mit Bestandsrückbuchung) · Produkte (Bilder-Upload, Varianten, Streichpreis, MwSt.) · Kategorien · Kunden · Gutscheine · Newsletter-Export · Startseite & Texte · Seiten · Allgemein & Kasse · Versandarten · Zahlungsarten · Team · Rollen & Rechte · Protokoll.
**Rollen & Rechte:** 20 Einzelrechte (`src/lib/permissions.ts`), beliebig zu Rollen kombinierbar. Die Rolle „Inhaber“ hat immer alles und kann nicht gelöscht werden; es bleibt immer mindestens ein aktiver Inhaber. Niemand kann Rechte vergeben, die er selbst nicht hat.
**Zahlungsarten:** Kreditkarte/Apple Pay/Google Pay, Klarna und SEPA-Lastschrift über Stripe Checkout · PayPal · Vorkasse · Kauf auf Rechnung · Nachnahme. Jede einzeln ein-/ausschaltbar mit Name, Text, Gebühr, Mindest-/Höchstbetrag und „nur für angemeldete Kunden“. Zugangsdaten für Stripe und PayPal werden im Admin eingetragen und lassen sich dort testen.
## Lokal starten
```bash
cp .env.example .env # DATABASE_URL anpassen
npm install
npx prisma migrate deploy
npm run db:seed # Rollen, Inhaber-Zugang, Beispielkatalog
npm run dev
```
Inhaber-Zugang: `ADMIN_EMAIL` / `ADMIN_PASSWORD` aus der `.env` (Standard ohne Angabe: `admin@sanamare.de` / `sanamare-admin` – sofort ändern).
## Server (Docker)
```bash
cat > .env <<EOT
DB_PASSWORD=ein-langes-zufallspasswort
ADMIN_PASSWORD=ein-sicheres-passwort
APP_URL=https://sanamare.maaxxs-coding.de
EOT
docker compose up -d --build
```
Die App lauscht auf `127.0.0.1:3000`; davor gehört ein Reverse Proxy mit HTTPS (z. B. Caddy: `sanamare.maaxxs-coding.de { reverse_proxy 127.0.0.1:3000 }`). Beim Start laufen Migrationen und Grunddaten automatisch. Hochgeladene Bilder liegen im Volume `uploads`.
Update: `git pull && docker compose up -d --build`
## Design-Tokens
`design/tokens.json` ist die Quelle. Nach Änderungen `npm run tokens` → erzeugt `src/styles/tokens.css`. Komponenten-CSS: `src/styles/bundle.css` (aus dem Design System), Ergänzungen in `shop.css` und `admin.css`.

6
deploy.sh Executable file
View file

@ -0,0 +1,6 @@
#!/bin/sh
# Auf dem Server im Projektordner ausführen: holt den neuesten Stand und startet neu.
set -e
git pull --ff-only
docker compose up -d --build
docker compose ps

35
docker-compose.yml Normal file
View file

@ -0,0 +1,35 @@
# Entwicklungsumgebung: docker compose up -d --build
services:
db:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_DB: sanamare
POSTGRES_USER: sanamare
POSTGRES_PASSWORD: ${DB_PASSWORD:?DB_PASSWORD in .env setzen}
volumes:
- db:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U sanamare"]
interval: 5s
retries: 10
app:
build: .
restart: unless-stopped
depends_on:
db:
condition: service_healthy
environment:
DATABASE_URL: postgresql://sanamare:${DB_PASSWORD}@db:5432/sanamare
APP_URL: ${APP_URL:-https://sanamare.maaxxs-coding.de}
ADMIN_EMAIL: ${ADMIN_EMAIL:-admin@sanamare.de}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?ADMIN_PASSWORD in .env setzen}
volumes:
- uploads:/app/uploads
ports:
- "127.0.0.1:3000:3000"
volumes:
db:
uploads:

7
docker/entrypoint.sh Normal file
View file

@ -0,0 +1,7 @@
#!/bin/sh
set -e
echo "Datenbank-Migrationen …"
npx prisma migrate deploy
echo "Grunddaten …"
npx tsx prisma/seed.ts
exec node server.js

View file

@ -0,0 +1,39 @@
"use server";
import { revalidatePath } from "next/cache";
import { assertPermission, audit } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { parsePrice } from "@/lib/money";
import { COUNTRIES, saveSettings } from "@/lib/settings";
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
export async function saveGeneral(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("settings.edit");
if (!str(fd, "shopName")) return fail("Bitte gib einen Shop-Namen ein.", { shopName: "Pflichtfeld" });
const countries = fd.getAll("countries").map(String).filter((c) => c in COUNTRIES);
if (countries.length === 0) return fail("Bitte wähle mindestens ein Lieferland.");
await saveSettings("general", {
shopName: str(fd, "shopName"),
tagline: str(fd, "tagline"),
email: str(fd, "email"),
phone: str(fd, "phone"),
company: str(fd, "company"),
street: str(fd, "street"),
zipCity: str(fd, "zipCity"),
country: str(fd, "country"),
vatId: str(fd, "vatId"),
orderPrefix: str(fd, "orderPrefix").toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 6) || "SM",
maintenance: fd.get("maintenance") === "on",
});
await saveSettings("checkout", {
guestCheckout: fd.get("guestCheckout") === "on",
requireTerms: fd.get("requireTerms") === "on",
requirePhone: fd.get("requirePhone") === "on",
freeShippingHint: fd.get("freeShippingHint") === "on",
minOrderValue: parsePrice(str(fd, "minOrderValue")) ?? 0,
countries,
});
await audit(user, "Einstellungen geändert");
revalidatePath("/", "layout");
return ok();
}

View file

@ -0,0 +1,58 @@
import { requireAdmin } from "@/lib/auth";
import { centsToInput } from "@/lib/money";
import { COUNTRIES, getSettings } from "@/lib/settings";
import { Field } from "@/components/Field";
import { AdminForm } from "@/components/admin/AdminForm";
import { Card, PageHead, Switch } from "@/components/admin/ui";
import { saveGeneral } from "./actions";
export default async function SettingsPage() {
await requireAdmin("settings.edit");
const s = await getSettings();
const g = s.general;
const c = s.checkout;
return (
<div className="ad-wrap ad-wrap--narrow">
<PageHead title="Allgemein & Kasse" lead="Name, Kontakt und wie die Bestellung abläuft." />
<AdminForm action={saveGeneral}>
<Card title="Shop">
<div className="sm-form-row">
<Field label="Shop-Name" name="shopName" defaultValue={g.shopName} required />
<Field label="Leitsatz" name="tagline" defaultValue={g.tagline} />
</div>
<Switch name="maintenance" label="Wartungsmodus" hint="Besucher sehen eine Hinweisseite. Das Team sieht den Shop weiterhin." defaultChecked={g.maintenance} />
</Card>
<Card title="Kontakt & Firma" lead="Erscheint im Shop und in Bestellbestätigungen.">
<div className="sm-form-row">
<Field label="E-Mail" name="email" type="email" defaultValue={g.email} />
<Field label="Telefon" optional name="phone" defaultValue={g.phone} />
</div>
<Field label="Firma" name="company" defaultValue={g.company} />
<Field label="Straße und Hausnummer" name="street" defaultValue={g.street} />
<div className="sm-form-row">
<Field label="PLZ und Ort" name="zipCity" defaultValue={g.zipCity} />
<Field label="Land" name="country" defaultValue={g.country} />
</div>
<Field label="USt-IdNr." optional name="vatId" defaultValue={g.vatId} />
</Card>
<Card title="Kasse">
<Switch name="guestCheckout" label="Gastbestellung erlauben" hint="Empfohlen: Kunden müssen kein Konto anlegen." defaultChecked={c.guestCheckout} />
<Switch name="requireTerms" label="AGB-Bestätigung verlangen" defaultChecked={c.requireTerms} />
<Switch name="requirePhone" label="Telefonnummer ist Pflicht" defaultChecked={c.requirePhone} />
<Switch name="freeShippingHint" label="Hinweis „Noch … bis zum kostenlosen Versand“" defaultChecked={c.freeShippingHint} />
<div className="sm-form-row" style={{ marginTop: "var(--space-4)" }}>
<Field label="Mindestbestellwert in €" optional name="minOrderValue" inputMode="decimal" defaultValue={c.minOrderValue ? centsToInput(c.minOrderValue) : ""} />
<Field label="Kürzel für Bestellnummern" name="orderPrefix" defaultValue={g.orderPrefix} hint="z. B. SM → SM-10001" />
</div>
</Card>
<Card title="Lieferländer" lead="In diese Länder kann bestellt werden. Die Versandkosten legst du unter Versand fest.">
<div className="ad-perm-grid">
{Object.entries(COUNTRIES).map(([code, name]) => (
<label className="sm-check" key={code}><input type="checkbox" name="countries" value={code} defaultChecked={c.countries.includes(code)} /><span className="sm-check__text">{name}</span></label>
))}
</div>
</Card>
</AdminForm>
</div>
);
}

View file

@ -0,0 +1,49 @@
"use server";
import { revalidatePath } from "next/cache";
import { assertPermission, audit } from "@/lib/auth";
import { ok, type ActionResult } from "@/lib/action-result";
import { saveSettings, type NavLink, type TrustItem } from "@/lib/settings";
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "");
const bool = (fd: FormData, k: string) => fd.get(k) === "on";
function json<T>(fd: FormData, k: string, fallback: T): T {
try {
return JSON.parse(str(fd, k)) as T;
} catch {
return fallback;
}
}
export async function saveAppearance(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("appearance.edit");
await saveSettings("appearance", {
promoText: str(fd, "promoText"),
promoLinkLabel: str(fd, "promoLinkLabel"),
promoLinkHref: str(fd, "promoLinkHref"),
navigation: json<NavLink[]>(fd, "navigation", []).map((n) => ({ label: String(n.label).slice(0, 40), href: String(n.href).slice(0, 200) })),
heroEyebrow: str(fd, "heroEyebrow"),
heroTitle: str(fd, "heroTitle"),
heroText: str(fd, "heroText"),
heroPrimaryLabel: str(fd, "heroPrimaryLabel"),
heroPrimaryHref: str(fd, "heroPrimaryHref"),
heroSecondaryLabel: str(fd, "heroSecondaryLabel"),
heroSecondaryHref: str(fd, "heroSecondaryHref"),
showTrustBar: bool(fd, "showTrustBar"),
trustItems: json<TrustItem[]>(fd, "trustItems", []).slice(0, 4),
showCategories: bool(fd, "showCategories"),
categoriesEyebrow: str(fd, "categoriesEyebrow"),
categoriesTitle: str(fd, "categoriesTitle"),
showFeatured: bool(fd, "showFeatured"),
featuredEyebrow: str(fd, "featuredEyebrow"),
featuredTitle: str(fd, "featuredTitle"),
showQuote: bool(fd, "showQuote"),
quoteText: str(fd, "quoteText"),
quoteAuthor: str(fd, "quoteAuthor"),
footerClaim: str(fd, "footerClaim"),
showNewsletter: bool(fd, "showNewsletter"),
darkHeader: bool(fd, "darkHeader"),
});
await audit(user, "Gestaltung geändert");
revalidatePath("/", "layout");
return ok("Gespeichert. Die Änderungen sind sofort im Shop sichtbar.");
}

View file

@ -0,0 +1,69 @@
import { requireAdmin } from "@/lib/auth";
import { getSettings } from "@/lib/settings";
import { Field, TextareaField } from "@/components/Field";
import { AdminForm } from "@/components/admin/AdminForm";
import { NavEditor, TrustEditor } from "@/components/admin/ListEditors";
import { Card, PageHead, Switch } from "@/components/admin/ui";
import { saveAppearance } from "./actions";
export default async function AppearancePage() {
await requireAdmin("appearance.edit");
const a = (await getSettings()).appearance;
return (
<div className="ad-wrap ad-wrap--narrow">
<PageHead title="Startseite & Texte" lead="Alles, was Besucher auf der Startseite, im Kopf und im Fuß des Shops sehen.">
<a className="sm-btn sm-btn--secondary" href="/" target="_blank">Shop ansehen</a>
</PageHead>
<AdminForm action={saveAppearance}>
<Card title="Hinweisleiste" lead="Der schwarze Streifen ganz oben. Leer lassen, um ihn auszublenden.">
<Field label="Text" name="promoText" defaultValue={a.promoText} />
<div className="sm-form-row">
<Field label="Link-Text" optional name="promoLinkLabel" defaultValue={a.promoLinkLabel} />
<Field label="Link-Ziel" optional name="promoLinkHref" defaultValue={a.promoLinkHref} />
</div>
</Card>
<Card title="Hauptmenü" lead="Die Punkte in der Kopfzeile, in dieser Reihenfolge.">
<NavEditor name="navigation" initial={a.navigation} />
<Switch name="darkHeader" label="Dunkle Kopfzeile" hint="Schwarz mit goldenem Logo statt hell." defaultChecked={a.darkHeader} />
</Card>
<Card title="Großer Einstieg (Hero)" lead="Der dunkle Bereich mit dem Logo ganz oben auf der Startseite.">
<Field label="Kleine Zeile darüber" name="heroEyebrow" defaultValue={a.heroEyebrow} hint="Höchstens drei Wörter." />
<TextareaField label="Überschrift" name="heroTitle" defaultValue={a.heroTitle} rows={2} hint="Ein Zeilenumbruch hier ist auch im Shop ein Zeilenumbruch." />
<TextareaField label="Text" name="heroText" defaultValue={a.heroText} rows={3} />
<div className="sm-form-row">
<Field label="Haupt-Knopf: Text" name="heroPrimaryLabel" defaultValue={a.heroPrimaryLabel} />
<Field label="Haupt-Knopf: Ziel" name="heroPrimaryHref" defaultValue={a.heroPrimaryHref} />
</div>
<div className="sm-form-row">
<Field label="Zweiter Link: Text" optional name="heroSecondaryLabel" defaultValue={a.heroSecondaryLabel} />
<Field label="Zweiter Link: Ziel" optional name="heroSecondaryHref" defaultValue={a.heroSecondaryHref} />
</div>
</Card>
<Card title="Versprechen" lead="Die Leiste mit Versand, Rückgabe usw. – bis zu vier Einträge.">
<Switch name="showTrustBar" label="Leiste anzeigen" defaultChecked={a.showTrustBar} />
<div style={{ marginTop: "var(--space-3)" }}><TrustEditor name="trustItems" initial={a.trustItems} /></div>
</Card>
<Card title="Abschnitte der Startseite">
<Switch name="showCategories" label="Kategorie-Kacheln" hint="Zeigt Kategorien mit „Als Kachel auf der Startseite“." defaultChecked={a.showCategories} />
<div className="sm-form-row" style={{ marginBottom: "var(--space-4)" }}>
<Field label="Kleine Zeile" name="categoriesEyebrow" defaultValue={a.categoriesEyebrow} />
<Field label="Überschrift" name="categoriesTitle" defaultValue={a.categoriesTitle} />
</div>
<Switch name="showFeatured" label="Ausgewählte Produkte" hint="Zeigt Produkte mit „Auf der Startseite zeigen“." defaultChecked={a.showFeatured} />
<div className="sm-form-row" style={{ marginBottom: "var(--space-4)" }}>
<Field label="Kleine Zeile" name="featuredEyebrow" defaultValue={a.featuredEyebrow} />
<Field label="Überschrift" name="featuredTitle" defaultValue={a.featuredTitle} />
</div>
<Switch name="showQuote" label="Zitat / Kundenstimme" defaultChecked={a.showQuote} />
<TextareaField label="Zitat" name="quoteText" defaultValue={a.quoteText} rows={2} />
<Field label="Von wem" name="quoteAuthor" defaultValue={a.quoteAuthor} />
</Card>
<Card title="Fußbereich">
<TextareaField label="Kurzer Text unter dem Logo" name="footerClaim" defaultValue={a.footerClaim} rows={2} />
<Switch name="showNewsletter" label="Newsletter-Anmeldung anzeigen" defaultChecked={a.showNewsletter} />
<p className="body-sm ad-muted" style={{ marginBottom: 0 }}>Die Links im Fuß kommen aus den Seiten (Einstellung „Im Fußbereich“) und den Kategorien.</p>
</Card>
</AdminForm>
</div>
);
}

View file

@ -0,0 +1,40 @@
"use server";
import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";
import { assertPermission, audit } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { parsePrice } from "@/lib/money";
export async function saveCoupon(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("coupons.edit");
const id = String(fd.get("id") ?? "");
const code = String(fd.get("code") ?? "").trim().toUpperCase().replace(/\s+/g, "");
if (!/^[A-Z0-9_-]{3,32}$/.test(code)) return fail("Der Code braucht 3–32 Zeichen: Buchstaben, Ziffern, - oder _.", { code: "Ungültiger Code." });
const clash = await db.coupon.findFirst({ where: { code, NOT: id ? { id } : undefined } });
if (clash) return fail("Diesen Code gibt es schon.", { code: "Schon vergeben." });
const type = fd.get("type") === "fixed" ? "fixed" : "percent";
const value = type === "percent" ? Math.round(Number(String(fd.get("value")).replace(",", "."))) : parsePrice(String(fd.get("value")));
if (!value || value <= 0 || (type === "percent" && value > 100)) return fail("Bitte gib einen gültigen Wert ein.", { value: "Ungültiger Wert." });
const until = String(fd.get("validUntil") ?? "");
const data = {
code,
type,
value,
minTotal: parsePrice(String(fd.get("minTotal") ?? "")) ?? 0,
maxUses: Math.max(0, Math.round(Number(fd.get("maxUses")) || 0)),
active: fd.get("active") === "on",
validUntil: until ? new Date(`${until}T23:59:59`) : null,
};
if (id) await db.coupon.update({ where: { id }, data });
else await db.coupon.create({ data });
await audit(user, id ? "Gutschein geändert" : "Gutschein angelegt", code);
revalidatePath("/admin/gutscheine");
return ok(id ? "Gespeichert." : "Gutschein angelegt.");
}
export async function deleteCoupon(fd: FormData) {
const user = await assertPermission("coupons.edit");
const c = await db.coupon.delete({ where: { id: String(fd.get("id")) } });
await audit(user, "Gutschein gelöscht", c.code);
revalidatePath("/admin/gutscheine");
}

View file

@ -0,0 +1,62 @@
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { centsToInput, formatPrice } from "@/lib/money";
import { Field, SelectField } from "@/components/Field";
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
import { PageHead, Pill } from "@/components/admin/ui";
import { deleteCoupon, saveCoupon } from "./actions";
import type { Coupon } from "@prisma/client";
function CouponFields({ c }: { c?: Coupon }) {
return (
<>
{c && <input type="hidden" name="id" value={c.id} />}
<div className="sm-form-row">
<Field label="Code" name="code" defaultValue={c?.code} placeholder="z. B. SOMMER15" required />
<SelectField label="Art" name="type" defaultValue={c?.type ?? "percent"}>
<option value="percent">Prozent vom Warenwert</option>
<option value="fixed">Fester Betrag in €</option>
</SelectField>
</div>
<div className="sm-form-row">
<Field label="Wert" name="value" inputMode="decimal" defaultValue={c ? (c.type === "percent" ? String(c.value) : centsToInput(c.value)) : ""} hint="z. B. 10 für 10 % oder 15,00 für 15 €" required />
<Field label="Mindestbestellwert in €" optional name="minTotal" inputMode="decimal" defaultValue={c?.minTotal ? centsToInput(c.minTotal) : ""} />
</div>
<div className="sm-form-row">
<Field label="Gültig bis" optional name="validUntil" type="date" defaultValue={c?.validUntil ? c.validUntil.toISOString().slice(0, 10) : ""} />
<Field label="Höchstens einlösbar" optional name="maxUses" type="number" min={0} defaultValue={c?.maxUses || ""} hint="Leer = unbegrenzt" />
</div>
<label className="ad-switch"><span className="ad-switch__text"><strong>Aktiv</strong></span><input type="checkbox" role="switch" name="active" defaultChecked={c?.active ?? true} /></label>
</>
);
}
export default async function CouponsPage() {
await requireAdmin("coupons.edit");
const coupons = await db.coupon.findMany({ orderBy: { createdAt: "desc" } });
return (
<div className="ad-wrap ad-wrap--narrow">
<PageHead title="Gutscheine" lead="Rabattcodes, die Kunden im Warenkorb einlösen." />
{coupons.map((c) => (
<details className="ad-card" key={c.id} style={{ marginBottom: "var(--space-3)" }}>
<summary className="ad-card__head" style={{ cursor: "pointer", listStyle: "none" }}>
<div>
<h2>{c.code}</h2>
<p>{c.type === "percent" ? `${c.value} %` : formatPrice(c.value)} · {c.usedCount}× eingelöst{c.maxUses ? ` von ${c.maxUses}` : ""}</p>
</div>
<Pill tone={c.active ? "success" : "neutral"}>{c.active ? "Aktiv" : "Aus"}</Pill>
</summary>
<div className="ad-card__body">
<AdminForm action={saveCoupon} extraActions={<ConfirmButton inForm action={deleteCoupon} confirm="Gutschein löschen?">Löschen</ConfirmButton>}>
<CouponFields c={c} />
</AdminForm>
</div>
</details>
))}
<section className="ad-card" style={{ marginTop: "var(--space-6)" }}>
<div className="ad-card__head"><h2>Neuer Gutschein</h2></div>
<div className="ad-card__body"><AdminForm action={saveCoupon} submitLabel="Gutschein anlegen"><CouponFields /></AdminForm></div>
</section>
</div>
);
}

View file

@ -0,0 +1,41 @@
"use server";
import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";
import { assertPermission, audit } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { slugify } from "@/lib/slug";
export async function saveCategory(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("categories.edit");
const id = String(fd.get("id") ?? "");
const name = String(fd.get("name") ?? "").trim();
if (!name) return fail("Bitte gib einen Namen ein.", { name: "Bitte gib einen Namen ein." });
const slug = slugify(String(fd.get("slug") ?? "") || name);
const clash = await db.category.findFirst({ where: { slug, NOT: id ? { id } : undefined } });
if (clash) return fail("Diese Web-Adresse ist schon vergeben.", { slug: "Schon vergeben." });
let image = "";
try {
image = (JSON.parse(String(fd.get("image") ?? "[]")) as string[])[0] ?? "";
} catch {}
const data = {
name,
slug,
description: String(fd.get("description") ?? ""),
image,
sort: Math.round(Number(fd.get("sort")) || 0),
active: fd.get("active") === "on",
showOnHome: fd.get("showOnHome") === "on",
};
if (id) await db.category.update({ where: { id }, data });
else await db.category.create({ data });
await audit(user, id ? "Kategorie geändert" : "Kategorie angelegt", name);
revalidatePath("/", "layout");
return ok(id ? "Gespeichert." : "Kategorie angelegt.");
}
export async function deleteCategory(fd: FormData) {
const user = await assertPermission("categories.edit");
const c = await db.category.delete({ where: { id: String(fd.get("id")) } });
await audit(user, "Kategorie gelöscht", c.name);
revalidatePath("/", "layout");
}

View file

@ -0,0 +1,62 @@
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { Field, TextareaField } from "@/components/Field";
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
import { ImageManager } from "@/components/admin/ImageManager";
import { PageHead } from "@/components/admin/ui";
import { deleteCategory, saveCategory } from "./actions";
type C = { id?: string; name: string; slug: string; description: string; image: string; sort: number; active: boolean; showOnHome: boolean };
function CategoryFields({ c }: { c: C }) {
return (
<div className="ad-grid ad-grid--2-1">
<div>
{c.id && <input type="hidden" name="id" value={c.id} />}
<div className="sm-form-row">
<Field label="Name" name="name" defaultValue={c.name} required />
<Field label="Web-Adresse" name="slug" defaultValue={c.slug} hint="Leer lassen für automatisch." />
</div>
<TextareaField label="Beschreibung" optional name="description" defaultValue={c.description} rows={2} />
<Field label="Reihenfolge" name="sort" type="number" defaultValue={c.sort} hint="Kleinere Zahl steht weiter vorne." />
<label className="ad-switch"><span className="ad-switch__text"><strong>Im Shop sichtbar</strong></span><input type="checkbox" role="switch" name="active" defaultChecked={c.active} /></label>
<label className="ad-switch"><span className="ad-switch__text"><strong>Als Kachel auf der Startseite</strong></span><input type="checkbox" role="switch" name="showOnHome" defaultChecked={c.showOnHome} /></label>
</div>
<div>
<span className="sm-field__label">Kachelbild</span>
<ImageManager name="image" initial={c.image ? [c.image] : []} multiple={false} />
</div>
</div>
);
}
export default async function CategoriesPage() {
await requireAdmin("categories.edit");
const categories = await db.category.findMany({ orderBy: { sort: "asc" }, include: { _count: { select: { products: true } } } });
return (
<div className="ad-wrap">
<PageHead title="Kategorien" lead="Kategorien gliedern den Shop und erscheinen als Kacheln auf der Startseite." />
{categories.map((c) => (
<details className="ad-card" key={c.id} style={{ marginBottom: "var(--space-3)" }}>
<summary className="ad-card__head" style={{ cursor: "pointer", listStyle: "none" }}>
<div><h2>{c.name}</h2><p>{c._count.products} Produkte · /{c.slug}{c.active ? "" : " · versteckt"}</p></div>
<span className="body-sm" style={{ color: "var(--link)" }}>Bearbeiten</span>
</summary>
<div className="ad-card__body">
<AdminForm action={saveCategory} extraActions={<ConfirmButton inForm action={deleteCategory} confirm="Kategorie löschen? Die Produkte bleiben erhalten.">Löschen</ConfirmButton>}>
<CategoryFields c={c} />
</AdminForm>
</div>
</details>
))}
<section className="ad-card" style={{ marginTop: "var(--space-6)" }}>
<div className="ad-card__head"><h2>Neue Kategorie</h2></div>
<div className="ad-card__body">
<AdminForm action={saveCategory} submitLabel="Kategorie anlegen">
<CategoryFields c={{ name: "", slug: "", description: "", image: "", sort: categories.length, active: true, showOnHome: true }} />
</AdminForm>
</div>
</section>
</div>
);
}

View file

@ -0,0 +1,54 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { can, requireAdmin } from "@/lib/auth";
import { formatPrice } from "@/lib/money";
import { ORDER_STATUS, dateFmt } from "@/lib/status";
import { Field } from "@/components/Field";
import { AdminForm } from "@/components/admin/AdminForm";
import { Card, PageHead, Pill } from "@/components/admin/ui";
import { saveCustomer } from "../actions";
export default async function CustomerDetail({ params }: { params: Promise<{ id: string }> }) {
const user = await requireAdmin("customers.view");
const { id } = await params;
const c = await db.user.findUnique({ where: { id }, include: { orders: { orderBy: { createdAt: "desc" } } } });
if (!c || c.roleId) notFound();
return (
<div className="ad-wrap">
<PageHead title={[c.firstName, c.lastName].filter(Boolean).join(" ") || c.email} lead={`${c.email} · Kunde seit ${dateFmt.format(c.createdAt)}`} back={{ href: "/admin/kunden", label: "Kunden" }} />
<div className="ad-grid ad-grid--2-1">
<Card title="Bestellungen" flush>
{c.orders.length === 0 ? <div className="ad-empty">Noch keine Bestellungen.</div> : (
<table className="ad-table">
<tbody>
{c.orders.map((o) => (
<tr key={o.id}>
<td><Link className="ad-rowlink" href={`/admin/bestellungen/${o.id}`}>{o.number}</Link></td>
<td className="body-sm">{dateFmt.format(o.createdAt)}</td>
<td><Pill tone={ORDER_STATUS[o.status].tone}>{ORDER_STATUS[o.status].label}</Pill></td>
<td className="num">{formatPrice(o.total)}</td>
</tr>
))}
</tbody>
</table>
)}
</Card>
<Card title="Daten">
{can(user, "customers.edit") ? (
<AdminForm action={saveCustomer}>
<input type="hidden" name="id" value={c.id} />
<Field label="Vorname" name="firstName" defaultValue={c.firstName} />
<Field label="Nachname" name="lastName" defaultValue={c.lastName} />
<Field label="Telefon" name="phone" defaultValue={c.phone} />
<label className="ad-switch"><span className="ad-switch__text"><strong>Newsletter</strong></span><input type="checkbox" role="switch" name="newsletter" defaultChecked={c.newsletter} /></label>
<label className="ad-switch"><span className="ad-switch__text"><strong>Konto aktiv</strong><small>Ausgeschaltet kann sich der Kunde nicht mehr anmelden.</small></span><input type="checkbox" role="switch" name="active" defaultChecked={c.active} /></label>
</AdminForm>
) : (
<dl className="ad-dl"><dt>Telefon</dt><dd>{c.phone || "—"}</dd><dt>Newsletter</dt><dd>{c.newsletter ? "Ja" : "Nein"}</dd></dl>
)}
</Card>
</div>
</div>
);
}

View file

@ -0,0 +1,27 @@
"use server";
import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";
import { assertPermission, audit } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
export async function saveCustomer(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("customers.edit");
const id = String(fd.get("id"));
const target = await db.user.findUnique({ where: { id } });
if (!target || target.roleId) return fail("Kunde nicht gefunden.");
const active = fd.get("active") === "on";
await db.user.update({
where: { id },
data: {
firstName: String(fd.get("firstName") ?? "").trim(),
lastName: String(fd.get("lastName") ?? "").trim(),
phone: String(fd.get("phone") ?? "").trim(),
newsletter: fd.get("newsletter") === "on",
active,
},
});
if (!active) await db.session.deleteMany({ where: { userId: id } });
await audit(user, "Kunde geändert", target.email);
revalidatePath(`/admin/kunden/${id}`);
return ok();
}

View file

@ -0,0 +1,53 @@
import Link from "next/link";
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { formatPrice } from "@/lib/money";
import { dayFmt } from "@/lib/status";
import { Card, Empty, PageHead } from "@/components/admin/ui";
export default async function CustomersPage({ searchParams }: { searchParams: Promise<{ q?: string }> }) {
await requireAdmin("customers.view");
const q = ((await searchParams).q ?? "").trim();
const customers = await db.user.findMany({
where: {
roleId: null,
...(q ? { OR: [{ email: { contains: q, mode: "insensitive" } }, { firstName: { contains: q, mode: "insensitive" } }, { lastName: { contains: q, mode: "insensitive" } }] } : {}),
},
include: { orders: { select: { total: true, status: true } } },
orderBy: { createdAt: "desc" },
take: 200,
});
return (
<div className="ad-wrap">
<PageHead title="Kunden" lead="Kunden mit Konto. Gastbestellungen findest du unter Bestellungen." />
<Card flush>
<form className="ad-toolbar" method="get">
<input className="sm-input" type="search" name="q" defaultValue={q} placeholder="Name oder E-Mail suchen" aria-label="Kunden suchen" />
</form>
{customers.length === 0 ? (
<Empty title="Noch keine Kunden" text="Sobald sich jemand registriert, erscheint er hier." />
) : (
<div className="ad-table-wrap">
<table className="ad-table">
<thead><tr><th>Name</th><th>E-Mail</th><th>Kunde seit</th><th className="num">Bestellungen</th><th className="num">Umsatz</th></tr></thead>
<tbody>
{customers.map((c) => {
const valid = c.orders.filter((o) => !["CANCELLED", "REFUNDED"].includes(o.status));
return (
<tr key={c.id}>
<td><Link className="ad-rowlink" href={`/admin/kunden/${c.id}`}>{[c.firstName, c.lastName].filter(Boolean).join(" ") || "—"}</Link>{!c.active && <div className="body-sm ad-muted">gesperrt</div>}</td>
<td>{c.email}</td>
<td className="body-sm">{dayFmt.format(c.createdAt)}</td>
<td className="num">{valid.length}</td>
<td className="num">{formatPrice(valid.reduce((s, o) => s + o.total, 0))}</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</Card>
</div>
);
}

View file

@ -0,0 +1,10 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { can, getCurrentUser } from "@/lib/auth";
export async function GET() {
if (!can(await getCurrentUser(), "newsletter.view")) return new NextResponse("Kein Zugriff", { status: 403 });
const subs = await db.newsletterSubscriber.findMany({ orderBy: { createdAt: "asc" } });
const csv = "email;angemeldet_am\n" + subs.map((s) => `${s.email};${s.createdAt.toISOString()}`).join("\n");
return new NextResponse(csv, { headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": 'attachment; filename="newsletter.csv"' } });
}

View file

@ -0,0 +1,24 @@
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { dateFmt } from "@/lib/status";
import { Card, Empty, PageHead } from "@/components/admin/ui";
export default async function NewsletterPage() {
await requireAdmin("newsletter.view");
const subs = await db.newsletterSubscriber.findMany({ orderBy: { createdAt: "desc" } });
return (
<div className="ad-wrap ad-wrap--narrow">
<PageHead title="Newsletter" lead={`${subs.length} Anmeldungen`}>
{subs.length > 0 && <a className="sm-btn sm-btn--secondary" href="/admin/newsletter/export">Als CSV herunterladen</a>}
</PageHead>
<Card flush>
{subs.length === 0 ? <Empty title="Noch keine Anmeldungen" /> : (
<table className="ad-table">
<thead><tr><th>E-Mail</th><th>Angemeldet am</th></tr></thead>
<tbody>{subs.map((s) => <tr key={s.id}><td>{s.email}</td><td className="body-sm">{dateFmt.format(s.createdAt)}</td></tr>)}</tbody>
</table>
)}
</Card>
</div>
);
}

View file

@ -0,0 +1,56 @@
import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { can, requireAdmin } from "@/lib/auth";
import { centsToInput } from "@/lib/money";
import { Alert } from "@/components/shop/Blocks";
import { ConfirmButton } from "@/components/admin/AdminForm";
import { PageHead } from "@/components/admin/ui";
import { ProductForm } from "@/components/admin/ProductForm";
import { deleteProduct, duplicateProduct } from "../actions";
export default async function EditProduct({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ neu?: string }> }) {
const user = await requireAdmin("products.view");
const [{ id }, { neu }] = await Promise.all([params, searchParams]);
const [p, categories] = await Promise.all([
db.product.findUnique({ where: { id }, include: { variants: { orderBy: { sort: "asc" } } } }),
db.category.findMany({ orderBy: { sort: "asc" } }),
]);
if (!p) notFound();
return (
<div className="ad-wrap">
<PageHead title={p.name} back={{ href: "/admin/produkte", label: "Produkte" }}>
{can(user, "products.edit") && (
<form action={duplicateProduct}><input type="hidden" name="id" value={p.id} /><button className="sm-btn sm-btn--secondary" type="submit">Duplizieren</button></form>
)}
{can(user, "products.delete") && (
<ConfirmButton action={deleteProduct} hidden={{ id: p.id }} confirm="Produkt endgültig löschen?" className="sm-btn sm-btn--ghost">Löschen</ConfirmButton>
)}
</PageHead>
{neu && <div style={{ marginBottom: "var(--space-5)" }}><Alert kind="success" title="Produkt angelegt." /></div>}
<ProductForm
canStock={can(user, "stock.edit")}
categories={categories}
values={{
id: p.id,
name: p.name,
slug: p.slug,
subtitle: p.subtitle,
description: p.description,
details: p.details,
sku: p.sku,
price: centsToInput(p.price),
compareAtPrice: centsToInput(p.compareAtPrice),
taxRate: p.taxRate,
stock: p.stock,
trackStock: p.trackStock,
active: p.active,
featured: p.featured,
badge: p.badge,
categoryId: p.categoryId ?? "",
images: p.images,
variants: p.variants.map((v) => ({ id: v.id, name: v.name, sku: v.sku, price: centsToInput(v.price), stock: String(v.stock) })),
}}
/>
</div>
);
}

View file

@ -0,0 +1,116 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { assertPermission, audit, can } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { parsePrice } from "@/lib/money";
import { slugify } from "@/lib/slug";
type VariantInput = { id?: string; name: string; sku: string; price: string; stock: string };
export async function saveProduct(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("products.edit");
const id = String(fd.get("id") ?? "");
const errors: Record<string, string> = {};
const name = String(fd.get("name") ?? "").trim();
if (!name) errors.name = "Bitte gib einen Namen ein.";
const price = parsePrice(String(fd.get("price")));
if (price == null) errors.price = "Bitte gib einen Preis ein, z. B. 129,00.";
const compareRaw = String(fd.get("compareAtPrice") ?? "").trim();
const compareAtPrice = compareRaw ? parsePrice(compareRaw) : null;
if (compareRaw && compareAtPrice == null) errors.compareAtPrice = "Bitte gib einen gültigen Preis ein.";
let slug = slugify(String(fd.get("slug") ?? "") || name);
if (!slug) errors.slug = "Bitte gib eine Web-Adresse ein.";
const clash = slug ? await db.product.findFirst({ where: { slug, NOT: id ? { id } : undefined } }) : null;
if (clash) errors.slug = "Diese Web-Adresse nutzt schon ein anderes Produkt.";
let variants: VariantInput[] = [];
try {
variants = JSON.parse(String(fd.get("variants") ?? "[]"));
} catch {}
variants = variants.filter((v) => v.name.trim());
for (const v of variants) {
if (v.price.trim() && parsePrice(v.price) == null) errors.variants = `Preis der Variante „${v.name}“ ist ungültig.`;
}
if (Object.keys(errors).length) return fail("Bitte prüfe die markierten Felder.", errors);
let images: string[] = [];
try {
images = (JSON.parse(String(fd.get("images") ?? "[]")) as string[]).filter((s) => typeof s === "string" && s.startsWith("/"));
} catch {}
const stockAllowed = can(user, "stock.edit");
const data = {
name,
slug,
subtitle: String(fd.get("subtitle") ?? "").trim(),
description: String(fd.get("description") ?? ""),
details: String(fd.get("details") ?? ""),
sku: String(fd.get("sku") ?? "").trim(),
price: price!,
compareAtPrice,
taxRate: Number(fd.get("taxRate")) === 7 ? 7 : Number(fd.get("taxRate")) === 0 ? 0 : 19,
trackStock: fd.get("trackStock") === "on",
active: fd.get("active") === "on",
featured: fd.get("featured") === "on",
badge: ["new", "best"].includes(String(fd.get("badge"))) ? String(fd.get("badge")) : "",
categoryId: String(fd.get("categoryId") ?? "") || null,
images,
...(stockAllowed ? { stock: Math.max(0, Math.round(Number(fd.get("stock")) || 0)) } : {}),
};
let productId = id;
await db.$transaction(async (tx) => {
if (id) await tx.product.update({ where: { id }, data });
else productId = (await tx.product.create({ data: { ...data, stock: data.stock ?? 0 } })).id;
const existing = await tx.productVariant.findMany({ where: { productId } });
const keep = variants.filter((v) => v.id).map((v) => v.id!);
await tx.productVariant.deleteMany({ where: { productId, id: { notIn: keep } } });
for (const [i, v] of variants.entries()) {
const vdata = { name: v.name.trim(), sku: v.sku.trim(), price: v.price.trim() ? parsePrice(v.price) : null, sort: i };
const stock = Math.max(0, Math.round(Number(v.stock) || 0));
if (v.id && existing.some((e) => e.id === v.id)) {
await tx.productVariant.update({ where: { id: v.id }, data: { ...vdata, ...(stockAllowed ? { stock } : {}) } });
} else {
await tx.productVariant.create({ data: { ...vdata, stock: stockAllowed ? stock : 0, productId } });
}
}
});
await audit(user, id ? "Produkt geändert" : "Produkt angelegt", name);
revalidatePath("/", "layout");
if (!id) redirect(`/admin/produkte/${productId}?neu=1`);
return ok();
}
export async function deleteProduct(fd: FormData) {
const user = await assertPermission("products.delete");
const id = String(fd.get("id"));
const p = await db.product.delete({ where: { id } });
await audit(user, "Produkt gelöscht", p.name);
revalidatePath("/", "layout");
redirect("/admin/produkte");
}
export async function duplicateProduct(fd: FormData) {
const user = await assertPermission("products.edit");
const id = String(fd.get("id"));
const p = await db.product.findUnique({ where: { id }, include: { variants: true } });
if (!p) return;
let slug = `${p.slug}-kopie`;
for (let i = 2; await db.product.findUnique({ where: { slug } }); i++) slug = `${p.slug}-kopie-${i}`;
const { id: _id, createdAt: _c, updatedAt: _u, variants, ...rest } = p;
const copy = await db.product.create({
data: { ...rest, name: `${p.name} (Kopie)`, slug, active: false, variants: { create: variants.map(({ id: _v, productId: _p, ...v }) => v) } },
});
await audit(user, "Produkt dupliziert", p.name);
redirect(`/admin/produkte/${copy.id}`);
}
export async function toggleProductActive(fd: FormData) {
await assertPermission("products.edit");
const id = String(fd.get("id"));
const p = await db.product.findUnique({ where: { id } });
if (!p) return;
await db.product.update({ where: { id }, data: { active: !p.active } });
revalidatePath("/admin/produkte");
revalidatePath("/", "layout");
}

View file

@ -0,0 +1,19 @@
import { db } from "@/lib/db";
import { can, requireAdmin } from "@/lib/auth";
import { PageHead } from "@/components/admin/ui";
import { ProductForm } from "@/components/admin/ProductForm";
export default async function NewProduct() {
const user = await requireAdmin("products.edit");
const categories = await db.category.findMany({ orderBy: { sort: "asc" } });
return (
<div className="ad-wrap">
<PageHead title="Neues Produkt" back={{ href: "/admin/produkte", label: "Produkte" }} />
<ProductForm
canStock={can(user, "stock.edit")}
categories={categories}
values={{ name: "", slug: "", subtitle: "", description: "", details: "", sku: "", price: "", compareAtPrice: "", taxRate: 19, stock: 0, trackStock: true, active: true, featured: false, badge: "", categoryId: "", images: [], variants: [] }}
/>
</div>
);
}

View file

@ -0,0 +1,82 @@
/* eslint-disable @next/next/no-img-element */
import Link from "next/link";
import type { Prisma } from "@prisma/client";
import { db } from "@/lib/db";
import { can, requireAdmin } from "@/lib/auth";
import { formatPrice } from "@/lib/money";
import { Icon } from "@/components/Icon";
import { Card, Empty, PageHead, Pill } from "@/components/admin/ui";
import { toggleProductActive } from "./actions";
export default async function ProductsPage({ searchParams }: { searchParams: Promise<{ q?: string; kategorie?: string; filter?: string }> }) {
const user = await requireAdmin("products.view");
const sp = await searchParams;
const q = (sp.q ?? "").trim();
const where: Prisma.ProductWhereInput = {
...(q ? { OR: [{ name: { contains: q, mode: "insensitive" } }, { sku: { contains: q, mode: "insensitive" } }] } : {}),
...(sp.kategorie ? { categoryId: sp.kategorie } : {}),
...(sp.filter === "versteckt" ? { active: false } : sp.filter === "aktiv" ? { active: true } : {}),
};
const [products, categories] = await Promise.all([
db.product.findMany({ where, include: { category: true, variants: true }, orderBy: [{ sort: "asc" }, { createdAt: "desc" }] }),
db.category.findMany({ orderBy: { sort: "asc" } }),
]);
const editable = can(user, "products.edit");
return (
<div className="ad-wrap">
<PageHead title="Produkte" lead={`${products.length} Produkte`}>
{editable && <Link className="sm-btn sm-btn--primary" href="/admin/produkte/neu"><Icon name="plus" size="sm" /> Produkt anlegen</Link>}
</PageHead>
<Card flush>
<form className="ad-toolbar" method="get">
<input className="sm-input" type="search" name="q" defaultValue={q} placeholder="Name oder Art.-Nr. suchen" aria-label="Produkte suchen" />
<span className="sm-select-wrap"><select className="sm-select" name="kategorie" defaultValue={sp.kategorie ?? ""} style={{ minHeight: "var(--control-height-sm)" }} aria-label="Kategorie">
<option value="">Alle Kategorien</option>
{categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
</select></span>
<span className="sm-select-wrap"><select className="sm-select" name="filter" defaultValue={sp.filter ?? ""} style={{ minHeight: "var(--control-height-sm)" }} aria-label="Sichtbarkeit">
<option value="">Alle</option><option value="aktiv">Sichtbar</option><option value="versteckt">Versteckt</option>
</select></span>
<button className="sm-btn sm-btn--secondary sm-btn--sm" type="submit">Filtern</button>
</form>
{products.length === 0 ? (
<Empty title="Keine Produkte gefunden" text="Lege dein erstes Produkt an oder ändere den Filter.">
{editable && <Link className="sm-btn sm-btn--primary" href="/admin/produkte/neu">Produkt anlegen</Link>}
</Empty>
) : (
<div className="ad-table-wrap">
<table className="ad-table">
<thead><tr><th /><th>Produkt</th><th>Kategorie</th><th className="num">Preis</th><th className="num">Bestand</th><th>Sichtbar</th></tr></thead>
<tbody>
{products.map((p) => {
const stock = p.variants.length ? p.variants.reduce((s, v) => s + v.stock, 0) : p.stock;
return (
<tr key={p.id}>
<td style={{ width: 60 }}>{p.images[0] ? <img className="ad-thumb" src={p.images[0]} alt="" /> : <div className="ad-thumb" />}</td>
<td><Link className="ad-rowlink" href={`/admin/produkte/${p.id}`}>{p.name}</Link><div className="body-sm ad-muted">{[p.sku, p.variants.length ? `${p.variants.length} Varianten` : ""].filter(Boolean).join(" · ")}</div></td>
<td className="body-sm">{p.category?.name ?? "—"}</td>
<td className="num">{formatPrice(p.price)}</td>
<td className="num">{p.trackStock ? <Pill tone={stock <= 0 ? "danger" : stock <= 3 ? "gold" : "neutral"}>{stock}</Pill> : "—"}</td>
<td>
{editable ? (
<form action={toggleProductActive}>
<input type="hidden" name="id" value={p.id} />
<button type="submit" className="ad-tab" style={{ border: 0, background: "none", cursor: "pointer", padding: 0 }} title="Umschalten">
<Pill tone={p.active ? "success" : "neutral"}>{p.active ? "Sichtbar" : "Versteckt"}</Pill>
</button>
</form>
) : (
<Pill tone={p.active ? "success" : "neutral"}>{p.active ? "Sichtbar" : "Versteckt"}</Pill>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</Card>
</div>
);
}

View file

@ -0,0 +1,28 @@
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { dateFmt } from "@/lib/status";
import { Card, Empty, PageHead } from "@/components/admin/ui";
export default async function AuditPage() {
await requireAdmin("audit.view");
const logs = await db.auditLog.findMany({ orderBy: { createdAt: "desc" }, take: 300 });
return (
<div className="ad-wrap">
<PageHead title="Protokoll" lead="Wer hat wann was geändert. Die letzten 300 Einträge." />
<Card flush>
{logs.length === 0 ? <Empty title="Noch keine Einträge" /> : (
<div className="ad-table-wrap">
<table className="ad-table">
<thead><tr><th>Zeit</th><th>Wer</th><th>Was</th><th>Details</th></tr></thead>
<tbody>
{logs.map((l) => (
<tr key={l.id}><td className="body-sm" style={{ whiteSpace: "nowrap" }}>{dateFmt.format(l.createdAt)}</td><td className="body-sm">{l.userEmail}</td><td>{l.action}</td><td className="body-sm ad-muted">{l.details}</td></tr>
))}
</tbody>
</table>
</div>
)}
</Card>
</div>
);
}

View file

@ -0,0 +1,44 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { ALL_PERMISSIONS } from "@/lib/permissions";
import { Field } from "@/components/Field";
import { Alert } from "@/components/shop/Blocks";
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
import { PermissionPicker } from "@/components/admin/PermissionPicker";
import { Card, PageHead } from "@/components/admin/ui";
import { deleteRole, saveRole } from "../actions";
export default async function RolePage({ params }: { params: Promise<{ id: string }> }) {
const me = await requireAdmin("roles.manage");
const { id } = await params;
const role = id === "neu" ? null : await db.role.findUnique({ where: { id }, include: { users: true } });
if (id !== "neu" && !role) notFound();
const allowed = me.role!.isSystem ? null : me.role!.permissions;
return (
<div className="ad-wrap ad-wrap--narrow">
<PageHead title={role?.name ?? "Neue Rolle"} back={{ href: "/admin/rollen", label: "Rollen & Rechte" }}>
{role && !role.isSystem && role.users.length === 0 && <ConfirmButton action={deleteRole} hidden={{ id: role.id }} confirm="Rolle löschen?">Löschen</ConfirmButton>}
</PageHead>
{role?.isSystem && <div style={{ marginBottom: "var(--space-5)" }}><Alert title="Die Inhaber-Rolle hat immer alle Rechte.">So kann sich niemand aus Versehen aussperren.</Alert></div>}
<AdminForm action={saveRole} submitLabel={role ? "Speichern" : "Rolle anlegen"}>
{role && <input type="hidden" name="id" value={role.id} />}
<Card title="Name">
<Field label="Name der Rolle" name="name" defaultValue={role?.name} placeholder="z. B. Lager" disabled={role?.isSystem} required />
<Field label="Beschreibung" optional name="description" defaultValue={role?.description} disabled={role?.isSystem} hint="Hilft später zu verstehen, wofür die Rolle gedacht ist." />
</Card>
<Card title="Rechte" lead={allowed ? "Rechte, die du selbst nicht hast, kannst du nicht vergeben." : "Hake an, was Personen mit dieser Rolle dürfen."}>
<PermissionPicker initial={role?.isSystem ? ALL_PERMISSIONS : (role?.permissions ?? ["dashboard.view"])} allowed={allowed} disabled={role?.isSystem} />
</Card>
{role && role.users.length > 0 && (
<Card title="Personen mit dieser Rolle">
<ul style={{ margin: 0, paddingLeft: "1.2em" }}>
{role.users.map((u) => <li key={u.id}><Link href={`/admin/team/${u.id}`}>{[u.firstName, u.lastName].filter(Boolean).join(" ") || u.email}</Link></li>)}
</ul>
</Card>
)}
</AdminForm>
</div>
);
}

View file

@ -0,0 +1,42 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { assertPermission, audit } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { isPermission } from "@/lib/permissions";
export async function saveRole(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const actor = await assertPermission("roles.manage");
const id = String(fd.get("id") ?? "");
const name = String(fd.get("name") ?? "").trim();
if (!name) return fail("Bitte gib der Rolle einen Namen.", { name: "Pflichtfeld" });
const clash = await db.role.findFirst({ where: { name, NOT: id ? { id } : undefined } });
if (clash) return fail("Eine Rolle mit diesem Namen gibt es schon.", { name: "Schon vergeben" });
const existing = id ? await db.role.findUnique({ where: { id } }) : null;
if (existing?.isSystem) return fail("Die Inhaber-Rolle hat immer alle Rechte und kann nicht geändert werden.");
const requested = fd.getAll("permissions").map(String).filter(isPermission);
// Niemand kann Rechte vergeben, die er selbst nicht hat
const own = actor.role!.isSystem ? null : new Set(actor.role!.permissions);
const before = new Set(existing?.permissions ?? []);
const permissions = own ? requested.filter((p) => own.has(p) || before.has(p)) : requested;
if (own && requested.some((p) => !own.has(p) && !before.has(p))) return fail("Du kannst nur Rechte vergeben, die du selbst hast.");
const data = { name, description: String(fd.get("description") ?? "").trim(), permissions };
let roleId = id;
if (id) await db.role.update({ where: { id }, data });
else roleId = (await db.role.create({ data })).id;
await audit(actor, id ? "Rolle geändert" : "Rolle angelegt", `${name}: ${permissions.length} Rechte`);
revalidatePath("/admin", "layout");
if (!id) redirect(`/admin/rollen/${roleId}`);
return ok();
}
export async function deleteRole(fd: FormData) {
const actor = await assertPermission("roles.manage");
const id = String(fd.get("id"));
const role = await db.role.findUnique({ where: { id }, include: { _count: { select: { users: true } } } });
if (!role || role.isSystem || role._count.users > 0) return;
await db.role.delete({ where: { id } });
await audit(actor, "Rolle gelöscht", role.name);
redirect("/admin/rollen");
}

View file

@ -0,0 +1,32 @@
import Link from "next/link";
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { ALL_PERMISSIONS } from "@/lib/permissions";
import { Icon } from "@/components/Icon";
import { Card, PageHead, Pill } from "@/components/admin/ui";
export default async function RolesPage() {
await requireAdmin("roles.manage");
const roles = await db.role.findMany({ include: { _count: { select: { users: true } } }, orderBy: [{ isSystem: "desc" }, { name: "asc" }] });
return (
<div className="ad-wrap ad-wrap--narrow">
<PageHead title="Rollen & Rechte" lead="Eine Rolle bündelt Rechte. Leg so viele Rollen an, wie du brauchst, und weise sie im Team zu.">
<Link className="sm-btn sm-btn--primary" href="/admin/rollen/neu"><Icon name="plus" size="sm" /> Rolle anlegen</Link>
</PageHead>
<Card flush>
<table className="ad-table">
<thead><tr><th>Rolle</th><th>Rechte</th><th className="num">Personen</th></tr></thead>
<tbody>
{roles.map((r) => (
<tr key={r.id}>
<td><Link className="ad-rowlink" href={`/admin/rollen/${r.id}`}>{r.name}</Link><div className="body-sm ad-muted">{r.description}</div></td>
<td>{r.isSystem ? <Pill tone="gold">Alle</Pill> : <span className="body-sm">{r.permissions.length} von {ALL_PERMISSIONS.length}</span>}</td>
<td className="num">{r._count.users}</td>
</tr>
))}
</tbody>
</table>
</Card>
</div>
);
}

View file

@ -0,0 +1,52 @@
import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { Field, SelectField, TextareaField } from "@/components/Field";
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
import { Card, PageHead, Switch } from "@/components/admin/ui";
import { deletePage, savePage } from "../actions";
export default async function EditPage({ params }: { params: Promise<{ id: string }> }) {
await requireAdmin("content.edit");
const { id } = await params;
const page = id === "neu" ? null : await db.page.findUnique({ where: { id } });
if (id !== "neu" && !page) notFound();
return (
<div className="ad-wrap">
<PageHead title={page?.title ?? "Neue Seite"} back={{ href: "/admin/seiten", label: "Seiten" }}>
{page && <a className="sm-btn sm-btn--secondary" href={`/seite/${page.slug}`} target="_blank">Ansehen</a>}
</PageHead>
<AdminForm action={savePage} extraActions={page && <ConfirmButton inForm action={deletePage} confirm="Seite löschen?">Löschen</ConfirmButton>}>
{page && <input type="hidden" name="id" value={page.id} />}
<div className="ad-grid ad-grid--2-1">
<Card title="Inhalt">
<Field label="Titel" name="title" defaultValue={page?.title} required />
<TextareaField label="Text" name="content" defaultValue={page?.content} rows={22} style={{ fontFamily: "var(--font-sans)", minHeight: 420 }} />
</Card>
<div>
<Card title="Einstellungen">
<Switch name="published" label="Veröffentlicht" defaultChecked={page?.published ?? true} />
<SelectField label="Im Fußbereich zeigen" name="showInFooter" defaultValue={page?.showInFooter ?? ""}>
<option value="">Nicht zeigen</option>
<option value="service">Spalte „Service“</option>
<option value="company">Spalte „Über uns“</option>
<option value="legal">Unterste Zeile (Rechtliches)</option>
</SelectField>
<Field label="Web-Adresse" name="slug" defaultValue={page?.slug} hint="Leer lassen für automatisch." />
<Field label="Reihenfolge" name="sort" type="number" defaultValue={page?.sort ?? 0} />
</Card>
<Card title="So formatierst du">
<div className="ad-help">
Leerzeile = neuer Absatz<br />
<code>## Überschrift</code><br />
<code>- Listenpunkt</code><br />
<code>**fett**</code><br />
<code>[Linktext](https://…)</code>
</div>
</Card>
</div>
</div>
</AdminForm>
</div>
);
}

View file

@ -0,0 +1,41 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { assertPermission, audit } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { slugify } from "@/lib/slug";
export async function savePage(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("content.edit");
const id = String(fd.get("id") ?? "");
const title = String(fd.get("title") ?? "").trim();
if (!title) return fail("Bitte gib einen Titel ein.", { title: "Bitte gib einen Titel ein." });
const slug = slugify(String(fd.get("slug") ?? "") || title);
const clash = await db.page.findFirst({ where: { slug, NOT: id ? { id } : undefined } });
if (clash) return fail("Diese Web-Adresse ist schon vergeben.", { slug: "Schon vergeben." });
const footer = String(fd.get("showInFooter") ?? "");
const data = {
title,
slug,
content: String(fd.get("content") ?? ""),
published: fd.get("published") === "on",
showInFooter: ["service", "company", "legal"].includes(footer) ? footer : "",
sort: Math.round(Number(fd.get("sort")) || 0),
};
let pageId = id;
if (id) await db.page.update({ where: { id }, data });
else pageId = (await db.page.create({ data })).id;
await audit(user, id ? "Seite geändert" : "Seite angelegt", title);
revalidatePath("/", "layout");
if (!id) redirect(`/admin/seiten/${pageId}`);
return ok();
}
export async function deletePage(fd: FormData) {
const user = await assertPermission("content.edit");
const p = await db.page.delete({ where: { id: String(fd.get("id")) } });
await audit(user, "Seite gelöscht", p.title);
revalidatePath("/", "layout");
redirect("/admin/seiten");
}

View file

@ -0,0 +1,37 @@
import Link from "next/link";
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { dateFmt } from "@/lib/status";
import { Icon } from "@/components/Icon";
import { Card, PageHead, Pill } from "@/components/admin/ui";
const AREA: Record<string, string> = { service: "Service", company: "Über uns", legal: "Rechtliches", "": "—" };
export default async function PagesPage() {
await requireAdmin("content.edit");
const pages = await db.page.findMany({ orderBy: [{ showInFooter: "asc" }, { sort: "asc" }] });
return (
<div className="ad-wrap ad-wrap--narrow">
<PageHead title="Seiten" lead="Impressum, AGB, Versandinfos und alle anderen Textseiten.">
<Link className="sm-btn sm-btn--primary" href="/admin/seiten/neu"><Icon name="plus" size="sm" /> Seite anlegen</Link>
</PageHead>
<Card flush>
<table className="ad-table">
<thead><tr><th>Titel</th><th>Im Fußbereich</th><th>Geändert</th><th>Status</th></tr></thead>
<tbody>
{pages.map((p) => (
<tr key={p.id}>
<td><Link className="ad-rowlink" href={`/admin/seiten/${p.id}`}>{p.title}</Link><div className="body-sm ad-muted">/seite/{p.slug}</div></td>
<td className="body-sm">{AREA[p.showInFooter]}</td>
<td className="body-sm">{dateFmt.format(p.updatedAt)}</td>
<td>
{p.content.startsWith("Bitte im Admin") ? <Pill tone="gold">Noch ausfüllen</Pill> : <Pill tone={p.published ? "success" : "neutral"}>{p.published ? "Veröffentlicht" : "Entwurf"}</Pill>}
</td>
</tr>
))}
</tbody>
</table>
</Card>
</div>
);
}

View file

@ -0,0 +1,54 @@
import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { dateFmt } from "@/lib/status";
import { PERMISSION_GROUPS } from "@/lib/permissions";
import { Field, SelectField } from "@/components/Field";
import { Alert } from "@/components/shop/Blocks";
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
import { Card, PageHead, Switch } from "@/components/admin/ui";
import { removeMember, updateMember } from "../actions";
export default async function MemberPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ neu?: string }> }) {
const me = await requireAdmin("users.manage");
const [{ id }, { neu }] = await Promise.all([params, searchParams]);
const [m, roles] = await Promise.all([db.user.findUnique({ where: { id }, include: { role: true } }), db.role.findMany({ orderBy: { name: "asc" } })]);
if (!m?.role) notFound();
const locked = m.role.isSystem && !me.role?.isSystem;
const assignable = roles.filter((r) => r.id === m.roleId || me.role?.isSystem || (!r.isSystem && r.permissions.every((p) => me.role!.permissions.includes(p))));
const perms = m.role.isSystem ? null : new Set(m.role.permissions);
return (
<div className="ad-wrap">
<PageHead title={[m.firstName, m.lastName].filter(Boolean).join(" ") || m.email} lead={`${m.email} · im System seit ${dateFmt.format(m.createdAt)}`} back={{ href: "/admin/team", label: "Team" }}>
{m.id !== me.id && !locked && <ConfirmButton action={removeMember} hidden={{ id: m.id }} confirm="Zugang zur Verwaltung entfernen?">Aus dem Team entfernen</ConfirmButton>}
</PageHead>
{neu && <div style={{ marginBottom: "var(--space-5)" }}><Alert kind="success" title="Zugang angelegt.">Gib der Person die E-Mail-Adresse und das Start-Passwort. Sie meldet sich unter /admin/login an.</Alert></div>}
{locked && <div style={{ marginBottom: "var(--space-5)" }}><Alert title="Nur Inhaber können Inhaber bearbeiten." /></div>}
<div className="ad-grid ad-grid--2-1">
<Card title="Zugang">
<AdminForm action={updateMember}>
<input type="hidden" name="id" value={m.id} />
<div className="sm-form-row">
<Field label="Vorname" name="firstName" defaultValue={m.firstName} disabled={locked} />
<Field label="Nachname" name="lastName" defaultValue={m.lastName} disabled={locked} />
</div>
<SelectField label="Rolle" name="roleId" defaultValue={m.roleId ?? ""} disabled={locked}>
{assignable.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
</SelectField>
<Field label="Neues Passwort" optional name="password" type="text" autoComplete="off" disabled={locked} hint="Leer lassen, um es nicht zu ändern." />
<Switch name="active" label="Zugang aktiv" hint="Ausgeschaltet kann sich die Person nicht mehr anmelden." defaultChecked={m.active} />
</AdminForm>
</Card>
<Card title={`Rechte als ${m.role.name}`}>
{perms === null ? (
<p className="body" style={{ margin: 0 }}>Inhaber dürfen alles.</p>
) : (
<ul style={{ margin: 0, paddingLeft: "1.2em" }} className="body-sm">
{PERMISSION_GROUPS.flatMap((g) => [...g.permissions] as { key: string; label: string }[]).filter((p) => perms.has(p.key)).map((p) => <li key={p.key}>{p.label}</li>)}
</ul>
)}
</Card>
</div>
</div>
);
}

View file

@ -0,0 +1,84 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import { db } from "@/lib/db";
import { assertPermission, audit, hashPassword, type CurrentUser } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
/** Darf `actor` diese Rolle vergeben? Nur Inhaber vergeben Inhaber; sonst nur Rollen mit Rechten, die man selbst hat. */
async function canAssign(actor: CurrentUser, roleId: string) {
const role = await db.role.findUnique({ where: { id: roleId } });
if (!role) return false;
if (actor.role?.isSystem) return true;
if (role.isSystem) return false;
return role.permissions.every((p) => actor.role!.permissions.includes(p));
}
async function ownerCount(excludeUserId?: string) {
return db.user.count({ where: { active: true, role: { isSystem: true }, NOT: excludeUserId ? { id: excludeUserId } : undefined } });
}
export async function inviteMember(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const actor = await assertPermission("users.manage");
const email = z.email().safeParse(String(fd.get("email") ?? "").trim().toLowerCase());
if (!email.success) return fail("Bitte gib eine gültige E-Mail-Adresse ein.", { email: "Ungültig" });
const password = String(fd.get("password") ?? "");
const roleId = String(fd.get("roleId") ?? "");
if (!(await canAssign(actor, roleId))) return fail("Diese Rolle darfst du nicht vergeben.", { roleId: "Nicht erlaubt" });
const existing = await db.user.findUnique({ where: { email: email.data } });
if (existing?.roleId) return fail("Diese Person ist schon im Team.", { email: "Schon im Team" });
if (!existing && password.length < 10) return fail("Das Start-Passwort braucht mindestens 10 Zeichen.", { password: "Zu kurz" });
const data = { firstName: String(fd.get("firstName") ?? "").trim(), lastName: String(fd.get("lastName") ?? "").trim(), roleId, active: true };
const user = existing
? await db.user.update({ where: { id: existing.id }, data })
: await db.user.create({ data: { ...data, email: email.data, passwordHash: await hashPassword(password) } });
await audit(actor, "Team-Mitglied hinzugefügt", user.email);
revalidatePath("/admin/team");
redirect(`/admin/team/${user.id}?neu=1`);
}
export async function updateMember(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const actor = await assertPermission("users.manage");
const id = String(fd.get("id"));
const target = await db.user.findUnique({ where: { id }, include: { role: true } });
if (!target?.roleId) return fail("Team-Mitglied nicht gefunden.");
if (target.role?.isSystem && !actor.role?.isSystem) return fail("Nur Inhaber können Inhaber bearbeiten.");
const roleId = String(fd.get("roleId") ?? "");
const active = fd.get("active") === "on";
if (roleId !== target.roleId && !(await canAssign(actor, roleId))) return fail("Diese Rolle darfst du nicht vergeben.");
const newRole = await db.role.findUnique({ where: { id: roleId } });
if (target.role?.isSystem && (!newRole?.isSystem || !active) && (await ownerCount(target.id)) === 0) {
return fail("Es muss mindestens ein aktiver Inhaber bleiben.");
}
const password = String(fd.get("password") ?? "");
if (password && password.length < 10) return fail("Das neue Passwort braucht mindestens 10 Zeichen.", { password: "Zu kurz" });
await db.user.update({
where: { id },
data: {
firstName: String(fd.get("firstName") ?? "").trim(),
lastName: String(fd.get("lastName") ?? "").trim(),
roleId,
active,
...(password ? { passwordHash: await hashPassword(password) } : {}),
},
});
if ((!active || password) && id !== actor.id) await db.session.deleteMany({ where: { userId: id } });
await audit(actor, "Team-Mitglied geändert", `${target.email}: Rolle ${newRole?.name}${active ? "" : ", deaktiviert"}${password ? ", Passwort neu gesetzt" : ""}`);
revalidatePath("/admin/team");
return ok();
}
export async function removeMember(fd: FormData) {
const actor = await assertPermission("users.manage");
const id = String(fd.get("id"));
const target = await db.user.findUnique({ where: { id }, include: { role: true } });
if (!target || id === actor.id) return;
if (target.role?.isSystem && (!actor.role?.isSystem || (await ownerCount(id)) === 0)) return;
// Konto bleibt als Kundenkonto bestehen, nur der Admin-Zugang entfällt
await db.user.update({ where: { id }, data: { roleId: null } });
await db.session.deleteMany({ where: { userId: id } });
await audit(actor, "Aus dem Team entfernt", target.email);
revalidatePath("/admin/team");
redirect("/admin/team");
}

View file

@ -0,0 +1,56 @@
import Link from "next/link";
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { dateFmt } from "@/lib/status";
import { Field, SelectField } from "@/components/Field";
import { AdminForm } from "@/components/admin/AdminForm";
import { Card, PageHead, Pill } from "@/components/admin/ui";
import { inviteMember } from "./actions";
export default async function TeamPage() {
const me = await requireAdmin("users.manage");
const [members, roles] = await Promise.all([
db.user.findMany({ where: { roleId: { not: null } }, include: { role: true }, orderBy: { createdAt: "asc" } }),
db.role.findMany({ orderBy: { name: "asc" } }),
]);
const assignable = roles.filter((r) => me.role?.isSystem || (!r.isSystem && r.permissions.every((p) => me.role!.permissions.includes(p))));
return (
<div className="ad-wrap">
<PageHead title="Team" lead="Wer Zugang zur Verwaltung hat. Was jemand darf, bestimmt die Rolle." >
<Link className="sm-btn sm-btn--secondary" href="/admin/rollen">Rollen & Rechte</Link>
</PageHead>
<div className="ad-grid ad-grid--2-1">
<Card flush title={`${members.length} Mitglieder`}>
<div className="ad-table-wrap">
<table className="ad-table">
<thead><tr><th>Name</th><th>Rolle</th><th>Zuletzt angemeldet</th><th>Status</th></tr></thead>
<tbody>
{members.map((m) => (
<tr key={m.id}>
<td><Link className="ad-rowlink" href={`/admin/team/${m.id}`}>{[m.firstName, m.lastName].filter(Boolean).join(" ") || m.email}</Link>{m.id === me.id && " (du)"}<div className="body-sm ad-muted">{m.email}</div></td>
<td>{m.role?.name}</td>
<td className="body-sm">{m.lastLoginAt ? dateFmt.format(m.lastLoginAt) : "noch nie"}</td>
<td><Pill tone={m.active ? "success" : "neutral"}>{m.active ? "Aktiv" : "Gesperrt"}</Pill></td>
</tr>
))}
</tbody>
</table>
</div>
</Card>
<Card title="Person hinzufügen" lead="Lege einen Zugang an und gib das Start-Passwort persönlich weiter.">
<AdminForm action={inviteMember} submitLabel="Hinzufügen">
<div className="sm-form-row">
<Field label="Vorname" name="firstName" />
<Field label="Nachname" name="lastName" />
</div>
<Field label="E-Mail-Adresse" name="email" type="email" required />
<Field label="Start-Passwort" name="password" type="text" autoComplete="off" hint="Mindestens 10 Zeichen. Hat die Person schon ein Kundenkonto, bleibt ihr Passwort." />
<SelectField label="Rolle" name="roleId" defaultValue={assignable.find((r) => !r.isSystem)?.id}>
{assignable.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
</SelectField>
</AdminForm>
</Card>
</div>
</div>
);
}

View file

@ -0,0 +1,37 @@
"use server";
import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";
import { assertPermission, audit } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { parsePrice } from "@/lib/money";
import { COUNTRIES } from "@/lib/settings";
export async function saveShippingMethod(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("shipping.edit");
const id = String(fd.get("id") ?? "");
const name = String(fd.get("name") ?? "").trim();
if (!name) return fail("Bitte gib einen Namen ein.", { name: "Pflichtfeld" });
const price = parsePrice(String(fd.get("price")));
if (price == null) return fail("Bitte gib einen Preis ein (0 für kostenlos).", { price: "Ungültig" });
const data = {
name,
description: String(fd.get("description") ?? ""),
price,
freeFrom: parsePrice(String(fd.get("freeFrom") ?? "")) ?? 0,
countries: fd.getAll("countries").map(String).filter((c) => c in COUNTRIES),
enabled: fd.get("enabled") === "on",
sort: Math.round(Number(fd.get("sort")) || 0),
};
if (id) await db.shippingMethod.update({ where: { id }, data });
else await db.shippingMethod.create({ data });
await audit(user, id ? "Versandart geändert" : "Versandart angelegt", name);
revalidatePath("/admin/versand");
return ok(id ? "Gespeichert." : "Versandart angelegt.");
}
export async function deleteShippingMethod(fd: FormData) {
const user = await assertPermission("shipping.edit");
const m = await db.shippingMethod.delete({ where: { id: String(fd.get("id")) } });
await audit(user, "Versandart gelöscht", m.name);
revalidatePath("/admin/versand");
}

View file

@ -0,0 +1,62 @@
import type { ShippingMethod } from "@prisma/client";
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { centsToInput, formatPrice } from "@/lib/money";
import { COUNTRIES, getSettings } from "@/lib/settings";
import { Field, TextareaField } from "@/components/Field";
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
import { PageHead, Pill, Switch } from "@/components/admin/ui";
import { deleteShippingMethod, saveShippingMethod } from "./actions";
function Fields({ m, countries }: { m?: ShippingMethod; countries: string[] }) {
return (
<>
{m && <input type="hidden" name="id" value={m.id} />}
<Field label="Name" name="name" defaultValue={m?.name} placeholder="z. B. Standardversand (DHL)" required />
<TextareaField label="Beschreibung" optional name="description" defaultValue={m?.description} rows={2} hint="Sehen Kunden bei der Auswahl, z. B. die Lieferzeit." />
<div className="sm-form-row">
<Field label="Preis in €" name="price" inputMode="decimal" defaultValue={m ? centsToInput(m.price) : ""} required />
<Field label="Kostenlos ab Warenwert in €" optional name="freeFrom" inputMode="decimal" defaultValue={m?.freeFrom ? centsToInput(m.freeFrom) : ""} hint="Leer = nie kostenlos" />
</div>
<span className="sm-field__label" style={{ marginTop: "var(--space-4)" }}>Gilt für</span>
<div className="ad-perm-grid">
{countries.map((c) => (
<label className="sm-check" key={c}><input type="checkbox" name="countries" value={c} defaultChecked={m ? m.countries.includes(c) : c === "DE"} /><span className="sm-check__text">{COUNTRIES[c] ?? c}</span></label>
))}
</div>
<Field label="Reihenfolge" name="sort" type="number" defaultValue={m?.sort ?? 0} />
<Switch name="enabled" label="Aktiv" defaultChecked={m?.enabled ?? true} />
</>
);
}
export default async function ShippingPage() {
await requireAdmin("shipping.edit");
const [methods, settings] = await Promise.all([db.shippingMethod.findMany({ orderBy: { sort: "asc" } }), getSettings()]);
const countries = settings.checkout.countries;
return (
<div className="ad-wrap ad-wrap--narrow">
<PageHead title="Versand" lead="Versandarten und ihre Kosten. Kunden wählen in der Kasse aus den aktiven Arten für ihr Land." />
{methods.map((m) => (
<details className="ad-card" key={m.id} style={{ marginBottom: "var(--space-3)" }}>
<summary className="ad-card__head" style={{ cursor: "pointer", listStyle: "none" }}>
<div>
<h2>{m.name}</h2>
<p>{formatPrice(m.price)}{m.freeFrom ? ` · kostenlos ab ${formatPrice(m.freeFrom)}` : ""} · {m.countries.map((c) => COUNTRIES[c] ?? c).join(", ")}</p>
</div>
<Pill tone={m.enabled ? "success" : "neutral"}>{m.enabled ? "Aktiv" : "Aus"}</Pill>
</summary>
<div className="ad-card__body">
<AdminForm action={saveShippingMethod} extraActions={<ConfirmButton inForm action={deleteShippingMethod} confirm="Versandart löschen?">Löschen</ConfirmButton>}>
<Fields m={m} countries={countries} />
</AdminForm>
</div>
</details>
))}
<section className="ad-card" style={{ marginTop: "var(--space-6)" }}>
<div className="ad-card__head"><h2>Neue Versandart</h2></div>
<div className="ad-card__body"><AdminForm action={saveShippingMethod} submitLabel="Versandart anlegen"><Fields countries={countries} /></AdminForm></div>
</section>
</div>
);
}

View file

@ -0,0 +1,94 @@
"use server";
import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";
import { assertPermission, audit } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { parsePrice } from "@/lib/money";
import { getDefinition } from "@/lib/payments/catalog";
import { getCredentials, saveCredentials } from "@/lib/payments/credentials";
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
export async function saveProviderCredentials(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("payments.edit");
const current = await getCredentials();
// Leere Geheimfelder behalten den gespeicherten Wert
const keep = (v: string, old: string) => (v ? v : old);
const stripeSecret = keep(str(fd, "stripeSecretKey"), current.stripe.secretKey);
if (stripeSecret && !/^(sk|rk)_(test|live)_/.test(stripeSecret)) return fail("Der Stripe-Geheimschlüssel beginnt mit sk_live_ oder sk_test_.", { stripeSecretKey: "Ungültiges Format" });
await saveCredentials({
stripe: {
publishableKey: str(fd, "stripePublishableKey"),
secretKey: fd.get("stripeClear") === "on" ? "" : stripeSecret,
webhookSecret: fd.get("stripeClear") === "on" ? "" : keep(str(fd, "stripeWebhookSecret"), current.stripe.webhookSecret),
},
paypal: {
clientId: str(fd, "paypalClientId"),
clientSecret: fd.get("paypalClear") === "on" ? "" : keep(str(fd, "paypalClientSecret"), current.paypal.clientSecret),
sandbox: fd.get("paypalSandbox") === "on",
},
});
await audit(user, "Zahlungs-Zugangsdaten geändert");
revalidatePath("/admin/zahlung");
return ok("Zugangsdaten gespeichert.");
}
export async function testProvider(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
await assertPermission("payments.edit");
const provider = str(fd, "provider");
const c = await getCredentials();
try {
if (provider === "stripe") {
if (!c.stripe.secretKey) return fail("Es ist noch kein Stripe-Schlüssel gespeichert.");
const res = await fetch("https://api.stripe.com/v1/balance", { headers: { Authorization: `Bearer ${c.stripe.secretKey}` }, cache: "no-store" });
const data = await res.json();
if (!res.ok) return fail(`Stripe lehnt ab: ${data?.error?.message ?? res.status}`);
return ok(`Stripe verbunden (${data.livemode ? "Live-Modus" : "Testmodus"}).`);
}
if (provider === "paypal") {
if (!c.paypal.clientId || !c.paypal.clientSecret) return fail("Es sind noch keine PayPal-Zugangsdaten gespeichert.");
const base = c.paypal.sandbox ? "https://api-m.sandbox.paypal.com" : "https://api-m.paypal.com";
const res = await fetch(`${base}/v1/oauth2/token`, {
method: "POST",
headers: { Authorization: "Basic " + Buffer.from(`${c.paypal.clientId}:${c.paypal.clientSecret}`).toString("base64"), "Content-Type": "application/x-www-form-urlencoded" },
body: "grant_type=client_credentials",
cache: "no-store",
});
if (!res.ok) return fail("PayPal lehnt die Zugangsdaten ab. Prüfe Client-ID, Secret und den Sandbox-Schalter.");
return ok(`PayPal verbunden (${c.paypal.sandbox ? "Sandbox" : "Live"}).`);
}
} catch (e) {
return fail(`Keine Verbindung: ${e instanceof Error ? e.message : e}`);
}
return fail("Unbekannter Anbieter.");
}
export async function savePaymentMethod(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("payments.edit");
const id = str(fd, "id");
const method = await db.paymentMethod.findUnique({ where: { id } });
if (!method) return fail("Zahlungsart nicht gefunden.");
const def = getDefinition(method.code);
const config: Record<string, string> = {};
for (const f of def?.fields ?? []) config[f.key] = str(fd, `cfg_${f.key}`);
const enabled = fd.get("enabled") === "on";
if (enabled && method.code === "prepayment" && !config.iban) return fail("Für Vorkasse brauchen Kunden deine IBAN.", { cfg_iban: "Bitte eintragen" });
await db.paymentMethod.update({
where: { id },
data: {
name: str(fd, "name") || def?.defaultName || method.name,
description: str(fd, "description"),
enabled,
fee: parsePrice(str(fd, "fee")) ?? 0,
minTotal: parsePrice(str(fd, "minTotal")) ?? 0,
maxTotal: parsePrice(str(fd, "maxTotal")) ?? 0,
loggedInOnly: fd.get("loggedInOnly") === "on",
sort: Math.round(Number(fd.get("sort")) || 0),
config,
},
});
await audit(user, "Zahlungsart geändert", `${method.name}: ${enabled ? "aktiv" : "aus"}`);
revalidatePath("/admin/zahlung");
revalidatePath("/", "layout");
return ok();
}

View file

@ -0,0 +1,86 @@
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
import { centsToInput, formatPrice } from "@/lib/money";
import { getDefinition } from "@/lib/payments/catalog";
import { getCredentials, isProviderReady, mask } from "@/lib/payments/credentials";
import { Field, TextareaField } from "@/components/Field";
import { AdminForm } from "@/components/admin/AdminForm";
import { TestButton } from "@/components/admin/TestButton";
import { Card, PageHead, Pill, Switch } from "@/components/admin/ui";
import { savePaymentMethod, saveProviderCredentials, testProvider } from "./actions";
export default async function PaymentsPage() {
await requireAdmin("payments.edit");
const [methods, creds] = await Promise.all([db.paymentMethod.findMany({ orderBy: { sort: "asc" } }), getCredentials()]);
const appUrl = (process.env.APP_URL ?? "https://sanamare.maaxxs-coding.de").replace(/\/$/, "");
return (
<div className="ad-wrap ad-wrap--narrow">
<PageHead title="Zahlungsarten" lead="Schalte Zahlungsarten ein und aus. Online-Zahlungen brauchen einmalig die Zugangsdaten des Anbieters." />
<h2 className="display-sm" style={{ margin: "0 0 var(--space-4)" }}>Zugangsdaten</h2>
<AdminForm action={saveProviderCredentials} submitLabel="Zugangsdaten speichern">
<Card title="Stripe" lead="Für Kreditkarte, Apple Pay, Google Pay, Klarna und SEPA-Lastschrift." action={<Pill tone={creds.stripe.secretKey ? "success" : "neutral"}>{creds.stripe.secretKey ? (creds.stripe.secretKey.includes("_test_") ? "Testmodus" : "Live") : "Nicht verbunden"}</Pill>}>
<Field label="Veröffentlichbarer Schlüssel" optional name="stripePublishableKey" defaultValue={creds.stripe.publishableKey} placeholder="pk_live_…" />
<Field label="Geheimschlüssel" name="stripeSecretKey" type="password" autoComplete="off" placeholder={creds.stripe.secretKey ? mask(creds.stripe.secretKey) : "sk_live_… oder sk_test_…"} hint={creds.stripe.secretKey ? "Leer lassen, um den gespeicherten Schlüssel zu behalten." : "Findest du im Stripe-Dashboard unter Entwickler → API-Schlüssel."} />
<Field label="Webhook-Signaturschlüssel" optional name="stripeWebhookSecret" type="password" autoComplete="off" placeholder={creds.stripe.webhookSecret ? mask(creds.stripe.webhookSecret) : "whsec_…"} />
<div className="ad-help" style={{ marginTop: "var(--space-4)" }}>
Webhook in Stripe anlegen mit der Adresse <code>{appUrl}/api/webhooks/stripe</code> und den Ereignissen <code>checkout.session.completed</code>, <code>checkout.session.async_payment_succeeded</code> und <code>checkout.session.async_payment_failed</code>. Nötig vor allem für SEPA, weil die Bestätigung dort später kommt.
</div>
{creds.stripe.secretKey && <label className="sm-check" style={{ marginTop: "var(--space-3)" }}><input type="checkbox" name="stripeClear" /><span className="sm-check__text">Stripe-Verbindung entfernen</span></label>}
</Card>
<Card title="PayPal" lead="Für die Zahlungsart PayPal." action={<Pill tone={creds.paypal.clientSecret ? "success" : "neutral"}>{creds.paypal.clientSecret ? (creds.paypal.sandbox ? "Sandbox" : "Live") : "Nicht verbunden"}</Pill>}>
<Field label="Client-ID" name="paypalClientId" defaultValue={creds.paypal.clientId} hint="Aus dem PayPal-Entwicklerbereich unter Apps & Zugangsdaten." />
<Field label="Secret" name="paypalClientSecret" type="password" autoComplete="off" placeholder={creds.paypal.clientSecret ? mask(creds.paypal.clientSecret) : ""} hint={creds.paypal.clientSecret ? "Leer lassen, um das gespeicherte Secret zu behalten." : undefined} />
<Switch name="paypalSandbox" label="Sandbox (Testmodus)" hint="Ausschalten, sobald echte Zahlungen ankommen sollen." defaultChecked={creds.paypal.sandbox} />
{creds.paypal.clientSecret && <label className="sm-check"><input type="checkbox" name="paypalClear" /><span className="sm-check__text">PayPal-Verbindung entfernen</span></label>}
</Card>
</AdminForm>
<div style={{ display: "flex", gap: "var(--space-5)", flexWrap: "wrap", margin: "var(--space-2) 0 var(--space-8)" }}>
<div><span className="label">Stripe</span><TestButton action={testProvider} provider="stripe" /></div>
<div><span className="label">PayPal</span><TestButton action={testProvider} provider="paypal" /></div>
</div>
<h2 className="display-sm" style={{ margin: "0 0 var(--space-4)" }}>Zahlungsarten im Shop</h2>
{methods.map((m) => {
const def = getDefinition(m.code);
const ready = isProviderReady(def?.provider ?? "manual", creds);
const cfg = (m.config ?? {}) as Record<string, string>;
return (
<details className="ad-card" key={m.id} style={{ marginBottom: "var(--space-3)" }}>
<summary className="ad-card__head" style={{ cursor: "pointer", listStyle: "none" }}>
<div>
<h2>{m.name}</h2>
<p>{def?.adminHint}{m.fee ? ` · Gebühr ${formatPrice(m.fee)}` : ""}</p>
</div>
{!ready ? <Pill tone="gold">Zugang fehlt</Pill> : <Pill tone={m.enabled ? "success" : "neutral"}>{m.enabled ? "Aktiv" : "Aus"}</Pill>}
</summary>
<div className="ad-card__body">
<AdminForm action={savePaymentMethod}>
<input type="hidden" name="id" value={m.id} />
<Switch name="enabled" label="Im Shop anbieten" hint={ready ? undefined : "Wird erst angezeigt, wenn die Zugangsdaten oben gespeichert sind."} defaultChecked={m.enabled} />
<Field label="Name im Shop" name="name" defaultValue={m.name} />
<TextareaField label="Beschreibung" name="description" defaultValue={m.description} rows={2} />
{def?.fields.map((f) =>
f.type === "textarea" ? (
<TextareaField key={f.key} label={f.label} name={`cfg_${f.key}`} defaultValue={cfg[f.key] ?? ""} hint={f.hint} />
) : (
<Field key={f.key} label={f.label} name={`cfg_${f.key}`} type={f.type} defaultValue={cfg[f.key] ?? ""} hint={f.hint} />
),
)}
<div className="sm-form-row">
<Field label="Gebühr in €" optional name="fee" inputMode="decimal" defaultValue={m.fee ? centsToInput(m.fee) : ""} />
<Field label="Reihenfolge" name="sort" type="number" defaultValue={m.sort} />
</div>
<div className="sm-form-row">
<Field label="Ab Bestellwert in €" optional name="minTotal" inputMode="decimal" defaultValue={m.minTotal ? centsToInput(m.minTotal) : ""} />
<Field label="Bis Bestellwert in €" optional name="maxTotal" inputMode="decimal" defaultValue={m.maxTotal ? centsToInput(m.maxTotal) : ""} />
</div>
<Switch name="loggedInOnly" label="Nur für angemeldete Kunden" hint="Sinnvoll für Kauf auf Rechnung." defaultChecked={m.loggedInOnly} />
</AdminForm>
</div>
</details>
);
})}
</div>
);
}

View file

@ -55,7 +55,7 @@ export function AdminForm({
); );
} }
/** Kleiner Knopf, der eine Server-Action mit Rückfrage ausführt (z. B. Löschen). */ /** Knopf mit Rückfrage (z. B. Löschen). `inForm`: sitzt in einem anderen Formular und nutzt dessen Felder. */
export function ConfirmButton({ export function ConfirmButton({
action, action,
confirm, confirm,
@ -63,6 +63,7 @@ export function ConfirmButton({
className = "sm-btn sm-btn--ghost", className = "sm-btn sm-btn--ghost",
hidden, hidden,
title, title,
inForm,
}: { }: {
action: (fd: FormData) => Promise<void>; action: (fd: FormData) => Promise<void>;
confirm: string; confirm: string;
@ -70,20 +71,23 @@ export function ConfirmButton({
className?: string; className?: string;
hidden?: Record<string, string>; hidden?: Record<string, string>;
title?: string; title?: string;
inForm?: boolean;
}) { }) {
const [armed, setArmed] = useState(false); const [armed, setArmed] = useState(false);
const inner = armed ? (
<span style={{ display: "inline-flex", gap: 8, alignItems: "center" }}>
<span className="body-sm">{confirm}</span>
<button className="sm-btn sm-btn--sm" type="submit" formAction={action} formNoValidate style={{ background: "var(--danger)", color: "var(--surface-raised)", borderColor: "var(--danger)" }}>Ja</button>
<button className="sm-btn sm-btn--sm sm-btn--secondary" type="button" onClick={() => setArmed(false)}>Nein</button>
</span>
) : (
<button className={className} type="button" onClick={() => setArmed(true)} title={title} aria-label={title}>{children}</button>
);
if (inForm) return inner;
return ( return (
<form action={action} style={{ display: "inline" }}> <form action={action} style={{ display: "inline" }}>
{hidden && Object.entries(hidden).map(([k, v]) => <input key={k} type="hidden" name={k} value={v} />)} {hidden && Object.entries(hidden).map(([k, v]) => <input key={k} type="hidden" name={k} value={v} />)}
{armed ? ( {inner}
<span style={{ display: "inline-flex", gap: 8, alignItems: "center" }}>
<span className="body-sm">{confirm}</span>
<button className="sm-btn sm-btn--sm" type="submit" style={{ background: "var(--danger)", color: "var(--surface-raised)", borderColor: "var(--danger)" }}>Ja</button>
<button className="sm-btn sm-btn--sm sm-btn--secondary" type="button" onClick={() => setArmed(false)}>Nein</button>
</span>
) : (
<button className={className} type="button" onClick={() => setArmed(true)} title={title} aria-label={title}>{children}</button>
)}
</form> </form>
); );
} }

View file

@ -0,0 +1,60 @@
"use client";
/* eslint-disable @next/next/no-img-element */
import { useRef, useState } from "react";
import { uploadImages } from "@/lib/upload";
import { Icon } from "../Icon";
export function ImageManager({ name, initial, multiple = true }: { name: string; initial: string[]; multiple?: boolean }) {
const [images, setImages] = useState<string[]>(initial);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const input = useRef<HTMLInputElement>(null);
async function onFiles(files: FileList | null) {
if (!files?.length) return;
setBusy(true);
setError(null);
const fd = new FormData();
for (const f of Array.from(files)) fd.append("files", f);
const res = await uploadImages(fd);
setBusy(false);
if (res.error) setError(res.error);
setImages((cur) => (multiple ? [...cur, ...res.urls] : res.urls.slice(0, 1).length ? res.urls.slice(0, 1) : cur));
if (input.current) input.current.value = "";
}
const move = (i: number, d: number) =>
setImages((cur) => {
const next = [...cur];
const j = i + d;
if (j < 0 || j >= next.length) return cur;
[next[i], next[j]] = [next[j], next[i]];
return next;
});
return (
<div>
<input type="hidden" name={name} value={JSON.stringify(images)} />
<div className="ad-images">
{images.map((src, i) => (
<div className="ad-image" key={src + i}>
<img src={src} alt="" />
{multiple && i === 0 && <span className="ad-image__first">Hauptbild</span>}
<div className="ad-image__actions">
{multiple && i > 0 && <button type="button" onClick={() => move(i, -1)} aria-label="Nach vorne"><Icon name="arrowLeft" size="sm" /></button>}
<button type="button" onClick={() => setImages((c) => c.filter((_, j) => j !== i))} aria-label="Bild entfernen"><Icon name="trash" size="sm" /></button>
</div>
</div>
))}
{(multiple || images.length === 0) && (
<label className="ad-upload">
<Icon name="image" />
{busy ? "Lädt hoch …" : multiple ? "Bilder hinzufügen" : "Bild wählen"}
<input ref={input} type="file" accept="image/jpeg,image/png,image/webp,image/gif" multiple={multiple} hidden onChange={(e) => onFiles(e.target.files)} />
</label>
)}
</div>
{error && <span className="sm-field__error" role="alert"><Icon name="alert" /> {error}</span>}
{multiple && <p className="caption ad-muted" style={{ marginTop: "var(--space-2)" }}>Das erste Bild ist das Hauptbild. Empfohlenes Format 4:5, z. B. 1600 × 2000 px.</p>}
</div>
);
}

View file

@ -0,0 +1,76 @@
"use client";
import { useState } from "react";
import type { NavLink, TrustItem } from "@/lib/settings";
import { Icon } from "../Icon";
function moveItem<T>(list: T[], i: number, d: number) {
const j = i + d;
if (j < 0 || j >= list.length) return list;
const next = [...list];
[next[i], next[j]] = [next[j], next[i]];
return next;
}
export function NavEditor({ name, initial }: { name: string; initial: NavLink[] }) {
const [items, setItems] = useState(initial);
const set = (i: number, k: keyof NavLink, v: string) => setItems((l) => l.map((x, j) => (j === i ? { ...x, [k]: v } : x)));
return (
<div>
<input type="hidden" name={name} value={JSON.stringify(items.filter((i) => i.label.trim()))} />
<table className="ad-variants">
<thead><tr><th>Text</th><th>Ziel (z. B. /shop oder /kategorie/matten)</th><th /></tr></thead>
<tbody>
{items.map((it, i) => (
<tr key={i}>
<td><input className="sm-input" value={it.label} onChange={(e) => set(i, "label", e.target.value)} aria-label="Text" /></td>
<td><input className="sm-input" value={it.href} onChange={(e) => set(i, "href", e.target.value)} aria-label="Ziel" /></td>
<td style={{ whiteSpace: "nowrap" }}>
<button type="button" className="ad-iconbtn" onClick={() => setItems((l) => moveItem(l, i, -1))} aria-label="Nach oben" disabled={i === 0}><Icon name="arrowLeft" className="rot90" /></button>{" "}
<button type="button" className="ad-iconbtn ad-iconbtn--danger" onClick={() => setItems((l) => l.filter((_, j) => j !== i))} aria-label="Entfernen"><Icon name="trash" /></button>
</td>
</tr>
))}
</tbody>
</table>
<button type="button" className="sm-btn sm-btn--secondary sm-btn--sm" style={{ marginTop: "var(--space-3)" }} onClick={() => setItems((l) => [...l, { label: "", href: "/" }])}>
<Icon name="plus" size="sm" /> Menüpunkt hinzufügen
</button>
</div>
);
}
const ICONS: { value: TrustItem["icon"]; label: string }[] = [
{ value: "truck", label: "Lieferwagen" },
{ value: "return", label: "Rückgabe" },
{ value: "lock", label: "Schloss" },
{ value: "chat", label: "Sprechblase" },
{ value: "leaf", label: "Blatt" },
{ value: "star", label: "Stern" },
];
export function TrustEditor({ name, initial }: { name: string; initial: TrustItem[] }) {
const [items, setItems] = useState(initial);
const set = (i: number, k: keyof TrustItem, v: string) => setItems((l) => l.map((x, j) => (j === i ? { ...x, [k]: v } : x)));
return (
<div>
<input type="hidden" name={name} value={JSON.stringify(items.filter((i) => i.title.trim()))} />
{items.map((it, i) => (
<div key={i} style={{ display: "grid", gridTemplateColumns: "140px 1fr 1.4fr auto", gap: 8, marginBottom: 8, alignItems: "center" }}>
<span className="sm-select-wrap">
<select className="sm-select" value={it.icon} onChange={(e) => set(i, "icon", e.target.value)} aria-label="Symbol" style={{ minHeight: "var(--control-height-sm)" }}>
{ICONS.map((ic) => <option key={ic.value} value={ic.value}>{ic.label}</option>)}
</select>
</span>
<input className="sm-input" style={{ minHeight: "var(--control-height-sm)" }} value={it.title} onChange={(e) => set(i, "title", e.target.value)} placeholder="Titel" aria-label="Titel" />
<input className="sm-input" style={{ minHeight: "var(--control-height-sm)" }} value={it.text} onChange={(e) => set(i, "text", e.target.value)} placeholder="Text" aria-label="Text" />
<button type="button" className="ad-iconbtn ad-iconbtn--danger" onClick={() => setItems((l) => l.filter((_, j) => j !== i))} aria-label="Entfernen"><Icon name="trash" /></button>
</div>
))}
{items.length < 4 && (
<button type="button" className="sm-btn sm-btn--secondary sm-btn--sm" onClick={() => setItems((l) => [...l, { icon: "star", title: "", text: "" }])}>
<Icon name="plus" size="sm" /> Versprechen hinzufügen
</button>
)}
</div>
);
}

View file

@ -0,0 +1,43 @@
"use client";
import { useState } from "react";
import { PERMISSION_GROUPS } from "@/lib/permissions";
export function PermissionPicker({ initial, allowed, disabled }: { initial: string[]; allowed: string[] | null; disabled?: boolean }) {
const [selected, setSelected] = useState(new Set(initial));
const toggle = (k: string, on: boolean) =>
setSelected((s) => {
const n = new Set(s);
if (on) n.add(k);
else n.delete(k);
return n;
});
const canTouch = (k: string) => !disabled && (allowed === null || allowed.includes(k) || initial.includes(k));
return (
<div>
{PERMISSION_GROUPS.map((g) => {
const keys = g.permissions.map((p) => p.key as string);
const all = keys.every((k) => selected.has(k));
return (
<fieldset className="ad-perm-group" key={g.label}>
<legend>{g.label}</legend>
<div style={{ display: "flex", justifyContent: "flex-end", marginTop: -8 }}>
{!disabled && (
<button type="button" className="body-sm" style={{ background: "none", border: 0, color: "var(--link)", cursor: "pointer", padding: 4 }} onClick={() => keys.filter(canTouch).forEach((k) => toggle(k, !all))}>
{all ? "Keine" : "Alle"}
</button>
)}
</div>
<div className="ad-perm-grid">
{g.permissions.map((p) => (
<label className="sm-check" key={p.key} style={{ opacity: canTouch(p.key) ? 1 : 0.55 }}>
<input type="checkbox" name="permissions" value={p.key} checked={selected.has(p.key)} disabled={!canTouch(p.key)} onChange={(e) => toggle(p.key, e.target.checked)} />
<span className="sm-check__text">{p.label}</span>
</label>
))}
</div>
</fieldset>
);
})}
</div>
);
}

View file

@ -0,0 +1,118 @@
"use client";
import type { Category } from "@prisma/client";
import { saveProduct } from "@/app/admin/(panel)/produkte/actions";
import { Field, SelectField, TextareaField } from "../Field";
import { Icon } from "../Icon";
import { AdminForm } from "./AdminForm";
import { ImageManager } from "./ImageManager";
import { VariantEditor, type VariantRow } from "./VariantEditor";
export type ProductFormValues = {
id?: string;
name: string;
slug: string;
subtitle: string;
description: string;
details: string;
sku: string;
price: string;
compareAtPrice: string;
taxRate: number;
stock: number;
trackStock: boolean;
active: boolean;
featured: boolean;
badge: string;
categoryId: string;
images: string[];
variants: VariantRow[];
};
export function ProductForm({ values, categories, canStock }: { values: ProductFormValues; categories: Category[]; canStock: boolean }) {
return (
<AdminForm action={saveProduct} submitLabel={values.id ? "Änderungen speichern" : "Produkt anlegen"}>
{(state) => {
const e = state?.errors ?? {};
return (
<div className="ad-grid ad-grid--2-1">
<div>
{values.id && <input type="hidden" name="id" value={values.id} />}
<section className="ad-card">
<div className="ad-card__head"><h2>Grunddaten</h2></div>
<div className="ad-card__body">
<Field label="Name" name="name" defaultValue={values.name} error={e.name} placeholder="z. B. Reformer Matte Pro" required />
<Field label="Kurzbeschreibung" optional name="subtitle" defaultValue={values.subtitle} hint="Steht unter dem Namen, z. B. „Anthrazit · 8 mm“." />
<TextareaField label="Beschreibung" name="description" defaultValue={values.description} rows={6} />
<TextareaField label="Material & Pflege" optional name="details" defaultValue={values.details} rows={3} />
</div>
</section>
<section className="ad-card">
<div className="ad-card__head"><div><h2>Bilder</h2><p>Ziehen ist nicht nötig: Mit dem Pfeil rückt ein Bild nach vorne.</p></div></div>
<div className="ad-card__body"><ImageManager name="images" initial={values.images} /></div>
</section>
<section className="ad-card">
<div className="ad-card__head"><h2>Preis</h2></div>
<div className="ad-card__body">
<div className="sm-form-row">
<Field label="Preis in € (brutto)" name="price" inputMode="decimal" defaultValue={values.price} error={e.price} placeholder="129,00" required />
<Field label="Streichpreis in €" optional name="compareAtPrice" inputMode="decimal" defaultValue={values.compareAtPrice} error={e.compareAtPrice} hint="Früherer Preis, wird durchgestrichen." />
</div>
<SelectField label="Mehrwertsteuer" name="taxRate" defaultValue={String(values.taxRate)}>
<option value="19">19 % (Standard)</option>
<option value="7">7 % (ermäßigt)</option>
<option value="0">0 %</option>
</SelectField>
</div>
</section>
<section className="ad-card">
<div className="ad-card__head"><div><h2>Varianten</h2><p>Größen, Längen oder Farben – jede mit eigenem Bestand.</p></div></div>
<div className="ad-card__body">
<VariantEditor initial={values.variants} />
{e.variants && <span className="sm-field__error"><Icon name="alert" /> {e.variants}</span>}
</div>
</section>
</div>
<div>
<section className="ad-card">
<div className="ad-card__head"><h2>Sichtbarkeit</h2></div>
<div className="ad-card__body">
<label className="ad-switch"><span className="ad-switch__text"><strong>Im Shop sichtbar</strong><small>Ausgeschaltet sieht nur das Team das Produkt.</small></span><input type="checkbox" role="switch" name="active" defaultChecked={values.active} /></label>
<label className="ad-switch"><span className="ad-switch__text"><strong>Auf der Startseite zeigen</strong><small>Im Abschnitt „Neu im Studio“.</small></span><input type="checkbox" role="switch" name="featured" defaultChecked={values.featured} /></label>
</div>
</section>
<section className="ad-card">
<div className="ad-card__head"><h2>Einordnung</h2></div>
<div className="ad-card__body">
<SelectField label="Kategorie" name="categoryId" defaultValue={values.categoryId}>
<option value="">Keine</option>
{categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
</SelectField>
<SelectField label="Kennzeichnung" name="badge" defaultValue={values.badge} hint="Rabatt und „Ausverkauft“ erscheinen automatisch.">
<option value="">Keine</option>
<option value="new">Neu</option>
<option value="best">Bestseller</option>
</SelectField>
</div>
</section>
<section className="ad-card">
<div className="ad-card__head"><h2>Lager</h2></div>
<div className="ad-card__body">
<Field label="Artikelnummer" optional name="sku" defaultValue={values.sku} />
<label className="ad-switch"><span className="ad-switch__text"><strong>Bestand verwalten</strong><small>Bei 0 wird das Produkt als ausverkauft gezeigt.</small></span><input type="checkbox" role="switch" name="trackStock" defaultChecked={values.trackStock} /></label>
<Field label="Bestand" name="stock" type="number" min={0} defaultValue={values.stock} disabled={!canStock} hint={values.variants.length ? "Bei Varianten zählt der Bestand je Variante." : canStock ? undefined : "Dafür fehlt dir das Recht."} />
</div>
</section>
<section className="ad-card">
<div className="ad-card__head"><h2>Web-Adresse</h2></div>
<div className="ad-card__body">
<Field label="Adresse" name="slug" defaultValue={values.slug} error={e.slug} hint="Wird aus dem Namen erzeugt, wenn leer." />
{values.id && values.slug && <a className="body-sm" href={`/produkt/${values.slug}`} target="_blank">Im Shop ansehen</a>}
</div>
</section>
</div>
</div>
);
}}
</AdminForm>
);
}

View file

@ -0,0 +1,15 @@
"use client";
import { useActionState } from "react";
import type { ActionResult } from "@/lib/action-result";
import { Icon } from "../Icon";
export function TestButton({ action, provider }: { action: (p: ActionResult, fd: FormData) => Promise<ActionResult>; provider: string }) {
const [state, formAction, pending] = useActionState(action, null);
return (
<form action={formAction} style={{ display: "flex", alignItems: "center", gap: "var(--space-3)", flexWrap: "wrap" }}>
<input type="hidden" name="provider" value={provider} />
<button className="sm-btn sm-btn--secondary sm-btn--sm" type="submit" disabled={pending}>{pending ? "Prüft …" : "Verbindung testen"}</button>
{state?.message && <span className={state.ok ? "ad-ok" : "ad-err"}><Icon name={state.ok ? "check" : "alert"} size="sm" /> {state.message}</span>}
</form>
);
}

View file

@ -0,0 +1,38 @@
"use client";
import { useState } from "react";
import { Icon } from "../Icon";
export type VariantRow = { id?: string; name: string; sku: string; price: string; stock: string };
export function VariantEditor({ initial }: { initial: VariantRow[] }) {
const [rows, setRows] = useState<VariantRow[]>(initial);
const set = (i: number, k: keyof VariantRow, v: string) => setRows((r) => r.map((row, j) => (j === i ? { ...row, [k]: v } : row)));
return (
<div>
<input type="hidden" name="variants" value={JSON.stringify(rows)} />
{rows.length === 0 ? (
<p className="body-sm ad-muted" style={{ marginTop: 0 }}>Keine Varianten. Füge welche hinzu, wenn es das Produkt in Größen oder Farben gibt.</p>
) : (
<div className="ad-table-wrap">
<table className="ad-variants">
<thead><tr><th>Bezeichnung</th><th>Art.-Nr.</th><th>Preis (leer = Produktpreis)</th><th>Bestand</th><th /></tr></thead>
<tbody>
{rows.map((r, i) => (
<tr key={i}>
<td><input className="sm-input" value={r.name} onChange={(e) => set(i, "name", e.target.value)} placeholder="z. B. 183 cm" aria-label="Bezeichnung" /></td>
<td><input className="sm-input" value={r.sku} onChange={(e) => set(i, "sku", e.target.value)} aria-label="Artikelnummer" /></td>
<td><input className="sm-input" value={r.price} onChange={(e) => set(i, "price", e.target.value)} inputMode="decimal" placeholder="—" aria-label="Preis" /></td>
<td><input className="sm-input" value={r.stock} onChange={(e) => set(i, "stock", e.target.value)} inputMode="numeric" style={{ maxWidth: 100 }} aria-label="Bestand" /></td>
<td><button type="button" className="ad-iconbtn ad-iconbtn--danger" onClick={() => setRows((rs) => rs.filter((_, j) => j !== i))} aria-label="Variante entfernen"><Icon name="trash" /></button></td>
</tr>
))}
</tbody>
</table>
</div>
)}
<button type="button" className="sm-btn sm-btn--secondary sm-btn--sm" style={{ marginTop: "var(--space-3)" }} onClick={() => setRows((r) => [...r, { name: "", sku: "", price: "", stock: "0" }])}>
<Icon name="plus" size="sm" /> Variante hinzufügen
</button>
</div>
);
}

View file

@ -68,6 +68,7 @@ export async function availablePayments(total: number, loggedIn: boolean): Promi
const def = getDefinition(m.code); const def = getDefinition(m.code);
if (!def || !isProviderReady(def.provider, creds)) return false; if (!def || !isProviderReady(def.provider, creds)) return false;
if (m.loggedInOnly && !loggedIn) return false; if (m.loggedInOnly && !loggedIn) return false;
if (m.code === "prepayment" && !(m.config as Record<string, string>)?.iban) return false;
if (m.minTotal > 0 && total < m.minTotal) return false; if (m.minTotal > 0 && total < m.minTotal) return false;
if (m.maxTotal > 0 && total > m.maxTotal) return false; if (m.maxTotal > 0 && total > m.maxTotal) return false;
return true; return true;

25
src/lib/upload.ts Normal file
View file

@ -0,0 +1,25 @@
"use server";
import { randomBytes } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { getCurrentUser, can } from "./auth";
const EXT: Record<string, string> = { "image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp", "image/gif": ".gif", "image/avif": ".avif" };
export async function uploadImages(fd: FormData): Promise<{ urls: string[]; error?: string }> {
const user = await getCurrentUser();
if (!can(user, "products.edit") && !can(user, "categories.edit") && !can(user, "appearance.edit")) return { urls: [], error: "Dafür fehlt dir das Recht." };
const dir = path.resolve(process.env.UPLOAD_DIR ?? "./uploads");
await mkdir(dir, { recursive: true });
const urls: string[] = [];
for (const file of fd.getAll("files")) {
if (!(file instanceof File) || file.size === 0) continue;
const ext = EXT[file.type];
if (!ext) return { urls, error: `${file.name}: Bitte JPG, PNG, WebP oder GIF hochladen.` };
if (file.size > 8 * 1024 * 1024) return { urls, error: `${file.name} ist größer als 8 MB.` };
const name = `${Date.now().toString(36)}-${randomBytes(6).toString("hex")}${ext}`;
await writeFile(path.join(dir, name), Buffer.from(await file.arrayBuffer()));
urls.push(`/uploads/${name}`);
}
return { urls };
}

View file

@ -57,7 +57,7 @@
.ad-kpi { background: var(--surface-raised); border: var(--hairline) solid var(--line); border-radius: var(--radius-md); padding: var(--space-4) var(--space-5); text-decoration: none; color: var(--ink); display: block; } .ad-kpi { background: var(--surface-raised); border: var(--hairline) solid var(--line); border-radius: var(--radius-md); padding: var(--space-4) var(--space-5); text-decoration: none; color: var(--ink); display: block; }
a.ad-kpi:hover { border-color: var(--line-strong); } a.ad-kpi:hover { border-color: var(--line-strong); }
.ad-kpi__label { font-size: 13px; color: var(--ink-muted); } .ad-kpi__label { font-size: 13px; color: var(--ink-muted); }
.ad-kpi__value { font-family: var(--font-serif); font-size: 34px; line-height: 1.15; font-weight: 500; font-variant-numeric: tabular-nums; margin-top: var(--space-1); } .ad-kpi__value { font-family: var(--font-serif); font-size: 34px; line-height: 1.15; font-weight: 500; font-variant-numeric: lining-nums tabular-nums; margin-top: var(--space-1); }
.ad-kpi__hint { font-size: 13px; color: var(--ink-muted); margin-top: var(--space-1); } .ad-kpi__hint { font-size: 13px; color: var(--ink-muted); margin-top: var(--space-1); }
/* Diagramm */ /* Diagramm */
@ -164,3 +164,5 @@ a.ad-kpi:hover { border-color: var(--line-strong); }
.ad-iconbtn:hover { border-color: var(--ink); } .ad-iconbtn:hover { border-color: var(--ink); }
.ad-iconbtn .sm-icon { width: 18px; height: 18px; } .ad-iconbtn .sm-icon { width: 18px; height: 18px; }
.ad-iconbtn--danger:hover { color: var(--danger); border-color: var(--danger); } .ad-iconbtn--danger:hover { color: var(--danger); border-color: var(--danger); }
.rot90 { transform: rotate(90deg); }
.ad-iconbtn:disabled { opacity: 0.4; cursor: default; }