diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..caec329 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +node_modules +.next +.env +uploads +.git diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d537409 --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..bbc6d74 --- /dev/null +++ b/README.md @@ -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 < String(fd.get(k) ?? "").trim(); + +export async function saveGeneral(_prev: ActionResult, fd: FormData): Promise { + 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(); +} diff --git a/src/app/admin/(panel)/einstellungen/page.tsx b/src/app/admin/(panel)/einstellungen/page.tsx new file mode 100644 index 0000000..a27d139 --- /dev/null +++ b/src/app/admin/(panel)/einstellungen/page.tsx @@ -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 ( +
+ + + +
+ + +
+ +
+ +
+ + +
+ + +
+ + +
+ +
+ + + + + +
+ + +
+
+ +
+ {Object.entries(COUNTRIES).map(([code, name]) => ( + + ))} +
+
+
+
+ ); +} diff --git a/src/app/admin/(panel)/gestaltung/actions.ts b/src/app/admin/(panel)/gestaltung/actions.ts new file mode 100644 index 0000000..9c42f67 --- /dev/null +++ b/src/app/admin/(panel)/gestaltung/actions.ts @@ -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(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 { + const user = await assertPermission("appearance.edit"); + await saveSettings("appearance", { + promoText: str(fd, "promoText"), + promoLinkLabel: str(fd, "promoLinkLabel"), + promoLinkHref: str(fd, "promoLinkHref"), + navigation: json(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(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."); +} diff --git a/src/app/admin/(panel)/gestaltung/page.tsx b/src/app/admin/(panel)/gestaltung/page.tsx new file mode 100644 index 0000000..c9c608a --- /dev/null +++ b/src/app/admin/(panel)/gestaltung/page.tsx @@ -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 ( +
+ + Shop ansehen + + + + +
+ + +
+
+ + + + + + + + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + +
+ +
+ + +
+ + + +
+ + + +

Die Links im Fuß kommen aus den Seiten (Einstellung „Im Fußbereich“) und den Kategorien.

+
+
+
+ ); +} diff --git a/src/app/admin/(panel)/gutscheine/actions.ts b/src/app/admin/(panel)/gutscheine/actions.ts new file mode 100644 index 0000000..70071b7 --- /dev/null +++ b/src/app/admin/(panel)/gutscheine/actions.ts @@ -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 { + 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"); +} diff --git a/src/app/admin/(panel)/gutscheine/page.tsx b/src/app/admin/(panel)/gutscheine/page.tsx new file mode 100644 index 0000000..a946612 --- /dev/null +++ b/src/app/admin/(panel)/gutscheine/page.tsx @@ -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 && } +
+ + + + + +
+
+ + +
+
+ + +
+ + + ); +} + +export default async function CouponsPage() { + await requireAdmin("coupons.edit"); + const coupons = await db.coupon.findMany({ orderBy: { createdAt: "desc" } }); + return ( +
+ + {coupons.map((c) => ( +
+ +
+

{c.code}

+

{c.type === "percent" ? `${c.value} %` : formatPrice(c.value)} · {c.usedCount}× eingelöst{c.maxUses ? ` von ${c.maxUses}` : ""}

+
+ {c.active ? "Aktiv" : "Aus"} +
+
+ Löschen}> + + +
+
+ ))} +
+

Neuer Gutschein

+
+
+
+ ); +} diff --git a/src/app/admin/(panel)/kategorien/actions.ts b/src/app/admin/(panel)/kategorien/actions.ts new file mode 100644 index 0000000..c73e728 --- /dev/null +++ b/src/app/admin/(panel)/kategorien/actions.ts @@ -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 { + 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"); +} diff --git a/src/app/admin/(panel)/kategorien/page.tsx b/src/app/admin/(panel)/kategorien/page.tsx new file mode 100644 index 0000000..9380dad --- /dev/null +++ b/src/app/admin/(panel)/kategorien/page.tsx @@ -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 ( +
+
+ {c.id && } +
+ + +
+ + + + +
+
+ Kachelbild + +
+
+ ); +} + +export default async function CategoriesPage() { + await requireAdmin("categories.edit"); + const categories = await db.category.findMany({ orderBy: { sort: "asc" }, include: { _count: { select: { products: true } } } }); + return ( +
+ + {categories.map((c) => ( +
+ +

{c.name}

{c._count.products} Produkte · /{c.slug}{c.active ? "" : " · versteckt"}

+ Bearbeiten +
+
+ Löschen}> + + +
+
+ ))} +
+

Neue Kategorie

+
+ + + +
+
+
+ ); +} diff --git a/src/app/admin/(panel)/kunden/[id]/page.tsx b/src/app/admin/(panel)/kunden/[id]/page.tsx new file mode 100644 index 0000000..85d6823 --- /dev/null +++ b/src/app/admin/(panel)/kunden/[id]/page.tsx @@ -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 ( +
+ +
+ + {c.orders.length === 0 ?
Noch keine Bestellungen.
: ( + + + {c.orders.map((o) => ( + + + + + + + ))} + +
{o.number}{dateFmt.format(o.createdAt)}{ORDER_STATUS[o.status].label}{formatPrice(o.total)}
+ )} +
+ + {can(user, "customers.edit") ? ( + + + + + + + + + ) : ( +
Telefon
{c.phone || "—"}
Newsletter
{c.newsletter ? "Ja" : "Nein"}
+ )} +
+
+
+ ); +} diff --git a/src/app/admin/(panel)/kunden/actions.ts b/src/app/admin/(panel)/kunden/actions.ts new file mode 100644 index 0000000..ed6cae4 --- /dev/null +++ b/src/app/admin/(panel)/kunden/actions.ts @@ -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 { + 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(); +} diff --git a/src/app/admin/(panel)/kunden/page.tsx b/src/app/admin/(panel)/kunden/page.tsx new file mode 100644 index 0000000..bd74390 --- /dev/null +++ b/src/app/admin/(panel)/kunden/page.tsx @@ -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 ( +
+ + +
+ +
+ {customers.length === 0 ? ( + + ) : ( +
+ + + + {customers.map((c) => { + const valid = c.orders.filter((o) => !["CANCELLED", "REFUNDED"].includes(o.status)); + return ( + + + + + + + + ); + })} + +
NameE-MailKunde seitBestellungenUmsatz
{[c.firstName, c.lastName].filter(Boolean).join(" ") || "—"}{!c.active &&
gesperrt
}
{c.email}{dayFmt.format(c.createdAt)}{valid.length}{formatPrice(valid.reduce((s, o) => s + o.total, 0))}
+
+ )} +
+
+ ); +} diff --git a/src/app/admin/(panel)/newsletter/export/route.ts b/src/app/admin/(panel)/newsletter/export/route.ts new file mode 100644 index 0000000..3afef27 --- /dev/null +++ b/src/app/admin/(panel)/newsletter/export/route.ts @@ -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"' } }); +} diff --git a/src/app/admin/(panel)/newsletter/page.tsx b/src/app/admin/(panel)/newsletter/page.tsx new file mode 100644 index 0000000..142bf5b --- /dev/null +++ b/src/app/admin/(panel)/newsletter/page.tsx @@ -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 ( +
+ + {subs.length > 0 && Als CSV herunterladen} + + + {subs.length === 0 ? : ( + + + {subs.map((s) => )} +
E-MailAngemeldet am
{s.email}{dateFmt.format(s.createdAt)}
+ )} +
+
+ ); +} diff --git a/src/app/admin/(panel)/produkte/[id]/page.tsx b/src/app/admin/(panel)/produkte/[id]/page.tsx new file mode 100644 index 0000000..faa462d --- /dev/null +++ b/src/app/admin/(panel)/produkte/[id]/page.tsx @@ -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 ( +
+ + {can(user, "products.edit") && ( +
+ )} + {can(user, "products.delete") && ( + + )} +
+ {neu &&
} + ({ id: v.id, name: v.name, sku: v.sku, price: centsToInput(v.price), stock: String(v.stock) })), + }} + /> +
+ ); +} diff --git a/src/app/admin/(panel)/produkte/actions.ts b/src/app/admin/(panel)/produkte/actions.ts new file mode 100644 index 0000000..b6835de --- /dev/null +++ b/src/app/admin/(panel)/produkte/actions.ts @@ -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 { + const user = await assertPermission("products.edit"); + const id = String(fd.get("id") ?? ""); + const errors: Record = {}; + 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"); +} diff --git a/src/app/admin/(panel)/produkte/neu/page.tsx b/src/app/admin/(panel)/produkte/neu/page.tsx new file mode 100644 index 0000000..1d8db49 --- /dev/null +++ b/src/app/admin/(panel)/produkte/neu/page.tsx @@ -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 ( +
+ + +
+ ); +} diff --git a/src/app/admin/(panel)/produkte/page.tsx b/src/app/admin/(panel)/produkte/page.tsx new file mode 100644 index 0000000..9806f35 --- /dev/null +++ b/src/app/admin/(panel)/produkte/page.tsx @@ -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 ( +
+ + {editable && Produkt anlegen} + + +
+ + + + +
+ {products.length === 0 ? ( + + {editable && Produkt anlegen} + + ) : ( +
+ + + + {products.map((p) => { + const stock = p.variants.length ? p.variants.reduce((s, v) => s + v.stock, 0) : p.stock; + return ( + + + + + + + + + ); + })} + +
ProduktKategoriePreisBestandSichtbar
{p.images[0] ? :
}
{p.name}
{[p.sku, p.variants.length ? `${p.variants.length} Varianten` : ""].filter(Boolean).join(" · ")}
{p.category?.name ?? "—"}{formatPrice(p.price)}{p.trackStock ? {stock} : "—"} + {editable ? ( +
+ + +
+ ) : ( + {p.active ? "Sichtbar" : "Versteckt"} + )} +
+
+ )} +
+
+ ); +} diff --git a/src/app/admin/(panel)/protokoll/page.tsx b/src/app/admin/(panel)/protokoll/page.tsx new file mode 100644 index 0000000..baed9c1 --- /dev/null +++ b/src/app/admin/(panel)/protokoll/page.tsx @@ -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 ( +
+ + + {logs.length === 0 ? : ( +
+ + + + {logs.map((l) => ( + + ))} + +
ZeitWerWasDetails
{dateFmt.format(l.createdAt)}{l.userEmail}{l.action}{l.details}
+
+ )} +
+
+ ); +} diff --git a/src/app/admin/(panel)/rollen/[id]/page.tsx b/src/app/admin/(panel)/rollen/[id]/page.tsx new file mode 100644 index 0000000..2e46a75 --- /dev/null +++ b/src/app/admin/(panel)/rollen/[id]/page.tsx @@ -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 ( +
+ + {role && !role.isSystem && role.users.length === 0 && } + + {role?.isSystem &&
So kann sich niemand aus Versehen aussperren.
} + + {role && } + + + + + + + + {role && role.users.length > 0 && ( + +
    + {role.users.map((u) =>
  • {[u.firstName, u.lastName].filter(Boolean).join(" ") || u.email}
  • )} +
+
+ )} +
+
+ ); +} diff --git a/src/app/admin/(panel)/rollen/actions.ts b/src/app/admin/(panel)/rollen/actions.ts new file mode 100644 index 0000000..8aadea7 --- /dev/null +++ b/src/app/admin/(panel)/rollen/actions.ts @@ -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 { + 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"); +} diff --git a/src/app/admin/(panel)/rollen/page.tsx b/src/app/admin/(panel)/rollen/page.tsx new file mode 100644 index 0000000..17d2c04 --- /dev/null +++ b/src/app/admin/(panel)/rollen/page.tsx @@ -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 ( +
+ + Rolle anlegen + + + + + + {roles.map((r) => ( + + + + + + ))} + +
RolleRechtePersonen
{r.name}
{r.description}
{r.isSystem ? Alle : {r.permissions.length} von {ALL_PERMISSIONS.length}}{r._count.users}
+
+
+ ); +} diff --git a/src/app/admin/(panel)/seiten/[id]/page.tsx b/src/app/admin/(panel)/seiten/[id]/page.tsx new file mode 100644 index 0000000..9c14409 --- /dev/null +++ b/src/app/admin/(panel)/seiten/[id]/page.tsx @@ -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 ( +
+ + {page && Ansehen} + + Löschen}> + {page && } +
+ + + + +
+ + + + + + + + + + + + +
+ Leerzeile = neuer Absatz
+ ## Überschrift
+ - Listenpunkt
+ **fett**
+ [Linktext](https://…) +
+
+
+
+
+
+ ); +} diff --git a/src/app/admin/(panel)/seiten/actions.ts b/src/app/admin/(panel)/seiten/actions.ts new file mode 100644 index 0000000..71a25cf --- /dev/null +++ b/src/app/admin/(panel)/seiten/actions.ts @@ -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 { + 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"); +} diff --git a/src/app/admin/(panel)/seiten/page.tsx b/src/app/admin/(panel)/seiten/page.tsx new file mode 100644 index 0000000..f7a6bb5 --- /dev/null +++ b/src/app/admin/(panel)/seiten/page.tsx @@ -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 = { 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 ( +
+ + Seite anlegen + + + + + + {pages.map((p) => ( + + + + + + + ))} + +
TitelIm FußbereichGeändertStatus
{p.title}
/seite/{p.slug}
{AREA[p.showInFooter]}{dateFmt.format(p.updatedAt)} + {p.content.startsWith("Bitte im Admin") ? Noch ausfüllen : {p.published ? "Veröffentlicht" : "Entwurf"}} +
+
+
+ ); +} diff --git a/src/app/admin/(panel)/team/[id]/page.tsx b/src/app/admin/(panel)/team/[id]/page.tsx new file mode 100644 index 0000000..923d48a --- /dev/null +++ b/src/app/admin/(panel)/team/[id]/page.tsx @@ -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 ( +
+ + {m.id !== me.id && !locked && } + + {neu &&
Gib der Person die E-Mail-Adresse und das Start-Passwort. Sie meldet sich unter /admin/login an.
} + {locked &&
} +
+ + + +
+ + +
+ + {assignable.map((r) => )} + + + +
+
+ + {perms === null ? ( +

Inhaber dürfen alles.

+ ) : ( +
    + {PERMISSION_GROUPS.flatMap((g) => [...g.permissions] as { key: string; label: string }[]).filter((p) => perms.has(p.key)).map((p) =>
  • {p.label}
  • )} +
+ )} +
+
+
+ ); +} diff --git a/src/app/admin/(panel)/team/actions.ts b/src/app/admin/(panel)/team/actions.ts new file mode 100644 index 0000000..86826f2 --- /dev/null +++ b/src/app/admin/(panel)/team/actions.ts @@ -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 { + 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 { + 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"); +} diff --git a/src/app/admin/(panel)/team/page.tsx b/src/app/admin/(panel)/team/page.tsx new file mode 100644 index 0000000..8693bf8 --- /dev/null +++ b/src/app/admin/(panel)/team/page.tsx @@ -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 ( +
+ + Rollen & Rechte + +
+ +
+ + + + {members.map((m) => ( + + + + + + + ))} + +
NameRolleZuletzt angemeldetStatus
{[m.firstName, m.lastName].filter(Boolean).join(" ") || m.email}{m.id === me.id && " (du)"}
{m.email}
{m.role?.name}{m.lastLoginAt ? dateFmt.format(m.lastLoginAt) : "noch nie"}{m.active ? "Aktiv" : "Gesperrt"}
+
+
+ + +
+ + +
+ + + !r.isSystem)?.id}> + {assignable.map((r) => )} + +
+
+
+
+ ); +} diff --git a/src/app/admin/(panel)/versand/actions.ts b/src/app/admin/(panel)/versand/actions.ts new file mode 100644 index 0000000..7551fbc --- /dev/null +++ b/src/app/admin/(panel)/versand/actions.ts @@ -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 { + 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"); +} diff --git a/src/app/admin/(panel)/versand/page.tsx b/src/app/admin/(panel)/versand/page.tsx new file mode 100644 index 0000000..95dced4 --- /dev/null +++ b/src/app/admin/(panel)/versand/page.tsx @@ -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 && } + + +
+ + +
+ Gilt für +
+ {countries.map((c) => ( + + ))} +
+ + + + ); +} + +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 ( +
+ + {methods.map((m) => ( +
+ +
+

{m.name}

+

{formatPrice(m.price)}{m.freeFrom ? ` · kostenlos ab ${formatPrice(m.freeFrom)}` : ""} · {m.countries.map((c) => COUNTRIES[c] ?? c).join(", ")}

+
+ {m.enabled ? "Aktiv" : "Aus"} +
+
+ Löschen}> + + +
+
+ ))} +
+

Neue Versandart

+
+
+
+ ); +} diff --git a/src/app/admin/(panel)/zahlung/actions.ts b/src/app/admin/(panel)/zahlung/actions.ts new file mode 100644 index 0000000..03b71ac --- /dev/null +++ b/src/app/admin/(panel)/zahlung/actions.ts @@ -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 { + 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 { + 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 { + 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 = {}; + 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(); +} diff --git a/src/app/admin/(panel)/zahlung/page.tsx b/src/app/admin/(panel)/zahlung/page.tsx new file mode 100644 index 0000000..156a51d --- /dev/null +++ b/src/app/admin/(panel)/zahlung/page.tsx @@ -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 ( +
+ + +

Zugangsdaten

+ + {creds.stripe.secretKey ? (creds.stripe.secretKey.includes("_test_") ? "Testmodus" : "Live") : "Nicht verbunden"}}> + + + +
+ Webhook in Stripe anlegen mit der Adresse {appUrl}/api/webhooks/stripe und den Ereignissen checkout.session.completed, checkout.session.async_payment_succeeded und checkout.session.async_payment_failed. Nötig vor allem für SEPA, weil die Bestätigung dort später kommt. +
+ {creds.stripe.secretKey && } +
+ {creds.paypal.clientSecret ? (creds.paypal.sandbox ? "Sandbox" : "Live") : "Nicht verbunden"}}> + + + + {creds.paypal.clientSecret && } + +
+
+
Stripe
+
PayPal
+
+ +

Zahlungsarten im Shop

+ {methods.map((m) => { + const def = getDefinition(m.code); + const ready = isProviderReady(def?.provider ?? "manual", creds); + const cfg = (m.config ?? {}) as Record; + return ( +
+ +
+

{m.name}

+

{def?.adminHint}{m.fee ? ` · Gebühr ${formatPrice(m.fee)}` : ""}

+
+ {!ready ? Zugang fehlt : {m.enabled ? "Aktiv" : "Aus"}} +
+
+ + + + + + {def?.fields.map((f) => + f.type === "textarea" ? ( + + ) : ( + + ), + )} +
+ + +
+
+ + +
+ +
+
+
+ ); + })} +
+ ); +} diff --git a/src/components/admin/AdminForm.tsx b/src/components/admin/AdminForm.tsx index 257579a..717fe87 100644 --- a/src/components/admin/AdminForm.tsx +++ b/src/components/admin/AdminForm.tsx @@ -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({ action, confirm, @@ -63,6 +63,7 @@ export function ConfirmButton({ className = "sm-btn sm-btn--ghost", hidden, title, + inForm, }: { action: (fd: FormData) => Promise; confirm: string; @@ -70,20 +71,23 @@ export function ConfirmButton({ className?: string; hidden?: Record; title?: string; + inForm?: boolean; }) { const [armed, setArmed] = useState(false); + const inner = armed ? ( + + {confirm} + + + + ) : ( + + ); + if (inForm) return inner; return (
{hidden && Object.entries(hidden).map(([k, v]) => )} - {armed ? ( - - {confirm} - - - - ) : ( - - )} + {inner}
); } diff --git a/src/components/admin/ImageManager.tsx b/src/components/admin/ImageManager.tsx new file mode 100644 index 0000000..9ccce8f --- /dev/null +++ b/src/components/admin/ImageManager.tsx @@ -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(initial); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const input = useRef(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 ( +
+ +
+ {images.map((src, i) => ( +
+ + {multiple && i === 0 && Hauptbild} +
+ {multiple && i > 0 && } + +
+
+ ))} + {(multiple || images.length === 0) && ( + + )} +
+ {error && {error}} + {multiple &&

Das erste Bild ist das Hauptbild. Empfohlenes Format 4:5, z. B. 1600 × 2000 px.

} +
+ ); +} diff --git a/src/components/admin/ListEditors.tsx b/src/components/admin/ListEditors.tsx new file mode 100644 index 0000000..be4d52d --- /dev/null +++ b/src/components/admin/ListEditors.tsx @@ -0,0 +1,76 @@ +"use client"; +import { useState } from "react"; +import type { NavLink, TrustItem } from "@/lib/settings"; +import { Icon } from "../Icon"; + +function moveItem(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 ( +
+ i.label.trim()))} /> + + + + {items.map((it, i) => ( + + + + + + ))} + +
TextZiel (z. B. /shop oder /kategorie/matten)
set(i, "label", e.target.value)} aria-label="Text" /> set(i, "href", e.target.value)} aria-label="Ziel" /> + {" "} + +
+ +
+ ); +} + +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 ( +
+ i.title.trim()))} /> + {items.map((it, i) => ( +
+ + + + set(i, "title", e.target.value)} placeholder="Titel" aria-label="Titel" /> + set(i, "text", e.target.value)} placeholder="Text" aria-label="Text" /> + +
+ ))} + {items.length < 4 && ( + + )} +
+ ); +} diff --git a/src/components/admin/PermissionPicker.tsx b/src/components/admin/PermissionPicker.tsx new file mode 100644 index 0000000..e1baa58 --- /dev/null +++ b/src/components/admin/PermissionPicker.tsx @@ -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 ( +
+ {PERMISSION_GROUPS.map((g) => { + const keys = g.permissions.map((p) => p.key as string); + const all = keys.every((k) => selected.has(k)); + return ( +
+ {g.label} +
+ {!disabled && ( + + )} +
+
+ {g.permissions.map((p) => ( + + ))} +
+
+ ); + })} +
+ ); +} diff --git a/src/components/admin/ProductForm.tsx b/src/components/admin/ProductForm.tsx new file mode 100644 index 0000000..3a55168 --- /dev/null +++ b/src/components/admin/ProductForm.tsx @@ -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 ( + + {(state) => { + const e = state?.errors ?? {}; + return ( +
+
+ {values.id && } +
+

Grunddaten

+
+ + + + +
+
+
+

Bilder

Ziehen ist nicht nötig: Mit dem Pfeil rückt ein Bild nach vorne.

+
+
+
+

Preis

+
+
+ + +
+ + + + + +
+
+
+

Varianten

Größen, Längen oder Farben – jede mit eigenem Bestand.

+
+ + {e.variants && {e.variants}} +
+
+
+
+
+

Sichtbarkeit

+
+ + +
+
+
+

Einordnung

+
+ + + {categories.map((c) => )} + + + + + + +
+
+
+

Lager

+
+ + + +
+
+
+

Web-Adresse

+
+ + {values.id && values.slug && Im Shop ansehen} +
+
+
+
+ ); + }} +
+ ); +} diff --git a/src/components/admin/TestButton.tsx b/src/components/admin/TestButton.tsx new file mode 100644 index 0000000..485ec39 --- /dev/null +++ b/src/components/admin/TestButton.tsx @@ -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; provider: string }) { + const [state, formAction, pending] = useActionState(action, null); + return ( +
+ + + {state?.message && {state.message}} +
+ ); +} diff --git a/src/components/admin/VariantEditor.tsx b/src/components/admin/VariantEditor.tsx new file mode 100644 index 0000000..0f86804 --- /dev/null +++ b/src/components/admin/VariantEditor.tsx @@ -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(initial); + const set = (i: number, k: keyof VariantRow, v: string) => setRows((r) => r.map((row, j) => (j === i ? { ...row, [k]: v } : row))); + return ( +
+ + {rows.length === 0 ? ( +

Keine Varianten. Füge welche hinzu, wenn es das Produkt in Größen oder Farben gibt.

+ ) : ( +
+ + + + {rows.map((r, i) => ( + + + + + + + + ))} + +
BezeichnungArt.-Nr.Preis (leer = Produktpreis)Bestand
set(i, "name", e.target.value)} placeholder="z. B. 183 cm" aria-label="Bezeichnung" /> set(i, "sku", e.target.value)} aria-label="Artikelnummer" /> set(i, "price", e.target.value)} inputMode="decimal" placeholder="—" aria-label="Preis" /> set(i, "stock", e.target.value)} inputMode="numeric" style={{ maxWidth: 100 }} aria-label="Bestand" />
+
+ )} + +
+ ); +} diff --git a/src/lib/checkout.ts b/src/lib/checkout.ts index f0b3006..27ef66f 100644 --- a/src/lib/checkout.ts +++ b/src/lib/checkout.ts @@ -68,6 +68,7 @@ export async function availablePayments(total: number, loggedIn: boolean): Promi const def = getDefinition(m.code); if (!def || !isProviderReady(def.provider, creds)) return false; if (m.loggedInOnly && !loggedIn) return false; + if (m.code === "prepayment" && !(m.config as Record)?.iban) return false; if (m.minTotal > 0 && total < m.minTotal) return false; if (m.maxTotal > 0 && total > m.maxTotal) return false; return true; diff --git a/src/lib/upload.ts b/src/lib/upload.ts new file mode 100644 index 0000000..1df1631 --- /dev/null +++ b/src/lib/upload.ts @@ -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 = { "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 }; +} diff --git a/src/styles/admin.css b/src/styles/admin.css index c14eba6..5304ce8 100644 --- a/src/styles/admin.css +++ b/src/styles/admin.css @@ -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; } a.ad-kpi:hover { border-color: var(--line-strong); } .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); } /* Diagramm */ @@ -164,3 +164,5 @@ a.ad-kpi:hover { border-color: var(--line-strong); } .ad-iconbtn:hover { border-color: var(--ink); } .ad-iconbtn .sm-icon { width: 18px; height: 18px; } .ad-iconbtn--danger:hover { color: var(--danger); border-color: var(--danger); } +.rot90 { transform: rotate(90deg); } +.ad-iconbtn:disabled { opacity: 0.4; cursor: default; }