Sanamare Shop: Grundgerüst, Storefront, Kasse, Zahlungen, Admin-Anfang
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:
commit
6c784e8a30
99 changed files with 7956 additions and 0 deletions
9
.env.example
Normal file
9
.env.example
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
# Datenbank
|
||||
DATABASE_URL="postgresql://sanamare:CHANGE_ME@db:5432/sanamare"
|
||||
# Öffentliche Adresse des Shops (für Zahlungs-Rückleitungen)
|
||||
APP_URL="https://sanamare.maaxxs-coding.de"
|
||||
# Ordner für hochgeladene Bilder
|
||||
UPLOAD_DIR="/app/uploads"
|
||||
# Erster Inhaber-Zugang (nur beim ersten Seed)
|
||||
ADMIN_EMAIL="admin@sanamare.de"
|
||||
ADMIN_PASSWORD="CHANGE_ME"
|
||||
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
node_modules
|
||||
.next
|
||||
.env
|
||||
uploads/*
|
||||
!uploads/.gitkeep
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
61
design/README.md
Normal file
61
design/README.md
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
Sanamare ist ein Online-Shop rund um Pilates – ruhig, edel, präzise. Das Logo gibt die Richtung vor: eine goldene Linie auf Schwarz, eine Figur in der Hundred-Position, Lotusblätter, ein Schriftzug mit viel Luft. Der Shop übersetzt das in **Elfenbein, Schwarz und Gold**, eine Serif für Überschriften und eine geometrische Sans für alles Bedienbare.
|
||||
|
||||
Die Reihenfolge der Prioritäten ist festgelegt: **1. Bedienbarkeit, 2. Klarheit, 3. Eleganz.** Wo Eleganz die Bedienung verschlechtern würde (hellgraue Schrift, winzige Buttons, Versalien im Fließtext, Icons ohne Beschriftung), gewinnt die Bedienung.
|
||||
|
||||
## Inhalt & Tonalität
|
||||
|
||||
- Sprache: Deutsch, **Du-Form**, kurze Sätze, ruhiger Ton. Keine Ausrufezeichen, keine Dringlichkeit („Nur noch heute!“), kein Emoji.
|
||||
- Beispiele im Ton der Marke: „Bewegung, die bleibt.“ · „Dein Studio für zu Hause.“ · „Kostenloser Versand ab 80 €.“ · „Du kannst innerhalb von 30 Tagen zurückgeben.“
|
||||
- Überschriften in Satzschreibweise („Neu im Studio“), nie in Versalien. Versalien gibt es nur in `eyebrow`, `nav`, `button` und `wordmark` – dort mit der Sperrung des Stils.
|
||||
- Buttons nennen die Handlung: „In den Warenkorb“, „Zur Kasse“, „Adresse speichern“. Nie „OK“, „Absenden“, „Weiter“ ohne Kontext.
|
||||
- Preise im deutschen Format: `129,00 €` (Komma, Leerzeichen, nachgestelltes €), immer mit `inkl. MwSt.`-Hinweis in `caption`. Streichpreise: `<s>` in `ink-muted`, der neue Preis in `ink`, nie in Rot.
|
||||
- Produktnamen: Produkt – Variante („Reformer Matte Pro – Anthrazit“). Der Marken-Schriftzug schreibt sich immer `SANAMARE.` mit Punkt.
|
||||
- Fehlermeldungen sagen, was zu tun ist: „Bitte gib eine gültige E-Mail-Adresse ein.“ statt „Ungültige Eingabe“.
|
||||
|
||||
## Farbe
|
||||
|
||||
Zwei Themes in `tokens.json`: **Hell** (Standard für Shop, Warenkorb, Checkout, Konto) und **Dunkel** (Hero, Kampagnenflächen, Dark-Mode). Das Theme ist ein `data-theme`-Attribut auf dem Wurzelelement oder einem Abschnitt – ein dunkler Hero liegt als `<section data-theme="dark">` auf einer hellen Seite.
|
||||
|
||||
- Grund: `surface` (Seite), `surface-raised` (Karten, Felder, Menüs), `surface-sunken` (Footer, Bestellübersicht, Bildplatzhalter). Nie reines Weiß als Seitenhintergrund.
|
||||
- Text: `ink` für alles Wichtige, `ink-muted` für Nebenzeilen, `ink-subtle` nur für Platzhalter und Deaktiviertes. Jede dieser Farben ist auf allen drei Surfaces lesbar (`ink-subtle` mit 3:1 – deshalb nie für Fließtext).
|
||||
- Gold in zwei Tönen: `gold` ist **Schmuck** (Zierlinie unter Überschriften, Ornament-Punkt, Sterne, Hover-Linie in der Navigation), `gold-deep` ist **Gold mit Bedeutung** (Links, Eyebrow, aktive Navigation, Fokusring, Hinweise). Im hellen Theme ist `gold` nur 2.2:1 auf dem Grund – als Text verboten.
|
||||
- Primäre Handlung ist `noir` mit `on-noir`: schwarz im hellen, elfenbein im dunklen Theme. Gold als Button-Fläche nur für den einen Akzent-Button pro Seite (Newsletter, Kampagne) mit `on-gold`.
|
||||
- Status trägt immer Wort oder Icon: `success` („Auf Lager“), `danger` („Ausverkauft“, Fehler), jeweils mit `-soft`-Grund. Es gibt keinen Warnton – „Nur noch 2 Stück“ steht in `gold-deep` auf `gold-soft`.
|
||||
- `overlay` hinter Dialogen, Off-Canvas-Warenkorb und Mobilmenü.
|
||||
|
||||
## Typografie
|
||||
|
||||
- `serif` (Cormorant Garamond) nur für die `Display`-Gruppe und `quote`. `sans` (Jost) für alles andere – jede Zeile, die jemand liest, um etwas zu tun, steht in Jost.
|
||||
- Hierarchie einer Shop-Seite: `eyebrow` (gold-deep) → `display-lg` (Titel) → `body` (Beschreibung). Abschnitte der Startseite: `display-md`, Karten: `title`.
|
||||
- Formularfelder und ihre Werte in `body` (16px): kleiner löst auf iOS den Auto-Zoom aus. Labels in `label`, Hilfe- und Fehlertexte in `caption`.
|
||||
- Beide Schriften sind Google-Fonts (SIL Open Font License). **Im Shop selbst hosten** (Dateien von fonts.google.com oder dem npm-Paket `@fontsource/jost` bzw. `@fontsource/cormorant-garamond` unter `fonts/` ablegen und in `tokens.json` `type.fonts` eintragen) – ein Laden von Google-Servern ist in Deutschland ein DSGVO-Risiko. Die Vorschauen hier laden sie zur Ansicht von Google.
|
||||
- Ziffern in Preisen und Tabellen: `font-variant-numeric: tabular-nums`.
|
||||
|
||||
## Abstand, Radien, Linien, Schatten
|
||||
|
||||
- 4er-Raster (`space-1` … `space-10`). Innerhalb von Komponenten `space-2`–`space-4`, Produktraster `space-5`, Abschnitte `space-8` (mobil) / `space-9` (Desktop).
|
||||
- Fast eckig: `radius-sm` (2px) für Buttons, Felder, Badges; `radius-md` (6px) für Karten und Bilder; `radius-pill` nur für Chips, Stepper und Zähler. Keine anderen Radien.
|
||||
- Linien statt Schatten: Karten, Tabellen und Felder trennen sich mit einer `hairline` in `line`. Rahmen mit Bedeutung (Feld, Sekundär-Button, Auswahl) in `line-strong`. Schatten nur für Schwebendes (`shadow-md` Dropdown, `shadow-lg` Dialog) und beim Hover einer Karte (`shadow-sm`).
|
||||
- Goldene Zierlinie: 1px `gold`, 48px breit, zentriert unter einer `display-md`-Überschrift, `space-4` Abstand – das Motiv aus dem Logo (Linie, Punkt, Linie). Höchstens einmal pro Abschnitt.
|
||||
|
||||
## Layout & Bedienung
|
||||
|
||||
- Mobile first, Breakpoints in `tokens.json` (`bp-sm` … `bp-xl`). Container `container-max` (1280px), Fließtext `container-text` (720px).
|
||||
- Produktraster: 2 / 3 / 4 Spalten, alle Bilder `product-image-ratio` (4:5), Abstand `space-5`.
|
||||
- Jedes Control ist `control-height` (48px) hoch, Klickziele mindestens `touch-target` (44px). „In den Warenkorb“ und „Zur Kasse“ sind `control-height-lg` (56px) und auf Mobilgeräten vollbreit und am unteren Rand fixiert.
|
||||
- Der Header ist sticky, `header-height` (72px), mit Logo links, Navigation mittig, Suche / Konto / Warenkorb rechts. Der Warenkorb zeigt die Stückzahl als Zähler. Unter `bp-lg` wird die Navigation zum Burger-Menü, Suche und Warenkorb bleiben sichtbar.
|
||||
- Checkout ist linear: Adresse → Versand → Zahlung → Prüfen. Ein Schritt pro Seite, Fortschritt oben (`CheckoutSteps`), Bestellübersicht rechts (Desktop) oder einklappbar oben (mobil). Gastbestellung immer möglich.
|
||||
- Formulare: ein Feld pro Zeile, Label über dem Feld, Fehler unter dem Feld in `danger` mit Icon, Autofill-Attribute gesetzt (`autocomplete="given-name"` …). Pflichtfelder sind die Regel – optionale Felder tragen „(optional)“ im Label.
|
||||
- Fokus ist immer sichtbar: 2px Abstand im Grund, dann 2px `focus-ring`. Hover auf Karten: Bild wird leicht größer (1.03, 400ms), Titel bleibt. Keine Animation länger als 400ms; `prefers-reduced-motion` schaltet sie ab.
|
||||
- Bilder: Produktfotos freigestellt auf `surface-sunken` oder auf warmem Studio-Hintergrund; Lifestyle-Bilder in gedämpften, warmen Tönen. Kein Stock-Lächeln, keine Stock-Fitness-Posen.
|
||||
|
||||
## Logo & Iconografie
|
||||
|
||||
- Das Original ist `assets/Logos/sanamare-logo-gold-auf-schwarz.png` (Gold auf Schwarz). Daraus abgeleitet, ohne eine Linie zu verändern: `sanamare-logo-gold.png` (freigestellt, für dunkle Gründe) und `sanamare-logo-ink.png` (dieselben Linien in `ink`, für helle Gründe) sowie die reine Bildmarke – Figur, Kreis, Lotus – als `sanamare-bildmarke-gold.png` und `sanamare-bildmarke-ink.png`.
|
||||
- Wo das Logo steht: **Header** – Bildmarke 44px hoch neben dem Schriftzug im `wordmark`-Stil (Ink im hellen, Gold im dunklen Theme; die Bildmarke bleibt auch mobil, der Schriftzug fällt unter `bp-sm` weg). **Hero und Footer** (beide dunkel) – das vollständige Logo in Gold, 160–420px breit. Nie das goldene Logo auf Elfenbein (2.2:1 – die feinen Linien verschwinden), nie das Original mit schwarzem Quadrat in eine helle Fläche setzen.
|
||||
- Freiraum mindestens `space-6`, Mindestbreite 120px für das vollständige Logo, 32px für die Bildmarke. Nicht verzerren, nicht drehen, keine Schatten. Siehe `assets/Logos/README.md`; eine Vektorversion (SVG) fehlt noch.
|
||||
- Icons: dünne Linien-Icons, 1.5px Strich, 24px Raster, `currentColor` (z. B. Lucide, ISC-Lizenz). Jedes Icon-Only-Control hat ein `aria-label`; neben Text steht das Icon links mit `space-2` Abstand. Keine Emoji.
|
||||
|
||||
## Komponenten
|
||||
|
||||
`components/bundle.css` ist reines CSS auf den Tokens – kein Framework, kein JavaScript. Jede Komponente hat eine Vorschau und eine Anleitung unter `components/<Name>/`. Die Klassen tragen das Präfix `sm-`. Die Seiten `Startseite`, `Produktseite` und `Warenkorb` zeigen, wie die Komponenten zusammen wirken.
|
||||
127
design/tokens.json
Normal file
127
design/tokens.json
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
{
|
||||
"name": "Sanamare",
|
||||
"version": 1,
|
||||
"color": {
|
||||
"note": "Zwei Themes: „Hell“ ist der Standard im Shop (Elfenbein-Grund, schwarze Schrift, Gold als Akzent). „Dunkel“ ist der Look des Logos – für Hero-Flächen, Kampagnen und den Dark-Mode. Jede Textfarbe nennt die Gründe, auf denen sie lesbar ist.",
|
||||
"themes": [
|
||||
{ "id": "light", "name": "Hell" },
|
||||
{ "id": "dark", "name": "Dunkel" }
|
||||
],
|
||||
"tokens": [
|
||||
{ "name": "surface", "value": { "light": "#f7f4ee", "dark": "#0d0d0f" }, "usage": "Seitenhintergrund. Warmes Elfenbein, nie reines Weiß – reines Weiß ist für surface-raised reserviert." },
|
||||
{ "name": "surface-raised", "value": { "light": "#ffffff", "dark": "#17171a" }, "usage": "Karten, Produktkacheln, Menüs, Dialoge, Eingabefelder – alles, was über dem Seitenhintergrund liegt." },
|
||||
{ "name": "surface-sunken", "value": { "light": "#efeadf", "dark": "#070708" }, "usage": "Zurückgesetzte Flächen: Bestellübersicht im Checkout, Footer, Bildplatzhalter, Zebrazeilen." },
|
||||
{ "name": "line", "value": { "light": "#e2dbcd", "dark": "#2a2926" }, "usage": "Haarlinien und Trenner, ruhende Kartenränder, Tabellenlinien. Trägt keine Bedeutung – dafür line-strong." },
|
||||
{ "name": "line-strong", "value": { "light": "#8c8270", "dark": "#6d6960" }, "usage": "Rahmen, die etwas bedeuten: Eingabefelder, Sekundär-Buttons, Auswahlrahmen (≥ 3:1 auf surface und surface-raised)." },
|
||||
{ "name": "ink", "value": { "light": "#161411", "dark": "#f2ede3" }, "usage": "Primärtext und Überschriften auf surface, surface-raised, surface-sunken und gold-soft." },
|
||||
{ "name": "ink-muted", "value": { "light": "#5d574d", "dark": "#b1a999" }, "usage": "Sekundärtext: Beschreibungen, Metadaten, Hilfetexte – auf allen drei Surfaces und gold-soft (≥ 4.5:1)." },
|
||||
{ "name": "ink-subtle", "value": { "light": "#7d766b", "dark": "#8a8275" }, "usage": "Nur Platzhalter in Feldern und deaktivierter Text (≥ 3:1). Nie für Fließtext oder Preise." },
|
||||
{ "name": "gold", "value": { "light": "#c6a24c", "dark": "#d4ae5e" }, "usage": "Das Gold des Logos – als Schmuck: Zierlinien, Ornament-Punkt, Sternbewertung, Hover-Linie, große Display-Ziffern. Im hellen Theme nur 2.2:1 auf surface, deshalb dort nie als Text oder bedeutungstragender Rahmen – dafür gold-deep." },
|
||||
{ "name": "gold-deep", "value": { "light": "#7a5e1a", "dark": "#e4c47c" }, "usage": "Gold als Text und Interaktion: Links, Eyebrow-Zeilen, Preis-Hinweise, aktive Navigation, Fokusring, Icons mit Bedeutung – auf surface, surface-raised und gold-soft (≥ 4.5:1)." },
|
||||
{ "name": "gold-soft", "value": { "light": "#f4ebd3", "dark": "#2a2211" }, "usage": "Getönter Grund hinter gold-deep-Text: Hinweisbalken, Badge „Neu“, ausgewählte Filterchips, Rabatt-Hinweis im Warenkorb." },
|
||||
{ "name": "on-gold", "value": { "light": "#161411", "dark": "#161411" }, "usage": "Text und Icons auf einer gold-Fläche (Badge „Bestseller“, goldener Akzent-Button). Immer dunkel, nie weiß." },
|
||||
{ "name": "noir", "value": { "light": "#161411", "dark": "#f2ede3" }, "usage": "Füllung des Primär-Buttons („In den Warenkorb“, „Zur Kasse“) und aktiver Schritte. Hell: schwarz, dunkel: elfenbein – immer der stärkste Kontrast zum Grund." },
|
||||
{ "name": "on-noir", "value": { "light": "#f7f4ee", "dark": "#0d0d0f" }, "usage": "Label und Icon auf einer noir-Fläche." },
|
||||
{ "name": "success", "value": { "light": "#1e6a5c", "dark": "#7fd3c0" }, "usage": "„Auf Lager“, „Bestellung eingegangen“, gültiger Gutschein – als Text auf surface, surface-raised und success-soft. Bewusst blaugrün statt reingrün, damit es sich von danger auch ohne Farbsehen unterscheidet; immer mit Wort oder Icon." },
|
||||
{ "name": "success-soft", "value": { "light": "#e0f1ec", "dark": "#11292a" }, "usage": "Getönter Grund hinter success-Text (Erfolgsmeldung, Lager-Badge)." },
|
||||
{ "name": "danger", "value": { "light": "#a8322b", "dark": "#f29a92" }, "usage": "Fehler in Formularen, „Ausverkauft“, „Entfernen“-Bestätigung – als Text auf surface, surface-raised und danger-soft. Immer mit Wort oder Icon." },
|
||||
{ "name": "danger-soft", "value": { "light": "#f9e4e2", "dark": "#3a1715" }, "usage": "Getönter Grund hinter danger-Text (Fehlermeldung, Fehlerfeld)." },
|
||||
{ "name": "link", "value": "{gold-deep}", "usage": "Textlinks – Alias von gold-deep, damit ein Theme, das das Gold verschiebt, auch die Links verschiebt." },
|
||||
{ "name": "focus-ring", "value": "{gold-deep}", "usage": "Tastaturfokus: 2px Abstand im Grund, dann 2px solider Ring in dieser Farbe (≥ 3:1 auf allen Surfaces). Nie outline:none ohne Ersatz." },
|
||||
{ "name": "overlay", "value": { "light": "#161411a6", "dark": "#000000b3" }, "usage": "Abdunkelung hinter Dialogen, Off-Canvas-Warenkorb und Mobilmenü." }
|
||||
]
|
||||
},
|
||||
"type": {
|
||||
"fonts": [],
|
||||
"families": {
|
||||
"serif": "\"Cormorant Garamond\", Cormorant, Georgia, \"Times New Roman\", serif",
|
||||
"sans": "Jost, Futura, \"Avenir Next\", \"Century Gothic\", \"Segoe UI\", system-ui, sans-serif"
|
||||
},
|
||||
"groups": [
|
||||
{
|
||||
"name": "Display",
|
||||
"family": "serif",
|
||||
"styles": [
|
||||
{ "name": "display-xl", "fontSize": "64px", "lineHeight": "1.0", "fontWeight": 500, "letterSpacing": "-0.01em", "sample": "Bewegung, die bleibt.", "usage": "Hero-Headline der Startseite, eine Zeile, maximal zwei. Mobil auf display-lg reduzieren." },
|
||||
{ "name": "display-lg", "fontSize": "44px", "lineHeight": "1.05", "fontWeight": 500, "letterSpacing": "-0.005em", "sample": "Die Reformer-Kollektion", "usage": "Seitentitel (Kategorie, Produktname auf der Produktseite), Kampagnen-Teaser." },
|
||||
{ "name": "display-md", "fontSize": "32px", "lineHeight": "1.15", "fontWeight": 500, "sample": "Neu im Studio", "usage": "Abschnittsüberschriften auf der Startseite, Titel von Dialogen und Checkout-Schritten." },
|
||||
{ "name": "display-sm", "fontSize": "24px", "lineHeight": "1.2", "fontWeight": 500, "sample": "Zusammenfassung", "usage": "Unterabschnitte, Boxentitel (Bestellübersicht), Akkordeon-Titel auf der Produktseite." },
|
||||
{ "name": "quote", "fontSize": "26px", "lineHeight": "1.3", "fontWeight": 400, "fontStyle": "italic", "sample": "„Nach zehn Stunden spürst du den Unterschied.“ – Joseph Pilates", "usage": "Zitate und Kundenstimmen, nie für UI-Text." }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Text",
|
||||
"family": "sans",
|
||||
"styles": [
|
||||
{ "name": "title", "fontSize": "18px", "lineHeight": "26px", "fontWeight": 500, "sample": "Reformer Matte Pro – Anthrazit", "usage": "Produktname auf Karten und im Warenkorb, Titel in Listen." },
|
||||
{ "name": "body", "fontSize": "16px", "lineHeight": "26px", "fontWeight": 400, "sample": "Griffige Oberfläche, 8 mm stark, aus recyceltem Naturkautschuk. Rutschfest auf jedem Boden.", "usage": "Fließtext, Produktbeschreibungen, Formularwerte. Nie unter 16px auf Mobilgeräten (verhindert Auto-Zoom in Feldern)." },
|
||||
{ "name": "body-sm", "fontSize": "14px", "lineHeight": "22px", "fontWeight": 400, "sample": "Kostenloser Versand ab 80 €, Lieferung in 2–4 Werktagen.", "usage": "Sekundärzeilen: Versandhinweise, Produktvarianten, Tabellenzellen, Footer-Links." },
|
||||
{ "name": "label", "fontSize": "14px", "lineHeight": "20px", "fontWeight": 500, "sample": "E-Mail-Adresse", "usage": "Formularlabels, Tabs, Breadcrumb, Mengenanzeige." },
|
||||
{ "name": "button", "fontSize": "14px", "lineHeight": "20px", "fontWeight": 500, "letterSpacing": "0.08em", "sample": "IN DEN WARENKORB", "usage": "Button-Labels, in Versalien gesetzt (text-transform: uppercase im CSS). Nie länger als vier Wörter." },
|
||||
{ "name": "nav", "fontSize": "13px", "lineHeight": "20px", "fontWeight": 500, "letterSpacing": "0.14em", "sample": "SHOP KOLLEKTIONEN STUDIO JOURNAL", "usage": "Hauptnavigation und Footer-Spaltentitel, Versalien." },
|
||||
{ "name": "eyebrow", "fontSize": "12px", "lineHeight": "16px", "fontWeight": 500, "letterSpacing": "0.2em", "sample": "NEUE KOLLEKTION", "usage": "Kleine Versalzeile über einer Display-Überschrift, in gold-deep. Höchstens drei Wörter." },
|
||||
{ "name": "caption", "fontSize": "12px", "lineHeight": "16px", "fontWeight": 400, "sample": "Art.-Nr. SM-2041 · inkl. MwSt., zzgl. Versand", "usage": "Metadaten, rechtliche Hinweise, Hilfetexte unter Feldern, Badge-Text – in ink-muted." },
|
||||
{ "name": "price", "fontSize": "18px", "lineHeight": "24px", "fontWeight": 500, "sample": "129,00 €", "usage": "Preise auf Karten und im Warenkorb. Tabellenziffern (font-variant-numeric: tabular-nums), deutsches Format mit Komma und nachgestelltem €." },
|
||||
{ "name": "price-lg", "fontSize": "28px", "lineHeight": "32px", "fontWeight": 500, "sample": "129,00 €", "usage": "Preis auf der Produktseite und Gesamtsumme im Warenkorb." },
|
||||
{ "name": "wordmark", "fontSize": "22px", "lineHeight": "28px", "fontWeight": 400, "letterSpacing": "0.32em", "sample": "SANAMARE.", "usage": "Der Schriftzug als Text, wo das Logo-Bild nicht passt (Header im hellen Theme, E-Mails, Footer). Immer mit Punkt, immer Versalien." }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"spacing": {
|
||||
"note": "4er-Raster. Innerhalb einer Komponente 1–4, zwischen Komponenten 5–6, zwischen Abschnitten 7–10.",
|
||||
"tokens": [
|
||||
{ "name": "space-1", "value": "4px", "usage": "Icon zu Text, Badge-Innenabstand vertikal." },
|
||||
{ "name": "space-2", "value": "8px", "usage": "Zwischen Label und Feld, Chip-Innenabstand, Abstand zwischen Sternen." },
|
||||
{ "name": "space-3", "value": "12px", "usage": "Innenabstand in Chips und kleinen Buttons, Zeilen in Listen." },
|
||||
{ "name": "space-4", "value": "16px", "usage": "Innenabstand von Feldern und Karten (mobil), Abstand Titel zu Preis, Seitenrand mobil." },
|
||||
{ "name": "space-5", "value": "24px", "usage": "Kartenabstand im Produktraster, Innenabstand Karten (Desktop), Seitenrand Tablet." },
|
||||
{ "name": "space-6", "value": "32px", "usage": "Abstand zwischen Formulargruppen, Innenabstand der Bestellübersicht, Seitenrand Desktop." },
|
||||
{ "name": "space-7", "value": "48px", "usage": "Abstand zwischen Überschrift und Inhalt eines Abschnitts, Footer-Innenabstand." },
|
||||
{ "name": "space-8", "value": "64px", "usage": "Abstand zwischen Abschnitten (mobil)." },
|
||||
{ "name": "space-9", "value": "96px", "usage": "Abstand zwischen Abschnitten (Desktop)." },
|
||||
{ "name": "space-10", "value": "128px", "usage": "Hero-Innenabstand oben/unten auf dem Desktop." }
|
||||
]
|
||||
},
|
||||
"radius": {
|
||||
"note": "Fast eckig. Edelmarken runden kaum – Weichheit kommt aus Farbe und Schrift, nicht aus Radien.",
|
||||
"tokens": [
|
||||
{ "name": "radius-none", "value": "0px", "usage": "Hero-Bilder, Vollbreite-Flächen, Tabellen." },
|
||||
{ "name": "radius-sm", "value": "2px", "usage": "Buttons, Eingabefelder, Badges, Checkboxen." },
|
||||
{ "name": "radius-md", "value": "6px", "usage": "Karten, Produktbilder im Raster, Dialoge, Dropdowns." },
|
||||
{ "name": "radius-lg", "value": "12px", "usage": "Bildkacheln in Kollektions-Teasern, Off-Canvas-Panels (innere Kante)." },
|
||||
{ "name": "radius-pill", "value": "999px", "usage": "Filterchips, Mengenstepper, Warenkorb-Zähler, Farbswatches." }
|
||||
]
|
||||
},
|
||||
"shadow": {
|
||||
"note": "Schatten sind leise. Ruhe kommt von Haarlinien (line); Schatten nur für Dinge, die wirklich schweben.",
|
||||
"tokens": [
|
||||
{ "name": "shadow-sm", "value": { "light": "0 1px 2px #16141114", "dark": "0 1px 2px #00000080" }, "usage": "Karten im Hover, Sticky-Header nach dem Scrollen." },
|
||||
{ "name": "shadow-md", "value": { "light": "0 4px 12px #1614111a, 0 1px 2px #1614110f", "dark": "0 4px 12px #00000099, 0 1px 2px #00000080" }, "usage": "Dropdowns, Suchvorschläge, Mini-Warenkorb." },
|
||||
{ "name": "shadow-lg", "value": { "light": "0 16px 48px #16141126", "dark": "0 16px 48px #000000bf" }, "usage": "Dialoge, Off-Canvas-Warenkorb, Zoom-Bild." }
|
||||
]
|
||||
},
|
||||
"layout": {
|
||||
"note": "Maße, die Bedienbarkeit garantieren. Kein Klickziel unter 44px, kein Formularfeld unter 48px.",
|
||||
"tokens": [
|
||||
{ "name": "container-max", "value": "1280px", "usage": "Maximale Inhaltsbreite, zentriert, Seitenrand space-4/5/6 je Breakpoint." },
|
||||
{ "name": "container-text", "value": "720px", "usage": "Breite für Fließtext (Journal, Produktbeschreibung, AGB) – ca. 70 Zeichen pro Zeile." },
|
||||
{ "name": "control-height", "value": "48px", "usage": "Höhe von Buttons, Eingabefeldern, Selects und Mengenstepper – Standard." },
|
||||
{ "name": "control-height-sm", "value": "40px", "usage": "Kompakte Controls in Tabellen, Chips, Warenkorb-Zeilen." },
|
||||
{ "name": "control-height-lg", "value": "56px", "usage": "„In den Warenkorb“ auf der Produktseite und „Zur Kasse“ – die wichtigsten Buttons sind die größten." },
|
||||
{ "name": "touch-target", "value": "44px", "usage": "Mindestgröße jedes Klick- oder Tippziels, auch für Icon-Buttons und Checkboxen (per Padding erreichen)." },
|
||||
{ "name": "header-height", "value": "72px", "usage": "Höhe des Headers auf dem Desktop; mobil 60px." },
|
||||
{ "name": "product-image-ratio", "value": "4 / 5", "usage": "aspect-ratio aller Produktbilder im Raster und Warenkorb – ein Format, damit das Raster ruhig bleibt." },
|
||||
{ "name": "hairline", "value": "1px", "usage": "Breite aller Linien und Rahmen. Keine 2px-Rahmen außer Fokusring und ausgewähltem Swatch." }
|
||||
]
|
||||
},
|
||||
"breakpoint": {
|
||||
"note": "Mobile first. Das Produktraster: 2 Spalten unter md, 3 ab md, 4 ab lg.",
|
||||
"tokens": [
|
||||
{ "name": "bp-sm", "value": "480px", "usage": "Große Telefone – Buttons nebeneinander statt gestapelt." },
|
||||
{ "name": "bp-md", "value": "768px", "usage": "Tablet – 3 Spalten im Raster, Filter als Sidebar." },
|
||||
{ "name": "bp-lg", "value": "1024px", "usage": "Desktop – 4 Spalten, Hauptnavigation sichtbar statt Burger-Menü." },
|
||||
{ "name": "bp-xl", "value": "1280px", "usage": "Container erreicht seine Maximalbreite." }
|
||||
]
|
||||
}
|
||||
}
|
||||
10
next.config.ts
Normal file
10
next.config.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
experimental: {
|
||||
serverActions: { bodySizeLimit: "10mb" },
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
2025
package-lock.json
generated
Normal file
2025
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
37
package.json
Normal file
37
package.json
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
{
|
||||
"name": "sanamare",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "tsc --noEmit",
|
||||
"db:push": "prisma db push",
|
||||
"db:migrate": "prisma migrate deploy",
|
||||
"db:seed": "tsx prisma/seed.ts",
|
||||
"tokens": "node scripts/build-tokens.mjs"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/cormorant-garamond": "^5.3.0",
|
||||
"@fontsource/jost": "^5.3.0",
|
||||
"@prisma/client": "6.19.3",
|
||||
"bcryptjs": "3.0.3",
|
||||
"next": "15.5.28",
|
||||
"react": "19.1.10",
|
||||
"react-dom": "19.1.10",
|
||||
"server-only": "^0.0.1",
|
||||
"zod": "4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "22.20.5",
|
||||
"@types/react": "19.1.10",
|
||||
"@types/react-dom": "19.1.10",
|
||||
"prisma": "6.19.3",
|
||||
"tsx": "^4.20.6",
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
}
|
||||
325
prisma/migrations/20261019125521_init/migration.sql
Normal file
325
prisma/migrations/20261019125521_init/migration.sql
Normal file
|
|
@ -0,0 +1,325 @@
|
|||
-- CreateEnum
|
||||
CREATE TYPE "OrderStatus" AS ENUM ('PENDING', 'PAID', 'PROCESSING', 'SHIPPED', 'COMPLETED', 'CANCELLED', 'REFUNDED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PaymentStatus" AS ENUM ('OPEN', 'AUTHORIZED', 'PAID', 'FAILED', 'REFUNDED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Role" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT NOT NULL DEFAULT '',
|
||||
"permissions" TEXT[],
|
||||
"isSystem" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Role_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "User" (
|
||||
"id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"passwordHash" TEXT NOT NULL,
|
||||
"firstName" TEXT NOT NULL DEFAULT '',
|
||||
"lastName" TEXT NOT NULL DEFAULT '',
|
||||
"phone" TEXT NOT NULL DEFAULT '',
|
||||
"roleId" TEXT,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"newsletter" BOOLEAN NOT NULL DEFAULT false,
|
||||
"lastLoginAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Session" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Address" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"firstName" TEXT NOT NULL,
|
||||
"lastName" TEXT NOT NULL,
|
||||
"company" TEXT NOT NULL DEFAULT '',
|
||||
"street" TEXT NOT NULL,
|
||||
"extra" TEXT NOT NULL DEFAULT '',
|
||||
"zip" TEXT NOT NULL,
|
||||
"city" TEXT NOT NULL,
|
||||
"country" TEXT NOT NULL DEFAULT 'DE',
|
||||
"isDefault" BOOLEAN NOT NULL DEFAULT false,
|
||||
|
||||
CONSTRAINT "Address_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Category" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"description" TEXT NOT NULL DEFAULT '',
|
||||
"image" TEXT NOT NULL DEFAULT '',
|
||||
"sort" INTEGER NOT NULL DEFAULT 0,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"showOnHome" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Category_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Product" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"subtitle" TEXT NOT NULL DEFAULT '',
|
||||
"description" TEXT NOT NULL DEFAULT '',
|
||||
"details" TEXT NOT NULL DEFAULT '',
|
||||
"sku" TEXT NOT NULL DEFAULT '',
|
||||
"price" INTEGER NOT NULL,
|
||||
"compareAtPrice" INTEGER,
|
||||
"taxRate" INTEGER NOT NULL DEFAULT 19,
|
||||
"stock" INTEGER NOT NULL DEFAULT 0,
|
||||
"trackStock" BOOLEAN NOT NULL DEFAULT true,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"featured" BOOLEAN NOT NULL DEFAULT false,
|
||||
"badge" TEXT NOT NULL DEFAULT '',
|
||||
"images" TEXT[],
|
||||
"sort" INTEGER NOT NULL DEFAULT 0,
|
||||
"categoryId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Product_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ProductVariant" (
|
||||
"id" TEXT NOT NULL,
|
||||
"productId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"sku" TEXT NOT NULL DEFAULT '',
|
||||
"price" INTEGER,
|
||||
"stock" INTEGER NOT NULL DEFAULT 0,
|
||||
"sort" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "ProductVariant_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Order" (
|
||||
"id" TEXT NOT NULL,
|
||||
"number" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"email" TEXT NOT NULL,
|
||||
"phone" TEXT NOT NULL DEFAULT '',
|
||||
"status" "OrderStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"paymentStatus" "PaymentStatus" NOT NULL DEFAULT 'OPEN',
|
||||
"paymentMethod" TEXT NOT NULL,
|
||||
"paymentRef" TEXT NOT NULL DEFAULT '',
|
||||
"shippingMethod" TEXT NOT NULL,
|
||||
"shippingAddress" JSONB NOT NULL,
|
||||
"billingAddress" JSONB,
|
||||
"subtotal" INTEGER NOT NULL,
|
||||
"shippingCost" INTEGER NOT NULL,
|
||||
"paymentFee" INTEGER NOT NULL DEFAULT 0,
|
||||
"discount" INTEGER NOT NULL DEFAULT 0,
|
||||
"couponCode" TEXT NOT NULL DEFAULT '',
|
||||
"taxAmount" INTEGER NOT NULL,
|
||||
"total" INTEGER NOT NULL,
|
||||
"note" TEXT NOT NULL DEFAULT '',
|
||||
"internalNote" TEXT NOT NULL DEFAULT '',
|
||||
"trackingNumber" TEXT NOT NULL DEFAULT '',
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Order_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "OrderItem" (
|
||||
"id" TEXT NOT NULL,
|
||||
"orderId" TEXT NOT NULL,
|
||||
"productId" TEXT,
|
||||
"variantId" TEXT,
|
||||
"name" TEXT NOT NULL,
|
||||
"variantName" TEXT NOT NULL DEFAULT '',
|
||||
"sku" TEXT NOT NULL DEFAULT '',
|
||||
"unitPrice" INTEGER NOT NULL,
|
||||
"quantity" INTEGER NOT NULL,
|
||||
"taxRate" INTEGER NOT NULL,
|
||||
"total" INTEGER NOT NULL,
|
||||
|
||||
CONSTRAINT "OrderItem_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "OrderEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"orderId" TEXT NOT NULL,
|
||||
"message" TEXT NOT NULL,
|
||||
"author" TEXT NOT NULL DEFAULT 'System',
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "OrderEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "PaymentMethod" (
|
||||
"id" TEXT NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT NOT NULL DEFAULT '',
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"sort" INTEGER NOT NULL DEFAULT 0,
|
||||
"fee" INTEGER NOT NULL DEFAULT 0,
|
||||
"minTotal" INTEGER NOT NULL DEFAULT 0,
|
||||
"maxTotal" INTEGER NOT NULL DEFAULT 0,
|
||||
"loggedInOnly" BOOLEAN NOT NULL DEFAULT false,
|
||||
"config" JSONB NOT NULL DEFAULT '{}',
|
||||
|
||||
CONSTRAINT "PaymentMethod_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ShippingMethod" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT NOT NULL DEFAULT '',
|
||||
"price" INTEGER NOT NULL,
|
||||
"freeFrom" INTEGER NOT NULL DEFAULT 0,
|
||||
"countries" TEXT[] DEFAULT ARRAY['DE']::TEXT[],
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"sort" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "ShippingMethod_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Coupon" (
|
||||
"id" TEXT NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"type" TEXT NOT NULL DEFAULT 'percent',
|
||||
"value" INTEGER NOT NULL,
|
||||
"minTotal" INTEGER NOT NULL DEFAULT 0,
|
||||
"maxUses" INTEGER NOT NULL DEFAULT 0,
|
||||
"usedCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"validUntil" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "Coupon_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Page" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"content" TEXT NOT NULL DEFAULT '',
|
||||
"published" BOOLEAN NOT NULL DEFAULT true,
|
||||
"showInFooter" TEXT NOT NULL DEFAULT '',
|
||||
"sort" INTEGER NOT NULL DEFAULT 0,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Page_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Setting" (
|
||||
"key" TEXT NOT NULL,
|
||||
"value" JSONB NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Setting_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "NewsletterSubscriber" (
|
||||
"id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "NewsletterSubscriber_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AuditLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"userEmail" TEXT NOT NULL DEFAULT '',
|
||||
"action" TEXT NOT NULL,
|
||||
"details" TEXT NOT NULL DEFAULT '',
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Role_name_key" ON "Role"("name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Session_tokenHash_key" ON "Session"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Category_slug_key" ON "Category"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Product_slug_key" ON "Product"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Order_number_key" ON "Order"("number");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PaymentMethod_code_key" ON "PaymentMethod"("code");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Coupon_code_key" ON "Coupon"("code");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Page_slug_key" ON "Page"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "NewsletterSubscriber_email_key" ON "NewsletterSubscriber"("email");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "User" ADD CONSTRAINT "User_roleId_fkey" FOREIGN KEY ("roleId") REFERENCES "Role"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Address" ADD CONSTRAINT "Address_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Product" ADD CONSTRAINT "Product_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "Category"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ProductVariant" ADD CONSTRAINT "ProductVariant_productId_fkey" FOREIGN KEY ("productId") REFERENCES "Product"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Order" ADD CONSTRAINT "Order_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "OrderItem" ADD CONSTRAINT "OrderItem_orderId_fkey" FOREIGN KEY ("orderId") REFERENCES "Order"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "OrderItem" ADD CONSTRAINT "OrderItem_productId_fkey" FOREIGN KEY ("productId") REFERENCES "Product"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "OrderEvent" ADD CONSTRAINT "OrderEvent_orderId_fkey" FOREIGN KEY ("orderId") REFERENCES "Order"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
3
prisma/migrations/migration_lock.toml
Normal file
3
prisma/migrations/migration_lock.toml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "postgresql"
|
||||
276
prisma/schema.prisma
Normal file
276
prisma/schema.prisma
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
// ---------- Benutzer, Rollen, Rechte ----------
|
||||
|
||||
model Role {
|
||||
id String @id @default(cuid())
|
||||
name String @unique
|
||||
description String @default("")
|
||||
// Liste von Rechte-Schlüsseln aus src/lib/permissions.ts
|
||||
permissions String[]
|
||||
// Systemrollen (Inhaber) können nicht gelöscht werden
|
||||
isSystem Boolean @default(false)
|
||||
users User[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
email String @unique
|
||||
passwordHash String
|
||||
firstName String @default("")
|
||||
lastName String @default("")
|
||||
phone String @default("")
|
||||
// Ohne Rolle ist ein Benutzer ein Kunde ohne Admin-Zugang
|
||||
roleId String?
|
||||
role Role? @relation(fields: [roleId], references: [id], onDelete: SetNull)
|
||||
active Boolean @default(true)
|
||||
newsletter Boolean @default(false)
|
||||
lastLoginAt DateTime?
|
||||
sessions Session[]
|
||||
orders Order[]
|
||||
addresses Address[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model Session {
|
||||
id String @id @default(cuid())
|
||||
tokenHash String @unique
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
expiresAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model Address {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
firstName String
|
||||
lastName String
|
||||
company String @default("")
|
||||
street String
|
||||
extra String @default("")
|
||||
zip String
|
||||
city String
|
||||
country String @default("DE")
|
||||
isDefault Boolean @default(false)
|
||||
}
|
||||
|
||||
// ---------- Katalog ----------
|
||||
|
||||
model Category {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
slug String @unique
|
||||
description String @default("")
|
||||
image String @default("")
|
||||
sort Int @default(0)
|
||||
active Boolean @default(true)
|
||||
showOnHome Boolean @default(true)
|
||||
products Product[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model Product {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
slug String @unique
|
||||
subtitle String @default("") // z. B. "Anthrazit · 8 mm"
|
||||
description String @default("")
|
||||
details String @default("") // Material & Pflege
|
||||
sku String @default("")
|
||||
// Preise in Cent, brutto
|
||||
price Int
|
||||
compareAtPrice Int?
|
||||
taxRate Int @default(19)
|
||||
stock Int @default(0)
|
||||
trackStock Boolean @default(true)
|
||||
active Boolean @default(true)
|
||||
featured Boolean @default(false)
|
||||
badge String @default("") // "", "new", "best"
|
||||
images String[]
|
||||
sort Int @default(0)
|
||||
categoryId String?
|
||||
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
||||
variants ProductVariant[]
|
||||
orderItems OrderItem[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model ProductVariant {
|
||||
id String @id @default(cuid())
|
||||
productId String
|
||||
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
|
||||
name String // z. B. "183 cm" oder "Anthrazit"
|
||||
sku String @default("")
|
||||
// Preis in Cent; leer = Produktpreis
|
||||
price Int?
|
||||
stock Int @default(0)
|
||||
sort Int @default(0)
|
||||
}
|
||||
|
||||
// ---------- Bestellungen ----------
|
||||
|
||||
enum OrderStatus {
|
||||
PENDING // angelegt, Zahlung offen
|
||||
PAID // bezahlt
|
||||
PROCESSING // in Bearbeitung
|
||||
SHIPPED // versendet
|
||||
COMPLETED // abgeschlossen
|
||||
CANCELLED // storniert
|
||||
REFUNDED // erstattet
|
||||
}
|
||||
|
||||
enum PaymentStatus {
|
||||
OPEN
|
||||
AUTHORIZED
|
||||
PAID
|
||||
FAILED
|
||||
REFUNDED
|
||||
}
|
||||
|
||||
model Order {
|
||||
id String @id @default(cuid())
|
||||
number String @unique
|
||||
userId String?
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
email String
|
||||
phone String @default("")
|
||||
status OrderStatus @default(PENDING)
|
||||
paymentStatus PaymentStatus @default(OPEN)
|
||||
paymentMethod String
|
||||
paymentRef String @default("")
|
||||
shippingMethod String
|
||||
shippingAddress Json
|
||||
billingAddress Json?
|
||||
subtotal Int
|
||||
shippingCost Int
|
||||
paymentFee Int @default(0)
|
||||
discount Int @default(0)
|
||||
couponCode String @default("")
|
||||
taxAmount Int
|
||||
total Int
|
||||
note String @default("")
|
||||
internalNote String @default("")
|
||||
trackingNumber String @default("")
|
||||
items OrderItem[]
|
||||
events OrderEvent[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model OrderItem {
|
||||
id String @id @default(cuid())
|
||||
orderId String
|
||||
order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)
|
||||
productId String?
|
||||
product Product? @relation(fields: [productId], references: [id], onDelete: SetNull)
|
||||
variantId String?
|
||||
name String
|
||||
variantName String @default("")
|
||||
sku String @default("")
|
||||
unitPrice Int
|
||||
quantity Int
|
||||
taxRate Int
|
||||
total Int
|
||||
}
|
||||
|
||||
model OrderEvent {
|
||||
id String @id @default(cuid())
|
||||
orderId String
|
||||
order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)
|
||||
message String
|
||||
author String @default("System")
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
// ---------- Konfiguration ----------
|
||||
|
||||
model PaymentMethod {
|
||||
id String @id @default(cuid())
|
||||
// stripe_card, stripe_sepa, stripe_klarna, paypal, prepayment, invoice, cod
|
||||
code String @unique
|
||||
name String
|
||||
description String @default("")
|
||||
enabled Boolean @default(false)
|
||||
sort Int @default(0)
|
||||
// Gebühr in Cent
|
||||
fee Int @default(0)
|
||||
// Mindest- und Höchstbestellwert in Cent (0 = keine Grenze)
|
||||
minTotal Int @default(0)
|
||||
maxTotal Int @default(0)
|
||||
// Nur für angemeldete Kunden (z. B. Rechnung)
|
||||
loggedInOnly Boolean @default(false)
|
||||
// Anbieter-spezifisch: Schlüssel, Testmodus, Bankdaten, Zahlungsziel …
|
||||
config Json @default("{}")
|
||||
}
|
||||
|
||||
model ShippingMethod {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
description String @default("")
|
||||
price Int
|
||||
// Ab diesem Warenwert kostenlos (0 = nie)
|
||||
freeFrom Int @default(0)
|
||||
countries String[] @default(["DE"])
|
||||
enabled Boolean @default(true)
|
||||
sort Int @default(0)
|
||||
}
|
||||
|
||||
model Coupon {
|
||||
id String @id @default(cuid())
|
||||
code String @unique
|
||||
// "percent" oder "fixed"
|
||||
type String @default("percent")
|
||||
value Int // Prozent oder Cent
|
||||
minTotal Int @default(0)
|
||||
maxUses Int @default(0)
|
||||
usedCount Int @default(0)
|
||||
active Boolean @default(true)
|
||||
validUntil DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model Page {
|
||||
id String @id @default(cuid())
|
||||
slug String @unique
|
||||
title String
|
||||
content String @default("")
|
||||
published Boolean @default(true)
|
||||
showInFooter String @default("") // "", "service", "company", "legal"
|
||||
sort Int @default(0)
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model Setting {
|
||||
key String @id
|
||||
value Json
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model NewsletterSubscriber {
|
||||
id String @id @default(cuid())
|
||||
email String @unique
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model AuditLog {
|
||||
id String @id @default(cuid())
|
||||
userId String?
|
||||
userEmail String @default("")
|
||||
action String
|
||||
details String @default("")
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
112
prisma/seed.ts
Normal file
112
prisma/seed.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
// Grunddaten: Rollen, Inhaber-Zugang, Zahlungs- und Versandarten, Rechtsseiten, Beispielkatalog.
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { ALL_PERMISSIONS } from "../src/lib/permissions";
|
||||
import { PAYMENT_DEFINITIONS } from "../src/lib/payments/catalog";
|
||||
|
||||
const db = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
const owner = await db.role.upsert({
|
||||
where: { name: "Inhaber" },
|
||||
create: { name: "Inhaber", description: "Voller Zugriff auf alles, kann nicht eingeschränkt werden.", permissions: ALL_PERMISSIONS, isSystem: true },
|
||||
update: { permissions: ALL_PERMISSIONS, isSystem: true },
|
||||
});
|
||||
await db.role.upsert({
|
||||
where: { name: "Shop-Manager" },
|
||||
create: {
|
||||
name: "Shop-Manager",
|
||||
description: "Bestellungen, Katalog, Kunden und Inhalte – ohne Team, Rollen und Zahlungszugänge.",
|
||||
permissions: ["dashboard.view", "orders.view", "orders.edit", "orders.refund", "products.view", "products.edit", "products.delete", "categories.edit", "stock.edit", "customers.view", "customers.edit", "coupons.edit", "newsletter.view", "content.edit", "appearance.edit", "shipping.edit"],
|
||||
},
|
||||
update: {},
|
||||
});
|
||||
await db.role.upsert({
|
||||
where: { name: "Versand" },
|
||||
create: { name: "Versand", description: "Sieht Bestellungen und trägt Versand und Sendungsnummern ein.", permissions: ["dashboard.view", "orders.view", "orders.edit", "products.view", "stock.edit"] },
|
||||
update: {},
|
||||
});
|
||||
await db.role.upsert({
|
||||
where: { name: "Redaktion" },
|
||||
create: { name: "Redaktion", description: "Pflegt Produkttexte, Seiten und die Startseite.", permissions: ["dashboard.view", "products.view", "products.edit", "content.edit", "appearance.edit"] },
|
||||
update: {},
|
||||
});
|
||||
|
||||
const email = (process.env.ADMIN_EMAIL ?? "admin@sanamare.de").toLowerCase();
|
||||
const password = process.env.ADMIN_PASSWORD ?? "sanamare-admin";
|
||||
const existing = await db.user.findUnique({ where: { email } });
|
||||
if (!existing) {
|
||||
await db.user.create({ data: { email, firstName: "Max", lastName: "", passwordHash: await bcrypt.hash(password, 12), roleId: owner.id } });
|
||||
console.log(`Inhaber-Zugang angelegt: ${email}`);
|
||||
}
|
||||
|
||||
for (const [i, def] of PAYMENT_DEFINITIONS.entries()) {
|
||||
await db.paymentMethod.upsert({
|
||||
where: { code: def.code },
|
||||
create: {
|
||||
code: def.code,
|
||||
name: def.defaultName,
|
||||
description: def.defaultDescription,
|
||||
sort: i,
|
||||
enabled: def.provider === "manual" && def.code !== "cod",
|
||||
loggedInOnly: def.code === "invoice",
|
||||
fee: def.code === "cod" ? 700 : 0,
|
||||
config: def.defaultConfig ?? {},
|
||||
},
|
||||
update: {},
|
||||
});
|
||||
}
|
||||
|
||||
if ((await db.shippingMethod.count()) === 0) {
|
||||
await db.shippingMethod.createMany({
|
||||
data: [
|
||||
{ name: "Standardversand (DHL)", description: "Lieferung in 2–4 Werktagen, klimaneutral.", price: 495, freeFrom: 8000, countries: ["DE"], sort: 0 },
|
||||
{ name: "Expressversand", description: "Lieferung am nächsten Werktag bei Bestellung bis 14 Uhr.", price: 1290, freeFrom: 0, countries: ["DE"], sort: 1 },
|
||||
{ name: "Versand EU", description: "Lieferung in 4–7 Werktagen.", price: 1290, freeFrom: 15000, countries: ["AT", "CH", "NL", "BE", "LU", "FR", "IT", "ES", "DK", "PL"], sort: 2 },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const pages = [
|
||||
{ slug: "versand", title: "Versand & Lieferung", showInFooter: "service", content: "## Lieferzeit\nWir liefern innerhalb Deutschlands in 2–4 Werktagen.\n\n## Versandkosten\nKostenloser Versand ab 80 €. Darunter berechnen wir 4,95 €." },
|
||||
{ slug: "rueckgabe", title: "Rückgabe", showInFooter: "service", content: "Du kannst innerhalb von 30 Tagen zurückgeben. Schreib uns eine kurze Nachricht, wir schicken dir ein Rücksendeetikett." },
|
||||
{ slug: "kontakt", title: "Kontakt", showInFooter: "service", content: "Du erreichst uns Mo–Fr von 9 bis 18 Uhr.\n\nE-Mail: [hallo@sanamare.de](mailto:hallo@sanamare.de)" },
|
||||
{ slug: "ueber-uns", title: "Über uns", showInFooter: "company", content: "Sanamare ist ein Pilates-Studio mit eigenem Shop. Wir verkaufen nur, was wir selbst im Studio benutzen." },
|
||||
{ slug: "studio", title: "Studio", showInFooter: "company", content: "Hier stellen wir bald unser Studio vor." },
|
||||
{ slug: "journal", title: "Journal", showInFooter: "company", content: "Hier erscheinen bald Übungen, Tipps und Neuigkeiten aus dem Studio." },
|
||||
{ slug: "impressum", title: "Impressum", showInFooter: "legal", content: "Bitte im Admin unter Inhalte → Seiten ausfüllen." },
|
||||
{ slug: "datenschutz", title: "Datenschutz", showInFooter: "legal", content: "Bitte im Admin unter Inhalte → Seiten ausfüllen." },
|
||||
{ slug: "agb", title: "AGB", showInFooter: "legal", content: "Bitte im Admin unter Inhalte → Seiten ausfüllen." },
|
||||
{ slug: "widerruf", title: "Widerruf", showInFooter: "legal", content: "Bitte im Admin unter Inhalte → Seiten ausfüllen." },
|
||||
];
|
||||
for (const [i, p] of pages.entries()) await db.page.upsert({ where: { slug: p.slug }, create: { ...p, sort: i }, update: {} });
|
||||
|
||||
if ((await db.category.count()) === 0) {
|
||||
const mats = await db.category.create({ data: { name: "Matten", slug: "matten", description: "Rutschfest, langlebig, angenehm unter den Händen.", sort: 0 } });
|
||||
const gear = await db.category.create({ data: { name: "Kleingeräte", slug: "kleingeraete", description: "Ringe, Bälle und Bänder für dein Training.", sort: 1 } });
|
||||
const wear = await db.category.create({ data: { name: "Bekleidung", slug: "bekleidung", description: "Bequem in jeder Position.", sort: 2 } });
|
||||
const products = [
|
||||
{ name: "Reformer Matte Pro", slug: "reformer-matte-pro", subtitle: "Anthrazit · 8 mm", price: 12900, compareAtPrice: 14900, stock: 24, featured: true, badge: "new", categoryId: mats.id, sku: "SM-2041", description: "Griffige Oberfläche, 8 mm stark, aus recyceltem Naturkautschuk. Rutschfest auf jedem Boden, auch bei langen Flows.", details: "Naturkautschuk, PVC-frei. Mit lauwarmem Wasser und einem weichen Tuch abwischen, liegend trocknen.", variants: [{ name: "173 cm", stock: 8 }, { name: "183 cm", stock: 12 }, { name: "200 cm", stock: 0, price: 13900 }] },
|
||||
{ name: "Pilates Ring Studio", slug: "pilates-ring-studio", subtitle: "Schwarz / Gold", price: 4900, compareAtPrice: 5900, stock: 40, featured: true, categoryId: gear.id, sku: "SM-1102", description: "Leichter, stabiler Ring mit gepolsterten Griffen für Innen- und Außenseite." },
|
||||
{ name: "Grip Socks, 2er-Pack", slug: "grip-socks", subtitle: "Sand", price: 2400, stock: 120, featured: true, badge: "best", categoryId: wear.id, sku: "SM-3010", description: "Rutschfeste Socken für Reformer und Matte.", variants: [{ name: "35–37", stock: 30 }, { name: "38–40", stock: 50 }, { name: "41–43", stock: 40 }] },
|
||||
{ name: "Flow Leggings", slug: "flow-leggings", subtitle: "Nachtblau · hoher Bund", price: 8900, stock: 30, featured: true, categoryId: wear.id, sku: "SM-3201", description: "Blickdicht, weich und mit hohem Bund, der nicht rutscht.", variants: [{ name: "XS", stock: 5 }, { name: "S", stock: 10 }, { name: "M", stock: 10 }, { name: "L", stock: 5 }] },
|
||||
{ name: "Soft Ball", slug: "soft-ball", subtitle: "Ø 25 cm", price: 1900, stock: 2, categoryId: gear.id, sku: "SM-1120", description: "Weicher Ball für Mobilisation und Stabilisation." },
|
||||
{ name: "Resistance Band Set", slug: "resistance-band-set", subtitle: "3 Stärken", price: 3400, stock: 60, categoryId: gear.id, sku: "SM-1140", description: "Drei Bänder aus Stoff in leicht, mittel und stark." },
|
||||
];
|
||||
for (const [i, p] of products.entries()) {
|
||||
const { variants, ...data } = p;
|
||||
await db.product.create({
|
||||
data: { ...data, images: [], sort: i, variants: variants ? { create: variants.map((v, j) => ({ ...v, sort: j })) } : undefined },
|
||||
});
|
||||
}
|
||||
await db.coupon.create({ data: { code: "WILLKOMMEN10", type: "percent", value: 10 } });
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
.then(() => db.$disconnect())
|
||||
.catch(async (e) => {
|
||||
console.error(e);
|
||||
await db.$disconnect();
|
||||
process.exit(1);
|
||||
});
|
||||
BIN
public/brand/bildmarke-gold.png
Normal file
BIN
public/brand/bildmarke-gold.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 218 KiB |
BIN
public/brand/bildmarke-ink.png
Normal file
BIN
public/brand/bildmarke-ink.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 65 KiB |
BIN
public/brand/logo-gold-auf-schwarz.png
Normal file
BIN
public/brand/logo-gold-auf-schwarz.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 356 KiB |
BIN
public/brand/logo-gold.png
Normal file
BIN
public/brand/logo-gold.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 321 KiB |
BIN
public/brand/logo-ink.png
Normal file
BIN
public/brand/logo-ink.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 97 KiB |
47
scripts/build-tokens.mjs
Normal file
47
scripts/build-tokens.mjs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
// Erzeugt src/styles/tokens.css aus design/tokens.json (Sanamare Design System).
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const t = JSON.parse(readFileSync(new URL("../design/tokens.json", import.meta.url)));
|
||||
const themes = t.color.themes.map((x) => x.id);
|
||||
const first = themes[0];
|
||||
|
||||
const colorValue = (v, theme) => {
|
||||
const raw = typeof v === "string" ? v : v[theme] ?? v[first];
|
||||
return raw.startsWith("{") ? `var(--${raw.slice(1, -1)})` : raw;
|
||||
};
|
||||
const themed = (v, theme) => (typeof v === "string" ? v : v[theme] ?? v[first]);
|
||||
|
||||
const block = (theme) => {
|
||||
const lines = [];
|
||||
for (const tok of t.color.tokens) lines.push(` --${tok.name}: ${colorValue(tok.value, theme)};`);
|
||||
for (const tok of t.shadow?.tokens ?? []) lines.push(` --${tok.name}: ${themed(tok.value, theme)};`);
|
||||
return lines.join("\n");
|
||||
};
|
||||
|
||||
let css = `/* ${t.name} — generated from design/tokens.json (npm run tokens) */\n:root {\n`;
|
||||
for (const [k, v] of Object.entries(t.type.families)) css += ` --font-${k}: ${v};\n`;
|
||||
for (const fam of ["spacing", "radius", "layout", "breakpoint"])
|
||||
for (const tok of t[fam]?.tokens ?? []) css += ` --${tok.name}: ${tok.value};\n`;
|
||||
css += block(first) + "\n color-scheme: light;\n}\n";
|
||||
for (const th of themes.slice(1)) {
|
||||
css += `[data-theme="${th}"] {\n${block(th)}\n color-scheme: ${th};\n background-color: var(--surface);\n color: var(--ink);\n}\n`;
|
||||
}
|
||||
for (const g of t.type.groups) {
|
||||
for (const s of g.styles) {
|
||||
const props = [
|
||||
`font-family: var(--font-${g.family})`,
|
||||
`font-size: ${s.fontSize}`,
|
||||
`line-height: ${s.lineHeight}`,
|
||||
`font-weight: ${s.fontWeight}`,
|
||||
];
|
||||
if (s.letterSpacing) props.push(`letter-spacing: ${s.letterSpacing}`);
|
||||
if (s.fontStyle) props.push(`font-style: ${s.fontStyle}`);
|
||||
if (["button", "nav", "eyebrow", "wordmark"].includes(s.name)) props.push("text-transform: uppercase");
|
||||
if (s.name === "eyebrow") props.push("color: var(--gold-deep)");
|
||||
if (s.name.startsWith("price")) props.push("font-variant-numeric: tabular-nums");
|
||||
css += `.${s.name} { ${props.join("; ")}; }\n`;
|
||||
}
|
||||
}
|
||||
css += `@media (max-width: 767px) { .display-xl { font-size: 44px; line-height: 1.05; } .display-lg { font-size: 34px; } }\n`;
|
||||
writeFileSync(new URL("../src/styles/tokens.css", import.meta.url), css);
|
||||
console.log("tokens.css geschrieben");
|
||||
69
src/app/(shop)/actions.ts
Normal file
69
src/app/(shop)/actions.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
"use server";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db";
|
||||
import { readCartCookie, writeCartCookie } from "@/lib/cart";
|
||||
import { findCoupon } from "@/lib/pricing";
|
||||
|
||||
export async function subscribeNewsletter(_prev: unknown, formData: FormData) {
|
||||
const email = z.email().safeParse(String(formData.get("email") ?? "").trim().toLowerCase());
|
||||
if (!email.success) return { ok: false, error: "Bitte gib eine gültige E-Mail-Adresse ein." };
|
||||
await db.newsletterSubscriber.upsert({ where: { email: email.data }, create: { email: email.data }, update: {} });
|
||||
return { ok: true, error: null };
|
||||
}
|
||||
|
||||
export async function addToCart(formData: FormData) {
|
||||
const productId = String(formData.get("productId") ?? "");
|
||||
const variantId = String(formData.get("variantId") ?? "") || null;
|
||||
const quantity = Math.max(1, Math.min(99, Number(formData.get("quantity") ?? 1) || 1));
|
||||
const product = await db.product.findFirst({ where: { id: productId, active: true }, include: { variants: true } });
|
||||
if (!product) return;
|
||||
if (product.variants.length > 0 && !product.variants.some((v) => v.id === variantId)) {
|
||||
redirect(`/produkt/${product.slug}?variante=fehlt`);
|
||||
}
|
||||
const entries = await readCartCookie();
|
||||
const existing = entries.find((e) => e.p === productId && e.v === variantId);
|
||||
if (existing) existing.q = Math.min(99, existing.q + quantity);
|
||||
else entries.push({ p: productId, v: variantId, q: quantity });
|
||||
await writeCartCookie(entries);
|
||||
revalidatePath("/", "layout");
|
||||
const back = String(formData.get("redirectTo") ?? "");
|
||||
redirect(back.startsWith("/") ? back : "/warenkorb?hinzugefuegt=1");
|
||||
}
|
||||
|
||||
export async function updateCartLine(formData: FormData) {
|
||||
const [productId, variantRaw] = String(formData.get("key") ?? "").split(":");
|
||||
const variantId = variantRaw || null;
|
||||
const quantity = Number(formData.get("quantity"));
|
||||
let entries = await readCartCookie();
|
||||
if (!Number.isFinite(quantity) || quantity <= 0) {
|
||||
entries = entries.filter((e) => !(e.p === productId && e.v === variantId));
|
||||
} else {
|
||||
const e = entries.find((x) => x.p === productId && x.v === variantId);
|
||||
if (e) e.q = Math.min(99, Math.round(quantity));
|
||||
}
|
||||
await writeCartCookie(entries);
|
||||
revalidatePath("/", "layout");
|
||||
}
|
||||
|
||||
export async function applyCoupon(_prev: unknown, formData: FormData) {
|
||||
const code = String(formData.get("code") ?? "").trim().toUpperCase();
|
||||
const jar = await cookies();
|
||||
if (!code) {
|
||||
jar.delete("sm_coupon");
|
||||
revalidatePath("/warenkorb");
|
||||
return { error: null };
|
||||
}
|
||||
const { error } = await findCoupon(code, Number.MAX_SAFE_INTEGER);
|
||||
if (error) return { error };
|
||||
jar.set("sm_coupon", code, { httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 7 });
|
||||
revalidatePath("/", "layout");
|
||||
return { error: null };
|
||||
}
|
||||
|
||||
export async function removeCoupon() {
|
||||
(await cookies()).delete("sm_coupon");
|
||||
revalidatePath("/", "layout");
|
||||
}
|
||||
131
src/app/(shop)/kasse/actions.ts
Normal file
131
src/app/(shop)/kasse/actions.ts
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
"use server";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { getCart } from "@/lib/cart";
|
||||
import { finishCheckoutSession } from "@/lib/checkout-finish";
|
||||
import { availablePayments, availableShipping, createOrder, readCheckout, writeCheckout } from "@/lib/checkout";
|
||||
import { computeTotals } from "@/lib/pricing";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
import { getDefinition } from "@/lib/payments/catalog";
|
||||
import { getCredentials } from "@/lib/payments/credentials";
|
||||
import { createCheckoutSession } from "@/lib/payments/stripe";
|
||||
import { createPaypalOrder } from "@/lib/payments/paypal";
|
||||
|
||||
export type FormState = { errors?: Record<string, string>; message?: string } | null;
|
||||
|
||||
const addressSchema = z.object({
|
||||
firstName: z.string().trim().min(1, "Bitte gib deinen Vornamen ein."),
|
||||
lastName: z.string().trim().min(1, "Bitte gib deinen Nachnamen ein."),
|
||||
company: z.string().trim().default(""),
|
||||
street: z.string().trim().min(3, "Bitte gib Straße und Hausnummer ein."),
|
||||
extra: z.string().trim().default(""),
|
||||
zip: z.string().trim().regex(/^[0-9A-Za-z -]{4,10}$/, "Bitte gib eine gültige Postleitzahl ein."),
|
||||
city: z.string().trim().min(2, "Bitte gib deinen Ort ein."),
|
||||
country: z.string().trim().length(2, "Bitte wähle ein Land."),
|
||||
});
|
||||
|
||||
function pick(formData: FormData, prefix = "") {
|
||||
const o: Record<string, string> = {};
|
||||
for (const k of ["firstName", "lastName", "company", "street", "extra", "zip", "city", "country"]) o[k] = String(formData.get(prefix + k) ?? "");
|
||||
return o;
|
||||
}
|
||||
|
||||
export async function saveAddress(_prev: FormState, formData: FormData): Promise<FormState> {
|
||||
const settings = await getSettings();
|
||||
const errors: Record<string, string> = {};
|
||||
const email = z.email().safeParse(String(formData.get("email") ?? "").trim().toLowerCase());
|
||||
if (!email.success) errors.email = "Bitte gib eine gültige E-Mail-Adresse ein.";
|
||||
const phone = String(formData.get("phone") ?? "").trim();
|
||||
if (settings.checkout.requirePhone && phone.length < 5) errors.phone = "Bitte gib deine Telefonnummer ein.";
|
||||
const address = addressSchema.safeParse(pick(formData));
|
||||
if (!address.success) for (const i of address.error.issues) errors[String(i.path[0])] ??= i.message;
|
||||
if (address.success && !settings.checkout.countries.includes(address.data.country)) errors.country = "In dieses Land liefern wir leider nicht.";
|
||||
const billingSame = formData.get("billingSame") === "on";
|
||||
let billing;
|
||||
if (!billingSame) {
|
||||
const b = addressSchema.safeParse(pick(formData, "b_"));
|
||||
if (!b.success) for (const i of b.error.issues) errors["b_" + String(i.path[0])] ??= i.message;
|
||||
else billing = b.data;
|
||||
}
|
||||
if (Object.keys(errors).length) return { errors, message: "Bitte prüfe die markierten Felder." };
|
||||
await writeCheckout({
|
||||
email: email.data,
|
||||
phone,
|
||||
address: address.data,
|
||||
billingSame,
|
||||
billing,
|
||||
newsletter: formData.get("newsletter") === "on",
|
||||
});
|
||||
redirect("/kasse/versand");
|
||||
}
|
||||
|
||||
export async function saveShipping(_prev: FormState, formData: FormData): Promise<FormState> {
|
||||
const id = String(formData.get("shippingMethodId") ?? "");
|
||||
const state = await readCheckout();
|
||||
const methods = await availableShipping(state.address?.country);
|
||||
if (!methods.some((m) => m.id === id)) return { message: "Bitte wähle eine Versandart." };
|
||||
await writeCheckout({ shippingMethodId: id });
|
||||
redirect("/kasse/zahlung");
|
||||
}
|
||||
|
||||
export async function savePayment(_prev: FormState, formData: FormData): Promise<FormState> {
|
||||
const id = String(formData.get("paymentMethodId") ?? "");
|
||||
const [lines, user, jar] = await Promise.all([getCart(), getCurrentUser(), cookies()]);
|
||||
const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value });
|
||||
const methods = await availablePayments(totals.total, Boolean(user));
|
||||
if (!methods.some((m) => m.id === id)) return { message: "Bitte wähle eine Zahlungsart." };
|
||||
await writeCheckout({ paymentMethodId: id });
|
||||
redirect("/kasse/pruefen");
|
||||
}
|
||||
|
||||
export async function placeOrder(_prev: FormState, formData: FormData): Promise<FormState> {
|
||||
const settings = await getSettings();
|
||||
if (settings.checkout.requireTerms && formData.get("terms") !== "on") {
|
||||
return { errors: { terms: "Bitte bestätige die AGB und die Widerrufsbelehrung." } };
|
||||
}
|
||||
const [state, lines, user, jar] = await Promise.all([readCheckout(), getCart(), getCurrentUser(), cookies()]);
|
||||
if (!lines.length) redirect("/warenkorb");
|
||||
if (!state.email || !state.address) redirect("/kasse/adresse");
|
||||
const shipping = state.shippingMethodId ? await db.shippingMethod.findUnique({ where: { id: state.shippingMethodId } }) : null;
|
||||
if (!shipping?.enabled) redirect("/kasse/versand");
|
||||
const payment = state.paymentMethodId ? await db.paymentMethod.findUnique({ where: { id: state.paymentMethodId } }) : null;
|
||||
if (!payment?.enabled) redirect("/kasse/zahlung");
|
||||
const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value, shipping, payment });
|
||||
if (settings.checkout.minOrderValue > 0 && totals.subtotal < settings.checkout.minOrderValue) redirect("/warenkorb");
|
||||
|
||||
let order;
|
||||
try {
|
||||
order = await createOrder({ state, lines, totals, shippingName: shipping.name, payment, userId: user?.id ?? null, note: String(formData.get("note") ?? "").slice(0, 1000) });
|
||||
} catch (e) {
|
||||
return { message: e instanceof Error ? e.message : "Die Bestellung konnte nicht angelegt werden." };
|
||||
}
|
||||
await writeCheckout({ lastOrderId: order.id });
|
||||
jar.set("sm_last_order", order.id, { httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 30 });
|
||||
|
||||
const def = getDefinition(payment.code);
|
||||
const appUrl = (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
|
||||
let target: string;
|
||||
try {
|
||||
if (def?.provider === "stripe") {
|
||||
const creds = await getCredentials();
|
||||
const session = await createCheckoutSession({ secretKey: creds.stripe.secretKey, order, stripeType: def.stripeType!, appUrl });
|
||||
await db.order.update({ where: { id: order.id }, data: { paymentRef: session.id } });
|
||||
target = session.url;
|
||||
} else if (def?.provider === "paypal") {
|
||||
const creds = await getCredentials();
|
||||
const pp = await createPaypalOrder(creds.paypal, order, appUrl);
|
||||
await db.order.update({ where: { id: order.id }, data: { paymentRef: pp.id } });
|
||||
target = pp.url;
|
||||
} else {
|
||||
await finishCheckoutSession();
|
||||
target = `/kasse/danke/${order.id}`;
|
||||
}
|
||||
} catch (e) {
|
||||
await db.orderEvent.create({ data: { orderId: order.id, message: `Zahlung konnte nicht gestartet werden: ${e instanceof Error ? e.message : e}` } });
|
||||
return { message: "Die Zahlung konnte nicht gestartet werden. Bitte wähle eine andere Zahlungsart oder versuche es gleich noch einmal." };
|
||||
}
|
||||
redirect(target);
|
||||
}
|
||||
50
src/app/(shop)/kasse/adresse/page.tsx
Normal file
50
src/app/(shop)/kasse/adresse/page.tsx
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import Link from "next/link";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { COUNTRIES, getSettings } from "@/lib/settings";
|
||||
import { AddressForm } from "@/components/shop/AddressForm";
|
||||
import { CheckoutSummary, loadCheckout } from "../shared";
|
||||
|
||||
export const metadata = { title: "Kasse – Adresse" };
|
||||
|
||||
export default async function AddressStep() {
|
||||
const [data, user, settings] = await Promise.all([loadCheckout(), getCurrentUser(), getSettings()]);
|
||||
if (!user && !settings.checkout.guestCheckout) {
|
||||
return (
|
||||
<div className="sm-auth sm-box" style={{ textAlign: "center" }}>
|
||||
<h1 className="display-md" style={{ marginBottom: "var(--space-3)" }}>Bitte melde dich an</h1>
|
||||
<p className="body" style={{ color: "var(--ink-muted)" }}>Für eine Bestellung brauchst du ein Kundenkonto.</p>
|
||||
<div className="sm-btn-row" style={{ justifyContent: "center" }}>
|
||||
<Link className="sm-btn sm-btn--primary" href="/konto/anmelden?weiter=/kasse/adresse">Anmelden</Link>
|
||||
<Link className="sm-btn sm-btn--secondary" href="/konto/registrieren?weiter=/kasse/adresse">Konto erstellen</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const saved = user ? await db.address.findFirst({ where: { userId: user.id }, orderBy: { isDefault: "desc" } }) : null;
|
||||
const s = data.state;
|
||||
const address = s.address ?? (saved ?? (user ? { firstName: user.firstName, lastName: user.lastName } : undefined));
|
||||
return (
|
||||
<div className="sm-checkout">
|
||||
<div>
|
||||
{!user && (
|
||||
<p className="body" style={{ marginBottom: "var(--space-6)" }}>
|
||||
Schon Kunde? <Link href="/konto/anmelden?weiter=/kasse/adresse">Anmelden</Link> · Du kannst auch als Gast bestellen.
|
||||
</p>
|
||||
)}
|
||||
<AddressForm
|
||||
email={user?.email ?? s.email}
|
||||
emailLocked={Boolean(user)}
|
||||
phone={s.phone ?? user?.phone}
|
||||
address={address ?? undefined}
|
||||
billing={s.billing}
|
||||
billingSame={s.billingSame ?? true}
|
||||
newsletter={s.newsletter ?? false}
|
||||
requirePhone={settings.checkout.requirePhone}
|
||||
countries={settings.checkout.countries.map((c) => [c, COUNTRIES[c] ?? c])}
|
||||
/>
|
||||
</div>
|
||||
<CheckoutSummary data={data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
73
src/app/(shop)/kasse/danke/[id]/page.tsx
Normal file
73
src/app/(shop)/kasse/danke/[id]/page.tsx
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import Link from "next/link";
|
||||
import { cookies } from "next/headers";
|
||||
import { notFound } from "next/navigation";
|
||||
import { db } from "@/lib/db";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { Alert } from "@/components/shop/Blocks";
|
||||
|
||||
export const metadata = { title: "Danke für deine Bestellung" };
|
||||
|
||||
export default async function ThanksPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const [order, jar, user] = await Promise.all([
|
||||
db.order.findUnique({ where: { id }, include: { items: true } }),
|
||||
cookies(),
|
||||
getCurrentUser(),
|
||||
]);
|
||||
if (!order) notFound();
|
||||
const allowed = jar.get("sm_last_order")?.value === order.id || (user && order.userId === user.id);
|
||||
if (!allowed) notFound();
|
||||
const payment = await db.paymentMethod.findUnique({ where: { code: order.paymentMethod } });
|
||||
const cfg = (payment?.config ?? {}) as Record<string, string>;
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 720, margin: "0 auto" }}>
|
||||
<span className="eyebrow">Bestellung {order.number}</span>
|
||||
<h1 className="display-lg" style={{ margin: "var(--space-2) 0 var(--space-4)" }}>Danke für deine Bestellung.</h1>
|
||||
<p className="body" style={{ color: "var(--ink-muted)" }}>
|
||||
Wir haben deine Bestellung erhalten und melden uns an {order.email}, sobald sie unterwegs ist.
|
||||
</p>
|
||||
{order.paymentMethod === "prepayment" && (
|
||||
<div style={{ margin: "var(--space-5) 0" }}>
|
||||
<Alert title={`Bitte überweise ${formatPrice(order.total)}.`}>
|
||||
<span style={{ display: "block" }}>Kontoinhaber: {cfg.accountHolder}</span>
|
||||
<span style={{ display: "block" }}>IBAN: {cfg.iban}</span>
|
||||
{cfg.bic && <span style={{ display: "block" }}>BIC: {cfg.bic}</span>}
|
||||
{cfg.bank && <span style={{ display: "block" }}>Bank: {cfg.bank}</span>}
|
||||
<span style={{ display: "block" }}>Verwendungszweck: {order.number}</span>
|
||||
Wir versenden, sobald das Geld da ist.
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
{order.paymentMethod === "invoice" && (
|
||||
<div style={{ margin: "var(--space-5) 0" }}>
|
||||
<Alert title="Du bezahlst bequem nach Erhalt.">Die Rechnung liegt dem Paket bei. Zahlungsziel: {cfg.dueDays || 14} Tage.</Alert>
|
||||
</div>
|
||||
)}
|
||||
{order.paymentStatus === "PAID" && (
|
||||
<div style={{ margin: "var(--space-5) 0" }}><Alert kind="success" title="Deine Zahlung ist bestätigt." /></div>
|
||||
)}
|
||||
<div className="sm-box" style={{ marginTop: "var(--space-5)" }}>
|
||||
<table className="sm-table">
|
||||
<tbody>
|
||||
{order.items.map((i) => (
|
||||
<tr key={i.id}>
|
||||
<td>{i.quantity} × {i.name}{i.variantName ? ` – ${i.variantName}` : ""}</td>
|
||||
<td style={{ textAlign: "right" }}>{formatPrice(i.total)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr><td>Versand ({order.shippingMethod})</td><td style={{ textAlign: "right" }}>{order.shippingCost ? formatPrice(order.shippingCost) : "Kostenlos"}</td></tr>
|
||||
{order.discount > 0 && <tr><td>Gutschein {order.couponCode}</td><td style={{ textAlign: "right" }}>−{formatPrice(order.discount)}</td></tr>}
|
||||
{order.paymentFee > 0 && <tr><td>Gebühr Zahlungsart</td><td style={{ textAlign: "right" }}>{formatPrice(order.paymentFee)}</td></tr>}
|
||||
<tr><td><strong>Gesamt</strong></td><td style={{ textAlign: "right" }}><strong>{formatPrice(order.total)}</strong></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="sm-btn-row" style={{ marginTop: "var(--space-6)" }}>
|
||||
<Link className="sm-btn sm-btn--primary" href="/shop">Weiter einkaufen</Link>
|
||||
{!user && <Link className="sm-btn sm-btn--secondary" href={`/konto/registrieren?email=${encodeURIComponent(order.email)}`}>Konto erstellen</Link>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
10
src/app/(shop)/kasse/layout.tsx
Normal file
10
src/app/(shop)/kasse/layout.tsx
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { CheckoutSteps } from "@/components/shop/CheckoutSteps";
|
||||
|
||||
export default function CheckoutLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<CheckoutSteps />
|
||||
{children}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
4
src/app/(shop)/kasse/page.tsx
Normal file
4
src/app/(shop)/kasse/page.tsx
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import { redirect } from "next/navigation";
|
||||
export default function Kasse() {
|
||||
redirect("/kasse/adresse");
|
||||
}
|
||||
49
src/app/(shop)/kasse/pruefen/page.tsx
Normal file
49
src/app/(shop)/kasse/pruefen/page.tsx
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
import { AddressLines } from "@/components/shop/AddressLines";
|
||||
import { getDefinition } from "@/lib/payments/catalog";
|
||||
import { PlaceOrderForm } from "@/components/shop/PlaceOrderForm";
|
||||
import { CheckoutSummary, loadCheckout } from "../shared";
|
||||
|
||||
export const metadata = { title: "Kasse – Prüfen" };
|
||||
|
||||
export default async function ReviewStep() {
|
||||
const [data, settings] = await Promise.all([loadCheckout(), getSettings()]);
|
||||
const { state, shipping, payment } = data;
|
||||
if (!state.address || !state.email) redirect("/kasse/adresse");
|
||||
if (!shipping) redirect("/kasse/versand");
|
||||
if (!payment) redirect("/kasse/zahlung");
|
||||
const provider = getDefinition(payment.code)?.provider;
|
||||
return (
|
||||
<div className="sm-checkout">
|
||||
<div className="sm-checkout__form">
|
||||
<h2 className="display-md" style={{ marginBottom: "var(--space-5)" }}>Alles richtig?</h2>
|
||||
<div className="sm-review">
|
||||
<div className="sm-review__box">
|
||||
<h3>Lieferadresse <Link href="/kasse/adresse">Ändern</Link></h3>
|
||||
<AddressLines a={state.address} />
|
||||
<p className="body-sm" style={{ color: "var(--ink-muted)", marginTop: "var(--space-2)" }}>{state.email}</p>
|
||||
</div>
|
||||
<div className="sm-review__box">
|
||||
<h3>Rechnungsadresse <Link href="/kasse/adresse">Ändern</Link></h3>
|
||||
{state.billingSame === false && state.billing ? <AddressLines a={state.billing} /> : <p className="body">Wie Lieferadresse</p>}
|
||||
</div>
|
||||
<div className="sm-review__box">
|
||||
<h3>Versand <Link href="/kasse/versand">Ändern</Link></h3>
|
||||
<p className="body">{shipping.name}</p>
|
||||
</div>
|
||||
<div className="sm-review__box">
|
||||
<h3>Zahlung <Link href="/kasse/zahlung">Ändern</Link></h3>
|
||||
<p className="body">{payment.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginTop: "var(--space-6)" }}>
|
||||
<PlaceOrderForm requireTerms={settings.checkout.requireTerms} total={formatPrice(data.totals.total)} online={provider === "stripe" || provider === "paypal"} />
|
||||
</div>
|
||||
</div>
|
||||
<CheckoutSummary data={data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
30
src/app/(shop)/kasse/shared.tsx
Normal file
30
src/app/(shop)/kasse/shared.tsx
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { db } from "@/lib/db";
|
||||
import { getCart } from "@/lib/cart";
|
||||
import { readCheckout } from "@/lib/checkout";
|
||||
import { computeTotals } from "@/lib/pricing";
|
||||
import { OrderSummary } from "@/components/shop/OrderSummary";
|
||||
|
||||
/** Gemeinsame Daten aller Kassen-Schritte; leerer Warenkorb → zurück. */
|
||||
export async function loadCheckout() {
|
||||
const [lines, state, jar] = await Promise.all([getCart(), readCheckout(), cookies()]);
|
||||
if (lines.length === 0) redirect("/warenkorb");
|
||||
const [shipping, payment] = await Promise.all([
|
||||
state.shippingMethodId ? db.shippingMethod.findUnique({ where: { id: state.shippingMethodId } }) : null,
|
||||
state.paymentMethodId ? db.paymentMethod.findUnique({ where: { id: state.paymentMethodId } }) : null,
|
||||
]);
|
||||
const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value, shipping, payment });
|
||||
return { lines, state, shipping, payment, totals };
|
||||
}
|
||||
|
||||
export function CheckoutSummary({ data }: { data: Awaited<ReturnType<typeof loadCheckout>> }) {
|
||||
return (
|
||||
<OrderSummary
|
||||
totals={data.totals}
|
||||
lines={data.lines}
|
||||
shippingLabel={data.shipping?.name}
|
||||
paymentLabel={data.payment?.name}
|
||||
/>
|
||||
);
|
||||
}
|
||||
43
src/app/(shop)/kasse/versand/page.tsx
Normal file
43
src/app/(shop)/kasse/versand/page.tsx
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { redirect } from "next/navigation";
|
||||
import { availableShipping } from "@/lib/checkout";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { shippingPrice } from "@/lib/pricing";
|
||||
import { ChoiceForm } from "@/components/shop/ChoiceForm";
|
||||
import { saveShipping } from "../actions";
|
||||
import { CheckoutSummary, loadCheckout } from "../shared";
|
||||
|
||||
export const metadata = { title: "Kasse – Versand" };
|
||||
|
||||
export default async function ShippingStep() {
|
||||
const data = await loadCheckout();
|
||||
if (!data.state.address) redirect("/kasse/adresse");
|
||||
const methods = await availableShipping(data.state.address.country);
|
||||
const merchandise = data.totals.subtotal - data.totals.discount;
|
||||
return (
|
||||
<div className="sm-checkout">
|
||||
<div>
|
||||
{methods.length === 0 ? (
|
||||
<p className="body">In dein Land können wir gerade nicht liefern. Bitte melde dich bei uns.</p>
|
||||
) : (
|
||||
<ChoiceForm
|
||||
action={saveShipping}
|
||||
name="shippingMethodId"
|
||||
legend="Wie sollen wir liefern?"
|
||||
submitLabel="Weiter zur Zahlung"
|
||||
selected={data.state.shippingMethodId}
|
||||
choices={methods.map((m) => {
|
||||
const price = shippingPrice(m, merchandise);
|
||||
return {
|
||||
id: m.id,
|
||||
title: m.name,
|
||||
price: price === 0 ? "Kostenlos" : formatPrice(price),
|
||||
text: [m.description, m.freeFrom > 0 && price > 0 ? `Kostenlos ab ${formatPrice(m.freeFrom)}` : ""].filter(Boolean).join(" · "),
|
||||
};
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<CheckoutSummary data={data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
46
src/app/(shop)/kasse/zahlung/page.tsx
Normal file
46
src/app/(shop)/kasse/zahlung/page.tsx
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { redirect } from "next/navigation";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { availablePayments } from "@/lib/checkout";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { Alert } from "@/components/shop/Blocks";
|
||||
import { ChoiceForm } from "@/components/shop/ChoiceForm";
|
||||
import { savePayment } from "../actions";
|
||||
import { CheckoutSummary, loadCheckout } from "../shared";
|
||||
|
||||
export const metadata = { title: "Kasse – Zahlung" };
|
||||
|
||||
export default async function PaymentStep({ searchParams }: { searchParams: Promise<{ abgebrochen?: string }> }) {
|
||||
const [{ abgebrochen }, data, user] = await Promise.all([searchParams, loadCheckout(), getCurrentUser()]);
|
||||
if (!data.state.address) redirect("/kasse/adresse");
|
||||
if (!data.shipping) redirect("/kasse/versand");
|
||||
const methods = await availablePayments(data.totals.total, Boolean(user));
|
||||
return (
|
||||
<div className="sm-checkout">
|
||||
<div>
|
||||
{abgebrochen && (
|
||||
<div style={{ marginBottom: "var(--space-5)" }}>
|
||||
<Alert kind="danger" title="Die Zahlung wurde nicht abgeschlossen.">Es wurde nichts abgebucht. Wähle eine Zahlungsart und versuche es noch einmal.</Alert>
|
||||
</div>
|
||||
)}
|
||||
{methods.length === 0 ? (
|
||||
<Alert title="Gerade ist keine Zahlungsart verfügbar.">Bitte melde dich bei uns, wir helfen dir weiter.</Alert>
|
||||
) : (
|
||||
<ChoiceForm
|
||||
action={savePayment}
|
||||
name="paymentMethodId"
|
||||
legend="Wie möchtest du bezahlen?"
|
||||
submitLabel="Weiter zur Übersicht"
|
||||
selected={data.state.paymentMethodId}
|
||||
choices={methods.map((m) => ({
|
||||
id: m.id,
|
||||
title: m.name,
|
||||
price: m.fee > 0 ? `+ ${formatPrice(m.fee)}` : "",
|
||||
text: m.description,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<CheckoutSummary data={data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
36
src/app/(shop)/kategorie/[slug]/page.tsx
Normal file
36
src/app/(shop)/kategorie/[slug]/page.tsx
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { notFound } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { db } from "@/lib/db";
|
||||
import { ProductList } from "@/components/shop/ProductList";
|
||||
|
||||
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await params;
|
||||
const c = await db.category.findUnique({ where: { slug } });
|
||||
return { title: c?.name ?? "Kategorie" };
|
||||
}
|
||||
|
||||
export default async function CategoryPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: Promise<{ slug: string }>;
|
||||
searchParams: Promise<{ sort?: string }>;
|
||||
}) {
|
||||
const [{ slug }, { sort }] = await Promise.all([params, searchParams]);
|
||||
const category = await db.category.findUnique({ where: { slug } });
|
||||
if (!category || !category.active) notFound();
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<nav aria-label="Du bist hier">
|
||||
<ol className="sm-crumbs">
|
||||
<li><Link href="/">Start</Link></li>
|
||||
<li><Link href="/shop">Shop</Link></li>
|
||||
<li aria-current="page">{category.name}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
<h1 className="display-lg sm-page__title" style={{ marginTop: "var(--space-5)" }}>{category.name}</h1>
|
||||
{category.description && <p className="body sm-page__lead">{category.description}</p>}
|
||||
<ProductList basePath={`/kategorie/${slug}`} where={{ categoryId: category.id }} sort={sort} showCategoryChips activeCategory={slug} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
25
src/app/(shop)/kollektionen/page.tsx
Normal file
25
src/app/(shop)/kollektionen/page.tsx
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import Link from "next/link";
|
||||
import { db } from "@/lib/db";
|
||||
import { Icon } from "@/components/Icon";
|
||||
import { ProductImage } from "@/components/shop/ProductImage";
|
||||
|
||||
export const metadata = { title: "Kollektionen" };
|
||||
|
||||
export default async function CollectionsPage() {
|
||||
const categories = await db.category.findMany({ where: { active: true }, orderBy: { sort: "asc" } });
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<span className="eyebrow">Kollektionen</span>
|
||||
<h1 className="display-lg sm-page__title">Alles für dein Studio</h1>
|
||||
<p className="body sm-page__lead">Wähle eine Kollektion.</p>
|
||||
<div className="sm-tiles">
|
||||
{categories.map((c) => (
|
||||
<Link className="sm-tile" href={`/kategorie/${c.slug}`} key={c.id}>
|
||||
<ProductImage src={c.image} alt={c.name} label={c.name} />
|
||||
<span className="sm-tile__label">{c.name} <Icon name="arrow" /></span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
23
src/app/(shop)/konto/anmelden/page.tsx
Normal file
23
src/app/(shop)/konto/anmelden/page.tsx
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { LoginForm } from "@/components/shop/AuthForms";
|
||||
|
||||
export const metadata = { title: "Anmelden" };
|
||||
|
||||
export default async function LoginPage({ searchParams }: { searchParams: Promise<{ weiter?: string }> }) {
|
||||
const { weiter } = await searchParams;
|
||||
if (await getCurrentUser()) redirect(weiter ?? "/konto");
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<div className="sm-auth">
|
||||
<h1 className="display-lg sm-page__title">Anmelden</h1>
|
||||
<p className="body sm-page__lead">Schön, dass du wieder da bist.</p>
|
||||
<LoginForm next={weiter} />
|
||||
<p className="body" style={{ marginTop: "var(--space-6)", textAlign: "center" }}>
|
||||
Noch kein Konto? <Link href={`/konto/registrieren${weiter ? `?weiter=${encodeURIComponent(weiter)}` : ""}`}>Jetzt erstellen</Link>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
42
src/app/(shop)/konto/bestellung/[number]/page.tsx
Normal file
42
src/app/(shop)/konto/bestellung/[number]/page.tsx
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import Link from "next/link";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { db } from "@/lib/db";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { ORDER_STATUS, PAYMENT_STATUS, dayFmt } from "@/lib/status";
|
||||
import type { AddressData } from "@/lib/checkout";
|
||||
import { AddressLines } from "@/components/shop/AddressLines";
|
||||
|
||||
export default async function OrderDetail({ params }: { params: Promise<{ number: string }> }) {
|
||||
const { number } = await params;
|
||||
const user = await getCurrentUser();
|
||||
if (!user) redirect("/konto/anmelden");
|
||||
const order = await db.order.findUnique({ where: { number }, include: { items: true } });
|
||||
if (!order || order.userId !== user.id) notFound();
|
||||
return (
|
||||
<main className="sm-container sm-page" style={{ maxWidth: 820 }}>
|
||||
<Link href="/konto" className="body-sm">← Zurück zum Konto</Link>
|
||||
<h1 className="display-lg sm-page__title" style={{ marginTop: "var(--space-4)" }}>Bestellung {order.number}</h1>
|
||||
<p className="body sm-page__lead">
|
||||
vom {dayFmt.format(order.createdAt)} · {ORDER_STATUS[order.status].label} · {PAYMENT_STATUS[order.paymentStatus].label}
|
||||
{order.trackingNumber && <> · Sendungsnummer {order.trackingNumber}</>}
|
||||
</p>
|
||||
<div className="sm-box" style={{ padding: 0 }}>
|
||||
<table className="sm-table">
|
||||
<tbody>
|
||||
{order.items.map((i) => (
|
||||
<tr key={i.id}><td>{i.quantity} × {i.name}{i.variantName ? ` – ${i.variantName}` : ""}</td><td style={{ textAlign: "right" }}>{formatPrice(i.total)}</td></tr>
|
||||
))}
|
||||
<tr><td>Versand</td><td style={{ textAlign: "right" }}>{formatPrice(order.shippingCost)}</td></tr>
|
||||
{order.discount > 0 && <tr><td>Gutschein</td><td style={{ textAlign: "right" }}>−{formatPrice(order.discount)}</td></tr>}
|
||||
<tr><td><strong>Gesamt</strong></td><td style={{ textAlign: "right" }}><strong>{formatPrice(order.total)}</strong></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="sm-review" style={{ marginTop: "var(--space-5)" }}>
|
||||
<div className="sm-review__box"><h3>Lieferadresse</h3><AddressLines a={order.shippingAddress as AddressData} /></div>
|
||||
<div className="sm-review__box"><h3>Rechnungsadresse</h3>{order.billingAddress ? <AddressLines a={order.billingAddress as AddressData} /> : <p className="body">Wie Lieferadresse</p>}</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
45
src/app/(shop)/konto/page.tsx
Normal file
45
src/app/(shop)/konto/page.tsx
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { db } from "@/lib/db";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { logout } from "@/lib/auth-actions";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { ORDER_STATUS, dayFmt } from "@/lib/status";
|
||||
|
||||
export const metadata = { title: "Mein Konto" };
|
||||
|
||||
export default async function AccountPage() {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) redirect("/konto/anmelden");
|
||||
const orders = await db.order.findMany({ where: { userId: user.id }, orderBy: { createdAt: "desc" } });
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<span className="eyebrow">Mein Konto</span>
|
||||
<h1 className="display-lg sm-page__title">Hallo {user.firstName || user.email}</h1>
|
||||
<div className="sm-btn-row" style={{ margin: "var(--space-4) 0 var(--space-7)" }}>
|
||||
{user.role && <Link className="sm-btn sm-btn--secondary" href="/admin">Zum Admin-Bereich</Link>}
|
||||
<form action={logout}><button className="sm-btn sm-btn--ghost" type="submit">Abmelden</button></form>
|
||||
</div>
|
||||
<h2 className="display-sm" style={{ marginBottom: "var(--space-4)" }}>Deine Bestellungen</h2>
|
||||
{orders.length === 0 ? (
|
||||
<p className="body" style={{ color: "var(--ink-muted)" }}>Du hast noch nichts bestellt. <Link href="/shop">Zum Shop</Link></p>
|
||||
) : (
|
||||
<div className="sm-box" style={{ padding: 0, overflowX: "auto" }}>
|
||||
<table className="sm-table">
|
||||
<thead><tr><th>Bestellung</th><th>Datum</th><th>Status</th><th style={{ textAlign: "right" }}>Summe</th></tr></thead>
|
||||
<tbody>
|
||||
{orders.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td><Link href={`/konto/bestellung/${o.number}`}>{o.number}</Link></td>
|
||||
<td>{dayFmt.format(o.createdAt)}</td>
|
||||
<td>{ORDER_STATUS[o.status].label}</td>
|
||||
<td style={{ textAlign: "right" }}>{formatPrice(o.total)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
23
src/app/(shop)/konto/registrieren/page.tsx
Normal file
23
src/app/(shop)/konto/registrieren/page.tsx
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { RegisterForm } from "@/components/shop/AuthForms";
|
||||
|
||||
export const metadata = { title: "Konto erstellen" };
|
||||
|
||||
export default async function RegisterPage({ searchParams }: { searchParams: Promise<{ weiter?: string; email?: string }> }) {
|
||||
const { weiter, email } = await searchParams;
|
||||
if (await getCurrentUser()) redirect(weiter ?? "/konto");
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<div className="sm-auth">
|
||||
<h1 className="display-lg sm-page__title">Konto erstellen</h1>
|
||||
<p className="body sm-page__lead">Bestellungen verfolgen und schneller bestellen.</p>
|
||||
<RegisterForm next={weiter} email={email} />
|
||||
<p className="body" style={{ marginTop: "var(--space-6)", textAlign: "center" }}>
|
||||
Schon ein Konto? <Link href="/konto/anmelden">Anmelden</Link>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
27
src/app/(shop)/layout.tsx
Normal file
27
src/app/(shop)/layout.tsx
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { Header } from "@/components/shop/Header";
|
||||
import { Footer } from "@/components/shop/Footer";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
import { can, getCurrentUser } from "@/lib/auth";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function ShopLayout({ children }: { children: React.ReactNode }) {
|
||||
const [settings, user] = await Promise.all([getSettings(), getCurrentUser()]);
|
||||
if (settings.general.maintenance && !can(user, "dashboard.view")) {
|
||||
return (
|
||||
<main className="sm-maintenance" data-theme="dark">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src="/brand/logo-gold.png" alt={settings.general.shopName} width={320} style={{ margin: "0 auto var(--space-6)" }} />
|
||||
<h1 className="display-md">Wir sind gleich wieder da.</h1>
|
||||
<p className="body" style={{ color: "var(--ink-muted)" }}>Der Shop wird gerade überarbeitet.</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Header />
|
||||
{children}
|
||||
<Footer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
111
src/app/(shop)/page.tsx
Normal file
111
src/app/(shop)/page.tsx
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import Link from "next/link";
|
||||
import { db } from "@/lib/db";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
import { Icon } from "@/components/Icon";
|
||||
import { SectionHeading, TrustBar } from "@/components/shop/Blocks";
|
||||
import { ProductCard } from "@/components/shop/ProductCard";
|
||||
import { ProductImage } from "@/components/shop/ProductImage";
|
||||
|
||||
export default async function HomePage() {
|
||||
const settings = await getSettings();
|
||||
const a = settings.appearance;
|
||||
const [categories, featured] = await Promise.all([
|
||||
a.showCategories ? db.category.findMany({ where: { active: true, showOnHome: true }, orderBy: { sort: "asc" }, take: 6 }) : [],
|
||||
a.showFeatured
|
||||
? db.product.findMany({
|
||||
where: { active: true, featured: true },
|
||||
include: { variants: true },
|
||||
orderBy: [{ sort: "asc" }, { createdAt: "desc" }],
|
||||
take: 8,
|
||||
})
|
||||
: [],
|
||||
]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="sm-hero" data-theme="dark">
|
||||
<div className="sm-container sm-hero__inner">
|
||||
<div>
|
||||
{a.heroEyebrow && <span className="sm-hero__eyebrow eyebrow">{a.heroEyebrow}</span>}
|
||||
<h1 className="sm-hero__title display-xl">
|
||||
{a.heroTitle.split("\n").map((line, i) => (
|
||||
<span key={i}>{i > 0 && <br />}{line}</span>
|
||||
))}
|
||||
</h1>
|
||||
<div className="sm-hero__rule" aria-hidden="true" />
|
||||
{a.heroText && <p className="sm-hero__text">{a.heroText}</p>}
|
||||
<div className="sm-hero__actions sm-btn-row">
|
||||
{a.heroPrimaryLabel && (
|
||||
<Link className="sm-btn sm-btn--primary sm-btn--lg" href={a.heroPrimaryHref || "/shop"}>
|
||||
{a.heroPrimaryLabel}
|
||||
</Link>
|
||||
)}
|
||||
{a.heroSecondaryLabel && (
|
||||
<Link className="sm-btn sm-btn--ghost" href={a.heroSecondaryHref || "/"}>
|
||||
{a.heroSecondaryLabel} <Icon name="arrow" size="sm" />
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="sm-hero__media">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img className="sm-hero__logo" src="/brand/logo-gold.png" alt={`${settings.general.shopName} Pilates – Logo`} width={962} height={783} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<main>
|
||||
{a.showTrustBar && (
|
||||
<div className="sm-container" style={{ paddingTop: "var(--space-5)" }}>
|
||||
<TrustBar items={a.trustItems} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{categories.length > 0 && (
|
||||
<section className="sm-container sm-section">
|
||||
<SectionHeading eyebrow={a.categoriesEyebrow} title={a.categoriesTitle} />
|
||||
<div className="sm-tiles" style={{ marginTop: "var(--space-7)" }}>
|
||||
{categories.map((c) => (
|
||||
<Link className="sm-tile" href={`/kategorie/${c.slug}`} key={c.id}>
|
||||
<ProductImage src={c.image} alt={c.name} label={c.name} />
|
||||
<span className="sm-tile__label">
|
||||
{c.name} <Icon name="arrow" />
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{featured.length > 0 && (
|
||||
<section className="sm-container sm-section">
|
||||
<SectionHeading eyebrow={a.featuredEyebrow} title={a.featuredTitle} />
|
||||
<div className="sm-grid" style={{ marginTop: "var(--space-7)" }}>
|
||||
{featured.map((p) => (
|
||||
<ProductCard key={p.id} product={p} />
|
||||
))}
|
||||
</div>
|
||||
<div style={{ textAlign: "center", marginTop: "var(--space-7)" }}>
|
||||
<Link className="sm-btn sm-btn--secondary" href="/shop">
|
||||
Alle Produkte
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{a.showQuote && a.quoteText && (
|
||||
<section style={{ marginTop: "var(--space-9)", padding: "var(--space-8) 0", background: "var(--surface-sunken)" }}>
|
||||
<div className="sm-container" style={{ maxWidth: 720, textAlign: "center" }}>
|
||||
<p className="quote" style={{ margin: 0 }}>{a.quoteText}</p>
|
||||
{a.quoteAuthor && (
|
||||
<p className="caption" style={{ margin: "var(--space-4) 0 0", color: "var(--ink-muted)", letterSpacing: "0.14em", textTransform: "uppercase" }}>
|
||||
{a.quoteAuthor}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
<div style={{ height: "var(--space-9)" }} />
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
108
src/app/(shop)/produkt/[slug]/page.tsx
Normal file
108
src/app/(shop)/produkt/[slug]/page.tsx
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import { notFound } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { db } from "@/lib/db";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
import { Icon } from "@/components/Icon";
|
||||
import { SectionHeading, TrustBar } from "@/components/shop/Blocks";
|
||||
import { BuyBox } from "@/components/shop/BuyBox";
|
||||
import { Gallery } from "@/components/shop/Gallery";
|
||||
import { ProductCard } from "@/components/shop/ProductCard";
|
||||
|
||||
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await params;
|
||||
const p = await db.product.findUnique({ where: { slug } });
|
||||
return { title: p?.name ?? "Produkt", description: p?.description.slice(0, 160) };
|
||||
}
|
||||
|
||||
export default async function ProductPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: Promise<{ slug: string }>;
|
||||
searchParams: Promise<{ variante?: string }>;
|
||||
}) {
|
||||
const [{ slug }, { variante }] = await Promise.all([params, searchParams]);
|
||||
const product = await db.product.findUnique({
|
||||
where: { slug },
|
||||
include: { category: true, variants: { orderBy: { sort: "asc" } } },
|
||||
});
|
||||
if (!product || !product.active) notFound();
|
||||
const [settings, related] = await Promise.all([
|
||||
getSettings(),
|
||||
db.product.findMany({
|
||||
where: { active: true, id: { not: product.id }, ...(product.categoryId ? { categoryId: product.categoryId } : {}) },
|
||||
include: { variants: true },
|
||||
take: 4,
|
||||
orderBy: { featured: "desc" },
|
||||
}),
|
||||
]);
|
||||
const shippingNote = settings.appearance.trustItems[0];
|
||||
|
||||
return (
|
||||
<main className="sm-container" style={{ paddingTop: "var(--space-5)", paddingBottom: "var(--space-9)" }}>
|
||||
<nav aria-label="Du bist hier">
|
||||
<ol className="sm-crumbs">
|
||||
<li><Link href="/">Start</Link></li>
|
||||
<li><Link href="/shop">Shop</Link></li>
|
||||
{product.category && <li><Link href={`/kategorie/${product.category.slug}`}>{product.category.name}</Link></li>}
|
||||
<li aria-current="page">{product.name}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
<div className="sm-pdp" style={{ marginTop: "var(--space-5)" }}>
|
||||
<Gallery images={product.images} alt={product.name} />
|
||||
<div className="sm-pdp__buy">
|
||||
{product.category && <span className="eyebrow">{product.category.name}</span>}
|
||||
<h1 className="sm-pdp__title display-lg">{product.name}</h1>
|
||||
{product.subtitle && <p className="body" style={{ margin: "0 0 var(--space-4)", color: "var(--ink-muted)" }}>{product.subtitle}</p>}
|
||||
<BuyBox
|
||||
productId={product.id}
|
||||
price={product.price}
|
||||
compareAt={product.compareAtPrice}
|
||||
stock={product.stock}
|
||||
trackStock={product.trackStock}
|
||||
variants={product.variants.map((v) => ({ id: v.id, name: v.name, price: v.price ?? product.price, stock: v.stock }))}
|
||||
variantLabel="Variante"
|
||||
missingVariant={variante === "fehlt"}
|
||||
/>
|
||||
<ul className="sm-pdp__facts" style={{ marginTop: "var(--space-2)" }}>
|
||||
{shippingNote && <li><Icon name={shippingNote.icon} /> {shippingNote.title}</li>}
|
||||
{product.sku && <li className="caption">Art.-Nr. {product.sku}</li>}
|
||||
</ul>
|
||||
<div style={{ marginTop: "var(--space-6)" }}>
|
||||
{product.description && (
|
||||
<details className="sm-acc" open>
|
||||
<summary>Beschreibung</summary>
|
||||
<div className="sm-acc__body" style={{ whiteSpace: "pre-line" }}>{product.description}</div>
|
||||
</details>
|
||||
)}
|
||||
{product.details && (
|
||||
<details className="sm-acc">
|
||||
<summary>Material & Pflege</summary>
|
||||
<div className="sm-acc__body" style={{ whiteSpace: "pre-line" }}>{product.details}</div>
|
||||
</details>
|
||||
)}
|
||||
<details className="sm-acc">
|
||||
<summary>Versand & Rückgabe</summary>
|
||||
<div className="sm-acc__body">
|
||||
{settings.appearance.trustItems.slice(0, 2).map((t) => `${t.title}. ${t.text}`).join(" ")}
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{related.length > 0 && (
|
||||
<section className="sm-section">
|
||||
<SectionHeading eyebrow="Passt dazu" title="Das Studio wird komplett" left />
|
||||
<div className="sm-grid" style={{ marginTop: "var(--space-7)" }}>
|
||||
{related.map((p) => <ProductCard key={p.id} product={p} />)}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{settings.appearance.showTrustBar && (
|
||||
<div className="sm-section">
|
||||
<TrustBar items={settings.appearance.trustItems} />
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
21
src/app/(shop)/seite/[slug]/page.tsx
Normal file
21
src/app/(shop)/seite/[slug]/page.tsx
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { notFound } from "next/navigation";
|
||||
import { db } from "@/lib/db";
|
||||
import { RichText } from "@/components/shop/Blocks";
|
||||
|
||||
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await params;
|
||||
const p = await db.page.findUnique({ where: { slug } });
|
||||
return { title: p?.title ?? "Seite" };
|
||||
}
|
||||
|
||||
export default async function ContentPage({ params }: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await params;
|
||||
const page = await db.page.findUnique({ where: { slug } });
|
||||
if (!page || !page.published) notFound();
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<h1 className="display-lg sm-page__title" style={{ marginBottom: "var(--space-6)" }}>{page.title}</h1>
|
||||
<RichText text={page.content} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
16
src/app/(shop)/shop/page.tsx
Normal file
16
src/app/(shop)/shop/page.tsx
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import type { Metadata } from "next";
|
||||
import { ProductList } from "@/components/shop/ProductList";
|
||||
|
||||
export const metadata: Metadata = { title: "Shop" };
|
||||
|
||||
export default async function ShopPage({ searchParams }: { searchParams: Promise<{ sort?: string }> }) {
|
||||
const { sort } = await searchParams;
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<span className="eyebrow">Shop</span>
|
||||
<h1 className="display-lg sm-page__title">Alle Produkte</h1>
|
||||
<p className="body sm-page__lead">Ausgewählt von Trainerinnen, für das Studio und für zu Hause.</p>
|
||||
<ProductList basePath="/shop" where={{}} sort={sort} showCategoryChips />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
42
src/app/(shop)/suche/page.tsx
Normal file
42
src/app/(shop)/suche/page.tsx
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { db } from "@/lib/db";
|
||||
import { ProductCard } from "@/components/shop/ProductCard";
|
||||
|
||||
export const metadata = { title: "Suche" };
|
||||
|
||||
export default async function SearchPage({ searchParams }: { searchParams: Promise<{ q?: string }> }) {
|
||||
const { q = "" } = await searchParams;
|
||||
const term = q.trim();
|
||||
const products = term
|
||||
? await db.product.findMany({
|
||||
where: {
|
||||
active: true,
|
||||
OR: [
|
||||
{ name: { contains: term, mode: "insensitive" } },
|
||||
{ subtitle: { contains: term, mode: "insensitive" } },
|
||||
{ description: { contains: term, mode: "insensitive" } },
|
||||
{ sku: { contains: term, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
include: { variants: true },
|
||||
take: 48,
|
||||
})
|
||||
: [];
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<h1 className="display-lg sm-page__title">Suche</h1>
|
||||
<form className="sm-search sm-input-group" role="search" method="get" style={{ margin: "var(--space-5) 0 var(--space-7)" }}>
|
||||
<label className="sm-visually-hidden" htmlFor="q">Suchbegriff</label>
|
||||
<input className="sm-input" id="q" name="q" type="search" defaultValue={term} placeholder="Wonach suchst du?" autoFocus />
|
||||
<button className="sm-btn sm-btn--primary" type="submit">Suchen</button>
|
||||
</form>
|
||||
{term && (
|
||||
<p className="body" style={{ color: "var(--ink-muted)", marginBottom: "var(--space-5)" }}>
|
||||
{products.length === 0 ? `Zu „${term}“ haben wir nichts gefunden. Versuch es mit einem anderen Wort.` : `${products.length} Treffer für „${term}“`}
|
||||
</p>
|
||||
)}
|
||||
<div className="sm-grid">
|
||||
{products.map((p) => <ProductCard key={p.id} product={p} />)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
110
src/app/(shop)/warenkorb/page.tsx
Normal file
110
src/app/(shop)/warenkorb/page.tsx
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
import Link from "next/link";
|
||||
import { cookies } from "next/headers";
|
||||
import { getCart } from "@/lib/cart";
|
||||
import { computeTotals } from "@/lib/pricing";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
import { Icon } from "@/components/Icon";
|
||||
import { Alert, TrustBar } from "@/components/shop/Blocks";
|
||||
import { CouponForm } from "@/components/shop/CouponForm";
|
||||
import { OrderSummary } from "@/components/shop/OrderSummary";
|
||||
import { ProductImage } from "@/components/shop/ProductImage";
|
||||
import { removeCoupon, updateCartLine } from "../actions";
|
||||
|
||||
export const metadata = { title: "Warenkorb" };
|
||||
|
||||
export default async function CartPage({ searchParams }: { searchParams: Promise<{ hinzugefuegt?: string }> }) {
|
||||
const { hinzugefuegt } = await searchParams;
|
||||
const [lines, settings, jar] = await Promise.all([getCart(), getSettings(), cookies()]);
|
||||
const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value });
|
||||
const count = lines.reduce((n, l) => n + l.quantity, 0);
|
||||
const minOrder = settings.checkout.minOrderValue;
|
||||
|
||||
if (lines.length === 0) {
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<div className="sm-empty">
|
||||
<h1 className="display-lg" style={{ marginBottom: "var(--space-3)" }}>Dein Warenkorb ist leer</h1>
|
||||
<p className="body">Schau dich im Shop um, es gibt viel zu entdecken.</p>
|
||||
<Link className="sm-btn sm-btn--primary" href="/shop">Zum Shop</Link>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<h1 className="display-lg sm-page__title">Dein Warenkorb</h1>
|
||||
<p className="body sm-page__lead">
|
||||
{count} {count === 1 ? "Artikel" : "Artikel"}
|
||||
{totals.freeShippingRemaining == null && totals.shippingCost === 0 ? " · Versand kostenlos" : ""}
|
||||
</p>
|
||||
<div className="sm-cart-layout">
|
||||
<div>
|
||||
{hinzugefuegt && <div style={{ marginBottom: "var(--space-4)" }}><Alert kind="success" title="Der Artikel liegt im Warenkorb." /></div>}
|
||||
{settings.checkout.freeShippingHint && totals.freeShippingRemaining != null && (
|
||||
<div style={{ marginBottom: "var(--space-4)" }}>
|
||||
<Alert title={`Noch ${formatPrice(totals.freeShippingRemaining)} bis zum kostenlosen Versand.`} />
|
||||
</div>
|
||||
)}
|
||||
{totals.coupon && (
|
||||
<div style={{ marginBottom: "var(--space-4)" }}>
|
||||
<Alert kind="success" title={`Gutschein ${totals.coupon.code} eingelöst.`}>
|
||||
<form action={removeCoupon} style={{ display: "inline" }}>
|
||||
<button type="submit" className="sm-cartline__remove" style={{ padding: 0 }}>Gutschein entfernen</button>
|
||||
</form>
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
{lines.map((l) => (
|
||||
<div className="sm-cartline" key={l.key}>
|
||||
<div className="sm-cartline__media"><ProductImage src={l.image} alt={l.name} /></div>
|
||||
<div>
|
||||
<h3 className="sm-cartline__title"><Link href={`/produkt/${l.slug}`}>{l.name}</Link></h3>
|
||||
<p className="sm-cartline__meta">{[l.variantName, l.subtitle].filter(Boolean).join(" · ")}</p>
|
||||
<form action={updateCartLine} className="sm-cartline__controls">
|
||||
<input type="hidden" name="key" value={l.key} />
|
||||
<div className="sm-qty sm-qty--sm" role="group" aria-label="Menge">
|
||||
<button className="sm-qty__btn" type="submit" name="quantity" value={l.quantity - 1} aria-label="Menge verringern" disabled={l.quantity <= 1}>
|
||||
<Icon name="minus" size="sm" />
|
||||
</button>
|
||||
<span className="sm-qty__value" style={{ display: "grid", placeContent: "center" }} aria-live="polite">{l.quantity}</span>
|
||||
<button className="sm-qty__btn" type="submit" name="quantity" value={l.quantity + 1} aria-label="Menge erhöhen" disabled={l.quantity >= l.maxQuantity}>
|
||||
<Icon name="plus" size="sm" />
|
||||
</button>
|
||||
</div>
|
||||
<button className="sm-cartline__remove" type="submit" name="quantity" value="0">Entfernen</button>
|
||||
</form>
|
||||
</div>
|
||||
<div className="sm-cartline__price">
|
||||
<span className="sm-cartline__unit">{l.quantity} × {formatPrice(l.unitPrice)}</span>
|
||||
<span className="sm-price">{formatPrice(l.total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginTop: "var(--space-5)", gap: "var(--space-4)", flexWrap: "wrap" }}>
|
||||
<Link className="sm-btn sm-btn--ghost" href="/shop" style={{ paddingLeft: 0 }}>
|
||||
<Icon name="arrowLeft" size="sm" /> Weiter einkaufen
|
||||
</Link>
|
||||
{!totals.coupon && <CouponForm />}
|
||||
</div>
|
||||
</div>
|
||||
<OrderSummary totals={totals}>
|
||||
<div className="sm-summary__cta">
|
||||
{minOrder > 0 && totals.subtotal < minOrder ? (
|
||||
<Alert title={`Der Mindestbestellwert ist ${formatPrice(minOrder)}.`} />
|
||||
) : (
|
||||
<Link className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block" href="/kasse/adresse">Zur Kasse</Link>
|
||||
)}
|
||||
</div>
|
||||
<p className="sm-summary__fine">
|
||||
Sichere Zahlung{settings.checkout.guestCheckout ? " · Auch als Gast bestellen" : ""}
|
||||
</p>
|
||||
</OrderSummary>
|
||||
</div>
|
||||
{settings.appearance.showTrustBar && (
|
||||
<div className="sm-section"><TrustBar items={settings.appearance.trustItems} /></div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
114
src/app/admin/(panel)/bestellungen/[id]/page.tsx
Normal file
114
src/app/admin/(panel)/bestellungen/[id]/page.tsx
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
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, PAYMENT_STATUS, dateFmt } from "@/lib/status";
|
||||
import type { AddressData } from "@/lib/checkout";
|
||||
import { AddressLines } from "@/components/shop/AddressLines";
|
||||
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
|
||||
import { Card, PageHead, Pill } from "@/components/admin/ui";
|
||||
import { SelectField, TextareaField, Field } from "@/components/Field";
|
||||
import { addOrderNote, cancelOrder, updateOrder } from "../actions";
|
||||
|
||||
export default async function OrderDetail({ params }: { params: Promise<{ id: string }> }) {
|
||||
const user = await requireAdmin("orders.view");
|
||||
const { id } = await params;
|
||||
const order = await db.order.findUnique({ where: { id }, include: { items: true, events: { orderBy: { createdAt: "desc" } }, user: true } });
|
||||
if (!order) notFound();
|
||||
const payment = await db.paymentMethod.findUnique({ where: { code: order.paymentMethod } });
|
||||
const canEdit = can(user, "orders.edit");
|
||||
const closed = order.status === "CANCELLED" || order.status === "REFUNDED";
|
||||
return (
|
||||
<div className="ad-wrap">
|
||||
<PageHead title={`Bestellung ${order.number}`} lead={`${dateFmt.format(order.createdAt)} · ${order.email}`} back={{ href: "/admin/bestellungen", label: "Bestellungen" }}>
|
||||
<Pill tone={PAYMENT_STATUS[order.paymentStatus].tone}>{PAYMENT_STATUS[order.paymentStatus].label}</Pill>
|
||||
<Pill tone={ORDER_STATUS[order.status].tone}>{ORDER_STATUS[order.status].label}</Pill>
|
||||
</PageHead>
|
||||
<div className="ad-grid ad-grid--2-1">
|
||||
<div>
|
||||
<Card title="Artikel" flush>
|
||||
<div className="ad-table-wrap">
|
||||
<table className="ad-table">
|
||||
<thead><tr><th>Artikel</th><th>Art.-Nr.</th><th className="num">Menge</th><th className="num">Einzelpreis</th><th className="num">Summe</th></tr></thead>
|
||||
<tbody>
|
||||
{order.items.map((i) => (
|
||||
<tr key={i.id}>
|
||||
<td>{i.productId ? <Link className="ad-rowlink" href={`/admin/produkte/${i.productId}`}>{i.name}</Link> : i.name}{i.variantName && <div className="body-sm ad-muted">{i.variantName}</div>}</td>
|
||||
<td className="body-sm">{i.sku}</td>
|
||||
<td className="num">{i.quantity}</td>
|
||||
<td className="num">{formatPrice(i.unitPrice)}</td>
|
||||
<td className="num">{formatPrice(i.total)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr><td colSpan={4}>Zwischensumme</td><td className="num">{formatPrice(order.subtotal)}</td></tr>
|
||||
{order.discount > 0 && <tr><td colSpan={4}>Gutschein {order.couponCode}</td><td className="num">−{formatPrice(order.discount)}</td></tr>}
|
||||
<tr><td colSpan={4}>Versand – {order.shippingMethod}</td><td className="num">{formatPrice(order.shippingCost)}</td></tr>
|
||||
{order.paymentFee > 0 && <tr><td colSpan={4}>Gebühr Zahlungsart</td><td className="num">{formatPrice(order.paymentFee)}</td></tr>}
|
||||
<tr><td colSpan={4}><strong>Gesamt</strong> <span className="body-sm ad-muted">inkl. {formatPrice(order.taxAmount)} MwSt.</span></td><td className="num"><strong>{formatPrice(order.total)}</strong></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Card>
|
||||
{canEdit && (
|
||||
<Card title="Bearbeiten" lead="Status, Versand und interne Notiz">
|
||||
<AdminForm action={updateOrder}>
|
||||
<input type="hidden" name="id" value={order.id} />
|
||||
<div className="sm-form-row">
|
||||
<SelectField label="Bestellstatus" name="status" defaultValue={order.status} disabled={closed}>
|
||||
{Object.entries(ORDER_STATUS).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
|
||||
</SelectField>
|
||||
<SelectField label="Zahlungsstatus" name="paymentStatus" defaultValue={order.paymentStatus}>
|
||||
{Object.entries(PAYMENT_STATUS).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
|
||||
</SelectField>
|
||||
</div>
|
||||
{closed && <input type="hidden" name="status" value={order.status} />}
|
||||
<Field label="Sendungsnummer" name="trackingNumber" defaultValue={order.trackingNumber} hint="Der Kunde sieht sie in seinem Konto." />
|
||||
<TextareaField label="Interne Notiz" name="internalNote" defaultValue={order.internalNote} hint="Nur für das Team sichtbar." rows={3} />
|
||||
</AdminForm>
|
||||
</Card>
|
||||
)}
|
||||
<Card title="Verlauf">
|
||||
{canEdit && (
|
||||
<form action={addOrderNote} style={{ display: "flex", gap: 8, marginBottom: "var(--space-5)" }}>
|
||||
<input type="hidden" name="id" value={order.id} />
|
||||
<input className="sm-input" name="message" placeholder="Notiz zum Verlauf hinzufügen" aria-label="Notiz" style={{ minHeight: "var(--control-height-sm)" }} />
|
||||
<button className="sm-btn sm-btn--secondary sm-btn--sm" type="submit">Hinzufügen</button>
|
||||
</form>
|
||||
)}
|
||||
<ul className="ad-timeline">
|
||||
{order.events.map((e) => (
|
||||
<li key={e.id}>{e.message}<small>{dateFmt.format(e.createdAt)} · {e.author}</small></li>
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
</div>
|
||||
<div>
|
||||
<Card title="Kunde">
|
||||
<dl className="ad-dl">
|
||||
<dt>E-Mail</dt><dd><a href={`mailto:${order.email}`}>{order.email}</a></dd>
|
||||
{order.phone && (<><dt>Telefon</dt><dd>{order.phone}</dd></>)}
|
||||
<dt>Konto</dt><dd>{order.user ? <Link href={`/admin/kunden/${order.user.id}`}>Kundenkonto ansehen</Link> : "Gastbestellung"}</dd>
|
||||
</dl>
|
||||
</Card>
|
||||
<Card title="Lieferadresse"><AddressLines a={order.shippingAddress as AddressData} /></Card>
|
||||
<Card title="Rechnungsadresse">{order.billingAddress ? <AddressLines a={order.billingAddress as AddressData} /> : <p className="body">Wie Lieferadresse</p>}</Card>
|
||||
<Card title="Zahlung">
|
||||
<dl className="ad-dl">
|
||||
<dt>Art</dt><dd>{payment?.name ?? order.paymentMethod}</dd>
|
||||
{order.paymentRef && (<><dt>Referenz</dt><dd className="body-sm" style={{ wordBreak: "break-all" }}>{order.paymentRef}</dd></>)}
|
||||
</dl>
|
||||
</Card>
|
||||
{order.note && <Card title="Anmerkung des Kunden"><p className="body" style={{ margin: 0, whiteSpace: "pre-line" }}>{order.note}</p></Card>}
|
||||
{can(user, "orders.refund") && !closed && (
|
||||
<Card title={order.paymentStatus === "PAID" ? "Erstatten" : "Stornieren"} lead="Bucht den Bestand zurück.">
|
||||
<ConfirmButton action={cancelOrder} hidden={{ id: order.id }} confirm="Wirklich?" className="sm-btn sm-btn--secondary sm-btn--block">
|
||||
{order.paymentStatus === "PAID" ? "Bestellung erstatten" : "Bestellung stornieren"}
|
||||
</ConfirmButton>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
87
src/app/admin/(panel)/bestellungen/actions.ts
Normal file
87
src/app/admin/(panel)/bestellungen/actions.ts
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
"use server";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import type { OrderStatus, PaymentStatus } from "@prisma/client";
|
||||
import { db } from "@/lib/db";
|
||||
import { assertPermission, audit } from "@/lib/auth";
|
||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||
import { restock } from "@/lib/checkout";
|
||||
import { ORDER_STATUS, PAYMENT_STATUS } from "@/lib/status";
|
||||
import { getDefinition } from "@/lib/payments/catalog";
|
||||
import { getCredentials } from "@/lib/payments/credentials";
|
||||
import { refundPayment } from "@/lib/payments/stripe";
|
||||
|
||||
const authorName = (u: { firstName: string; lastName: string; email: string }) => [u.firstName, u.lastName].filter(Boolean).join(" ") || u.email;
|
||||
|
||||
export async function updateOrder(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||
const user = await assertPermission("orders.edit");
|
||||
const id = String(fd.get("id"));
|
||||
const order = await db.order.findUnique({ where: { id } });
|
||||
if (!order) return fail("Bestellung nicht gefunden.");
|
||||
const status = String(fd.get("status")) as OrderStatus;
|
||||
const paymentStatus = String(fd.get("paymentStatus")) as PaymentStatus;
|
||||
if (!(status in ORDER_STATUS) || !(paymentStatus in PAYMENT_STATUS)) return fail("Ungültiger Status.");
|
||||
if ((status === "CANCELLED" || status === "REFUNDED") && order.status !== status) {
|
||||
return fail("Zum Stornieren oder Erstatten nutze bitte den Knopf unten – so wird auch der Bestand zurückgebucht.");
|
||||
}
|
||||
const trackingNumber = String(fd.get("trackingNumber") ?? "").trim();
|
||||
const internalNote = String(fd.get("internalNote") ?? "");
|
||||
const events: string[] = [];
|
||||
if (status !== order.status) events.push(`Status: ${ORDER_STATUS[order.status].label} → ${ORDER_STATUS[status].label}`);
|
||||
if (paymentStatus !== order.paymentStatus) events.push(`Zahlung: ${PAYMENT_STATUS[order.paymentStatus].label} → ${PAYMENT_STATUS[paymentStatus].label}`);
|
||||
if (trackingNumber !== order.trackingNumber) events.push(`Sendungsnummer: ${trackingNumber || "entfernt"}`);
|
||||
await db.order.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status,
|
||||
paymentStatus,
|
||||
trackingNumber,
|
||||
internalNote,
|
||||
events: { create: events.map((message) => ({ message, author: authorName(user) })) },
|
||||
},
|
||||
});
|
||||
if (events.length) await audit(user, "Bestellung geändert", `${order.number}: ${events.join(", ")}`);
|
||||
revalidatePath(`/admin/bestellungen/${id}`);
|
||||
return ok();
|
||||
}
|
||||
|
||||
export async function addOrderNote(fd: FormData) {
|
||||
const user = await assertPermission("orders.edit");
|
||||
const id = String(fd.get("id"));
|
||||
const message = String(fd.get("message") ?? "").trim();
|
||||
if (!message) return;
|
||||
await db.orderEvent.create({ data: { orderId: id, message, author: authorName(user) } });
|
||||
revalidatePath(`/admin/bestellungen/${id}`);
|
||||
}
|
||||
|
||||
export async function cancelOrder(fd: FormData) {
|
||||
const user = await assertPermission("orders.refund");
|
||||
const id = String(fd.get("id"));
|
||||
const order = await db.order.findUnique({ where: { id } });
|
||||
if (!order || order.status === "CANCELLED" || order.status === "REFUNDED") return;
|
||||
const wasPaid = order.paymentStatus === "PAID";
|
||||
let refundNote = "";
|
||||
if (wasPaid && getDefinition(order.paymentMethod)?.provider === "stripe" && order.paymentRef.startsWith("pi_")) {
|
||||
try {
|
||||
const creds = await getCredentials();
|
||||
await refundPayment(creds.stripe.secretKey, order.paymentRef);
|
||||
refundNote = " Betrag über Stripe erstattet.";
|
||||
} catch (e) {
|
||||
refundNote = ` Stripe-Erstattung fehlgeschlagen (${e instanceof Error ? e.message : e}) – bitte im Stripe-Dashboard erstatten.`;
|
||||
}
|
||||
} else if (wasPaid) {
|
||||
refundNote = " Bitte den Betrag manuell erstatten (z. B. im PayPal-Konto oder per Überweisung).";
|
||||
}
|
||||
await db.$transaction(async (tx) => {
|
||||
await restock(tx, id);
|
||||
await tx.order.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: wasPaid ? "REFUNDED" : "CANCELLED",
|
||||
paymentStatus: wasPaid && refundNote.includes("erstattet.") ? "REFUNDED" : order.paymentStatus,
|
||||
events: { create: { message: `${wasPaid ? "Erstattet" : "Storniert"}, Bestand zurückgebucht.${refundNote}`, author: authorName(user) } },
|
||||
},
|
||||
});
|
||||
});
|
||||
await audit(user, wasPaid ? "Bestellung erstattet" : "Bestellung storniert", order.number);
|
||||
revalidatePath(`/admin/bestellungen/${id}`);
|
||||
}
|
||||
88
src/app/admin/(panel)/bestellungen/page.tsx
Normal file
88
src/app/admin/(panel)/bestellungen/page.tsx
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import Link from "next/link";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { db } from "@/lib/db";
|
||||
import { requireAdmin } from "@/lib/auth";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { ORDER_STATUS, PAYMENT_STATUS, dateFmt } from "@/lib/status";
|
||||
import { Card, Empty, PageHead, Pill } from "@/components/admin/ui";
|
||||
|
||||
const TABS: { key: string; label: string; where: Prisma.OrderWhereInput }[] = [
|
||||
{ key: "alle", label: "Alle", where: {} },
|
||||
{ key: "offen", label: "Zu versenden", where: { status: { in: ["PAID", "PROCESSING"] } } },
|
||||
{ key: "zahlung", label: "Zahlung offen", where: { status: "PENDING" } },
|
||||
{ key: "versendet", label: "Versendet", where: { status: "SHIPPED" } },
|
||||
{ key: "abgeschlossen", label: "Abgeschlossen", where: { status: "COMPLETED" } },
|
||||
{ key: "storniert", label: "Storniert", where: { status: { in: ["CANCELLED", "REFUNDED"] } } },
|
||||
];
|
||||
|
||||
export default async function OrdersPage({ searchParams }: { searchParams: Promise<{ status?: string; q?: string; seite?: string }> }) {
|
||||
await requireAdmin("orders.view");
|
||||
const sp = await searchParams;
|
||||
const tab = TABS.find((t) => t.key === sp.status) ?? TABS[0];
|
||||
const q = (sp.q ?? "").trim();
|
||||
const page = Math.max(1, Number(sp.seite) || 1);
|
||||
const where: Prisma.OrderWhereInput = {
|
||||
...tab.where,
|
||||
...(q ? { OR: [{ number: { contains: q, mode: "insensitive" } }, { email: { contains: q, mode: "insensitive" } }] } : {}),
|
||||
};
|
||||
const [orders, total, counts] = await Promise.all([
|
||||
db.order.findMany({ where, orderBy: { createdAt: "desc" }, take: 50, skip: (page - 1) * 50, include: { _count: { select: { items: true } } } }),
|
||||
db.order.count({ where }),
|
||||
Promise.all(TABS.map((t) => db.order.count({ where: t.where }))),
|
||||
]);
|
||||
return (
|
||||
<div className="ad-wrap">
|
||||
<PageHead title="Bestellungen" lead="Alle Bestellungen auf einen Blick. Klick auf eine Bestellung, um sie zu bearbeiten." />
|
||||
<Card flush>
|
||||
<div className="ad-toolbar">
|
||||
<nav className="ad-tabs" aria-label="Filter">
|
||||
{TABS.map((t, i) => (
|
||||
<Link key={t.key} className={`ad-tab${t.key === tab.key ? " is-active" : ""}`} href={`/admin/bestellungen?status=${t.key}`}>
|
||||
{t.label} <span>{counts[i]}</span>
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<form method="get" style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
|
||||
<input type="hidden" name="status" value={tab.key} />
|
||||
<input className="sm-input" type="search" name="q" defaultValue={q} placeholder="Nummer oder E-Mail suchen" aria-label="Bestellungen durchsuchen" />
|
||||
</form>
|
||||
</div>
|
||||
{orders.length === 0 ? (
|
||||
<Empty title="Keine Bestellungen gefunden" text={q ? "Versuch es mit einem anderen Suchbegriff." : "In diesem Filter ist gerade nichts."} />
|
||||
) : (
|
||||
<div className="ad-table-wrap">
|
||||
<table className="ad-table">
|
||||
<thead>
|
||||
<tr><th>Bestellung</th><th>Datum</th><th>Kunde</th><th>Zahlung</th><th>Status</th><th className="num">Summe</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{orders.map((o) => {
|
||||
const addr = o.shippingAddress as { firstName?: string; lastName?: string };
|
||||
return (
|
||||
<tr key={o.id}>
|
||||
<td><Link className="ad-rowlink" href={`/admin/bestellungen/${o.id}`}>{o.number}</Link><div className="body-sm ad-muted">{o._count.items} Positionen</div></td>
|
||||
<td className="body-sm">{dateFmt.format(o.createdAt)}</td>
|
||||
<td>{addr.firstName} {addr.lastName}<div className="body-sm ad-muted">{o.email}</div></td>
|
||||
<td><Pill tone={PAYMENT_STATUS[o.paymentStatus].tone}>{PAYMENT_STATUS[o.paymentStatus].label}</Pill></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>
|
||||
</div>
|
||||
)}
|
||||
{total > 50 && (
|
||||
<div className="ad-card__foot" style={{ justifyContent: "space-between" }}>
|
||||
<span className="body-sm ad-muted">Seite {page} von {Math.ceil(total / 50)}</span>
|
||||
<span className="sm-btn-row">
|
||||
{page > 1 && <Link className="sm-btn sm-btn--secondary sm-btn--sm" href={`?status=${tab.key}&q=${q}&seite=${page - 1}`}>Zurück</Link>}
|
||||
{page * 50 < total && <Link className="sm-btn sm-btn--secondary sm-btn--sm" href={`?status=${tab.key}&q=${q}&seite=${page + 1}`}>Weiter</Link>}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
69
src/app/admin/(panel)/layout.tsx
Normal file
69
src/app/admin/(panel)/layout.tsx
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import Link from "next/link";
|
||||
import "@/styles/admin.css";
|
||||
import { db } from "@/lib/db";
|
||||
import { can, requireAdmin } from "@/lib/auth";
|
||||
import { logout } from "@/lib/auth-actions";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
import { Icon } from "@/components/Icon";
|
||||
import { AdminNav } from "@/components/admin/AdminNav";
|
||||
import { MobileAdminNav } from "@/components/admin/MobileAdminNav";
|
||||
import { ADMIN_NAV } from "@/components/admin/nav";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata = { title: "Admin", robots: { index: false } };
|
||||
|
||||
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
const user = await requireAdmin();
|
||||
const settings = await getSettings();
|
||||
const groups = ADMIN_NAV.map((g) => ({ ...g, items: g.items.filter((i) => can(user, i.permission)) })).filter((g) => g.items.length);
|
||||
const openOrders = can(user, "orders.view") ? await db.order.count({ where: { status: { in: ["PAID", "PROCESSING"] } } }) : 0;
|
||||
const badges = { openOrders };
|
||||
const nav = <AdminNav groups={groups} badges={badges} />;
|
||||
const foot = (
|
||||
<div className="ad-side__foot">
|
||||
<p>{[user.firstName, user.lastName].filter(Boolean).join(" ") || user.email}</p>
|
||||
<p className="ad-muted">{user.role?.name}</p>
|
||||
<div style={{ display: "flex", gap: "var(--space-3)", marginTop: "var(--space-3)", flexWrap: "wrap" }}>
|
||||
<Link href="/" target="_blank" className="body-sm" style={{ display: "inline-flex", gap: 4, alignItems: "center" }}>
|
||||
<Icon name="external" size="sm" /> Shop ansehen
|
||||
</Link>
|
||||
<form action={logout}>
|
||||
<button type="submit" className="body-sm" style={{ background: "none", border: 0, padding: 0, color: "var(--link)", cursor: "pointer", display: "inline-flex", gap: 4, alignItems: "center" }}>
|
||||
<Icon name="logout" size="sm" /> Abmelden
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
const brand = (
|
||||
<Link href="/admin" className="ad-side__brand">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src="/brand/bildmarke-ink.png" alt="" />
|
||||
<span>
|
||||
<strong>{settings.general.shopName}.</strong>
|
||||
<small>Verwaltung</small>
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
return (
|
||||
<div className="ad">
|
||||
<aside className="ad-side">
|
||||
{brand}
|
||||
{nav}
|
||||
{foot}
|
||||
</aside>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<div className="ad-top">
|
||||
<MobileAdminNav>
|
||||
{brand}
|
||||
{nav}
|
||||
{foot}
|
||||
</MobileAdminNav>
|
||||
<strong style={{ letterSpacing: "0.24em", fontWeight: 400, textTransform: "uppercase" }}>{settings.general.shopName}.</strong>
|
||||
<Link className="sm-header__btn" href="/" aria-label="Shop ansehen"><Icon name="external" /></Link>
|
||||
</div>
|
||||
<main className="ad-main">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
167
src/app/admin/(panel)/page.tsx
Normal file
167
src/app/admin/(panel)/page.tsx
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
import Link from "next/link";
|
||||
import { db } from "@/lib/db";
|
||||
import { can, requireAdmin } from "@/lib/auth";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { ORDER_STATUS, dateFmt } from "@/lib/status";
|
||||
import { getCredentials, isProviderReady } from "@/lib/payments/credentials";
|
||||
import { getDefinition } from "@/lib/payments/catalog";
|
||||
import { Icon } from "@/components/Icon";
|
||||
import { Alert } from "@/components/shop/Blocks";
|
||||
import { Card, PageHead, Pill } from "@/components/admin/ui";
|
||||
|
||||
const PAID = { in: ["PAID", "PROCESSING", "SHIPPED", "COMPLETED"] as ("PAID" | "PROCESSING" | "SHIPPED" | "COMPLETED")[] };
|
||||
|
||||
export default async function Dashboard({ searchParams }: { searchParams: Promise<{ "kein-zugriff"?: string }> }) {
|
||||
const user = await requireAdmin();
|
||||
const noAccess = (await searchParams)["kein-zugriff"];
|
||||
if (!can(user, "dashboard.view")) {
|
||||
return (
|
||||
<div className="ad-wrap">
|
||||
<PageHead title={`Hallo ${user.firstName || ""}`.trim()} lead="Wähle links einen Bereich." />
|
||||
{noAccess && <Alert kind="danger" title="Für diese Seite fehlt dir das Recht." />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const now = new Date();
|
||||
const startToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const start30 = new Date(startToday.getTime() - 29 * 86400000);
|
||||
|
||||
const [today, last30, toShip, customers, recent, lowStock, lowVariants, chartOrders, payments, creds, legal, productCount] = await Promise.all([
|
||||
db.order.aggregate({ where: { createdAt: { gte: startToday }, status: { notIn: ["CANCELLED"] } }, _sum: { total: true }, _count: true }),
|
||||
db.order.aggregate({ where: { createdAt: { gte: start30 }, status: PAID }, _sum: { total: true }, _count: true }),
|
||||
db.order.count({ where: { status: { in: ["PAID", "PROCESSING"] } } }),
|
||||
db.user.count({ where: { roleId: null } }),
|
||||
db.order.findMany({ orderBy: { createdAt: "desc" }, take: 6 }),
|
||||
db.product.findMany({ where: { trackStock: true, active: true, stock: { lte: 3 }, variants: { none: {} } }, take: 6 }),
|
||||
db.productVariant.findMany({ where: { stock: { lte: 3 }, product: { trackStock: true, active: true } }, include: { product: true }, take: 6 }),
|
||||
db.order.findMany({ where: { createdAt: { gte: start30 }, status: PAID }, select: { createdAt: true, total: true } }),
|
||||
db.paymentMethod.findMany({ where: { enabled: true } }),
|
||||
getCredentials(),
|
||||
db.page.findMany({ where: { slug: { in: ["impressum", "datenschutz", "agb", "widerruf"] } } }),
|
||||
db.product.count(),
|
||||
]);
|
||||
|
||||
const days = Array.from({ length: 30 }, (_, i) => {
|
||||
const d = new Date(start30.getTime() + i * 86400000);
|
||||
return { d, total: 0 };
|
||||
});
|
||||
for (const o of chartOrders) {
|
||||
const idx = Math.floor((o.createdAt.getTime() - start30.getTime()) / 86400000);
|
||||
if (days[idx]) days[idx].total += o.total;
|
||||
}
|
||||
const max = Math.max(1, ...days.map((d) => d.total));
|
||||
|
||||
const readyPayments = payments.filter((p) => isProviderReady(getDefinition(p.code)?.provider ?? "manual", creds));
|
||||
const legalDone = legal.length === 4 && legal.every((p) => !p.content.startsWith("Bitte im Admin"));
|
||||
const setup = [
|
||||
{ done: productCount > 0, label: "Erstes Produkt anlegen", href: "/admin/produkte/neu" },
|
||||
{ done: readyPayments.some((p) => getDefinition(p.code)?.provider !== "manual"), label: "Online-Zahlung (Stripe oder PayPal) einrichten", href: "/admin/zahlung" },
|
||||
{ done: legalDone, label: "Impressum, Datenschutz, AGB und Widerruf ausfüllen", href: "/admin/seiten" },
|
||||
{ done: payments.some((p) => p.code === "prepayment" && (p.config as Record<string, string>)?.iban), label: "Bankverbindung für Vorkasse eintragen", href: "/admin/zahlung" },
|
||||
];
|
||||
const lows = [
|
||||
...lowStock.map((p) => ({ id: p.id, name: p.name, stock: p.stock, productId: p.id })),
|
||||
...lowVariants.map((v) => ({ id: v.id, name: `${v.product.name} – ${v.name}`, stock: v.stock, productId: v.productId })),
|
||||
].slice(0, 6);
|
||||
|
||||
return (
|
||||
<div className="ad-wrap">
|
||||
<PageHead title={`Guten Tag${user.firstName ? `, ${user.firstName}` : ""}`} lead="Das passiert gerade in deinem Shop.">
|
||||
{can(user, "products.edit") && (
|
||||
<Link className="sm-btn sm-btn--primary" href="/admin/produkte/neu"><Icon name="plus" size="sm" /> Produkt anlegen</Link>
|
||||
)}
|
||||
</PageHead>
|
||||
{noAccess && <div style={{ marginBottom: "var(--space-5)" }}><Alert kind="danger" title="Für diese Seite fehlt dir das Recht." /></div>}
|
||||
|
||||
<div className="ad-kpis">
|
||||
<div className="ad-kpi">
|
||||
<div className="ad-kpi__label">Umsatz heute</div>
|
||||
<div className="ad-kpi__value">{formatPrice(today._sum.total ?? 0)}</div>
|
||||
<div className="ad-kpi__hint">{today._count} Bestellungen</div>
|
||||
</div>
|
||||
<div className="ad-kpi">
|
||||
<div className="ad-kpi__label">Umsatz 30 Tage</div>
|
||||
<div className="ad-kpi__value">{formatPrice(last30._sum.total ?? 0)}</div>
|
||||
<div className="ad-kpi__hint">{last30._count} bezahlte Bestellungen</div>
|
||||
</div>
|
||||
<Link className="ad-kpi" href="/admin/bestellungen?status=offen">
|
||||
<div className="ad-kpi__label">Zu versenden</div>
|
||||
<div className="ad-kpi__value">{toShip}</div>
|
||||
<div className="ad-kpi__hint">bezahlt, noch nicht versendet</div>
|
||||
</Link>
|
||||
<Link className="ad-kpi" href="/admin/kunden">
|
||||
<div className="ad-kpi__label">Kunden mit Konto</div>
|
||||
<div className="ad-kpi__value">{customers}</div>
|
||||
<div className="ad-kpi__hint">insgesamt</div>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="ad-grid ad-grid--2-1">
|
||||
<div>
|
||||
<Card title="Umsatz der letzten 30 Tage" lead="Bezahlte Bestellungen pro Tag">
|
||||
<div className="ad-chart" role="img" aria-label="Umsatz pro Tag">
|
||||
{days.map((d, i) => (
|
||||
<div key={i} className="ad-chart__bar" style={{ height: `${(d.total / max) * 100}%` }} title={`${d.d.toLocaleDateString("de-DE")}: ${formatPrice(d.total)}`} />
|
||||
))}
|
||||
</div>
|
||||
<div className="ad-chart__axis">
|
||||
<span>{days[0].d.toLocaleDateString("de-DE", { day: "numeric", month: "short" })}</span>
|
||||
<span>heute</span>
|
||||
</div>
|
||||
</Card>
|
||||
<Card title="Neueste Bestellungen" action={<Link href="/admin/bestellungen" className="body-sm">Alle ansehen</Link>} flush>
|
||||
{recent.length === 0 ? (
|
||||
<div className="ad-empty"><strong>Noch keine Bestellungen</strong>Sobald jemand bestellt, steht es hier.</div>
|
||||
) : (
|
||||
<div className="ad-table-wrap">
|
||||
<table className="ad-table">
|
||||
<tbody>
|
||||
{recent.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td><Link className="ad-rowlink" href={`/admin/bestellungen/${o.id}`}>{o.number}</Link><div className="ad-muted body-sm">{o.email}</div></td>
|
||||
<td className="body-sm ad-muted">{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>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
<div>
|
||||
{setup.some((s) => !s.done) && (
|
||||
<Card title="Shop einrichten" lead={`${setup.filter((s) => s.done).length} von ${setup.length} erledigt`}>
|
||||
<ul className="ad-setup">
|
||||
{setup.map((s) => (
|
||||
<li key={s.label} className={s.done ? "is-done" : undefined}>
|
||||
<span className="ad-setup__dot">{s.done && <Icon name="check" size="sm" />}</span>
|
||||
<span className="ad-setup__label">{s.label}</span>
|
||||
{!s.done && <Link href={s.href}>Los</Link>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
)}
|
||||
<Card title="Bestand niedrig" lead="3 Stück oder weniger" flush>
|
||||
{lows.length === 0 ? (
|
||||
<div className="ad-empty" style={{ padding: "var(--space-5)" }}>Alles gut gefüllt.</div>
|
||||
) : (
|
||||
<table className="ad-table">
|
||||
<tbody>
|
||||
{lows.map((l) => (
|
||||
<tr key={l.id}>
|
||||
<td><Link className="ad-rowlink" href={`/admin/produkte/${l.productId}`}>{l.name}</Link></td>
|
||||
<td className="num"><Pill tone={l.stock <= 0 ? "danger" : "gold"}>{l.stock <= 0 ? "Ausverkauft" : `${l.stock} Stück`}</Pill></td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
27
src/app/admin/login/page.tsx
Normal file
27
src/app/admin/login/page.tsx
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { redirect } from "next/navigation";
|
||||
import "@/styles/admin.css";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { LoginForm } from "@/components/shop/AuthForms";
|
||||
|
||||
export const metadata = { title: "Admin – Anmelden", robots: { index: false } };
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function AdminLogin() {
|
||||
const user = await getCurrentUser();
|
||||
if (user?.role) redirect("/admin");
|
||||
return (
|
||||
<main className="ad-login">
|
||||
<div className="ad-login__box">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src="/brand/logo-ink.png" alt="Sanamare" style={{ width: 200, margin: "0 auto var(--space-6)" }} />
|
||||
<div className="ad-card">
|
||||
<div className="ad-card__body">
|
||||
<h1 className="display-sm" style={{ marginBottom: "var(--space-2)" }}>Verwaltung</h1>
|
||||
<p className="body-sm ad-muted" style={{ marginTop: 0, marginBottom: "var(--space-5)" }}>Melde dich mit deinem Team-Zugang an.</p>
|
||||
<LoginForm area="admin" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
25
src/app/api/payments/paypal/return/route.ts
Normal file
25
src/app/api/payments/paypal/return/route.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { markOrderPaid } from "@/lib/checkout";
|
||||
import { finishCheckoutSession } from "@/lib/checkout-finish";
|
||||
import { getCredentials } from "@/lib/payments/credentials";
|
||||
import { capturePaypalOrder } from "@/lib/payments/paypal";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const orderId = req.nextUrl.searchParams.get("order") ?? "";
|
||||
const token = req.nextUrl.searchParams.get("token") ?? "";
|
||||
const appUrl = process.env.APP_URL ?? req.nextUrl.origin;
|
||||
const order = await db.order.findUnique({ where: { id: orderId } });
|
||||
if (!order || order.paymentRef !== token) return NextResponse.redirect(new URL("/kasse/zahlung?abgebrochen=1", appUrl));
|
||||
try {
|
||||
const creds = await getCredentials();
|
||||
const result = await capturePaypalOrder(creds.paypal, token);
|
||||
if (result.status === "COMPLETED") await markOrderPaid(order.id, token, "PayPal");
|
||||
else await db.orderEvent.create({ data: { orderId: order.id, message: `PayPal meldet Status „${result.status}“` } });
|
||||
} catch (e) {
|
||||
await db.orderEvent.create({ data: { orderId: order.id, message: `PayPal-Zahlung fehlgeschlagen: ${e instanceof Error ? e.message : e}` } });
|
||||
return NextResponse.redirect(new URL("/kasse/zahlung?abgebrochen=1", appUrl));
|
||||
}
|
||||
await finishCheckoutSession();
|
||||
return NextResponse.redirect(new URL(`/kasse/danke/${order.id}`, appUrl));
|
||||
}
|
||||
28
src/app/api/payments/stripe/return/route.ts
Normal file
28
src/app/api/payments/stripe/return/route.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { markOrderPaid } from "@/lib/checkout";
|
||||
import { finishCheckoutSession } from "@/lib/checkout-finish";
|
||||
import { getCredentials } from "@/lib/payments/credentials";
|
||||
import { retrieveCheckoutSession } from "@/lib/payments/stripe";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const orderId = req.nextUrl.searchParams.get("order") ?? "";
|
||||
const sessionId = req.nextUrl.searchParams.get("session_id") ?? "";
|
||||
const appUrl = process.env.APP_URL ?? req.nextUrl.origin;
|
||||
const order = await db.order.findUnique({ where: { id: orderId } });
|
||||
if (!order || order.paymentRef !== sessionId) return NextResponse.redirect(new URL("/kasse/zahlung?abgebrochen=1", appUrl));
|
||||
try {
|
||||
const creds = await getCredentials();
|
||||
const session = await retrieveCheckoutSession(creds.stripe.secretKey, sessionId);
|
||||
if (session.payment_status === "paid") {
|
||||
await markOrderPaid(order.id, session.payment_intent ?? session.id, "Stripe");
|
||||
} else {
|
||||
// z. B. SEPA: Zahlung läuft noch, Bestätigung kommt per Webhook
|
||||
await db.orderEvent.create({ data: { orderId: order.id, message: `Stripe meldet Zahlungsstatus „${session.payment_status}“` } });
|
||||
}
|
||||
} catch (e) {
|
||||
await db.orderEvent.create({ data: { orderId: order.id, message: `Stripe-Prüfung fehlgeschlagen: ${e instanceof Error ? e.message : e}` } });
|
||||
}
|
||||
await finishCheckoutSession();
|
||||
return NextResponse.redirect(new URL(`/kasse/danke/${order.id}`, appUrl));
|
||||
}
|
||||
28
src/app/api/webhooks/stripe/route.ts
Normal file
28
src/app/api/webhooks/stripe/route.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { markOrderPaid } from "@/lib/checkout";
|
||||
import { getCredentials } from "@/lib/payments/credentials";
|
||||
import { verifyWebhook } from "@/lib/payments/stripe";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const payload = await req.text();
|
||||
const creds = await getCredentials();
|
||||
if (!creds.stripe.webhookSecret || !verifyWebhook(payload, req.headers.get("stripe-signature"), creds.stripe.webhookSecret)) {
|
||||
return NextResponse.json({ error: "invalid signature" }, { status: 400 });
|
||||
}
|
||||
const event = JSON.parse(payload) as { type: string; data: { object: { id: string; metadata?: Record<string, string>; payment_intent?: string } } };
|
||||
const obj = event.data.object;
|
||||
const orderId = obj.metadata?.orderId;
|
||||
if (orderId) {
|
||||
if (event.type === "checkout.session.completed" || event.type === "checkout.session.async_payment_succeeded") {
|
||||
const full = event.type === "checkout.session.completed" ? (obj as { payment_status?: string }).payment_status === "paid" : true;
|
||||
if (full) await markOrderPaid(orderId, obj.payment_intent ?? obj.id, "Stripe-Webhook");
|
||||
} else if (event.type === "checkout.session.async_payment_failed") {
|
||||
await db.order.update({
|
||||
where: { id: orderId },
|
||||
data: { paymentStatus: "FAILED", events: { create: { message: "Stripe: Zahlung fehlgeschlagen (Webhook)" } } },
|
||||
});
|
||||
}
|
||||
}
|
||||
return NextResponse.json({ received: true });
|
||||
}
|
||||
29
src/app/layout.tsx
Normal file
29
src/app/layout.tsx
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import type { Metadata } from "next";
|
||||
import "@fontsource/jost/400.css";
|
||||
import "@fontsource/jost/500.css";
|
||||
import "@fontsource/jost/600.css";
|
||||
import "@fontsource/cormorant-garamond/400.css";
|
||||
import "@fontsource/cormorant-garamond/400-italic.css";
|
||||
import "@fontsource/cormorant-garamond/500.css";
|
||||
import "@fontsource/cormorant-garamond/600.css";
|
||||
import "@/styles/tokens.css";
|
||||
import "@/styles/bundle.css";
|
||||
import "@/styles/shop.css";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const s = await getSettings();
|
||||
return {
|
||||
title: { default: `${s.general.shopName} – ${s.general.tagline}`, template: `%s · ${s.general.shopName}` },
|
||||
description: s.appearance.footerClaim,
|
||||
icons: { icon: "/brand/bildmarke-ink.png" },
|
||||
};
|
||||
}
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="de">
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
20
src/app/uploads/[...path]/route.ts
Normal file
20
src/app/uploads/[...path]/route.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
const TYPES: Record<string, string> = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".gif": "image/gif", ".avif": "image/avif" };
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ path: string[] }> }) {
|
||||
const parts = (await params).path;
|
||||
const root = path.resolve(process.env.UPLOAD_DIR ?? "./uploads");
|
||||
const file = path.resolve(root, ...parts);
|
||||
if (!file.startsWith(root + path.sep)) return new NextResponse("Not found", { status: 404 });
|
||||
const type = TYPES[path.extname(file).toLowerCase()];
|
||||
if (!type) return new NextResponse("Not found", { status: 404 });
|
||||
try {
|
||||
const data = await readFile(file);
|
||||
return new NextResponse(new Uint8Array(data), { headers: { "Content-Type": type, "Cache-Control": "public, max-age=31536000, immutable" } });
|
||||
} catch {
|
||||
return new NextResponse("Not found", { status: 404 });
|
||||
}
|
||||
}
|
||||
69
src/components/Field.tsx
Normal file
69
src/components/Field.tsx
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { Icon } from "./Icon";
|
||||
|
||||
type Props = {
|
||||
label: string;
|
||||
name: string;
|
||||
error?: string;
|
||||
hint?: string;
|
||||
optional?: boolean;
|
||||
} & React.InputHTMLAttributes<HTMLInputElement>;
|
||||
|
||||
export function Field({ label, name, error, hint, optional, ...rest }: Props) {
|
||||
const id = rest.id ?? `f-${name}`;
|
||||
return (
|
||||
<label className={`sm-field${error ? " is-invalid" : ""}`} htmlFor={id}>
|
||||
<span className="sm-field__label">
|
||||
{label} {optional && <span className="sm-optional">(optional)</span>}
|
||||
</span>
|
||||
<input className="sm-input" id={id} name={name} aria-invalid={error ? true : undefined} aria-describedby={error ? `${id}-e` : undefined} {...rest} />
|
||||
{hint && !error && <span className="sm-field__hint">{hint}</span>}
|
||||
{error && (
|
||||
<span className="sm-field__error" id={`${id}-e`}>
|
||||
<Icon name="alert" /> {error}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function SelectField({
|
||||
label,
|
||||
name,
|
||||
error,
|
||||
hint,
|
||||
children,
|
||||
...rest
|
||||
}: { label: string; name: string; error?: string; hint?: string; children: React.ReactNode } & React.SelectHTMLAttributes<HTMLSelectElement>) {
|
||||
const id = rest.id ?? `f-${name}`;
|
||||
return (
|
||||
<label className={`sm-field${error ? " is-invalid" : ""}`} htmlFor={id}>
|
||||
<span className="sm-field__label">{label}</span>
|
||||
<span className="sm-select-wrap">
|
||||
<select className="sm-select" id={id} name={name} {...rest}>{children}</select>
|
||||
</span>
|
||||
{hint && !error && <span className="sm-field__hint">{hint}</span>}
|
||||
{error && <span className="sm-field__error"><Icon name="alert" /> {error}</span>}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function TextareaField({
|
||||
label,
|
||||
name,
|
||||
error,
|
||||
hint,
|
||||
optional,
|
||||
...rest
|
||||
}: { label: string; name: string; error?: string; hint?: string; optional?: boolean } & React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
|
||||
const id = rest.id ?? `f-${name}`;
|
||||
return (
|
||||
<label className={`sm-field${error ? " is-invalid" : ""}`} htmlFor={id}>
|
||||
<span className="sm-field__label">
|
||||
{label} {optional && <span className="sm-optional">(optional)</span>}
|
||||
</span>
|
||||
<textarea className="sm-textarea" id={id} name={name} {...rest} />
|
||||
{hint && !error && <span className="sm-field__hint">{hint}</span>}
|
||||
{error && <span className="sm-field__error"><Icon name="alert" /> {error}</span>}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
67
src/components/Icon.tsx
Normal file
67
src/components/Icon.tsx
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// Linien-Icons aus dem Sanamare Design System (1.5px Strich, 24px Raster, currentColor).
|
||||
const PATHS = {
|
||||
menu: <path d="M4 7h16M4 12h16M4 17h16" />,
|
||||
close: <path d="M6 6l12 12M18 6 6 18" />,
|
||||
search: (<><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></>),
|
||||
user: (<><circle cx="12" cy="8" r="4" /><path d="M4 21a8 8 0 0 1 16 0" /></>),
|
||||
cart: (<><circle cx="9" cy="20" r="1" /><circle cx="18" cy="20" r="1" /><path d="M2 3h2.5l2.4 11.2a1 1 0 0 0 1 .8h9.7a1 1 0 0 0 1-.8L20.5 7H6" /></>),
|
||||
arrow: <path d="M5 12h14M13 6l6 6-6 6" />,
|
||||
arrowLeft: <path d="M19 12H5M11 6l-6 6 6 6" />,
|
||||
truck: (<><path d="M3 6h11v10H3zM14 10h4l3 3v3h-7z" /><circle cx="7" cy="18" r="1.5" /><circle cx="17" cy="18" r="1.5" /></>),
|
||||
return: (<><path d="M9 14 4 9l5-5" /><path d="M4 9h11a5 5 0 0 1 0 10h-3" /></>),
|
||||
lock: (<><rect x="5" y="11" width="14" height="10" rx="1" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></>),
|
||||
chat: <path d="M4 5h16v11H9l-5 4z" />,
|
||||
leaf: (<><path d="M5 19C5 9 11 5 20 4c-1 9-5 15-15 15Z" /><path d="M5 19c3-4 6-7 10-9" /></>),
|
||||
star: <path d="m12 3 2.8 5.9 6.4.8-4.7 4.4 1.2 6.4L12 17.4l-5.7 3.1 1.2-6.4L2.8 9.7l6.4-.8z" />,
|
||||
heart: <path d="M12 20.5s-7.5-4.6-7.5-10A4 4 0 0 1 12 8a4 4 0 0 1 7.5 2.5c0 5.4-7.5 10-7.5 10Z" />,
|
||||
minus: <path d="M6 12h12" />,
|
||||
plus: <path d="M12 6v12M6 12h12" />,
|
||||
check: <path d="M20 6 9 17l-5-5" />,
|
||||
info: (<><circle cx="12" cy="12" r="9" /><path d="M12 11v5M12 8h.01" /></>),
|
||||
alert: (<><circle cx="12" cy="12" r="9" /><path d="M12 8v5M12 16h.01" /></>),
|
||||
// Admin
|
||||
dashboard: (<><rect x="3" y="3" width="7" height="9" rx="1" /><rect x="14" y="3" width="7" height="5" rx="1" /><rect x="14" y="12" width="7" height="9" rx="1" /><rect x="3" y="16" width="7" height="5" rx="1" /></>),
|
||||
box: (<><path d="M21 8 12 3 3 8v8l9 5 9-5z" /><path d="m3 8 9 5 9-5M12 13v8" /></>),
|
||||
tag: (<><path d="M3 12V3h9l9 9-9 9z" /><circle cx="7.5" cy="7.5" r="1.5" /></>),
|
||||
folder: <path d="M3 6a1 1 0 0 1 1-1h5l2 2h9a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1z" />,
|
||||
receipt: (<><path d="M6 3h12v18l-3-2-3 2-3-2-3 2z" /><path d="M9 8h6M9 12h6" /></>),
|
||||
users: (<><circle cx="9" cy="8" r="3.5" /><path d="M2.5 20a6.5 6.5 0 0 1 13 0" /><path d="M16 4.5a3.5 3.5 0 0 1 0 7M18 14a6 6 0 0 1 3.5 6" /></>),
|
||||
shield: (<><path d="M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6z" /><path d="m9 12 2 2 4-4" /></>),
|
||||
card: (<><rect x="3" y="5" width="18" height="14" rx="1.5" /><path d="M3 10h18M7 15h4" /></>),
|
||||
settings: (<><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z" /></>),
|
||||
brush: (<><path d="M14 4l6 6-9 9H5v-6z" /><path d="m12 6 6 6" /></>),
|
||||
file: (<><path d="M6 3h8l4 4v14H6z" /><path d="M14 3v4h4M9 13h6M9 17h6" /></>),
|
||||
ticket: (<><path d="M3 8a2 2 0 0 0 0 4v4h18v-4a2 2 0 0 1 0-4V4H3z" transform="translate(0 2)" /><path d="M14 6v12" strokeDasharray="2 2" /></>),
|
||||
mail: (<><rect x="3" y="5" width="18" height="14" rx="1" /><path d="m3 7 9 6 9-6" /></>),
|
||||
history: (<><path d="M3 12a9 9 0 1 0 3-6.7L3 8" /><path d="M3 3v5h5M12 7v5l3 2" /></>),
|
||||
external: (<><path d="M14 4h6v6M20 4l-9 9" /><path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5" /></>),
|
||||
logout: (<><path d="M15 4h4a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1h-4" /><path d="M10 17l-5-5 5-5M5 12h11" /></>),
|
||||
trash: (<><path d="M4 7h16M10 11v6M14 11v6" /><path d="M6 7l1 13h10l1-13M9 7V4h6v3" /></>),
|
||||
edit: (<><path d="M4 20h4L19 9l-4-4L4 16z" /><path d="m13 7 4 4" /></>),
|
||||
eye: (<><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z" /><circle cx="12" cy="12" r="3" /></>),
|
||||
image: (<><rect x="3" y="4" width="18" height="16" rx="1" /><circle cx="9" cy="10" r="2" /><path d="m21 16-5-5-9 9" /></>),
|
||||
grip: <path d="M9 6h.01M15 6h.01M9 12h.01M15 12h.01M9 18h.01M15 18h.01" />,
|
||||
};
|
||||
|
||||
export type IconName = keyof typeof PATHS;
|
||||
|
||||
export function Icon({ name, size, className }: { name: IconName; size?: "sm"; className?: string }) {
|
||||
return (
|
||||
<svg className={`sm-icon${size === "sm" ? " sm-icon--sm" : ""}${className ? ` ${className}` : ""}`} viewBox="0 0 24 24" aria-hidden="true">
|
||||
{PATHS[name]}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function Stars({ value, count }: { value: number; count?: number }) {
|
||||
return (
|
||||
<span className="sm-stars" aria-label={`${value} von 5 Sternen`}>
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
<svg key={i} viewBox="0 0 24 24" aria-hidden="true" className={i > Math.round(value) ? "is-empty" : undefined}>
|
||||
{PATHS.star}
|
||||
</svg>
|
||||
))}
|
||||
{count != null && <span className="sm-stars__count">({count})</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
89
src/components/admin/AdminForm.tsx
Normal file
89
src/components/admin/AdminForm.tsx
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
"use client";
|
||||
import { useActionState, useEffect, useState } from "react";
|
||||
import { useFormStatus } from "react-dom";
|
||||
import type { ActionResult } from "@/lib/action-result";
|
||||
import { Icon } from "../Icon";
|
||||
|
||||
function SaveButton({ label }: { label: string }) {
|
||||
const { pending } = useFormStatus();
|
||||
return (
|
||||
<button className="sm-btn sm-btn--primary" type="submit" disabled={pending}>
|
||||
{pending ? "Speichert …" : label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** Formular mit Speicherleiste und Rückmeldung. Felder als children. */
|
||||
export function AdminForm({
|
||||
action,
|
||||
children,
|
||||
submitLabel = "Speichern",
|
||||
extraActions,
|
||||
className,
|
||||
}: {
|
||||
action: (prev: ActionResult, fd: FormData) => Promise<ActionResult>;
|
||||
children: React.ReactNode | ((state: ActionResult) => React.ReactNode);
|
||||
submitLabel?: string;
|
||||
extraActions?: React.ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
const [state, formAction] = useActionState(action, null);
|
||||
const [visible, setVisible] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!state) return;
|
||||
setVisible(true);
|
||||
if (state.ok) {
|
||||
const t = setTimeout(() => setVisible(false), 4000);
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [state]);
|
||||
return (
|
||||
<form action={formAction} className={`ad-form ${className ?? ""}`} noValidate>
|
||||
{typeof children === "function" ? children(state) : children}
|
||||
<div className="ad-savebar">
|
||||
<span className="ad-savebar__msg" role="status" aria-live="polite">
|
||||
{visible && state?.message && (
|
||||
<span className={state.ok ? "ad-ok" : "ad-err"}>
|
||||
<Icon name={state.ok ? "check" : "alert"} size="sm" /> {state.message}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{extraActions}
|
||||
<SaveButton label={submitLabel} />
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** Kleiner Knopf, der eine Server-Action mit Rückfrage ausführt (z. B. Löschen). */
|
||||
export function ConfirmButton({
|
||||
action,
|
||||
confirm,
|
||||
children,
|
||||
className = "sm-btn sm-btn--ghost",
|
||||
hidden,
|
||||
title,
|
||||
}: {
|
||||
action: (fd: FormData) => Promise<void>;
|
||||
confirm: string;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
hidden?: Record<string, string>;
|
||||
title?: string;
|
||||
}) {
|
||||
const [armed, setArmed] = useState(false);
|
||||
return (
|
||||
<form action={action} style={{ display: "inline" }}>
|
||||
{hidden && Object.entries(hidden).map(([k, v]) => <input key={k} type="hidden" name={k} value={v} />)}
|
||||
{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" 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>
|
||||
);
|
||||
}
|
||||
26
src/components/admin/AdminNav.tsx
Normal file
26
src/components/admin/AdminNav.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
"use client";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Icon } from "../Icon";
|
||||
import type { NavItem } from "./nav";
|
||||
|
||||
export function AdminNav({ groups, badges }: { groups: { group: string; items: NavItem[] }[]; badges: Record<string, number> }) {
|
||||
const pathname = usePathname();
|
||||
const active = (href: string) => (href === "/admin" ? pathname === "/admin" : pathname === href || pathname.startsWith(href + "/"));
|
||||
return (
|
||||
<nav className="ad-nav" aria-label="Admin-Navigation">
|
||||
{groups.map((g) => (
|
||||
<div key={g.group} style={{ display: "contents" }}>
|
||||
{g.group && <div className="ad-nav__group">{g.group}</div>}
|
||||
{g.items.map((i) => (
|
||||
<Link key={i.href} href={i.href} aria-current={active(i.href) ? "page" : undefined}>
|
||||
<Icon name={i.icon} />
|
||||
{i.label}
|
||||
{i.badge && badges[i.badge] > 0 && <span className="ad-nav__badge">{badges[i.badge]}</span>}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
23
src/components/admin/MobileAdminNav.tsx
Normal file
23
src/components/admin/MobileAdminNav.tsx
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
"use client";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Icon } from "../Icon";
|
||||
|
||||
export function MobileAdminNav({ children }: { children: React.ReactNode }) {
|
||||
const ref = useRef<HTMLDetailsElement>(null);
|
||||
const pathname = usePathname();
|
||||
useEffect(() => {
|
||||
if (ref.current) ref.current.open = false;
|
||||
}, [pathname]);
|
||||
const close = () => ref.current && (ref.current.open = false);
|
||||
return (
|
||||
<details className="sm-mnav" ref={ref}>
|
||||
<summary className="sm-header__btn" aria-label="Menü öffnen" style={{ display: "grid" }}><Icon name="menu" /></summary>
|
||||
<div className="sm-mnav__overlay" onClick={close} />
|
||||
<div className="sm-mnav__panel">
|
||||
<button type="button" className="sm-header__btn sm-mnav__close" aria-label="Menü schließen" onClick={close}><Icon name="close" /></button>
|
||||
{children}
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
45
src/components/admin/nav.ts
Normal file
45
src/components/admin/nav.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import type { IconName } from "../Icon";
|
||||
import type { Permission } from "@/lib/permissions";
|
||||
|
||||
export type NavItem = { href: string; label: string; icon: IconName; permission: Permission; badge?: "openOrders" };
|
||||
|
||||
export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [
|
||||
{
|
||||
group: "",
|
||||
items: [{ href: "/admin", label: "Übersicht", icon: "dashboard", permission: "dashboard.view" }],
|
||||
},
|
||||
{
|
||||
group: "Verkauf",
|
||||
items: [
|
||||
{ href: "/admin/bestellungen", label: "Bestellungen", icon: "receipt", permission: "orders.view", badge: "openOrders" },
|
||||
{ href: "/admin/kunden", label: "Kunden", icon: "users", permission: "customers.view" },
|
||||
{ href: "/admin/gutscheine", label: "Gutscheine", icon: "ticket", permission: "coupons.edit" },
|
||||
{ href: "/admin/newsletter", label: "Newsletter", icon: "mail", permission: "newsletter.view" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Katalog",
|
||||
items: [
|
||||
{ href: "/admin/produkte", label: "Produkte", icon: "box", permission: "products.view" },
|
||||
{ href: "/admin/kategorien", label: "Kategorien", icon: "folder", permission: "categories.edit" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Shop gestalten",
|
||||
items: [
|
||||
{ href: "/admin/gestaltung", label: "Startseite & Texte", icon: "brush", permission: "appearance.edit" },
|
||||
{ href: "/admin/seiten", label: "Seiten", icon: "file", permission: "content.edit" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Einstellungen",
|
||||
items: [
|
||||
{ href: "/admin/einstellungen", label: "Allgemein & Kasse", icon: "settings", permission: "settings.edit" },
|
||||
{ href: "/admin/zahlung", label: "Zahlungsarten", icon: "card", permission: "payments.edit" },
|
||||
{ href: "/admin/versand", label: "Versand", icon: "truck", permission: "shipping.edit" },
|
||||
{ href: "/admin/team", label: "Team", icon: "users", permission: "users.manage" },
|
||||
{ href: "/admin/rollen", label: "Rollen & Rechte", icon: "shield", permission: "roles.manage" },
|
||||
{ href: "/admin/protokoll", label: "Protokoll", icon: "history", permission: "audit.view" },
|
||||
],
|
||||
},
|
||||
];
|
||||
63
src/components/admin/ui.tsx
Normal file
63
src/components/admin/ui.tsx
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import Link from "next/link";
|
||||
import { Icon } from "../Icon";
|
||||
|
||||
export function PageHead({ title, lead, back, children }: { title: string; lead?: string; back?: { href: string; label: string }; children?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="ad-head">
|
||||
<div>
|
||||
{back && (
|
||||
<Link className="ad-back" href={back.href}>
|
||||
<Icon name="arrowLeft" size="sm" /> {back.label}
|
||||
</Link>
|
||||
)}
|
||||
<h1>{title}</h1>
|
||||
{lead && <p>{lead}</p>}
|
||||
</div>
|
||||
{children && <div className="sm-btn-row">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Pill({ tone, children }: { tone: "neutral" | "gold" | "success" | "danger"; children: React.ReactNode }) {
|
||||
return <span className={`ad-pill${tone !== "neutral" ? ` ad-pill--${tone}` : ""}`}>{children}</span>;
|
||||
}
|
||||
|
||||
export function Card({ title, lead, action, children, foot, flush }: { title?: string; lead?: string; action?: React.ReactNode; children: React.ReactNode; foot?: React.ReactNode; flush?: boolean }) {
|
||||
return (
|
||||
<section className="ad-card">
|
||||
{title && (
|
||||
<div className="ad-card__head">
|
||||
<div>
|
||||
<h2>{title}</h2>
|
||||
{lead && <p>{lead}</p>}
|
||||
</div>
|
||||
{action}
|
||||
</div>
|
||||
)}
|
||||
{flush ? children : <div className="ad-card__body">{children}</div>}
|
||||
{foot && <div className="ad-card__foot">{foot}</div>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function Switch({ name, label, hint, defaultChecked }: { name: string; label: string; hint?: string; defaultChecked?: boolean }) {
|
||||
return (
|
||||
<label className="ad-switch">
|
||||
<span className="ad-switch__text">
|
||||
<strong>{label}</strong>
|
||||
{hint && <small>{hint}</small>}
|
||||
</span>
|
||||
<input type="checkbox" role="switch" name={name} defaultChecked={defaultChecked} />
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function Empty({ title, text, children }: { title: string; text?: string; children?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="ad-empty">
|
||||
<strong>{title}</strong>
|
||||
{text && <p style={{ margin: "0 0 var(--space-4)" }}>{text}</p>}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
75
src/components/shop/AddressForm.tsx
Normal file
75
src/components/shop/AddressForm.tsx
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
"use client";
|
||||
import { useActionState, useState } from "react";
|
||||
import { saveAddress } from "@/app/(shop)/kasse/actions";
|
||||
import type { AddressData } from "@/lib/checkout";
|
||||
import { Field, SelectField } from "../Field";
|
||||
import { Alert } from "./Blocks";
|
||||
|
||||
function AddressFields({ prefix, values, errors, countries }: { prefix: string; values?: Partial<AddressData>; errors: Record<string, string>; countries: [string, string][] }) {
|
||||
const e = (k: string) => errors[prefix + k];
|
||||
return (
|
||||
<>
|
||||
<div className="sm-form-row">
|
||||
<Field label="Vorname" name={prefix + "firstName"} autoComplete={prefix ? "billing given-name" : "shipping given-name"} defaultValue={values?.firstName} error={e("firstName")} required />
|
||||
<Field label="Nachname" name={prefix + "lastName"} autoComplete={prefix ? "billing family-name" : "shipping family-name"} defaultValue={values?.lastName} error={e("lastName")} required />
|
||||
</div>
|
||||
<Field label="Firma" optional name={prefix + "company"} autoComplete="organization" defaultValue={values?.company} />
|
||||
<Field label="Straße und Hausnummer" name={prefix + "street"} autoComplete={prefix ? "billing address-line1" : "shipping address-line1"} defaultValue={values?.street} error={e("street")} required />
|
||||
<Field label="Adresszusatz" optional name={prefix + "extra"} autoComplete="address-line2" defaultValue={values?.extra} hint="Hilft dem Paketboten, dich zu finden." />
|
||||
<div className="sm-form-row">
|
||||
<Field label="PLZ" name={prefix + "zip"} autoComplete={prefix ? "billing postal-code" : "shipping postal-code"} inputMode="numeric" defaultValue={values?.zip} error={e("zip")} required />
|
||||
<Field label="Ort" name={prefix + "city"} autoComplete={prefix ? "billing address-level2" : "shipping address-level2"} defaultValue={values?.city} error={e("city")} required />
|
||||
</div>
|
||||
<SelectField label="Land" name={prefix + "country"} autoComplete="country" defaultValue={values?.country ?? countries[0]?.[0]} error={e("country")}>
|
||||
{countries.map(([code, name]) => <option key={code} value={code}>{name}</option>)}
|
||||
</SelectField>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddressForm(props: {
|
||||
email?: string;
|
||||
phone?: string;
|
||||
address?: Partial<AddressData>;
|
||||
billing?: Partial<AddressData>;
|
||||
billingSame: boolean;
|
||||
newsletter: boolean;
|
||||
requirePhone: boolean;
|
||||
countries: [string, string][];
|
||||
emailLocked: boolean;
|
||||
}) {
|
||||
const [state, action, pending] = useActionState(saveAddress, null);
|
||||
const [same, setSame] = useState(props.billingSame);
|
||||
const errors = state?.errors ?? {};
|
||||
return (
|
||||
<form action={action} className="sm-checkout__form" noValidate>
|
||||
{state?.message && <div style={{ marginBottom: "var(--space-5)" }}><Alert kind="danger" title={state.message} /></div>}
|
||||
<h2 className="display-md" style={{ marginBottom: "var(--space-5)" }}>Kontakt</h2>
|
||||
<Field label="E-Mail-Adresse" name="email" type="email" autoComplete="email" defaultValue={props.email} readOnly={props.emailLocked} error={errors.email} hint="Hierhin schicken wir die Bestellbestätigung." required />
|
||||
<Field label="Telefon" optional={!props.requirePhone} name="phone" type="tel" autoComplete="tel" defaultValue={props.phone} error={errors.phone} hint="Nur für Rückfragen zur Lieferung." />
|
||||
<h2 className="display-md" style={{ margin: "var(--space-7) 0 var(--space-5)" }}>Lieferadresse</h2>
|
||||
<AddressFields prefix="" values={props.address} errors={errors} countries={props.countries} />
|
||||
<div className="sm-field" style={{ marginTop: "var(--space-5)" }}>
|
||||
<label className="sm-check">
|
||||
<input type="checkbox" name="billingSame" checked={same} onChange={(e) => setSame(e.target.checked)} />
|
||||
<span className="sm-check__text">Rechnungsadresse ist Lieferadresse</span>
|
||||
</label>
|
||||
<label className="sm-check">
|
||||
<input type="checkbox" name="newsletter" defaultChecked={props.newsletter} />
|
||||
<span className="sm-check__text">
|
||||
Newsletter erhalten <small>Neuheiten und Studio-Termine, etwa zweimal im Monat. Jederzeit abbestellbar.</small>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
{!same && (
|
||||
<>
|
||||
<h2 className="display-md" style={{ margin: "var(--space-7) 0 var(--space-5)" }}>Rechnungsadresse</h2>
|
||||
<AddressFields prefix="b_" values={props.billing} errors={errors} countries={props.countries} />
|
||||
</>
|
||||
)}
|
||||
<div style={{ marginTop: "var(--space-7)" }}>
|
||||
<button className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block" type="submit" disabled={pending}>Weiter zum Versand</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
16
src/components/shop/AddressLines.tsx
Normal file
16
src/components/shop/AddressLines.tsx
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import type { AddressData } from "@/lib/checkout";
|
||||
import { COUNTRIES } from "@/lib/settings";
|
||||
|
||||
export function AddressLines({ a }: { a: AddressData }) {
|
||||
return (
|
||||
<p className="body">
|
||||
{a.firstName} {a.lastName}<br />
|
||||
{a.company && <>{a.company}<br /></>}
|
||||
{a.street}<br />
|
||||
{a.extra && <>{a.extra}<br /></>}
|
||||
{a.zip} {a.city}<br />
|
||||
{COUNTRIES[a.country] ?? a.country}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
46
src/components/shop/AuthForms.tsx
Normal file
46
src/components/shop/AuthForms.tsx
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
"use client";
|
||||
import { useActionState } from "react";
|
||||
import { login, register } from "@/lib/auth-actions";
|
||||
import { Field } from "../Field";
|
||||
import { Alert } from "./Blocks";
|
||||
|
||||
export function LoginForm({ next, area }: { next?: string; area?: "admin" }) {
|
||||
const [state, action, pending] = useActionState(login, null);
|
||||
return (
|
||||
<form action={action} noValidate>
|
||||
{state?.error && <div style={{ marginBottom: "var(--space-4)" }}><Alert kind="danger" title={state.error} /></div>}
|
||||
<input type="hidden" name="weiter" value={next ?? ""} />
|
||||
{area && <input type="hidden" name="area" value={area} />}
|
||||
<Field label="E-Mail-Adresse" name="email" type="email" autoComplete="email" required autoFocus />
|
||||
<Field label="Passwort" name="password" type="password" autoComplete="current-password" required />
|
||||
<div style={{ marginTop: "var(--space-6)" }}>
|
||||
<button className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block" type="submit" disabled={pending}>Anmelden</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function RegisterForm({ next, email }: { next?: string; email?: string }) {
|
||||
const [state, action, pending] = useActionState(register, null);
|
||||
const e = state?.errors ?? {};
|
||||
return (
|
||||
<form action={action} noValidate>
|
||||
<input type="hidden" name="weiter" value={next ?? ""} />
|
||||
<div className="sm-form-row">
|
||||
<Field label="Vorname" name="firstName" autoComplete="given-name" error={e.firstName} required />
|
||||
<Field label="Nachname" name="lastName" autoComplete="family-name" error={e.lastName} required />
|
||||
</div>
|
||||
<Field label="E-Mail-Adresse" name="email" type="email" autoComplete="email" defaultValue={email} error={e.email} required />
|
||||
<Field label="Passwort" name="password" type="password" autoComplete="new-password" error={e.password} hint="Mindestens 8 Zeichen." required />
|
||||
<div className="sm-field" style={{ marginTop: "var(--space-4)" }}>
|
||||
<label className="sm-check">
|
||||
<input type="checkbox" name="newsletter" />
|
||||
<span className="sm-check__text">Newsletter erhalten <small>Jederzeit abbestellbar.</small></span>
|
||||
</label>
|
||||
</div>
|
||||
<div style={{ marginTop: "var(--space-6)" }}>
|
||||
<button className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block" type="submit" disabled={pending}>Konto erstellen</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
81
src/components/shop/Blocks.tsx
Normal file
81
src/components/shop/Blocks.tsx
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import type { TrustItem } from "@/lib/settings";
|
||||
import { Icon } from "../Icon";
|
||||
|
||||
export function SectionHeading({ eyebrow, title, left }: { eyebrow?: string; title: string; left?: boolean }) {
|
||||
return (
|
||||
<div className={`sm-heading${left ? " sm-heading--left" : ""}`}>
|
||||
{eyebrow && <span className="sm-heading__eyebrow eyebrow">{eyebrow}</span>}
|
||||
<h2 className="sm-heading__title display-md">{title}</h2>
|
||||
<span className="sm-heading__rule" aria-hidden="true" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TrustBar({ items }: { items: TrustItem[] }) {
|
||||
if (!items.length) return null;
|
||||
return (
|
||||
<section className="sm-trust" aria-label="Unsere Versprechen">
|
||||
{items.map((t, i) => (
|
||||
<div className="sm-trust__item" key={i}>
|
||||
<Icon name={t.icon} />
|
||||
<div>
|
||||
<p className="sm-trust__title">{t.title}</p>
|
||||
<p className="sm-trust__text">{t.text}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function Alert({ kind, title, children }: { kind?: "success" | "danger"; title: string; children?: React.ReactNode }) {
|
||||
return (
|
||||
<div className={`sm-alert${kind ? ` sm-alert--${kind}` : ""}`} role={kind === "danger" ? "alert" : "status"}>
|
||||
<Icon name={kind === "success" ? "check" : kind === "danger" ? "alert" : "info"} />
|
||||
<div>
|
||||
<span className="sm-alert__title">{title}</span>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Einfacher Text-Renderer: Absätze, Überschriften (## …), Listen (- …), Links [Text](url). */
|
||||
export function RichText({ text }: { text: string }) {
|
||||
const blocks = text.replace(/\r/g, "").split(/\n{2,}/);
|
||||
const inline = (s: string) => {
|
||||
const parts: React.ReactNode[] = [];
|
||||
const re = /\[([^\]]+)\]\(([^)\s]+)\)|\*\*([^*]+)\*\*/g;
|
||||
let last = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
let i = 0;
|
||||
while ((m = re.exec(s))) {
|
||||
parts.push(s.slice(last, m.index));
|
||||
if (m[1]) {
|
||||
const href = /^(https?:|mailto:|\/)/.test(m[2]) ? m[2] : "#";
|
||||
parts.push(<a key={i++} href={href}>{m[1]}</a>);
|
||||
} else parts.push(<strong key={i++}>{m[3]}</strong>);
|
||||
last = m.index + m[0].length;
|
||||
}
|
||||
parts.push(s.slice(last));
|
||||
return parts;
|
||||
};
|
||||
return (
|
||||
<div className="sm-prose">
|
||||
{blocks.map((b, i) => {
|
||||
if (b.startsWith("## ")) return <h2 key={i}>{inline(b.slice(3))}</h2>;
|
||||
if (b.startsWith("### ")) return <h3 key={i}>{inline(b.slice(4))}</h3>;
|
||||
const lines = b.split("\n");
|
||||
if (lines.every((l) => l.startsWith("- ")))
|
||||
return <ul key={i}>{lines.map((l, j) => <li key={j}>{inline(l.slice(2))}</li>)}</ul>;
|
||||
return (
|
||||
<p key={i}>
|
||||
{lines.map((l, j) => (
|
||||
<span key={j}>{j > 0 && <br />}{inline(l)}</span>
|
||||
))}
|
||||
</p>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
128
src/components/shop/BuyBox.tsx
Normal file
128
src/components/shop/BuyBox.tsx
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
"use client";
|
||||
import { useState } from "react";
|
||||
import { useFormStatus } from "react-dom";
|
||||
import { addToCart } from "@/app/(shop)/actions";
|
||||
import { Icon } from "../Icon";
|
||||
|
||||
type Variant = { id: string; name: string; price: number; stock: number };
|
||||
|
||||
const fmt = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
|
||||
function Submit({ disabled }: { disabled: boolean }) {
|
||||
const { pending } = useFormStatus();
|
||||
return (
|
||||
<button className="sm-btn sm-btn--primary sm-btn--lg" type="submit" disabled={disabled || pending}>
|
||||
{pending ? "Wird hinzugefügt …" : "In den Warenkorb"}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function BuyBox(props: {
|
||||
productId: string;
|
||||
price: number;
|
||||
compareAt: number | null;
|
||||
stock: number;
|
||||
trackStock: boolean;
|
||||
variants: Variant[];
|
||||
variantLabel: string;
|
||||
missingVariant: boolean;
|
||||
}) {
|
||||
const firstAvailable = props.variants.find((v) => !props.trackStock || v.stock > 0);
|
||||
const [variantId, setVariantId] = useState<string | null>(props.variants.length === 1 ? (firstAvailable?.id ?? null) : null);
|
||||
const [qty, setQty] = useState(1);
|
||||
const variant = props.variants.find((v) => v.id === variantId) ?? null;
|
||||
const price = variant?.price ?? props.price;
|
||||
const stock = props.trackStock ? (variant ? variant.stock : props.variants.length ? Infinity : props.stock) : 99;
|
||||
const soldOut = props.variants.length ? props.trackStock && props.variants.every((v) => v.stock <= 0) : stock <= 0;
|
||||
const max = Math.min(Number.isFinite(stock) ? stock : 99, 99);
|
||||
const needsVariant = props.variants.length > 0 && !variant;
|
||||
const compare = props.compareAt && props.compareAt > price ? props.compareAt : null;
|
||||
|
||||
return (
|
||||
<form action={addToCart}>
|
||||
<input type="hidden" name="productId" value={props.productId} />
|
||||
<input type="hidden" name="variantId" value={variantId ?? ""} />
|
||||
<div className="sm-price sm-price--lg">
|
||||
{fmt.format(price / 100)}
|
||||
{compare && (
|
||||
<>
|
||||
<s className="sm-price__old">{fmt.format(compare / 100)}</s>
|
||||
<span className="sm-price__save">Du sparst {fmt.format((compare - price) / 100)}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<span className="sm-price__note">inkl. MwSt., zzgl. <a href="/seite/versand">Versand</a></span>
|
||||
|
||||
{props.variants.length > 0 && (
|
||||
<div className="sm-pdp__options">
|
||||
<div className="sm-pdp__option-label">
|
||||
{props.variantLabel} {variant && <span>{variant.name}</span>}
|
||||
</div>
|
||||
<div className="sm-pdp__sizes" role="radiogroup" aria-label={`${props.variantLabel} wählen`}>
|
||||
{props.variants.map((v) => {
|
||||
const disabled = props.trackStock && v.stock <= 0;
|
||||
return (
|
||||
<span key={v.id}>
|
||||
<input
|
||||
type="radio"
|
||||
id={`v-${v.id}`}
|
||||
name="_variant"
|
||||
checked={variantId === v.id}
|
||||
disabled={disabled}
|
||||
onChange={() => {
|
||||
setVariantId(v.id);
|
||||
setQty(1);
|
||||
}}
|
||||
/>
|
||||
<label className="sm-pdp__size" htmlFor={`v-${v.id}`}>{v.name}</label>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{props.missingVariant && needsVariant && (
|
||||
<span className="sm-field__error" role="alert" style={{ marginTop: "var(--space-2)" }}>
|
||||
<Icon name="alert" /> Bitte wähle zuerst eine Variante.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="sm-pdp__cta">
|
||||
<div className="sm-qty" role="group" aria-label="Menge">
|
||||
<button className="sm-qty__btn" type="button" aria-label="Menge verringern" disabled={qty <= 1} onClick={() => setQty((q) => Math.max(1, q - 1))}>
|
||||
<Icon name="minus" size="sm" />
|
||||
</button>
|
||||
<input
|
||||
className="sm-qty__value"
|
||||
type="number"
|
||||
name="quantity"
|
||||
value={qty}
|
||||
min={1}
|
||||
max={max}
|
||||
aria-label="Menge"
|
||||
onChange={(e) => setQty(Math.max(1, Math.min(max, Number(e.target.value) || 1)))}
|
||||
/>
|
||||
<button className="sm-qty__btn" type="button" aria-label="Menge erhöhen" disabled={qty >= max} onClick={() => setQty((q) => Math.min(max, q + 1))}>
|
||||
<Icon name="plus" size="sm" />
|
||||
</button>
|
||||
</div>
|
||||
<Submit disabled={soldOut || needsVariant} />
|
||||
</div>
|
||||
{needsVariant && !soldOut && (
|
||||
<p className="caption" style={{ color: "var(--ink-muted)", marginTop: "var(--space-2)" }}>Wähle oben eine Variante, dann kannst du bestellen.</p>
|
||||
)}
|
||||
<ul className="sm-pdp__facts">
|
||||
<li>
|
||||
{soldOut ? (
|
||||
<span className="sm-badge sm-badge--soldout">Ausverkauft</span>
|
||||
) : max <= 3 && props.trackStock && !needsVariant ? (
|
||||
<span className="sm-badge sm-badge--low">Nur noch {max} Stück</span>
|
||||
) : (
|
||||
<span className="sm-badge sm-badge--stock"><span className="sm-dot" aria-hidden="true" />Auf Lager</span>
|
||||
)}
|
||||
{!soldOut && " Lieferung in 2–4 Werktagen"}
|
||||
</li>
|
||||
</ul>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
25
src/components/shop/CheckoutSteps.tsx
Normal file
25
src/components/shop/CheckoutSteps.tsx
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
"use client";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
const STEPS = [
|
||||
{ href: "/kasse/adresse", label: "Adresse" },
|
||||
{ href: "/kasse/versand", label: "Versand" },
|
||||
{ href: "/kasse/zahlung", label: "Zahlung" },
|
||||
{ href: "/kasse/pruefen", label: "Prüfen" },
|
||||
];
|
||||
|
||||
export function CheckoutSteps() {
|
||||
const pathname = usePathname();
|
||||
const current = STEPS.findIndex((s) => pathname.startsWith(s.href));
|
||||
if (current < 0) return null;
|
||||
return (
|
||||
<ol className="sm-steps sm-checkout__steps" aria-label="Checkout-Fortschritt">
|
||||
{STEPS.map((s, i) => (
|
||||
<li key={s.href} className={`sm-steps__item${i < current ? " is-done" : ""}${i === current ? " is-current" : ""}`} aria-current={i === current ? "step" : undefined}>
|
||||
{i < current ? <Link href={s.href}>{s.label}</Link> : <span>{s.label}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
44
src/components/shop/ChoiceForm.tsx
Normal file
44
src/components/shop/ChoiceForm.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"use client";
|
||||
import { useActionState } from "react";
|
||||
import type { FormState } from "@/app/(shop)/kasse/actions";
|
||||
import { Alert } from "./Blocks";
|
||||
|
||||
export type Choice = { id: string; title: string; price: string; text?: string };
|
||||
|
||||
export function ChoiceForm({
|
||||
action,
|
||||
name,
|
||||
choices,
|
||||
selected,
|
||||
submitLabel,
|
||||
legend,
|
||||
}: {
|
||||
action: (prev: FormState, fd: FormData) => Promise<FormState>;
|
||||
name: string;
|
||||
choices: Choice[];
|
||||
selected?: string;
|
||||
submitLabel: string;
|
||||
legend: string;
|
||||
}) {
|
||||
const [state, formAction, pending] = useActionState(action, null);
|
||||
return (
|
||||
<form action={formAction} className="sm-checkout__form">
|
||||
<fieldset style={{ border: 0, padding: 0, margin: 0 }}>
|
||||
<legend className="display-md" style={{ marginBottom: "var(--space-5)" }}>{legend}</legend>
|
||||
{state?.message && <div style={{ marginBottom: "var(--space-4)" }}><Alert kind="danger" title={state.message} /></div>}
|
||||
{choices.map((c, i) => (
|
||||
<label className="sm-option" key={c.id}>
|
||||
<input type="radio" name={name} value={c.id} defaultChecked={selected ? selected === c.id : i === 0} />
|
||||
<span className="sm-option__body">
|
||||
<span className="sm-option__title"><span>{c.title}</span><span>{c.price}</span></span>
|
||||
{c.text && <span className="sm-option__text">{c.text}</span>}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<div style={{ marginTop: "var(--space-7)" }}>
|
||||
<button className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block" type="submit" disabled={pending || choices.length === 0}>{submitLabel}</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
17
src/components/shop/CouponForm.tsx
Normal file
17
src/components/shop/CouponForm.tsx
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
"use client";
|
||||
import { useActionState } from "react";
|
||||
import { applyCoupon } from "@/app/(shop)/actions";
|
||||
|
||||
export function CouponForm() {
|
||||
const [state, action, pending] = useActionState(applyCoupon, null);
|
||||
return (
|
||||
<form action={action} style={{ maxWidth: 360, flex: 1 }} aria-label="Gutschein">
|
||||
<div className="sm-input-group">
|
||||
<label className="sm-visually-hidden" htmlFor="gs">Gutscheincode</label>
|
||||
<input className="sm-input" id="gs" name="code" placeholder="Gutscheincode" autoCapitalize="characters" />
|
||||
<button className="sm-btn sm-btn--secondary" type="submit" disabled={pending}>Einlösen</button>
|
||||
</div>
|
||||
{state?.error && <span className="sm-field__error" role="alert">{state.error}</span>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
86
src/components/shop/Footer.tsx
Normal file
86
src/components/shop/Footer.tsx
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import Link from "next/link";
|
||||
import { db } from "@/lib/db";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
import { NewsletterForm } from "./NewsletterForm";
|
||||
|
||||
export async function Footer() {
|
||||
const [settings, categories, pages, payments] = await Promise.all([
|
||||
getSettings(),
|
||||
db.category.findMany({ where: { active: true }, orderBy: { sort: "asc" }, take: 5 }),
|
||||
db.page.findMany({ where: { published: true, NOT: { showInFooter: "" } }, orderBy: { sort: "asc" } }),
|
||||
db.paymentMethod.findMany({ where: { enabled: true }, orderBy: { sort: "asc" } }),
|
||||
]);
|
||||
const s = settings.general;
|
||||
const a = settings.appearance;
|
||||
const service = pages.filter((p) => p.showInFooter === "service");
|
||||
const company = pages.filter((p) => p.showInFooter === "company");
|
||||
const legal = pages.filter((p) => p.showInFooter === "legal");
|
||||
return (
|
||||
<footer className="sm-footer" data-theme="dark">
|
||||
<div className="sm-container">
|
||||
<div className="sm-footer__grid">
|
||||
<div className="sm-footer__brand">
|
||||
<Link className="sm-footer__logo" href="/">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src="/brand/logo-gold.png" alt={`${s.shopName} Pilates`} width={962} height={783} />
|
||||
</Link>
|
||||
<p className="sm-footer__claim">{a.footerClaim}</p>
|
||||
{a.showNewsletter && (
|
||||
<>
|
||||
<p className="sm-footer__title" style={{ marginTop: "var(--space-5)" }}>
|
||||
Newsletter
|
||||
</p>
|
||||
<NewsletterForm />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<p className="sm-footer__title">Shop</p>
|
||||
<ul className="sm-footer__links">
|
||||
<li><Link href="/shop">Alle Produkte</Link></li>
|
||||
{categories.map((c) => (
|
||||
<li key={c.id}><Link href={`/kategorie/${c.slug}`}>{c.name}</Link></li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<p className="sm-footer__title">Service</p>
|
||||
<ul className="sm-footer__links">
|
||||
{service.map((p) => (
|
||||
<li key={p.id}><Link href={`/seite/${p.slug}`}>{p.title}</Link></li>
|
||||
))}
|
||||
<li><Link href="/konto">Mein Konto</Link></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<p className="sm-footer__title">{s.shopName}</p>
|
||||
<ul className="sm-footer__links">
|
||||
{company.map((p) => (
|
||||
<li key={p.id}><Link href={`/seite/${p.slug}`}>{p.title}</Link></li>
|
||||
))}
|
||||
{s.email && <li><a href={`mailto:${s.email}`}>{s.email}</a></li>}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div className="sm-footer__bottom">
|
||||
<div>
|
||||
© {new Date().getFullYear()} {s.shopName}
|
||||
{legal.map((p) => (
|
||||
<span key={p.id}>
|
||||
{" · "}
|
||||
<Link href={`/seite/${p.slug}`} style={{ color: "inherit" }}>{p.title}</Link>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{payments.length > 0 && (
|
||||
<div className="sm-footer__pay" aria-label="Zahlungsarten">
|
||||
{payments.map((p) => (
|
||||
<span key={p.id}>{p.name.split(",")[0]}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
37
src/components/shop/Gallery.tsx
Normal file
37
src/components/shop/Gallery.tsx
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
"use client";
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import { useState } from "react";
|
||||
|
||||
export function Gallery({ images, alt }: { images: string[]; alt: string }) {
|
||||
const [active, setActive] = useState(0);
|
||||
if (images.length === 0) {
|
||||
return (
|
||||
<div className="sm-pdp__gallery">
|
||||
<div className="sm-ph" role="img" aria-label={alt}><span>Produktfoto</span></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="sm-pdp__gallery">
|
||||
<div className="sm-pdp__main">
|
||||
<img src={images[active]} alt={alt} />
|
||||
</div>
|
||||
{images.length > 1 && (
|
||||
<div className="sm-pdp__thumbs">
|
||||
{images.map((src, i) => (
|
||||
<button
|
||||
key={src + i}
|
||||
className={`sm-pdp__thumb${i === active ? " is-active" : ""}`}
|
||||
type="button"
|
||||
aria-label={`Bild ${i + 1} anzeigen`}
|
||||
aria-pressed={i === active}
|
||||
onClick={() => setActive(i)}
|
||||
>
|
||||
<img src={src} alt="" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
57
src/components/shop/Header.tsx
Normal file
57
src/components/shop/Header.tsx
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import Link from "next/link";
|
||||
import { getCartCount } from "@/lib/cart";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
import { Icon } from "../Icon";
|
||||
import { MobileNav, NavLinks } from "./NavLinks";
|
||||
|
||||
export async function Header() {
|
||||
const [settings, count, user] = await Promise.all([getSettings(), getCartCount(), getCurrentUser()]);
|
||||
const a = settings.appearance;
|
||||
return (
|
||||
<header className="sm-header" data-theme={a.darkHeader ? "dark" : undefined}>
|
||||
{(a.promoText || a.promoLinkLabel) && (
|
||||
<div className="sm-header__promo">
|
||||
{a.promoText}
|
||||
{a.promoText && a.promoLinkLabel && " · "}
|
||||
{a.promoLinkLabel && <Link href={a.promoLinkHref || "#"}>{a.promoLinkLabel}</Link>}
|
||||
</div>
|
||||
)}
|
||||
<div className="sm-container sm-header__bar">
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "var(--space-2)" }}>
|
||||
<MobileNav
|
||||
links={a.navigation}
|
||||
extra={[
|
||||
{ label: user ? "Mein Konto" : "Anmelden", href: "/konto" },
|
||||
...(user?.role ? [{ label: "Admin", href: "/admin" }] : []),
|
||||
]}
|
||||
/>
|
||||
<Link className="sm-header__logo" href="/" aria-label={`${settings.general.shopName} – Startseite`}>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img className="sm-logo sm-logo--ink" src="/brand/bildmarke-ink.png" alt="" />
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img className="sm-logo sm-logo--gold" src="/brand/bildmarke-gold.png" alt="" />
|
||||
<span>{settings.general.shopName}.</span>
|
||||
</Link>
|
||||
</div>
|
||||
<NavLinks links={a.navigation} />
|
||||
<div className="sm-header__actions">
|
||||
<Link className="sm-header__btn" href="/suche" aria-label="Suchen">
|
||||
<Icon name="search" />
|
||||
</Link>
|
||||
<Link className="sm-header__btn" href="/konto" aria-label={user ? "Mein Konto" : "Anmelden"}>
|
||||
<Icon name="user" />
|
||||
</Link>
|
||||
<Link className="sm-header__btn" href="/warenkorb" aria-label={`Warenkorb, ${count} Artikel`}>
|
||||
<Icon name="cart" />
|
||||
{count > 0 && (
|
||||
<span className="sm-header__count" aria-hidden="true">
|
||||
{count}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
51
src/components/shop/NavLinks.tsx
Normal file
51
src/components/shop/NavLinks.tsx
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"use client";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useRef } from "react";
|
||||
import type { NavLink } from "@/lib/settings";
|
||||
import { Icon } from "../Icon";
|
||||
|
||||
function isActive(pathname: string, href: string) {
|
||||
if (href === "/") return pathname === "/";
|
||||
return pathname === href || pathname.startsWith(href + "/");
|
||||
}
|
||||
|
||||
export function NavLinks({ links }: { links: NavLink[] }) {
|
||||
const pathname = usePathname();
|
||||
return (
|
||||
<nav className="sm-header__nav" aria-label="Hauptnavigation">
|
||||
{links.map((l) => (
|
||||
<Link key={l.href + l.label} href={l.href} aria-current={isActive(pathname, l.href) ? "page" : undefined}>
|
||||
{l.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
export function MobileNav({ links, extra }: { links: NavLink[]; extra: NavLink[] }) {
|
||||
const pathname = usePathname();
|
||||
const ref = useRef<HTMLDetailsElement>(null);
|
||||
useEffect(() => {
|
||||
if (ref.current) ref.current.open = false;
|
||||
}, [pathname]);
|
||||
const close = () => ref.current && (ref.current.open = false);
|
||||
return (
|
||||
<details className="sm-mnav" ref={ref}>
|
||||
<summary className="sm-header__btn sm-header__btn--menu" aria-label="Menü öffnen">
|
||||
<Icon name="menu" />
|
||||
</summary>
|
||||
<div className="sm-mnav__overlay" onClick={close} />
|
||||
<nav className="sm-mnav__panel" aria-label="Menü">
|
||||
<button type="button" className="sm-header__btn sm-mnav__close" aria-label="Menü schließen" onClick={close}>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
{[...links, ...extra].map((l) => (
|
||||
<Link key={l.href + l.label} href={l.href} aria-current={isActive(pathname, l.href) ? "page" : undefined}>
|
||||
{l.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
16
src/components/shop/NewsletterForm.tsx
Normal file
16
src/components/shop/NewsletterForm.tsx
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
"use client";
|
||||
import { useActionState } from "react";
|
||||
import { subscribeNewsletter } from "@/app/(shop)/actions";
|
||||
|
||||
export function NewsletterForm() {
|
||||
const [state, action, pending] = useActionState(subscribeNewsletter, null);
|
||||
if (state?.ok) return <p className="sm-footer__claim">Danke. Du bist angemeldet.</p>;
|
||||
return (
|
||||
<form className="sm-footer__news sm-input-group" aria-label="Newsletter abonnieren" action={action}>
|
||||
<label className="sm-visually-hidden" htmlFor="nl">E-Mail-Adresse</label>
|
||||
<input className="sm-input" id="nl" name="email" type="email" placeholder="E-Mail-Adresse" autoComplete="email" required />
|
||||
<button className="sm-btn sm-btn--gold" type="submit" disabled={pending}>Anmelden</button>
|
||||
{state?.error && <span className="sm-field__error" role="alert">{state.error}</span>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
54
src/components/shop/OrderSummary.tsx
Normal file
54
src/components/shop/OrderSummary.tsx
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import type { Totals } from "@/lib/pricing";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
|
||||
export function OrderSummary({
|
||||
totals,
|
||||
shippingLabel,
|
||||
paymentLabel,
|
||||
children,
|
||||
lines,
|
||||
}: {
|
||||
totals: Totals;
|
||||
shippingLabel?: string;
|
||||
paymentLabel?: string;
|
||||
children?: React.ReactNode;
|
||||
lines?: { key: string; name: string; quantity: number; total: number; variantName: string }[];
|
||||
}) {
|
||||
return (
|
||||
<aside className="sm-summary" aria-labelledby="sum">
|
||||
<h2 className="sm-summary__title display-sm" id="sum">Zusammenfassung</h2>
|
||||
{lines && (
|
||||
<div className="sm-summary__lines">
|
||||
{lines.map((l) => (
|
||||
<div className="sm-summary__line" key={l.key}>
|
||||
<span>{l.quantity} × {l.name}{l.variantName ? ` – ${l.variantName}` : ""}</span>
|
||||
<span>{formatPrice(l.total)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="sm-summary__row"><span>Zwischensumme</span><span>{formatPrice(totals.subtotal)}</span></div>
|
||||
{totals.coupon && totals.discount > 0 && (
|
||||
<div className="sm-summary__row sm-summary__row--muted">
|
||||
<span>Gutschein {totals.coupon.code}</span><span>−{formatPrice(totals.discount)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="sm-summary__row sm-summary__row--muted">
|
||||
<span>Versand{shippingLabel ? ` (${shippingLabel})` : ""}</span>
|
||||
<span>{totals.shippingCost === 0 ? "Kostenlos" : formatPrice(totals.shippingCost)}</span>
|
||||
</div>
|
||||
{totals.paymentFee > 0 && (
|
||||
<div className="sm-summary__row sm-summary__row--muted">
|
||||
<span>Gebühr {paymentLabel ?? "Zahlungsart"}</span><span>{formatPrice(totals.paymentFee)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="sm-summary__row sm-summary__row--total">
|
||||
<span>Gesamt</span><span className="sm-price sm-price--lg">{formatPrice(totals.total)}</span>
|
||||
</div>
|
||||
<p className="sm-summary__fine" style={{ textAlign: "left", marginTop: "var(--space-1)" }}>
|
||||
inkl. {formatPrice(totals.taxAmount)} MwSt.
|
||||
</p>
|
||||
{children}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
33
src/components/shop/PlaceOrderForm.tsx
Normal file
33
src/components/shop/PlaceOrderForm.tsx
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
"use client";
|
||||
import { useActionState } from "react";
|
||||
import { placeOrder } from "@/app/(shop)/kasse/actions";
|
||||
import { Icon } from "../Icon";
|
||||
import { TextareaField } from "../Field";
|
||||
import { Alert } from "./Blocks";
|
||||
|
||||
export function PlaceOrderForm({ requireTerms, total, online }: { requireTerms: boolean; total: string; online: boolean }) {
|
||||
const [state, action, pending] = useActionState(placeOrder, null);
|
||||
return (
|
||||
<form action={action}>
|
||||
{state?.message && <div style={{ marginBottom: "var(--space-4)" }}><Alert kind="danger" title={state.message} /></div>}
|
||||
<TextareaField label="Anmerkung zur Bestellung" optional name="note" rows={3} maxLength={1000} />
|
||||
{requireTerms && (
|
||||
<div className={`sm-field${state?.errors?.terms ? " is-invalid" : ""}`} style={{ marginTop: "var(--space-4)" }}>
|
||||
<label className="sm-check">
|
||||
<input type="checkbox" name="terms" required />
|
||||
<span className="sm-check__text">
|
||||
Ich habe die <a href="/seite/agb" target="_blank">AGB</a> und die <a href="/seite/widerruf" target="_blank">Widerrufsbelehrung</a> gelesen und stimme zu.
|
||||
</span>
|
||||
</label>
|
||||
{state?.errors?.terms && <span className="sm-field__error"><Icon name="alert" /> {state.errors.terms}</span>}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ marginTop: "var(--space-6)" }}>
|
||||
<button className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block" type="submit" disabled={pending}>
|
||||
{pending ? "Einen Moment …" : `Zahlungspflichtig bestellen · ${total}`}
|
||||
</button>
|
||||
{online && <p className="caption" style={{ color: "var(--ink-muted)", marginTop: "var(--space-2)", textAlign: "center" }}>Du wirst zur sicheren Zahlungsseite weitergeleitet.</p>}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
76
src/components/shop/ProductCard.tsx
Normal file
76
src/components/shop/ProductCard.tsx
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import Link from "next/link";
|
||||
import type { Product, ProductVariant } from "@prisma/client";
|
||||
import { formatPrice } from "@/lib/money";
|
||||
import { addToCart } from "@/app/(shop)/actions";
|
||||
import { ProductImage } from "./ProductImage";
|
||||
|
||||
type P = Product & { variants: ProductVariant[] };
|
||||
|
||||
export function stockOf(p: P) {
|
||||
if (!p.trackStock) return 99;
|
||||
return p.variants.length ? p.variants.reduce((s, v) => s + v.stock, 0) : p.stock;
|
||||
}
|
||||
|
||||
export function ProductBadge({ product }: { product: P }) {
|
||||
if (stockOf(product) <= 0) return <span className="sm-badge sm-badge--soldout">Ausverkauft</span>;
|
||||
if (product.compareAtPrice && product.compareAtPrice > product.price) {
|
||||
const pct = Math.round((1 - product.price / product.compareAtPrice) * 100);
|
||||
return <span className="sm-badge sm-badge--sale">–{pct} %</span>;
|
||||
}
|
||||
if (product.badge === "new") return <span className="sm-badge sm-badge--new">Neu</span>;
|
||||
if (product.badge === "best") return <span className="sm-badge sm-badge--best">Bestseller</span>;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function PriceTag({ price, compareAt, large }: { price: number; compareAt?: number | null; large?: boolean }) {
|
||||
return (
|
||||
<div className={`sm-price${large ? " sm-price--lg" : ""}`}>
|
||||
{formatPrice(price)}
|
||||
{compareAt && compareAt > price && <s className="sm-price__old">{formatPrice(compareAt)}</s>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProductCard({ product }: { product: P }) {
|
||||
const soldOut = stockOf(product) <= 0;
|
||||
const minPrice = product.variants.length
|
||||
? Math.min(...product.variants.map((v) => v.price ?? product.price))
|
||||
: product.price;
|
||||
const hasVariants = product.variants.length > 0;
|
||||
return (
|
||||
<article className="sm-card">
|
||||
<div className="sm-card__media">
|
||||
<div className="sm-card__badges">
|
||||
<ProductBadge product={product} />
|
||||
</div>
|
||||
<ProductImage src={product.images[0]} alt={product.name} />
|
||||
{!soldOut &&
|
||||
(hasVariants ? (
|
||||
<Link className="sm-btn sm-btn--primary sm-btn--sm sm-btn--block sm-card__quick" href={`/produkt/${product.slug}`}>
|
||||
Variante wählen
|
||||
</Link>
|
||||
) : (
|
||||
<form action={addToCart} className="sm-card__quick" style={{ padding: 0, border: 0 }}>
|
||||
<input type="hidden" name="productId" value={product.id} />
|
||||
<button className="sm-btn sm-btn--primary sm-btn--sm sm-btn--block" type="submit" style={{ width: "100%" }}>
|
||||
In den Warenkorb
|
||||
</button>
|
||||
</form>
|
||||
))}
|
||||
</div>
|
||||
<div className="sm-card__body">
|
||||
<h3 className="sm-card__title">
|
||||
<Link href={`/produkt/${product.slug}`}>{product.name}</Link>
|
||||
</h3>
|
||||
{product.subtitle && <div className="sm-card__variant">{product.subtitle}</div>}
|
||||
<div className="sm-price">
|
||||
{hasVariants && product.variants.some((v) => (v.price ?? product.price) !== minPrice) ? "ab " : ""}
|
||||
{formatPrice(minPrice)}
|
||||
{product.compareAtPrice && product.compareAtPrice > product.price && (
|
||||
<s className="sm-price__old">{formatPrice(product.compareAtPrice)}</s>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
11
src/components/shop/ProductImage.tsx
Normal file
11
src/components/shop/ProductImage.tsx
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
/* eslint-disable @next/next/no-img-element */
|
||||
export function ProductImage({ src, alt, label = "Produktfoto" }: { src?: string; alt: string; label?: string }) {
|
||||
if (!src) {
|
||||
return (
|
||||
<div className="sm-ph" role="img" aria-label={alt}>
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <img src={src} alt={alt} loading="lazy" />;
|
||||
}
|
||||
73
src/components/shop/ProductList.tsx
Normal file
73
src/components/shop/ProductList.tsx
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import Link from "next/link";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { db } from "@/lib/db";
|
||||
import { ProductCard } from "./ProductCard";
|
||||
|
||||
const SORTS: Record<string, { label: string; orderBy: Prisma.ProductOrderByWithRelationInput[] }> = {
|
||||
empfohlen: { label: "Empfohlen", orderBy: [{ featured: "desc" }, { sort: "asc" }, { createdAt: "desc" }] },
|
||||
neu: { label: "Neueste", orderBy: [{ createdAt: "desc" }] },
|
||||
"preis-auf": { label: "Preis aufsteigend", orderBy: [{ price: "asc" }] },
|
||||
"preis-ab": { label: "Preis absteigend", orderBy: [{ price: "desc" }] },
|
||||
};
|
||||
|
||||
export async function ProductList({
|
||||
basePath,
|
||||
where,
|
||||
sort,
|
||||
showCategoryChips,
|
||||
activeCategory,
|
||||
}: {
|
||||
basePath: string;
|
||||
where: Prisma.ProductWhereInput;
|
||||
sort?: string;
|
||||
showCategoryChips?: boolean;
|
||||
activeCategory?: string;
|
||||
}) {
|
||||
const s = SORTS[sort ?? ""] ? sort! : "empfohlen";
|
||||
const [products, categories] = await Promise.all([
|
||||
db.product.findMany({ where: { active: true, ...where }, include: { variants: true }, orderBy: SORTS[s].orderBy }),
|
||||
showCategoryChips ? db.category.findMany({ where: { active: true }, orderBy: { sort: "asc" } }) : [],
|
||||
]);
|
||||
return (
|
||||
<>
|
||||
<div className="sm-shop-toolbar">
|
||||
{showCategoryChips ? (
|
||||
<nav className="sm-chips" aria-label="Kategorien">
|
||||
<Link className={`sm-chip${!activeCategory ? " is-active" : ""}`} href="/shop">Alle</Link>
|
||||
{categories.map((c) => (
|
||||
<Link key={c.id} className={`sm-chip${activeCategory === c.slug ? " is-active" : ""}`} href={`/kategorie/${c.slug}`}>
|
||||
{c.name}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
) : (
|
||||
<p className="body-sm" style={{ margin: 0, color: "var(--ink-muted)" }}>{products.length} Produkte</p>
|
||||
)}
|
||||
<form method="get" action={basePath} style={{ display: "flex", gap: "var(--space-2)", alignItems: "center" }}>
|
||||
<label className="label" htmlFor="sort">Sortieren</label>
|
||||
<span className="sm-select-wrap">
|
||||
<select className="sm-select" id="sort" name="sort" defaultValue={s} style={{ minHeight: "var(--control-height-sm)" }}>
|
||||
{Object.entries(SORTS).map(([k, v]) => (
|
||||
<option key={k} value={k}>{v.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</span>
|
||||
<button className="sm-btn sm-btn--secondary sm-btn--sm" type="submit">Anwenden</button>
|
||||
</form>
|
||||
</div>
|
||||
{products.length === 0 ? (
|
||||
<div className="sm-empty">
|
||||
<h2 className="display-sm">Hier ist noch nichts.</h2>
|
||||
<p>Schau dich gern im ganzen Shop um.</p>
|
||||
<Link className="sm-btn sm-btn--secondary" href="/shop">Zum Shop</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="sm-grid">
|
||||
{products.map((p) => (
|
||||
<ProductCard key={p.id} product={p} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
4
src/lib/action-result.ts
Normal file
4
src/lib/action-result.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export type ActionResult = { ok: boolean; message?: string; errors?: Record<string, string>; at?: number } | null;
|
||||
|
||||
export const ok = (message = "Gespeichert."): ActionResult => ({ ok: true, message, at: Date.now() });
|
||||
export const fail = (message: string, errors?: Record<string, string>): ActionResult => ({ ok: false, message, errors, at: Date.now() });
|
||||
74
src/lib/auth-actions.ts
Normal file
74
src/lib/auth-actions.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
"use server";
|
||||
import { redirect } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
import { db } from "./db";
|
||||
import { createSession, destroySession, hashPassword, verifyPassword } from "./auth";
|
||||
|
||||
export type AuthState = { error?: string; errors?: Record<string, string> } | null;
|
||||
|
||||
const safeNext = (v: FormDataEntryValue | null, fallback: string) => {
|
||||
const s = String(v ?? "");
|
||||
return s.startsWith("/") && !s.startsWith("//") ? s : fallback;
|
||||
};
|
||||
|
||||
// Einfache Bremse gegen Durchprobieren von Passwörtern (pro Prozess)
|
||||
const attempts = new Map<string, { n: number; until: number }>();
|
||||
|
||||
export async function login(_prev: AuthState, formData: FormData): Promise<AuthState> {
|
||||
const email = String(formData.get("email") ?? "").trim().toLowerCase();
|
||||
const password = String(formData.get("password") ?? "");
|
||||
const a = attempts.get(email);
|
||||
if (a && a.until > Date.now()) return { error: "Zu viele Versuche. Bitte warte eine Minute." };
|
||||
const user = await db.user.findUnique({ where: { email }, include: { role: true } });
|
||||
if (!user || !user.active || !(await verifyPassword(password, user.passwordHash))) {
|
||||
const n = (a?.n ?? 0) + 1;
|
||||
attempts.set(email, { n, until: n >= 5 ? Date.now() + 60_000 : 0 });
|
||||
return { error: "E-Mail-Adresse oder Passwort stimmen nicht." };
|
||||
}
|
||||
attempts.delete(email);
|
||||
await createSession(user.id);
|
||||
const admin = formData.get("area") === "admin";
|
||||
if (admin && !user.role) return { error: "Dieses Konto hat keinen Zugang zum Admin-Bereich." };
|
||||
redirect(safeNext(formData.get("weiter"), admin ? "/admin" : "/konto"));
|
||||
}
|
||||
|
||||
const registerSchema = z.object({
|
||||
firstName: z.string().trim().min(1, "Bitte gib deinen Vornamen ein."),
|
||||
lastName: z.string().trim().min(1, "Bitte gib deinen Nachnamen ein."),
|
||||
email: z.email("Bitte gib eine gültige E-Mail-Adresse ein."),
|
||||
password: z.string().min(8, "Das Passwort braucht mindestens 8 Zeichen."),
|
||||
});
|
||||
|
||||
export async function register(_prev: AuthState, formData: FormData): Promise<AuthState> {
|
||||
const parsed = registerSchema.safeParse({
|
||||
firstName: formData.get("firstName"),
|
||||
lastName: formData.get("lastName"),
|
||||
email: String(formData.get("email") ?? "").trim().toLowerCase(),
|
||||
password: formData.get("password"),
|
||||
});
|
||||
if (!parsed.success) {
|
||||
const errors: Record<string, string> = {};
|
||||
for (const i of parsed.error.issues) errors[String(i.path[0])] ??= i.message;
|
||||
return { errors };
|
||||
}
|
||||
const exists = await db.user.findUnique({ where: { email: parsed.data.email } });
|
||||
if (exists) return { errors: { email: "Zu dieser E-Mail-Adresse gibt es schon ein Konto. Melde dich einfach an." } };
|
||||
const user = await db.user.create({
|
||||
data: {
|
||||
email: parsed.data.email,
|
||||
firstName: parsed.data.firstName,
|
||||
lastName: parsed.data.lastName,
|
||||
passwordHash: await hashPassword(parsed.data.password),
|
||||
newsletter: formData.get("newsletter") === "on",
|
||||
},
|
||||
});
|
||||
// Frühere Gastbestellungen mit derselben Adresse dem Konto zuordnen
|
||||
await db.order.updateMany({ where: { email: user.email, userId: null }, data: { userId: user.id } });
|
||||
await createSession(user.id);
|
||||
redirect(safeNext(formData.get("weiter"), "/konto"));
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
await destroySession();
|
||||
redirect("/");
|
||||
}
|
||||
82
src/lib/auth.ts
Normal file
82
src/lib/auth.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import "server-only";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { cache } from "react";
|
||||
import { db } from "./db";
|
||||
import type { Permission } from "./permissions";
|
||||
|
||||
export const SESSION_COOKIE = "sm_session";
|
||||
const SESSION_DAYS = 30;
|
||||
|
||||
const hashToken = (token: string) => createHash("sha256").update(token).digest("hex");
|
||||
|
||||
export async function hashPassword(password: string) {
|
||||
return bcrypt.hash(password, 12);
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, hash: string) {
|
||||
return bcrypt.compare(password, hash);
|
||||
}
|
||||
|
||||
export async function createSession(userId: string) {
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const expiresAt = new Date(Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000);
|
||||
await db.session.create({ data: { tokenHash: hashToken(token), userId, expiresAt } });
|
||||
await db.user.update({ where: { id: userId }, data: { lastLoginAt: new Date() } });
|
||||
const jar = await cookies();
|
||||
jar.set(SESSION_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: (process.env.APP_URL ?? "").startsWith("https://"),
|
||||
path: "/",
|
||||
expires: expiresAt,
|
||||
});
|
||||
}
|
||||
|
||||
export async function destroySession() {
|
||||
const jar = await cookies();
|
||||
const token = jar.get(SESSION_COOKIE)?.value;
|
||||
if (token) await db.session.deleteMany({ where: { tokenHash: hashToken(token) } });
|
||||
jar.delete(SESSION_COOKIE);
|
||||
}
|
||||
|
||||
export const getCurrentUser = cache(async () => {
|
||||
const jar = await cookies();
|
||||
const token = jar.get(SESSION_COOKIE)?.value;
|
||||
if (!token) return null;
|
||||
const session = await db.session.findUnique({
|
||||
where: { tokenHash: hashToken(token) },
|
||||
include: { user: { include: { role: true } } },
|
||||
});
|
||||
if (!session || session.expiresAt < new Date() || !session.user.active) return null;
|
||||
return session.user;
|
||||
});
|
||||
|
||||
export type CurrentUser = NonNullable<Awaited<ReturnType<typeof getCurrentUser>>>;
|
||||
|
||||
export function can(user: CurrentUser | null, permission: Permission): boolean {
|
||||
if (!user?.role) return false;
|
||||
return user.role.isSystem || user.role.permissions.includes(permission);
|
||||
}
|
||||
|
||||
/** Für Admin-Seiten: angemeldet, mit Rolle und dem nötigen Recht – sonst Umleitung. */
|
||||
export async function requireAdmin(permission?: Permission): Promise<CurrentUser> {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) redirect("/admin/login");
|
||||
if (!user.role) redirect("/konto");
|
||||
if (permission && !can(user, permission)) redirect("/admin?kein-zugriff=1");
|
||||
return user;
|
||||
}
|
||||
|
||||
/** Für Server-Actions: wirft statt umzuleiten. */
|
||||
export async function assertPermission(permission: Permission): Promise<CurrentUser> {
|
||||
const user = await getCurrentUser();
|
||||
if (!user || !can(user, permission)) throw new Error("Dafür fehlt dir das Recht.");
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function audit(user: CurrentUser | null, action: string, details = "") {
|
||||
await db.auditLog.create({ data: { userId: user?.id, userEmail: user?.email ?? "", action, details } });
|
||||
}
|
||||
93
src/lib/cart.ts
Normal file
93
src/lib/cart.ts
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import "server-only";
|
||||
import { cookies } from "next/headers";
|
||||
import { db } from "./db";
|
||||
|
||||
export const CART_COOKIE = "sm_cart";
|
||||
export type CartEntry = { p: string; v: string | null; q: number };
|
||||
|
||||
export async function readCartCookie(): Promise<CartEntry[]> {
|
||||
const raw = (await cookies()).get(CART_COOKIE)?.value;
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed
|
||||
.filter((e) => e && typeof e.p === "string" && Number.isInteger(e.q) && e.q > 0)
|
||||
.map((e) => ({ p: e.p, v: typeof e.v === "string" ? e.v : null, q: Math.min(e.q, 99) }));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeCartCookie(entries: CartEntry[]) {
|
||||
(await cookies()).set(CART_COOKIE, JSON.stringify(entries), {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 60 * 60 * 24 * 30,
|
||||
});
|
||||
}
|
||||
|
||||
export async function clearCart() {
|
||||
(await cookies()).delete(CART_COOKIE);
|
||||
}
|
||||
|
||||
export type CartLine = {
|
||||
key: string;
|
||||
productId: string;
|
||||
variantId: string | null;
|
||||
name: string;
|
||||
slug: string;
|
||||
variantName: string;
|
||||
subtitle: string;
|
||||
sku: string;
|
||||
image: string;
|
||||
unitPrice: number;
|
||||
quantity: number;
|
||||
maxQuantity: number;
|
||||
taxRate: number;
|
||||
total: number;
|
||||
};
|
||||
|
||||
/** Löst die Cookie-Einträge gegen die Datenbank auf; Preise kommen immer aus der DB. */
|
||||
export async function getCart(): Promise<CartLine[]> {
|
||||
const entries = await readCartCookie();
|
||||
if (entries.length === 0) return [];
|
||||
const products = await db.product.findMany({
|
||||
where: { id: { in: entries.map((e) => e.p) }, active: true },
|
||||
include: { variants: true },
|
||||
});
|
||||
const lines: CartLine[] = [];
|
||||
for (const e of entries) {
|
||||
const product = products.find((p) => p.id === e.p);
|
||||
if (!product) continue;
|
||||
const variant = e.v ? product.variants.find((v) => v.id === e.v) : null;
|
||||
if (e.v && !variant) continue;
|
||||
const unitPrice = variant?.price ?? product.price;
|
||||
const available = product.trackStock ? (variant ? variant.stock : product.stock) : 99;
|
||||
const quantity = Math.min(e.q, Math.max(available, 0));
|
||||
if (quantity <= 0) continue;
|
||||
lines.push({
|
||||
key: `${product.id}:${variant?.id ?? ""}`,
|
||||
productId: product.id,
|
||||
variantId: variant?.id ?? null,
|
||||
name: product.name,
|
||||
slug: product.slug,
|
||||
variantName: variant?.name ?? "",
|
||||
subtitle: product.subtitle,
|
||||
sku: variant?.sku || product.sku,
|
||||
image: product.images[0] ?? "",
|
||||
unitPrice,
|
||||
quantity,
|
||||
maxQuantity: Math.min(available, 99),
|
||||
taxRate: product.taxRate,
|
||||
total: unitPrice * quantity,
|
||||
});
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
export async function getCartCount(): Promise<number> {
|
||||
const entries = await readCartCookie();
|
||||
return entries.reduce((n, e) => n + e.q, 0);
|
||||
}
|
||||
12
src/lib/checkout-finish.ts
Normal file
12
src/lib/checkout-finish.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import "server-only";
|
||||
import { cookies } from "next/headers";
|
||||
import { clearCart } from "./cart";
|
||||
import { readCheckout, writeCheckout } from "./checkout";
|
||||
|
||||
/** Nach erfolgreicher Zahlung: Warenkorb, Gutschein und Kassenauswahl leeren. */
|
||||
export async function finishCheckoutSession() {
|
||||
await clearCart();
|
||||
(await cookies()).delete("sm_coupon");
|
||||
const state = await readCheckout();
|
||||
await writeCheckout({ ...state, shippingMethodId: undefined, paymentMethodId: undefined, lastOrderId: undefined });
|
||||
}
|
||||
180
src/lib/checkout.ts
Normal file
180
src/lib/checkout.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
import "server-only";
|
||||
import { cookies } from "next/headers";
|
||||
import type { PaymentMethod, Prisma } from "@prisma/client";
|
||||
import { db } from "./db";
|
||||
import type { CartLine } from "./cart";
|
||||
import type { Totals } from "./pricing";
|
||||
import { getDefinition } from "./payments/catalog";
|
||||
import { getCredentials, isProviderReady } from "./payments/credentials";
|
||||
import { getSettings } from "./settings";
|
||||
|
||||
export const CHECKOUT_COOKIE = "sm_checkout";
|
||||
|
||||
export type AddressData = {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
company: string;
|
||||
street: string;
|
||||
extra: string;
|
||||
zip: string;
|
||||
city: string;
|
||||
country: string;
|
||||
};
|
||||
|
||||
export type CheckoutState = {
|
||||
email?: string;
|
||||
phone?: string;
|
||||
address?: AddressData;
|
||||
billingSame?: boolean;
|
||||
billing?: AddressData;
|
||||
newsletter?: boolean;
|
||||
shippingMethodId?: string;
|
||||
paymentMethodId?: string;
|
||||
lastOrderId?: string;
|
||||
};
|
||||
|
||||
export async function readCheckout(): Promise<CheckoutState> {
|
||||
const raw = (await cookies()).get(CHECKOUT_COOKIE)?.value;
|
||||
if (!raw) return {};
|
||||
try {
|
||||
return JSON.parse(raw) as CheckoutState;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeCheckout(patch: Partial<CheckoutState>) {
|
||||
const next = { ...(await readCheckout()), ...patch };
|
||||
(await cookies()).set(CHECKOUT_COOKIE, JSON.stringify(next), {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
});
|
||||
return next;
|
||||
}
|
||||
|
||||
export async function availableShipping(country: string | undefined) {
|
||||
const methods = await db.shippingMethod.findMany({ where: { enabled: true }, orderBy: { sort: "asc" } });
|
||||
return methods.filter((m) => !country || m.countries.length === 0 || m.countries.includes(country));
|
||||
}
|
||||
|
||||
export async function availablePayments(total: number, loggedIn: boolean): Promise<PaymentMethod[]> {
|
||||
const [methods, creds] = await Promise.all([
|
||||
db.paymentMethod.findMany({ where: { enabled: true }, orderBy: { sort: "asc" } }),
|
||||
getCredentials(),
|
||||
]);
|
||||
return methods.filter((m) => {
|
||||
const def = getDefinition(m.code);
|
||||
if (!def || !isProviderReady(def.provider, creds)) return false;
|
||||
if (m.loggedInOnly && !loggedIn) return false;
|
||||
if (m.minTotal > 0 && total < m.minTotal) return false;
|
||||
if (m.maxTotal > 0 && total > m.maxTotal) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
async function nextOrderNumber(tx: Prisma.TransactionClient) {
|
||||
const settings = await getSettings();
|
||||
const count = await tx.order.count();
|
||||
return `${settings.general.orderPrefix || "SM"}-${10001 + count}`;
|
||||
}
|
||||
|
||||
/** Bestand zurückbuchen, z. B. bei Storno */
|
||||
export async function restock(tx: Prisma.TransactionClient, orderId: string) {
|
||||
const items = await tx.orderItem.findMany({ where: { orderId }, include: { product: true } });
|
||||
for (const it of items) {
|
||||
if (!it.product?.trackStock) continue;
|
||||
if (it.variantId) await tx.productVariant.updateMany({ where: { id: it.variantId }, data: { stock: { increment: it.quantity } } });
|
||||
else await tx.product.update({ where: { id: it.product.id }, data: { stock: { increment: it.quantity } } });
|
||||
}
|
||||
}
|
||||
|
||||
export async function createOrder(opts: {
|
||||
state: CheckoutState;
|
||||
lines: CartLine[];
|
||||
totals: Totals;
|
||||
shippingName: string;
|
||||
payment: PaymentMethod;
|
||||
userId: string | null;
|
||||
note: string;
|
||||
}) {
|
||||
const { state, lines, totals, payment } = opts;
|
||||
return db.$transaction(async (tx) => {
|
||||
// Eine noch offene, nie bezahlte Bestellung aus demselben Checkout wird ersetzt
|
||||
if (state.lastOrderId) {
|
||||
const prev = await tx.order.findUnique({ where: { id: state.lastOrderId } });
|
||||
if (prev && prev.status === "PENDING" && prev.paymentStatus === "OPEN" && ["stripe", "paypal"].includes(getDefinition(prev.paymentMethod)?.provider ?? "")) {
|
||||
await restock(tx, prev.id);
|
||||
await tx.order.update({ where: { id: prev.id }, data: { status: "CANCELLED" } });
|
||||
await tx.orderEvent.create({ data: { orderId: prev.id, message: "Automatisch storniert: Kunde hat neu bestellt, Zahlung wurde nie abgeschlossen." } });
|
||||
}
|
||||
}
|
||||
// Bestand prüfen und reservieren
|
||||
for (const l of lines) {
|
||||
const product = await tx.product.findUnique({ where: { id: l.productId } });
|
||||
if (!product?.trackStock) continue;
|
||||
if (l.variantId) {
|
||||
const r = await tx.productVariant.updateMany({ where: { id: l.variantId, stock: { gte: l.quantity } }, data: { stock: { decrement: l.quantity } } });
|
||||
if (r.count === 0) throw new Error(`${l.name} – ${l.variantName} ist nicht mehr in dieser Menge verfügbar.`);
|
||||
} else {
|
||||
const r = await tx.product.updateMany({ where: { id: l.productId, stock: { gte: l.quantity } }, data: { stock: { decrement: l.quantity } } });
|
||||
if (r.count === 0) throw new Error(`${l.name} ist nicht mehr in dieser Menge verfügbar.`);
|
||||
}
|
||||
}
|
||||
if (totals.coupon) await tx.coupon.update({ where: { id: totals.coupon.id }, data: { usedCount: { increment: 1 } } });
|
||||
const number = await nextOrderNumber(tx);
|
||||
const order = await tx.order.create({
|
||||
data: {
|
||||
number,
|
||||
userId: opts.userId,
|
||||
email: state.email!,
|
||||
phone: state.phone ?? "",
|
||||
paymentMethod: payment.code,
|
||||
shippingMethod: opts.shippingName,
|
||||
shippingAddress: state.address!,
|
||||
billingAddress: state.billingSame === false && state.billing ? state.billing : undefined,
|
||||
subtotal: totals.subtotal,
|
||||
shippingCost: totals.shippingCost,
|
||||
paymentFee: totals.paymentFee,
|
||||
discount: totals.discount,
|
||||
couponCode: totals.coupon?.code ?? "",
|
||||
taxAmount: totals.taxAmount,
|
||||
total: totals.total,
|
||||
note: opts.note,
|
||||
items: {
|
||||
create: lines.map((l) => ({
|
||||
productId: l.productId,
|
||||
variantId: l.variantId,
|
||||
name: l.name,
|
||||
variantName: l.variantName,
|
||||
sku: l.sku,
|
||||
unitPrice: l.unitPrice,
|
||||
quantity: l.quantity,
|
||||
taxRate: l.taxRate,
|
||||
total: l.total,
|
||||
})),
|
||||
},
|
||||
events: { create: { message: `Bestellung aufgegeben, Zahlungsart: ${payment.name}` } },
|
||||
},
|
||||
});
|
||||
if (state.newsletter) {
|
||||
await tx.newsletterSubscriber.upsert({ where: { email: order.email }, create: { email: order.email }, update: {} });
|
||||
}
|
||||
return order;
|
||||
});
|
||||
}
|
||||
|
||||
export async function markOrderPaid(orderId: string, reference: string, source: string) {
|
||||
const order = await db.order.findUnique({ where: { id: orderId } });
|
||||
if (!order || order.paymentStatus === "PAID") return order;
|
||||
return db.order.update({
|
||||
where: { id: orderId },
|
||||
data: {
|
||||
paymentStatus: "PAID",
|
||||
paymentRef: reference,
|
||||
status: order.status === "PENDING" ? "PAID" : order.status,
|
||||
events: { create: { message: `Zahlung bestätigt (${source})` } },
|
||||
},
|
||||
});
|
||||
}
|
||||
7
src/lib/db.ts
Normal file
7
src/lib/db.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
|
||||
|
||||
export const db = globalForPrisma.prisma ?? new PrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = db;
|
||||
28
src/lib/money.ts
Normal file
28
src/lib/money.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
const fmt = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
|
||||
/** 12900 → "129,00 €" */
|
||||
export function formatPrice(cents: number): string {
|
||||
return fmt.format(cents / 100);
|
||||
}
|
||||
|
||||
/** "129,00" / "129.5" / "129" → 12900; ungültig → null */
|
||||
export function parsePrice(input: string | null | undefined): number | null {
|
||||
if (input == null) return null;
|
||||
const s = String(input).trim().replace(/\s|€/g, "");
|
||||
if (!s) return null;
|
||||
const normalized = s.includes(",") ? s.replace(/\./g, "").replace(",", ".") : s;
|
||||
const n = Number(normalized);
|
||||
if (!Number.isFinite(n) || n < 0) return null;
|
||||
return Math.round(n * 100);
|
||||
}
|
||||
|
||||
/** 12900 → "129,00" (für Eingabefelder) */
|
||||
export function centsToInput(cents: number | null | undefined): string {
|
||||
if (cents == null) return "";
|
||||
return (cents / 100).toFixed(2).replace(".", ",");
|
||||
}
|
||||
|
||||
/** Enthaltene MwSt. aus einem Bruttobetrag */
|
||||
export function includedTax(gross: number, rate: number): number {
|
||||
return Math.round(gross - gross / (1 + rate / 100));
|
||||
}
|
||||
92
src/lib/payments/catalog.ts
Normal file
92
src/lib/payments/catalog.ts
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
// Alle Zahlungsarten, die der Shop kennt. Welche aktiv sind, entscheidet der Admin.
|
||||
export type PaymentProvider = "stripe" | "paypal" | "manual";
|
||||
|
||||
export type ConfigField = {
|
||||
key: string;
|
||||
label: string;
|
||||
type: "text" | "textarea" | "number";
|
||||
hint?: string;
|
||||
};
|
||||
|
||||
export type PaymentDefinition = {
|
||||
code: string;
|
||||
provider: PaymentProvider;
|
||||
defaultName: string;
|
||||
defaultDescription: string;
|
||||
adminHint: string;
|
||||
stripeType?: string;
|
||||
fields: ConfigField[];
|
||||
defaultConfig?: Record<string, string>;
|
||||
};
|
||||
|
||||
export const PAYMENT_DEFINITIONS: PaymentDefinition[] = [
|
||||
{
|
||||
code: "stripe_card",
|
||||
provider: "stripe",
|
||||
stripeType: "card",
|
||||
defaultName: "Kreditkarte, Apple Pay, Google Pay",
|
||||
defaultDescription: "Visa, Mastercard, American Express. Apple Pay und Google Pay erscheinen automatisch auf passenden Geräten.",
|
||||
adminHint: "Läuft über Stripe. Braucht die Stripe-Zugangsdaten oben.",
|
||||
fields: [],
|
||||
},
|
||||
{
|
||||
code: "paypal",
|
||||
provider: "paypal",
|
||||
defaultName: "PayPal",
|
||||
defaultDescription: "Du wirst zu PayPal weitergeleitet und kommst danach hierher zurück.",
|
||||
adminHint: "Braucht die PayPal-Zugangsdaten oben.",
|
||||
fields: [],
|
||||
},
|
||||
{
|
||||
code: "stripe_klarna",
|
||||
provider: "stripe",
|
||||
stripeType: "klarna",
|
||||
defaultName: "Klarna",
|
||||
defaultDescription: "Später bezahlen oder in Raten – über Klarna.",
|
||||
adminHint: "Läuft über Stripe. Klarna muss in deinem Stripe-Konto freigeschaltet sein.",
|
||||
fields: [],
|
||||
},
|
||||
{
|
||||
code: "stripe_sepa",
|
||||
provider: "stripe",
|
||||
stripeType: "sepa_debit",
|
||||
defaultName: "SEPA-Lastschrift",
|
||||
defaultDescription: "Der Betrag wird von deinem Konto abgebucht.",
|
||||
adminHint: "Läuft über Stripe. SEPA-Lastschrift muss in deinem Stripe-Konto aktiv sein.",
|
||||
fields: [],
|
||||
},
|
||||
{
|
||||
code: "prepayment",
|
||||
provider: "manual",
|
||||
defaultName: "Vorkasse (Überweisung)",
|
||||
defaultDescription: "Du überweist den Betrag, wir versenden nach Zahlungseingang.",
|
||||
adminHint: "Kunden sehen die Bankverbindung nach der Bestellung und in der Bestätigung.",
|
||||
fields: [
|
||||
{ key: "accountHolder", label: "Kontoinhaber", type: "text" },
|
||||
{ key: "iban", label: "IBAN", type: "text" },
|
||||
{ key: "bic", label: "BIC", type: "text" },
|
||||
{ key: "bank", label: "Bank", type: "text" },
|
||||
],
|
||||
},
|
||||
{
|
||||
code: "invoice",
|
||||
provider: "manual",
|
||||
defaultName: "Kauf auf Rechnung",
|
||||
defaultDescription: "Du bezahlst nach Erhalt der Ware.",
|
||||
adminHint: "Ohne Zahlungsdienstleister: Du prüfst und mahnst selbst. Empfehlung: nur für angemeldete Kunden.",
|
||||
fields: [{ key: "dueDays", label: "Zahlungsziel in Tagen", type: "number" }],
|
||||
defaultConfig: { dueDays: "14" },
|
||||
},
|
||||
{
|
||||
code: "cod",
|
||||
provider: "manual",
|
||||
defaultName: "Nachnahme",
|
||||
defaultDescription: "Du bezahlst bar beim Paketboten.",
|
||||
adminHint: "Die Nachnahmegebühr kannst du als Gebühr eintragen.",
|
||||
fields: [],
|
||||
},
|
||||
];
|
||||
|
||||
export function getDefinition(code: string) {
|
||||
return PAYMENT_DEFINITIONS.find((d) => d.code === code);
|
||||
}
|
||||
41
src/lib/payments/credentials.ts
Normal file
41
src/lib/payments/credentials.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import "server-only";
|
||||
import { db } from "../db";
|
||||
|
||||
export type PaymentCredentials = {
|
||||
stripe: { publishableKey: string; secretKey: string; webhookSecret: string };
|
||||
paypal: { clientId: string; clientSecret: string; sandbox: boolean };
|
||||
};
|
||||
|
||||
const DEFAULTS: PaymentCredentials = {
|
||||
stripe: { publishableKey: "", secretKey: "", webhookSecret: "" },
|
||||
paypal: { clientId: "", clientSecret: "", sandbox: true },
|
||||
};
|
||||
|
||||
export async function getCredentials(): Promise<PaymentCredentials> {
|
||||
const row = await db.setting.findUnique({ where: { key: "payment_credentials" } });
|
||||
const value = (row?.value ?? {}) as Partial<PaymentCredentials>;
|
||||
return {
|
||||
stripe: { ...DEFAULTS.stripe, ...(value.stripe ?? {}) },
|
||||
paypal: { ...DEFAULTS.paypal, ...(value.paypal ?? {}) },
|
||||
};
|
||||
}
|
||||
|
||||
export async function saveCredentials(value: PaymentCredentials) {
|
||||
await db.setting.upsert({
|
||||
where: { key: "payment_credentials" },
|
||||
create: { key: "payment_credentials", value },
|
||||
update: { value },
|
||||
});
|
||||
}
|
||||
|
||||
export function isProviderReady(provider: string, c: PaymentCredentials) {
|
||||
if (provider === "stripe") return Boolean(c.stripe.secretKey);
|
||||
if (provider === "paypal") return Boolean(c.paypal.clientId && c.paypal.clientSecret);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Zeigt nur die letzten Zeichen eines Schlüssels. */
|
||||
export function mask(secret: string) {
|
||||
if (!secret) return "";
|
||||
return "••••••••" + secret.slice(-4);
|
||||
}
|
||||
69
src/lib/payments/paypal.ts
Normal file
69
src/lib/payments/paypal.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import "server-only";
|
||||
import type { Order } from "@prisma/client";
|
||||
|
||||
const base = (sandbox: boolean) => (sandbox ? "https://api-m.sandbox.paypal.com" : "https://api-m.paypal.com");
|
||||
|
||||
async function accessToken(clientId: string, clientSecret: string, sandbox: boolean) {
|
||||
const res = await fetch(`${base(sandbox)}/v1/oauth2/token`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Basic " + Buffer.from(`${clientId}:${clientSecret}`).toString("base64"),
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: "grant_type=client_credentials",
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data?.error_description ?? "PayPal-Anmeldung fehlgeschlagen");
|
||||
return data.access_token as string;
|
||||
}
|
||||
|
||||
type Creds = { clientId: string; clientSecret: string; sandbox: boolean };
|
||||
|
||||
export async function createPaypalOrder(creds: Creds, order: Order, appUrl: string) {
|
||||
const token = await accessToken(creds.clientId, creds.clientSecret, creds.sandbox);
|
||||
const res = await fetch(`${base(creds.sandbox)}/v2/checkout/orders`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
intent: "CAPTURE",
|
||||
purchase_units: [
|
||||
{
|
||||
reference_id: order.id,
|
||||
invoice_id: order.number,
|
||||
description: `Bestellung ${order.number}`,
|
||||
amount: { currency_code: "EUR", value: (order.total / 100).toFixed(2) },
|
||||
},
|
||||
],
|
||||
payment_source: {
|
||||
paypal: {
|
||||
experience_context: {
|
||||
locale: "de-DE",
|
||||
user_action: "PAY_NOW",
|
||||
shipping_preference: "NO_SHIPPING",
|
||||
return_url: `${appUrl}/api/payments/paypal/return?order=${order.id}`,
|
||||
cancel_url: `${appUrl}/kasse/zahlung?abgebrochen=1`,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data?.message ?? "PayPal-Bestellung fehlgeschlagen");
|
||||
const approve = (data.links as { rel: string; href: string }[]).find((l) => l.rel === "payer-action" || l.rel === "approve");
|
||||
if (!approve) throw new Error("PayPal hat keinen Bezahl-Link geliefert");
|
||||
return { id: data.id as string, url: approve.href };
|
||||
}
|
||||
|
||||
export async function capturePaypalOrder(creds: Creds, paypalOrderId: string) {
|
||||
const token = await accessToken(creds.clientId, creds.clientSecret, creds.sandbox);
|
||||
const res = await fetch(`${base(creds.sandbox)}/v2/checkout/orders/${encodeURIComponent(paypalOrderId)}/capture`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok && data?.details?.[0]?.issue !== "ORDER_ALREADY_CAPTURED") throw new Error(data?.message ?? "PayPal-Zahlung fehlgeschlagen");
|
||||
return { status: (data.status as string) ?? "COMPLETED", referenceId: data?.purchase_units?.[0]?.reference_id as string | undefined };
|
||||
}
|
||||
75
src/lib/payments/stripe.ts
Normal file
75
src/lib/payments/stripe.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import "server-only";
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
import type { Order } from "@prisma/client";
|
||||
|
||||
const API = "https://api.stripe.com/v1";
|
||||
|
||||
async function stripeRequest<T>(secretKey: string, path: string, params?: URLSearchParams, method = "POST"): Promise<T> {
|
||||
const res = await fetch(`${API}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${secretKey}`,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: method === "POST" ? params?.toString() : undefined,
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data?.error?.message ?? `Stripe-Fehler ${res.status}`);
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export async function createCheckoutSession(opts: {
|
||||
secretKey: string;
|
||||
order: Order;
|
||||
stripeType: string;
|
||||
appUrl: string;
|
||||
}) {
|
||||
const { order, appUrl } = opts;
|
||||
const p = new URLSearchParams();
|
||||
p.set("mode", "payment");
|
||||
p.set("customer_email", order.email);
|
||||
p.set("client_reference_id", order.id);
|
||||
p.set("metadata[orderId]", order.id);
|
||||
p.set("metadata[orderNumber]", order.number);
|
||||
p.set("payment_intent_data[metadata][orderId]", order.id);
|
||||
p.set("locale", "de");
|
||||
p.append("payment_method_types[]", opts.stripeType);
|
||||
p.set("line_items[0][quantity]", "1");
|
||||
p.set("line_items[0][price_data][currency]", "eur");
|
||||
p.set("line_items[0][price_data][unit_amount]", String(order.total));
|
||||
p.set("line_items[0][price_data][product_data][name]", `Bestellung ${order.number}`);
|
||||
p.set("success_url", `${appUrl}/api/payments/stripe/return?order=${order.id}&session_id={CHECKOUT_SESSION_ID}`);
|
||||
p.set("cancel_url", `${appUrl}/kasse/zahlung?abgebrochen=1`);
|
||||
return stripeRequest<{ id: string; url: string }>(opts.secretKey, "/checkout/sessions", p);
|
||||
}
|
||||
|
||||
export async function retrieveCheckoutSession(secretKey: string, id: string) {
|
||||
return stripeRequest<{ id: string; payment_status: string; metadata: Record<string, string>; payment_intent: string | null }>(
|
||||
secretKey,
|
||||
`/checkout/sessions/${encodeURIComponent(id)}`,
|
||||
undefined,
|
||||
"GET",
|
||||
);
|
||||
}
|
||||
|
||||
export async function refundPayment(secretKey: string, paymentIntent: string) {
|
||||
const p = new URLSearchParams({ payment_intent: paymentIntent });
|
||||
return stripeRequest<{ id: string; status: string }>(secretKey, "/refunds", p);
|
||||
}
|
||||
|
||||
/** Prüft die Stripe-Signatur (Header "Stripe-Signature"). */
|
||||
export function verifyWebhook(payload: string, header: string | null, secret: string, toleranceSec = 300) {
|
||||
if (!header) return false;
|
||||
const parts = Object.fromEntries(header.split(",").map((kv) => kv.split("=") as [string, string]));
|
||||
const timestamp = parts["t"];
|
||||
const signatures = header.split(",").filter((kv) => kv.startsWith("v1=")).map((kv) => kv.slice(3));
|
||||
if (!timestamp || signatures.length === 0) return false;
|
||||
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSec) return false;
|
||||
const expected = createHmac("sha256", secret).update(`${timestamp}.${payload}`).digest("hex");
|
||||
return signatures.some((sig) => {
|
||||
const a = Buffer.from(sig);
|
||||
const b = Buffer.from(expected);
|
||||
return a.length === b.length && timingSafeEqual(a, b);
|
||||
});
|
||||
}
|
||||
65
src/lib/permissions.ts
Normal file
65
src/lib/permissions.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
// Katalog aller Rechte. Rollen im Admin kombinieren diese Schlüssel frei.
|
||||
export const PERMISSION_GROUPS = [
|
||||
{
|
||||
label: "Übersicht",
|
||||
permissions: [{ key: "dashboard.view", label: "Dashboard und Kennzahlen ansehen" }],
|
||||
},
|
||||
{
|
||||
label: "Bestellungen",
|
||||
permissions: [
|
||||
{ key: "orders.view", label: "Bestellungen ansehen" },
|
||||
{ key: "orders.edit", label: "Status, Versand und Notizen ändern" },
|
||||
{ key: "orders.refund", label: "Bestellungen stornieren und erstatten" },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Katalog",
|
||||
permissions: [
|
||||
{ key: "products.view", label: "Produkte und Kategorien ansehen" },
|
||||
{ key: "products.edit", label: "Produkte anlegen und bearbeiten" },
|
||||
{ key: "products.delete", label: "Produkte löschen" },
|
||||
{ key: "categories.edit", label: "Kategorien verwalten" },
|
||||
{ key: "stock.edit", label: "Lagerbestand ändern" },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Kunden & Marketing",
|
||||
permissions: [
|
||||
{ key: "customers.view", label: "Kunden ansehen" },
|
||||
{ key: "customers.edit", label: "Kunden bearbeiten" },
|
||||
{ key: "coupons.edit", label: "Gutscheine verwalten" },
|
||||
{ key: "newsletter.view", label: "Newsletter-Anmeldungen ansehen" },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Inhalte & Aussehen",
|
||||
permissions: [
|
||||
{ key: "content.edit", label: "Seiten (Impressum, AGB …) bearbeiten" },
|
||||
{ key: "appearance.edit", label: "Startseite, Navigation und Texte gestalten" },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Einstellungen",
|
||||
permissions: [
|
||||
{ key: "settings.edit", label: "Allgemeine Shop-Einstellungen" },
|
||||
{ key: "shipping.edit", label: "Versandarten verwalten" },
|
||||
{ key: "payments.edit", label: "Zahlungsarten und Zugangsdaten verwalten" },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Team & Sicherheit",
|
||||
permissions: [
|
||||
{ key: "users.manage", label: "Team-Mitglieder einladen und verwalten" },
|
||||
{ key: "roles.manage", label: "Rollen und Rechte festlegen" },
|
||||
{ key: "audit.view", label: "Aktivitätsprotokoll ansehen" },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type Permission = (typeof PERMISSION_GROUPS)[number]["permissions"][number]["key"];
|
||||
|
||||
export const ALL_PERMISSIONS: Permission[] = PERMISSION_GROUPS.flatMap((g) => g.permissions.map((p) => p.key));
|
||||
|
||||
export function isPermission(value: string): value is Permission {
|
||||
return (ALL_PERMISSIONS as string[]).includes(value);
|
||||
}
|
||||
77
src/lib/pricing.ts
Normal file
77
src/lib/pricing.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import "server-only";
|
||||
import type { Coupon, PaymentMethod, ShippingMethod } from "@prisma/client";
|
||||
import { db } from "./db";
|
||||
import type { CartLine } from "./cart";
|
||||
|
||||
export type Totals = {
|
||||
subtotal: number;
|
||||
discount: number;
|
||||
shippingCost: number;
|
||||
paymentFee: number;
|
||||
taxAmount: number;
|
||||
total: number;
|
||||
freeShippingRemaining: number | null;
|
||||
coupon: Coupon | null;
|
||||
couponError: string | null;
|
||||
};
|
||||
|
||||
export async function findCoupon(code: string | null | undefined, subtotal: number) {
|
||||
if (!code) return { coupon: null, error: null };
|
||||
const coupon = await db.coupon.findUnique({ where: { code: code.trim().toUpperCase() } });
|
||||
if (!coupon || !coupon.active) return { coupon: null, error: "Diesen Gutscheincode kennen wir nicht." };
|
||||
if (coupon.validUntil && coupon.validUntil < new Date()) return { coupon: null, error: "Dieser Gutschein ist abgelaufen." };
|
||||
if (coupon.maxUses > 0 && coupon.usedCount >= coupon.maxUses) return { coupon: null, error: "Dieser Gutschein wurde schon zu oft eingelöst." };
|
||||
if (subtotal < coupon.minTotal) return { coupon: null, error: "Der Mindestbestellwert für diesen Gutschein ist noch nicht erreicht." };
|
||||
return { coupon, error: null };
|
||||
}
|
||||
|
||||
export function shippingPrice(method: ShippingMethod | null, merchandise: number) {
|
||||
if (!method) return 0;
|
||||
if (method.freeFrom > 0 && merchandise >= method.freeFrom) return 0;
|
||||
return method.price;
|
||||
}
|
||||
|
||||
export async function computeTotals(opts: {
|
||||
lines: CartLine[];
|
||||
couponCode?: string | null;
|
||||
shipping?: ShippingMethod | null;
|
||||
payment?: PaymentMethod | null;
|
||||
}): Promise<Totals> {
|
||||
const subtotal = opts.lines.reduce((s, l) => s + l.total, 0);
|
||||
const { coupon, error } = await findCoupon(opts.couponCode, subtotal);
|
||||
let discount = 0;
|
||||
if (coupon) discount = coupon.type === "percent" ? Math.round((subtotal * coupon.value) / 100) : Math.min(coupon.value, subtotal);
|
||||
const merchandise = subtotal - discount;
|
||||
|
||||
let shipping = opts.shipping ?? null;
|
||||
if (shipping === undefined || shipping === null) {
|
||||
shipping = await db.shippingMethod.findFirst({ where: { enabled: true }, orderBy: { sort: "asc" } });
|
||||
}
|
||||
const shippingCost = opts.lines.length ? shippingPrice(shipping, merchandise) : 0;
|
||||
const paymentFee = opts.payment?.fee ?? 0;
|
||||
const total = merchandise + shippingCost + paymentFee;
|
||||
|
||||
// MwSt.: anteilig je Steuersatz der Positionen, Versand/Gebühr mit dem überwiegenden Satz
|
||||
const ratio = subtotal > 0 ? merchandise / subtotal : 0;
|
||||
let taxAmount = 0;
|
||||
const byRate = new Map<number, number>();
|
||||
for (const l of opts.lines) byRate.set(l.taxRate, (byRate.get(l.taxRate) ?? 0) + l.total * ratio);
|
||||
for (const [rate, gross] of byRate) taxAmount += gross - gross / (1 + rate / 100);
|
||||
const mainRate = [...byRate.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? 19;
|
||||
taxAmount += (shippingCost + paymentFee) - (shippingCost + paymentFee) / (1 + mainRate / 100);
|
||||
|
||||
const freeFrom = shipping?.freeFrom ?? 0;
|
||||
const freeShippingRemaining = freeFrom > 0 && merchandise < freeFrom ? freeFrom - merchandise : null;
|
||||
|
||||
return {
|
||||
subtotal,
|
||||
discount,
|
||||
shippingCost,
|
||||
paymentFee,
|
||||
taxAmount: Math.round(taxAmount),
|
||||
total,
|
||||
freeShippingRemaining,
|
||||
coupon,
|
||||
couponError: error,
|
||||
};
|
||||
}
|
||||
156
src/lib/settings.ts
Normal file
156
src/lib/settings.ts
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
import "server-only";
|
||||
import { cache } from "react";
|
||||
import { db } from "./db";
|
||||
|
||||
export type NavLink = { label: string; href: string };
|
||||
export type TrustItem = { icon: "truck" | "return" | "lock" | "chat" | "leaf" | "star"; title: string; text: string };
|
||||
|
||||
export type ShopSettings = {
|
||||
general: {
|
||||
shopName: string;
|
||||
tagline: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
company: string;
|
||||
street: string;
|
||||
zipCity: string;
|
||||
country: string;
|
||||
vatId: string;
|
||||
orderPrefix: string;
|
||||
maintenance: boolean;
|
||||
};
|
||||
appearance: {
|
||||
promoText: string;
|
||||
promoLinkLabel: string;
|
||||
promoLinkHref: string;
|
||||
navigation: NavLink[];
|
||||
heroEyebrow: string;
|
||||
heroTitle: string;
|
||||
heroText: string;
|
||||
heroPrimaryLabel: string;
|
||||
heroPrimaryHref: string;
|
||||
heroSecondaryLabel: string;
|
||||
heroSecondaryHref: string;
|
||||
showTrustBar: boolean;
|
||||
trustItems: TrustItem[];
|
||||
showCategories: boolean;
|
||||
categoriesEyebrow: string;
|
||||
categoriesTitle: string;
|
||||
showFeatured: boolean;
|
||||
featuredEyebrow: string;
|
||||
featuredTitle: string;
|
||||
showQuote: boolean;
|
||||
quoteText: string;
|
||||
quoteAuthor: string;
|
||||
footerClaim: string;
|
||||
showNewsletter: boolean;
|
||||
darkHeader: boolean;
|
||||
};
|
||||
checkout: {
|
||||
guestCheckout: boolean;
|
||||
requireTerms: boolean;
|
||||
requirePhone: boolean;
|
||||
minOrderValue: number;
|
||||
freeShippingHint: boolean;
|
||||
countries: string[];
|
||||
};
|
||||
};
|
||||
|
||||
export const DEFAULT_SETTINGS: ShopSettings = {
|
||||
general: {
|
||||
shopName: "Sanamare",
|
||||
tagline: "Bewegung, die bleibt.",
|
||||
email: "hallo@sanamare.de",
|
||||
phone: "",
|
||||
company: "Sanamare",
|
||||
street: "",
|
||||
zipCity: "",
|
||||
country: "Deutschland",
|
||||
vatId: "",
|
||||
orderPrefix: "SM",
|
||||
maintenance: false,
|
||||
},
|
||||
appearance: {
|
||||
promoText: "Kostenloser Versand ab 80 €",
|
||||
promoLinkLabel: "30 Tage Rückgabe",
|
||||
promoLinkHref: "/seite/rueckgabe",
|
||||
navigation: [
|
||||
{ label: "Shop", href: "/shop" },
|
||||
{ label: "Kollektionen", href: "/kollektionen" },
|
||||
{ label: "Studio", href: "/seite/studio" },
|
||||
{ label: "Journal", href: "/seite/journal" },
|
||||
],
|
||||
heroEyebrow: "Neue Kollektion",
|
||||
heroTitle: "Bewegung,\ndie bleibt.",
|
||||
heroText: "Matten, Ringe und Studio-Essentials, die unsere Trainerinnen selbst benutzen. Für das Studio und für zu Hause.",
|
||||
heroPrimaryLabel: "Kollektion entdecken",
|
||||
heroPrimaryHref: "/shop",
|
||||
heroSecondaryLabel: "Mehr über Sanamare",
|
||||
heroSecondaryHref: "/seite/ueber-uns",
|
||||
showTrustBar: true,
|
||||
trustItems: [
|
||||
{ icon: "truck", title: "Kostenloser Versand ab 80 €", text: "Lieferung in 2–4 Werktagen, klimaneutral." },
|
||||
{ icon: "return", title: "30 Tage Rückgabe", text: "Kostenlos, ohne Angabe von Gründen." },
|
||||
{ icon: "lock", title: "Sichere Zahlung", text: "Kauf auf Rechnung, PayPal, Karte, Klarna." },
|
||||
{ icon: "chat", title: "Beratung aus dem Studio", text: "Mo–Fr 9–18 Uhr, persönlich und ehrlich." },
|
||||
],
|
||||
showCategories: true,
|
||||
categoriesEyebrow: "Kollektionen",
|
||||
categoriesTitle: "Alles für dein Studio",
|
||||
showFeatured: true,
|
||||
featuredEyebrow: "Neu im Studio",
|
||||
featuredTitle: "Was unsere Trainerinnen gerade benutzen",
|
||||
showQuote: true,
|
||||
quoteText: "„Seit die Matte hier liegt, rolle ich sie morgens einfach aus. Zehn Minuten, jeden Tag.“",
|
||||
quoteAuthor: "Marie K. · Kundin seit 2024",
|
||||
footerClaim: "Pilates-Equipment und Studio-Essentials, ausgewählt von Trainerinnen. Bewegung, die bleibt.",
|
||||
showNewsletter: true,
|
||||
darkHeader: false,
|
||||
},
|
||||
checkout: {
|
||||
guestCheckout: true,
|
||||
requireTerms: true,
|
||||
requirePhone: false,
|
||||
minOrderValue: 0,
|
||||
freeShippingHint: true,
|
||||
countries: ["DE", "AT", "CH"],
|
||||
},
|
||||
};
|
||||
|
||||
export type SettingsSection = keyof ShopSettings;
|
||||
|
||||
export const getSettings = cache(async (): Promise<ShopSettings> => {
|
||||
const rows = await db.setting.findMany();
|
||||
const result = structuredClone(DEFAULT_SETTINGS);
|
||||
for (const row of rows) {
|
||||
if (row.key in result && row.value && typeof row.value === "object") {
|
||||
const key = row.key as SettingsSection;
|
||||
Object.assign(result[key], row.value as object);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
export async function saveSettings<K extends SettingsSection>(section: K, value: Partial<ShopSettings[K]>) {
|
||||
const current = (await getSettings())[section];
|
||||
const merged = { ...current, ...value };
|
||||
await db.setting.upsert({
|
||||
where: { key: section },
|
||||
create: { key: section, value: merged as object },
|
||||
update: { value: merged as object },
|
||||
});
|
||||
}
|
||||
|
||||
export const COUNTRIES: Record<string, string> = {
|
||||
DE: "Deutschland",
|
||||
AT: "Österreich",
|
||||
CH: "Schweiz",
|
||||
NL: "Niederlande",
|
||||
BE: "Belgien",
|
||||
LU: "Luxemburg",
|
||||
FR: "Frankreich",
|
||||
IT: "Italien",
|
||||
ES: "Spanien",
|
||||
DK: "Dänemark",
|
||||
PL: "Polen",
|
||||
};
|
||||
9
src/lib/slug.ts
Normal file
9
src/lib/slug.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
export function slugify(input: string): string {
|
||||
return input
|
||||
.toLowerCase()
|
||||
.replace(/ä/g, "ae").replace(/ö/g, "oe").replace(/ü/g, "ue").replace(/ß/g, "ss")
|
||||
.normalize("NFKD").replace(/[̀-ͯ]/g, "")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 80);
|
||||
}
|
||||
22
src/lib/status.ts
Normal file
22
src/lib/status.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import type { OrderStatus, PaymentStatus } from "@prisma/client";
|
||||
|
||||
export const ORDER_STATUS: Record<OrderStatus, { label: string; tone: "neutral" | "gold" | "success" | "danger" }> = {
|
||||
PENDING: { label: "Offen", tone: "gold" },
|
||||
PAID: { label: "Bezahlt", tone: "success" },
|
||||
PROCESSING: { label: "In Bearbeitung", tone: "gold" },
|
||||
SHIPPED: { label: "Versendet", tone: "success" },
|
||||
COMPLETED: { label: "Abgeschlossen", tone: "neutral" },
|
||||
CANCELLED: { label: "Storniert", tone: "danger" },
|
||||
REFUNDED: { label: "Erstattet", tone: "neutral" },
|
||||
};
|
||||
|
||||
export const PAYMENT_STATUS: Record<PaymentStatus, { label: string; tone: "neutral" | "gold" | "success" | "danger" }> = {
|
||||
OPEN: { label: "Zahlung offen", tone: "gold" },
|
||||
AUTHORIZED: { label: "Autorisiert", tone: "gold" },
|
||||
PAID: { label: "Bezahlt", tone: "success" },
|
||||
FAILED: { label: "Fehlgeschlagen", tone: "danger" },
|
||||
REFUNDED: { label: "Erstattet", tone: "neutral" },
|
||||
};
|
||||
|
||||
export const dateFmt = new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeStyle: "short", timeZone: "Europe/Berlin" });
|
||||
export const dayFmt = new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeZone: "Europe/Berlin" });
|
||||
166
src/styles/admin.css
Normal file
166
src/styles/admin.css
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
/* Admin-Bereich: ruhig, übersichtlich, auf den Tokens des Design Systems. */
|
||||
.ad { display: grid; grid-template-columns: 1fr; min-height: 100vh; background: var(--surface); }
|
||||
@media (min-width: 1024px) { .ad { grid-template-columns: 260px 1fr; } }
|
||||
|
||||
/* Seitenleiste */
|
||||
.ad-side { background: var(--surface); border-right: var(--hairline) solid var(--line); display: none; flex-direction: column; position: sticky; top: 0; height: 100vh; overflow-y: auto; }
|
||||
@media (min-width: 1024px) { .ad-side { display: flex; } }
|
||||
.ad-side__brand { display: flex; align-items: center; gap: var(--space-3); padding: var(--space-5) var(--space-5) var(--space-4); text-decoration: none; color: var(--ink); }
|
||||
.ad-side__brand img { height: 36px; width: auto; }
|
||||
.ad-side__brand strong { display: block; font-size: 15px; letter-spacing: 0.24em; text-transform: uppercase; font-weight: 400; }
|
||||
.ad-side__brand small { display: block; font-size: 12px; color: var(--ink-muted); letter-spacing: 0.04em; }
|
||||
.ad-nav { padding: var(--space-2) var(--space-3) var(--space-5); display: flex; flex-direction: column; gap: 2px; }
|
||||
.ad-nav__group { margin: var(--space-4) var(--space-3) var(--space-1); font-size: 11px; line-height: 16px; letter-spacing: 0.16em; text-transform: uppercase; color: var(--ink-muted); font-weight: 500; }
|
||||
.ad-nav a { display: flex; align-items: center; gap: var(--space-3); min-height: 40px; padding: 0 var(--space-3); border-radius: var(--radius-sm); color: var(--ink); text-decoration: none; font-size: 15px; }
|
||||
.ad-nav a .sm-icon { width: 20px; height: 20px; color: var(--ink-muted); }
|
||||
.ad-nav a:hover { background: var(--surface-sunken); }
|
||||
.ad-nav a[aria-current="page"] { background: var(--noir); color: var(--on-noir); }
|
||||
.ad-nav a[aria-current="page"] .sm-icon { color: var(--gold); }
|
||||
.ad-nav__badge { margin-left: auto; min-width: 22px; height: 22px; padding: 0 6px; border-radius: var(--radius-pill); background: var(--gold-soft); color: var(--gold-deep); font-size: 12px; font-weight: 500; display: grid; place-content: center; }
|
||||
.ad-side__foot { margin-top: auto; padding: var(--space-4) var(--space-5); border-top: var(--hairline) solid var(--line); font-size: 14px; }
|
||||
.ad-side__foot p { margin: 0; }
|
||||
.ad-side__foot .ad-muted { font-size: 12px; }
|
||||
|
||||
/* Kopfzeile mobil */
|
||||
.ad-top { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); padding: var(--space-2) var(--space-4); border-bottom: var(--hairline) solid var(--line); background: var(--surface-raised); position: sticky; top: 0; z-index: 20; }
|
||||
@media (min-width: 1024px) { .ad-top { display: none; } }
|
||||
.ad-top .sm-mnav__panel { padding: var(--space-3); }
|
||||
.ad-top .sm-mnav__panel .ad-nav a { text-transform: none; letter-spacing: 0; font-size: 15px; border-bottom: 0; min-height: 44px; }
|
||||
.ad-top .sm-mnav { display: block; }
|
||||
|
||||
/* Inhalt */
|
||||
.ad-main { min-width: 0; padding: var(--space-5) var(--space-4) var(--space-9); }
|
||||
@media (min-width: 768px) { .ad-main { padding: var(--space-6) var(--space-6) var(--space-9); } }
|
||||
.ad-wrap { max-width: 1200px; margin: 0 auto; }
|
||||
.ad-wrap--narrow { max-width: 860px; }
|
||||
.ad-head { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: var(--space-4); margin-bottom: var(--space-6); }
|
||||
.ad-head h1 { font-family: var(--font-serif); font-weight: 500; font-size: 36px; line-height: 1.1; margin: 0; }
|
||||
.ad-head p { margin: var(--space-2) 0 0; color: var(--ink-muted); }
|
||||
.ad-back { display: inline-flex; align-items: center; gap: var(--space-1); font-size: 14px; color: var(--ink-muted); text-decoration: none; margin-bottom: var(--space-2); }
|
||||
.ad-back:hover { color: var(--ink); }
|
||||
.ad-muted { color: var(--ink-muted); }
|
||||
|
||||
/* Karten */
|
||||
.ad-card { background: var(--surface-raised); border: var(--hairline) solid var(--line); border-radius: var(--radius-md); }
|
||||
.ad-card + .ad-card { margin-top: var(--space-5); }
|
||||
.ad-card__head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); padding: var(--space-4) var(--space-5); border-bottom: var(--hairline) solid var(--line); }
|
||||
.ad-card__head h2 { font-size: 17px; line-height: 24px; font-weight: 500; margin: 0; }
|
||||
.ad-card__head p { margin: 2px 0 0; font-size: 14px; color: var(--ink-muted); }
|
||||
.ad-card__body { padding: var(--space-5); }
|
||||
.ad-card__foot { padding: var(--space-4) var(--space-5); border-top: var(--hairline) solid var(--line); display: flex; justify-content: flex-end; gap: var(--space-3); background: var(--surface); border-radius: 0 0 var(--radius-md) var(--radius-md); }
|
||||
.ad-grid { display: grid; gap: var(--space-5); }
|
||||
@media (min-width: 1024px) { .ad-grid--2-1 { grid-template-columns: 2fr 1fr; align-items: start; } .ad-grid--2 { grid-template-columns: 1fr 1fr; } }
|
||||
|
||||
/* Kennzahlen */
|
||||
.ad-kpis { display: grid; gap: var(--space-4); grid-template-columns: repeat(2, 1fr); margin-bottom: var(--space-5); }
|
||||
@media (min-width: 1024px) { .ad-kpis { grid-template-columns: repeat(4, 1fr); } }
|
||||
.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__hint { font-size: 13px; color: var(--ink-muted); margin-top: var(--space-1); }
|
||||
|
||||
/* Diagramm */
|
||||
.ad-chart { display: flex; align-items: flex-end; gap: 4px; height: 160px; }
|
||||
.ad-chart__bar { flex: 1; background: var(--gold); border-radius: 2px 2px 0 0; min-height: 2px; position: relative; }
|
||||
.ad-chart__bar:hover { background: var(--gold-deep); }
|
||||
.ad-chart__axis { display: flex; justify-content: space-between; font-size: 12px; color: var(--ink-muted); margin-top: var(--space-2); }
|
||||
|
||||
/* Tabellen */
|
||||
.ad-table-wrap { overflow-x: auto; }
|
||||
.ad-table { width: 100%; border-collapse: collapse; font-size: 15px; line-height: 22px; }
|
||||
.ad-table th { text-align: left; font-size: 13px; font-weight: 500; color: var(--ink-muted); padding: var(--space-3) var(--space-4); border-bottom: var(--hairline) solid var(--line); white-space: nowrap; background: var(--surface); }
|
||||
.ad-table td { padding: var(--space-3) var(--space-4); border-bottom: var(--hairline) solid var(--line); vertical-align: middle; font-variant-numeric: tabular-nums; }
|
||||
.ad-table tr:last-child td { border-bottom: 0; }
|
||||
.ad-table tbody tr:hover { background: var(--surface); }
|
||||
.ad-table .num { text-align: right; white-space: nowrap; }
|
||||
.ad-table a.ad-rowlink { color: var(--ink); font-weight: 500; text-decoration: none; }
|
||||
.ad-table a.ad-rowlink:hover { text-decoration: underline; }
|
||||
.ad-thumb { width: 44px; height: 55px; border-radius: var(--radius-sm); background: var(--surface-sunken); object-fit: cover; display: block; }
|
||||
.ad-empty { padding: var(--space-8) var(--space-5); text-align: center; color: var(--ink-muted); }
|
||||
.ad-empty strong { display: block; color: var(--ink); font-size: 18px; margin-bottom: var(--space-2); font-weight: 500; }
|
||||
|
||||
/* Status-Pillen */
|
||||
.ad-pill { display: inline-flex; align-items: center; gap: 6px; height: 24px; padding: 0 10px; border-radius: var(--radius-pill); font-size: 13px; font-weight: 500; white-space: nowrap; background: var(--surface-sunken); color: var(--ink-muted); }
|
||||
.ad-pill::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
|
||||
.ad-pill--gold { background: var(--gold-soft); color: var(--gold-deep); }
|
||||
.ad-pill--success { background: var(--success-soft); color: var(--success); }
|
||||
.ad-pill--danger { background: var(--danger-soft); color: var(--danger); }
|
||||
|
||||
/* Werkzeugleiste */
|
||||
.ad-toolbar { display: flex; flex-wrap: wrap; gap: var(--space-3); align-items: center; padding: var(--space-4) var(--space-5); border-bottom: var(--hairline) solid var(--line); }
|
||||
.ad-toolbar .sm-input { min-height: var(--control-height-sm); max-width: 320px; }
|
||||
.ad-tabs { display: flex; gap: var(--space-1); flex-wrap: wrap; }
|
||||
.ad-tab { display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0 var(--space-3); border-radius: var(--radius-pill); font-size: 14px; color: var(--ink); text-decoration: none; border: var(--hairline) solid transparent; }
|
||||
.ad-tab:hover { background: var(--surface-sunken); }
|
||||
.ad-tab.is-active { background: var(--noir); color: var(--on-noir); }
|
||||
.ad-tab span { font-size: 12px; opacity: 0.7; }
|
||||
|
||||
/* Formulare */
|
||||
.ad-form .sm-field + .sm-field { margin-top: var(--space-4); }
|
||||
.ad-form .sm-form-row + .sm-field, .ad-form .sm-field + .sm-form-row { margin-top: var(--space-4); }
|
||||
.ad-form .sm-textarea { min-height: 120px; padding: var(--space-3) var(--space-4); }
|
||||
.ad-switch { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--space-4); padding: var(--space-3) 0; cursor: pointer; }
|
||||
.ad-switch + .ad-switch { border-top: var(--hairline) solid var(--line); }
|
||||
.ad-switch__text strong { display: block; font-weight: 500; }
|
||||
.ad-switch__text small { display: block; color: var(--ink-muted); font-size: 14px; line-height: 20px; }
|
||||
.ad-switch input { appearance: none; -webkit-appearance: none; flex: none; width: 44px; height: 26px; border-radius: var(--radius-pill); background: var(--line-strong); position: relative; cursor: pointer; transition: background 150ms; margin-top: 2px; }
|
||||
.ad-switch input::after { content: ""; position: absolute; top: 3px; left: 3px; width: 20px; height: 20px; border-radius: 50%; background: var(--surface-raised); transition: transform 150ms; }
|
||||
.ad-switch input:checked { background: var(--success); }
|
||||
.ad-switch input:checked::after { transform: translateX(18px); }
|
||||
.ad-perm-group { border: var(--hairline) solid var(--line); border-radius: var(--radius-md); padding: var(--space-3) var(--space-4); }
|
||||
.ad-perm-group + .ad-perm-group { margin-top: var(--space-3); }
|
||||
.ad-perm-group legend { font-weight: 500; padding: 0 var(--space-2); }
|
||||
.ad-perm-grid { display: grid; gap: 0 var(--space-4); }
|
||||
@media (min-width: 768px) { .ad-perm-grid { grid-template-columns: 1fr 1fr; } }
|
||||
.ad-perm-grid .sm-check { font-size: 15px; min-height: 40px; }
|
||||
.ad-savebar { position: sticky; bottom: 0; z-index: 5; display: flex; justify-content: flex-end; align-items: center; gap: var(--space-3); padding: var(--space-3) 0; margin-top: var(--space-5); background: linear-gradient(to top, var(--surface) 70%, transparent); }
|
||||
.ad-savebar__msg { margin-right: auto; font-size: 14px; }
|
||||
.ad-ok { color: var(--success); display: inline-flex; gap: 6px; align-items: center; }
|
||||
.ad-err { color: var(--danger); display: inline-flex; gap: 6px; align-items: center; }
|
||||
|
||||
/* Bilder-Verwaltung */
|
||||
.ad-images { display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: var(--space-3); }
|
||||
.ad-image { position: relative; aspect-ratio: 4 / 5; border-radius: var(--radius-sm); overflow: hidden; background: var(--surface-sunken); border: var(--hairline) solid var(--line); }
|
||||
.ad-image img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.ad-image__actions { position: absolute; inset: auto 4px 4px 4px; display: flex; gap: 4px; justify-content: flex-end; }
|
||||
.ad-image__actions button { width: 32px; height: 32px; display: grid; place-content: center; border: 0; border-radius: var(--radius-sm); background: var(--surface-raised); box-shadow: var(--shadow-sm); cursor: pointer; }
|
||||
.ad-image__first { position: absolute; top: 4px; left: 4px; font-size: 11px; background: var(--noir); color: var(--on-noir); padding: 1px 6px; border-radius: var(--radius-sm); }
|
||||
.ad-upload { aspect-ratio: 4 / 5; border: 1px dashed var(--line-strong); border-radius: var(--radius-sm); display: grid; place-content: center; text-align: center; gap: var(--space-1); color: var(--ink-muted); font-size: 13px; cursor: pointer; background: var(--surface); }
|
||||
.ad-upload:hover { border-color: var(--ink); color: var(--ink); }
|
||||
.ad-upload .sm-icon { margin: 0 auto; }
|
||||
|
||||
/* Varianten-Editor */
|
||||
.ad-variants { width: 100%; border-collapse: collapse; }
|
||||
.ad-variants th { font-size: 13px; font-weight: 500; color: var(--ink-muted); text-align: left; padding: 0 var(--space-2) var(--space-2); }
|
||||
.ad-variants td { padding: var(--space-1) var(--space-2); }
|
||||
.ad-variants .sm-input { min-height: var(--control-height-sm); }
|
||||
|
||||
/* Zeitleiste */
|
||||
.ad-timeline { list-style: none; margin: 0; padding: 0; }
|
||||
.ad-timeline li { position: relative; padding: 0 0 var(--space-4) var(--space-5); font-size: 14px; line-height: 20px; }
|
||||
.ad-timeline li::before { content: ""; position: absolute; left: 4px; top: 6px; width: 8px; height: 8px; border-radius: 50%; background: var(--gold); }
|
||||
.ad-timeline li::after { content: ""; position: absolute; left: 7px; top: 18px; bottom: 0; width: 1px; background: var(--line); }
|
||||
.ad-timeline li:last-child::after { display: none; }
|
||||
.ad-timeline small { display: block; color: var(--ink-muted); font-size: 12px; }
|
||||
|
||||
/* Einrichtungs-Checkliste */
|
||||
.ad-setup { list-style: none; margin: 0; padding: 0; }
|
||||
.ad-setup li { display: flex; align-items: center; gap: var(--space-3); padding: var(--space-3) 0; border-bottom: var(--hairline) solid var(--line); }
|
||||
.ad-setup li:last-child { border-bottom: 0; }
|
||||
.ad-setup__dot { width: 24px; height: 24px; border-radius: 50%; border: var(--hairline) solid var(--line-strong); display: grid; place-content: center; flex: none; }
|
||||
.ad-setup li.is-done .ad-setup__dot { background: var(--success); border-color: var(--success); color: var(--surface-raised); }
|
||||
.ad-setup li.is-done .ad-setup__label { color: var(--ink-muted); text-decoration: line-through; }
|
||||
.ad-setup a { margin-left: auto; font-size: 14px; white-space: nowrap; }
|
||||
.ad-dl { display: grid; grid-template-columns: auto 1fr; gap: var(--space-2) var(--space-4); margin: 0; font-size: 15px; }
|
||||
.ad-dl dt { color: var(--ink-muted); }
|
||||
.ad-dl dd { margin: 0; }
|
||||
.ad-login { min-height: 100vh; display: grid; place-items: center; padding: var(--space-5); background: var(--surface); }
|
||||
.ad-login__box { width: 100%; max-width: 420px; }
|
||||
.ad-help { font-size: 14px; line-height: 22px; color: var(--ink-muted); background: var(--surface); border: var(--hairline) solid var(--line); border-radius: var(--radius-sm); padding: var(--space-3) var(--space-4); }
|
||||
.ad-help code { font-size: 13px; background: var(--surface-sunken); padding: 1px 4px; border-radius: 2px; word-break: break-all; }
|
||||
.ad-row-actions { display: flex; gap: var(--space-2); justify-content: flex-end; }
|
||||
.ad-iconbtn { width: 36px; height: 36px; display: inline-grid; place-content: center; border: var(--hairline) solid var(--line); border-radius: var(--radius-sm); background: var(--surface-raised); color: var(--ink); cursor: pointer; text-decoration: none; }
|
||||
.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); }
|
||||
329
src/styles/bundle.css
Normal file
329
src/styles/bundle.css
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
/* Sanamare — Komponenten. Reines CSS auf den Tokens aus tokens.json (tokens.css wird davor geladen). Präfix sm-. */
|
||||
|
||||
/* ---------- Grundlagen ---------- */
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
html { -webkit-text-size-adjust: 100%; }
|
||||
body { margin: 0; background: var(--surface); color: var(--ink); font-family: var(--font-sans); font-size: 16px; line-height: 26px; -webkit-font-smoothing: antialiased; }
|
||||
img, svg { display: block; max-width: 100%; }
|
||||
a { color: var(--link); text-underline-offset: 3px; }
|
||||
button { font: inherit; color: inherit; }
|
||||
:where(a, button, input, select, textarea, summary, [tabindex]):focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
|
||||
.sm-sans { font-family: var(--font-sans); }
|
||||
.sm-serif { font-family: var(--font-serif); }
|
||||
.sm-container { max-width: var(--container-max); margin-inline: auto; padding-inline: var(--space-4); }
|
||||
@media (min-width: 768px) { .sm-container { padding-inline: var(--space-5); } }
|
||||
@media (min-width: 1024px) { .sm-container { padding-inline: var(--space-6); } }
|
||||
.sm-stack > * + * { margin-top: var(--space-4); }
|
||||
.sm-muted { color: var(--ink-muted); }
|
||||
.sm-visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition-duration: 0s !important; animation-duration: 0s !important; } }
|
||||
|
||||
/* ---------- Icons (Linien, 1.5px, currentColor) ---------- */
|
||||
.sm-icon { width: 24px; height: 24px; flex: none; stroke: currentColor; fill: none; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.sm-icon--sm { width: 18px; height: 18px; }
|
||||
|
||||
/* ---------- Abschnittsüberschrift (Eyebrow · Display · Zierlinie) ---------- */
|
||||
.sm-heading { text-align: center; max-width: var(--container-text); margin-inline: auto; }
|
||||
.sm-heading--left { text-align: left; margin-inline: 0; }
|
||||
.sm-heading__eyebrow { display: block; color: var(--gold-deep); text-transform: uppercase; margin-bottom: var(--space-3); }
|
||||
.sm-heading__title { margin: 0; color: var(--ink); }
|
||||
.sm-heading__rule { display: block; width: 48px; height: var(--hairline); background: var(--gold); margin: var(--space-4) auto 0; }
|
||||
.sm-heading--left .sm-heading__rule { margin-inline: 0; }
|
||||
.sm-heading__lead { margin: var(--space-4) 0 0; color: var(--ink-muted); }
|
||||
|
||||
/* ---------- Button ---------- */
|
||||
.sm-btn { display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2); min-height: var(--control-height); min-width: var(--touch-target); padding: 0 var(--space-5); border: var(--hairline) solid transparent; border-radius: var(--radius-sm); background: transparent; color: var(--ink); font-size: 14px; line-height: 20px; font-weight: 500; letter-spacing: 0.08em; text-transform: uppercase; text-decoration: none; cursor: pointer; white-space: nowrap; transition: background-color 200ms, color 200ms, border-color 200ms; }
|
||||
.sm-btn--primary { background: var(--noir); border-color: var(--noir); color: var(--on-noir); }
|
||||
.sm-btn--primary:hover { background: var(--ink-muted); border-color: var(--ink-muted); }
|
||||
.sm-btn--secondary { border-color: var(--line-strong); color: var(--ink); background: var(--surface-raised); }
|
||||
.sm-btn--secondary:hover { border-color: var(--ink); }
|
||||
.sm-btn--gold { background: var(--gold); border-color: var(--gold); color: var(--on-gold); }
|
||||
.sm-btn--gold:hover { background: var(--gold-deep); border-color: var(--gold-deep); color: var(--surface); }
|
||||
[data-theme="dark"] .sm-btn--gold:hover { color: var(--on-gold); }
|
||||
.sm-btn--ghost { padding-inline: var(--space-2); color: var(--gold-deep); text-transform: none; letter-spacing: 0; font-size: 16px; }
|
||||
.sm-btn--ghost:hover { text-decoration: underline; text-underline-offset: 4px; }
|
||||
.sm-btn--sm { min-height: var(--control-height-sm); padding-inline: var(--space-4); font-size: 13px; }
|
||||
.sm-btn--lg { min-height: var(--control-height-lg); padding-inline: var(--space-6); font-size: 15px; }
|
||||
.sm-btn--block { display: flex; width: 100%; }
|
||||
.sm-btn--icon { padding: 0; width: var(--control-height); min-width: 0; }
|
||||
.sm-btn--icon.sm-btn--sm { width: var(--control-height-sm); }
|
||||
.sm-btn[disabled], .sm-btn[aria-disabled="true"] { cursor: not-allowed; background: var(--surface-sunken); border-color: var(--line); color: var(--ink-subtle); }
|
||||
.sm-btn.is-loading { position: relative; color: transparent; pointer-events: none; }
|
||||
.sm-btn.is-loading::after { content: ""; position: absolute; width: 18px; height: 18px; border: 2px solid var(--on-noir); border-right-color: transparent; border-radius: var(--radius-pill); animation: sm-spin 800ms linear infinite; }
|
||||
.sm-btn--secondary.is-loading::after { border-color: var(--ink); border-right-color: transparent; }
|
||||
@keyframes sm-spin { to { transform: rotate(360deg); } }
|
||||
.sm-btn-row { display: flex; flex-wrap: wrap; gap: var(--space-3); align-items: center; }
|
||||
|
||||
/* ---------- Formularfeld ---------- */
|
||||
.sm-field { display: block; }
|
||||
.sm-field + .sm-field { margin-top: var(--space-5); }
|
||||
.sm-field__label { display: block; margin-bottom: var(--space-2); font-size: 14px; line-height: 20px; font-weight: 500; color: var(--ink); }
|
||||
.sm-field__label .sm-optional { color: var(--ink-muted); font-weight: 400; }
|
||||
.sm-input, .sm-select, .sm-textarea { display: block; width: 100%; min-height: var(--control-height); padding: 0 var(--space-4); border: var(--hairline) solid var(--line-strong); border-radius: var(--radius-sm); background: var(--surface-raised); color: var(--ink); font: inherit; font-size: 16px; line-height: 26px; transition: border-color 200ms; }
|
||||
.sm-textarea { padding-block: var(--space-3); min-height: 120px; resize: vertical; }
|
||||
.sm-input::placeholder, .sm-textarea::placeholder { color: var(--ink-subtle); }
|
||||
.sm-input:hover, .sm-select:hover, .sm-textarea:hover { border-color: var(--ink); }
|
||||
.sm-input:focus-visible, .sm-select:focus-visible, .sm-textarea:focus-visible { border-color: var(--ink); outline-offset: 2px; }
|
||||
.sm-select { appearance: none; -webkit-appearance: none; padding-right: var(--space-7); }
|
||||
.sm-select-wrap { position: relative; display: block; }
|
||||
.sm-select-wrap::after { content: ""; position: absolute; right: var(--space-4); top: 50%; width: 8px; height: 8px; border-right: 1.5px solid var(--ink-muted); border-bottom: 1.5px solid var(--ink-muted); transform: translateY(-70%) rotate(45deg); pointer-events: none; }
|
||||
.sm-field__hint { display: block; margin-top: var(--space-2); font-size: 12px; line-height: 16px; color: var(--ink-muted); }
|
||||
.sm-field__error { display: flex; gap: var(--space-1); align-items: flex-start; margin-top: var(--space-2); font-size: 12px; line-height: 16px; color: var(--danger); }
|
||||
.sm-field__error .sm-icon { width: 16px; height: 16px; }
|
||||
.sm-field.is-invalid .sm-input, .sm-field.is-invalid .sm-select, .sm-field.is-invalid .sm-textarea { border-color: var(--danger); background: var(--danger-soft); }
|
||||
.sm-field.is-valid .sm-input { border-color: var(--success); }
|
||||
.sm-input[disabled] { background: var(--surface-sunken); color: var(--ink-subtle); border-color: var(--line); }
|
||||
.sm-input-group { display: flex; align-items: stretch; }
|
||||
.sm-input-group .sm-input { border-radius: var(--radius-sm) 0 0 var(--radius-sm); }
|
||||
.sm-input-group .sm-btn { border-radius: 0 var(--radius-sm) var(--radius-sm) 0; }
|
||||
.sm-form-row { display: grid; gap: var(--space-4); }
|
||||
@media (min-width: 480px) { .sm-form-row { grid-template-columns: 1fr 1fr; } }
|
||||
.sm-form-row .sm-field + .sm-field { margin-top: 0; }
|
||||
.sm-form-row + .sm-field, .sm-form-row + .sm-form-row { margin-top: var(--space-5); }
|
||||
|
||||
/* Checkbox & Radio */
|
||||
.sm-check { display: flex; align-items: flex-start; gap: var(--space-3); min-height: var(--touch-target); padding-block: var(--space-2); cursor: pointer; font-size: 16px; line-height: 26px; }
|
||||
.sm-check input { appearance: none; -webkit-appearance: none; flex: none; width: 22px; height: 22px; margin: 2px 0 0; border: var(--hairline) solid var(--line-strong); border-radius: var(--radius-sm); background: var(--surface-raised); cursor: pointer; display: grid; place-content: center; }
|
||||
.sm-check input[type="radio"] { border-radius: var(--radius-pill); }
|
||||
.sm-check input::before { content: ""; width: 12px; height: 12px; background: var(--on-noir); transform: scale(0); clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%); transition: transform 150ms; }
|
||||
.sm-check input[type="radio"]::before { clip-path: none; border-radius: var(--radius-pill); width: 10px; height: 10px; }
|
||||
.sm-check input:checked { background: var(--noir); border-color: var(--noir); }
|
||||
.sm-check input:checked::before { transform: scale(1); }
|
||||
.sm-check__text small { display: block; color: var(--ink-muted); font-size: 14px; line-height: 22px; }
|
||||
|
||||
/* ---------- Mengenstepper ---------- */
|
||||
.sm-qty { display: inline-flex; align-items: center; height: var(--control-height); border: var(--hairline) solid var(--line-strong); border-radius: var(--radius-pill); background: var(--surface-raised); }
|
||||
.sm-qty--sm { height: var(--control-height-sm); }
|
||||
.sm-qty__btn { width: var(--touch-target); height: 100%; border: 0; background: transparent; color: var(--ink); cursor: pointer; display: grid; place-content: center; border-radius: var(--radius-pill); }
|
||||
.sm-qty__btn:hover { color: var(--gold-deep); }
|
||||
.sm-qty__btn[disabled] { color: var(--ink-subtle); cursor: not-allowed; }
|
||||
.sm-qty__btn:focus-visible { outline-offset: -4px; }
|
||||
.sm-qty__value { width: 40px; height: 100%; border: 0; background: transparent; text-align: center; font: inherit; font-size: 16px; font-weight: 500; color: var(--ink); -moz-appearance: textfield; font-variant-numeric: tabular-nums; }
|
||||
.sm-qty__value::-webkit-inner-spin-button, .sm-qty__value::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
|
||||
|
||||
/* ---------- Badge ---------- */
|
||||
.sm-badge { display: inline-flex; align-items: center; gap: var(--space-1); height: 24px; padding: 0 var(--space-2); border-radius: var(--radius-sm); font-size: 12px; line-height: 16px; font-weight: 500; letter-spacing: 0.06em; text-transform: uppercase; background: var(--surface-sunken); color: var(--ink); white-space: nowrap; }
|
||||
.sm-badge--new { background: var(--gold-soft); color: var(--gold-deep); }
|
||||
.sm-badge--best { background: var(--gold); color: var(--on-gold); }
|
||||
.sm-badge--sale { background: var(--noir); color: var(--on-noir); }
|
||||
.sm-badge--stock { background: var(--success-soft); color: var(--success); text-transform: none; letter-spacing: 0; }
|
||||
.sm-badge--low { background: var(--gold-soft); color: var(--gold-deep); text-transform: none; letter-spacing: 0; }
|
||||
.sm-badge--soldout { background: var(--danger-soft); color: var(--danger); text-transform: none; letter-spacing: 0; }
|
||||
.sm-badge .sm-dot { width: 6px; height: 6px; border-radius: var(--radius-pill); background: currentColor; }
|
||||
|
||||
/* ---------- Preis ---------- */
|
||||
.sm-price { display: inline-flex; align-items: baseline; flex-wrap: wrap; gap: var(--space-2); font-size: 18px; line-height: 24px; font-weight: 500; color: var(--ink); font-variant-numeric: tabular-nums; }
|
||||
.sm-price--lg { font-size: 28px; line-height: 32px; }
|
||||
.sm-price__old { font-size: 0.78em; font-weight: 400; color: var(--ink-muted); text-decoration: line-through; }
|
||||
.sm-price__save { font-size: 12px; line-height: 16px; font-weight: 500; color: var(--gold-deep); background: var(--gold-soft); padding: 0 var(--space-2); border-radius: var(--radius-sm); align-self: center; }
|
||||
.sm-price__note { display: block; margin-top: var(--space-1); font-size: 12px; line-height: 16px; font-weight: 400; color: var(--ink-muted); }
|
||||
.sm-price__note a { color: inherit; }
|
||||
|
||||
/* ---------- Sterne ---------- */
|
||||
.sm-stars { display: inline-flex; align-items: center; gap: var(--space-1); color: var(--gold); font-size: 12px; line-height: 16px; }
|
||||
.sm-stars svg { width: 14px; height: 14px; fill: currentColor; stroke: none; }
|
||||
.sm-stars svg.is-empty { fill: none; stroke: currentColor; stroke-width: 1.5; }
|
||||
.sm-stars__count { color: var(--ink-muted); margin-left: var(--space-1); }
|
||||
|
||||
/* ---------- Bildplatzhalter (kein Produktfoto vorhanden) ---------- */
|
||||
.sm-ph { position: relative; display: grid; place-content: center; background: var(--surface-sunken); color: var(--ink-subtle); aspect-ratio: var(--product-image-ratio); overflow: hidden; }
|
||||
.sm-ph--wide { aspect-ratio: 16 / 9; }
|
||||
.sm-ph--square { aspect-ratio: 1; }
|
||||
.sm-ph::before { content: ""; position: absolute; inset: 18%; border: var(--hairline) solid var(--line); border-radius: var(--radius-pill); }
|
||||
.sm-ph::after { content: ""; position: absolute; inset: 32%; border: var(--hairline) solid var(--line); border-radius: var(--radius-pill); }
|
||||
.sm-ph span { position: relative; z-index: 1; font-size: 12px; line-height: 16px; letter-spacing: 0.14em; text-transform: uppercase; }
|
||||
|
||||
/* ---------- Produktkarte ---------- */
|
||||
.sm-card { position: relative; display: flex; flex-direction: column; gap: var(--space-3); color: var(--ink); text-decoration: none; }
|
||||
.sm-card__media { position: relative; overflow: hidden; border-radius: var(--radius-md); background: var(--surface-sunken); aspect-ratio: var(--product-image-ratio); }
|
||||
.sm-card__media > img, .sm-card__media > .sm-ph { width: 100%; height: 100%; object-fit: cover; transition: transform 400ms ease; }
|
||||
.sm-card:hover .sm-card__media > img, .sm-card:hover .sm-card__media > .sm-ph { transform: scale(1.03); }
|
||||
.sm-card__badges { position: absolute; top: var(--space-3); left: var(--space-3); display: flex; gap: var(--space-1); z-index: 1; }
|
||||
.sm-card__wish { position: absolute; top: var(--space-2); right: var(--space-2); z-index: 1; width: var(--touch-target); height: var(--touch-target); display: grid; place-content: center; border: 0; border-radius: var(--radius-pill); background: var(--surface-raised); color: var(--ink); cursor: pointer; box-shadow: var(--shadow-sm); }
|
||||
.sm-card__wish:hover { color: var(--gold-deep); }
|
||||
.sm-card__quick { position: absolute; left: var(--space-3); right: var(--space-3); bottom: var(--space-3); z-index: 1; opacity: 0; transform: translateY(4px); transition: opacity 200ms, transform 200ms; }
|
||||
.sm-card:hover .sm-card__quick, .sm-card:focus-within .sm-card__quick { opacity: 1; transform: none; }
|
||||
@media (hover: none) { .sm-card__quick { display: none; } }
|
||||
.sm-card__body { display: flex; flex-direction: column; gap: var(--space-1); }
|
||||
.sm-card__title { margin: 0; font-size: 18px; line-height: 26px; font-weight: 500; }
|
||||
.sm-card__title a { color: inherit; text-decoration: none; }
|
||||
.sm-card__title a::after { content: ""; position: absolute; inset: 0; z-index: 0; }
|
||||
.sm-card__variant { font-size: 14px; line-height: 22px; color: var(--ink-muted); }
|
||||
.sm-card__swatches { display: flex; gap: var(--space-2); margin-top: var(--space-1); }
|
||||
.sm-swatch { width: 18px; height: 18px; border-radius: var(--radius-pill); border: var(--hairline) solid var(--line-strong); box-shadow: inset 0 0 0 2px var(--surface-raised); }
|
||||
.sm-swatch.is-active { border: 2px solid var(--ink); }
|
||||
.sm-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--space-5) var(--space-4); }
|
||||
@media (min-width: 768px) { .sm-grid { grid-template-columns: repeat(3, 1fr); gap: var(--space-5); } }
|
||||
@media (min-width: 1024px) { .sm-grid { grid-template-columns: repeat(4, 1fr); gap: var(--space-6) var(--space-5); } }
|
||||
|
||||
/* ---------- Header ---------- */
|
||||
.sm-header { position: sticky; top: 0; z-index: 10; background: var(--surface); border-bottom: var(--hairline) solid var(--line); }
|
||||
.sm-header.is-scrolled { box-shadow: var(--shadow-sm); }
|
||||
.sm-header__bar { display: flex; align-items: center; justify-content: space-between; gap: var(--space-4); height: 60px; }
|
||||
@media (min-width: 1024px) { .sm-header__bar { height: var(--header-height); display: grid; grid-template-columns: 1fr auto 1fr; } }
|
||||
.sm-header__logo { display: inline-flex; align-items: center; gap: var(--space-3); font-size: 22px; line-height: 28px; letter-spacing: 0.32em; text-transform: uppercase; color: var(--ink); text-decoration: none; white-space: nowrap; }
|
||||
.sm-header__logo img { height: 44px; width: auto; }
|
||||
.sm-header__logo span { padding-left: 0.1em; }
|
||||
@media (max-width: 479px) { .sm-header__logo span { display: none; } }
|
||||
/* Logo-Varianten: je Theme wird die passende Datei gezeigt (Ink auf Hell, Gold auf Dunkel) */
|
||||
.sm-logo--gold { display: none; }
|
||||
[data-theme="dark"] .sm-logo--gold { display: block; }
|
||||
[data-theme="dark"] .sm-logo--ink { display: none; }
|
||||
.sm-header__nav { display: none; }
|
||||
@media (min-width: 1024px) { .sm-header__nav { display: flex; gap: var(--space-6); justify-content: center; } }
|
||||
.sm-header__nav a { position: relative; display: inline-flex; align-items: center; height: var(--touch-target); font-size: 13px; line-height: 20px; font-weight: 500; letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink); text-decoration: none; }
|
||||
.sm-header__nav a::after { content: ""; position: absolute; left: 0; right: 0; bottom: 6px; height: var(--hairline); background: var(--gold); transform: scaleX(0); transform-origin: left; transition: transform 200ms; }
|
||||
.sm-header__nav a:hover::after, .sm-header__nav a[aria-current="page"]::after { transform: scaleX(1); }
|
||||
.sm-header__nav a[aria-current="page"] { color: var(--gold-deep); }
|
||||
.sm-header__actions { display: flex; align-items: center; gap: var(--space-1); justify-content: flex-end; }
|
||||
.sm-header__btn { position: relative; display: grid; place-content: center; width: var(--touch-target); height: var(--touch-target); border: 0; background: transparent; color: var(--ink); cursor: pointer; border-radius: var(--radius-pill); text-decoration: none; }
|
||||
.sm-header__btn:hover { color: var(--gold-deep); }
|
||||
.sm-header__btn--menu { display: grid; }
|
||||
@media (min-width: 1024px) { .sm-header__btn--menu { display: none; } }
|
||||
.sm-header__count { position: absolute; top: 4px; right: 2px; min-width: 18px; height: 18px; padding: 0 5px; border-radius: var(--radius-pill); background: var(--noir); color: var(--on-noir); font-size: 11px; line-height: 18px; font-weight: 500; text-align: center; }
|
||||
.sm-header__promo { background: var(--noir); color: var(--on-noir); text-align: center; font-size: 13px; line-height: 20px; padding: var(--space-2) var(--space-4); letter-spacing: 0.04em; }
|
||||
.sm-header__promo a { color: var(--gold); }
|
||||
|
||||
/* ---------- Breadcrumb ---------- */
|
||||
.sm-crumbs { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); margin: 0; padding: 0; list-style: none; font-size: 14px; line-height: 20px; color: var(--ink-muted); }
|
||||
.sm-crumbs a { color: var(--ink-muted); text-decoration: none; display: inline-block; padding-block: var(--space-2); }
|
||||
.sm-crumbs a:hover { color: var(--gold-deep); text-decoration: underline; }
|
||||
.sm-crumbs li + li::before { content: "/"; color: var(--line-strong); margin-right: var(--space-2); }
|
||||
.sm-crumbs [aria-current="page"] { color: var(--ink); }
|
||||
|
||||
/* ---------- Filterchips ---------- */
|
||||
.sm-chips { display: flex; flex-wrap: wrap; gap: var(--space-2); }
|
||||
.sm-chip { display: inline-flex; align-items: center; gap: var(--space-2); min-height: var(--control-height-sm); padding: 0 var(--space-4); border: var(--hairline) solid var(--line-strong); border-radius: var(--radius-pill); background: var(--surface-raised); color: var(--ink); font-size: 14px; line-height: 20px; font-weight: 500; cursor: pointer; transition: border-color 200ms, background-color 200ms; }
|
||||
.sm-chip:hover { border-color: var(--ink); }
|
||||
.sm-chip.is-active, .sm-chip[aria-pressed="true"] { background: var(--gold-soft); border-color: var(--gold-deep); color: var(--gold-deep); }
|
||||
.sm-chip__x { display: grid; place-content: center; width: 20px; height: 20px; margin-right: calc(-1 * var(--space-2)); border-radius: var(--radius-pill); }
|
||||
.sm-chip__count { color: var(--ink-muted); font-weight: 400; }
|
||||
.sm-chip.is-active .sm-chip__count { color: inherit; }
|
||||
.sm-chips__reset { font-size: 14px; color: var(--ink-muted); background: none; border: 0; min-height: var(--control-height-sm); padding: 0 var(--space-2); cursor: pointer; text-decoration: underline; text-underline-offset: 3px; }
|
||||
.sm-chips__reset:hover { color: var(--gold-deep); }
|
||||
|
||||
/* ---------- Warenkorb-Zeile ---------- */
|
||||
.sm-cartline { display: grid; grid-template-columns: 96px 1fr; gap: var(--space-4); padding: var(--space-5) 0; border-bottom: var(--hairline) solid var(--line); }
|
||||
@media (min-width: 768px) { .sm-cartline { grid-template-columns: 120px 1fr auto; align-items: start; } }
|
||||
.sm-cartline__media { border-radius: var(--radius-md); overflow: hidden; background: var(--surface-sunken); aspect-ratio: var(--product-image-ratio); }
|
||||
.sm-cartline__media img, .sm-cartline__media .sm-ph { width: 100%; height: 100%; object-fit: cover; }
|
||||
.sm-cartline__title { margin: 0; font-size: 18px; line-height: 26px; font-weight: 500; }
|
||||
.sm-cartline__title a { color: inherit; text-decoration: none; }
|
||||
.sm-cartline__meta { margin: var(--space-1) 0 0; font-size: 14px; line-height: 22px; color: var(--ink-muted); }
|
||||
.sm-cartline__controls { display: flex; align-items: center; gap: var(--space-4); margin-top: var(--space-3); flex-wrap: wrap; }
|
||||
.sm-cartline__remove { background: none; border: 0; padding: var(--space-2) 0; min-height: var(--touch-target); font-size: 14px; color: var(--ink-muted); text-decoration: underline; text-underline-offset: 3px; cursor: pointer; }
|
||||
.sm-cartline__remove:hover { color: var(--danger); }
|
||||
.sm-cartline__price { grid-column: 2; display: flex; justify-content: space-between; align-items: baseline; gap: var(--space-3); font-variant-numeric: tabular-nums; }
|
||||
@media (min-width: 768px) { .sm-cartline__price { grid-column: auto; flex-direction: column; align-items: flex-end; text-align: right; } }
|
||||
.sm-cartline__unit { font-size: 14px; line-height: 22px; color: var(--ink-muted); }
|
||||
|
||||
/* ---------- Bestellübersicht ---------- */
|
||||
.sm-summary { background: var(--surface-sunken); border-radius: var(--radius-md); padding: var(--space-5); }
|
||||
@media (min-width: 768px) { .sm-summary { padding: var(--space-6); } }
|
||||
.sm-summary__title { margin: 0 0 var(--space-4); }
|
||||
.sm-summary__row { display: flex; justify-content: space-between; gap: var(--space-4); padding: var(--space-2) 0; font-size: 16px; line-height: 26px; font-variant-numeric: tabular-nums; }
|
||||
.sm-summary__row--muted { color: var(--ink-muted); font-size: 14px; }
|
||||
.sm-summary__row--total { margin-top: var(--space-3); padding-top: var(--space-4); border-top: var(--hairline) solid var(--line-strong); font-size: 18px; font-weight: 500; }
|
||||
.sm-summary__row--total .sm-price--lg { font-size: 28px; line-height: 32px; }
|
||||
.sm-summary__cta { margin-top: var(--space-5); }
|
||||
.sm-summary__fine { margin: var(--space-3) 0 0; font-size: 12px; line-height: 16px; color: var(--ink-muted); text-align: center; }
|
||||
|
||||
/* ---------- Checkout-Schritte ---------- */
|
||||
.sm-steps { display: flex; align-items: flex-start; margin: 0; padding: 0; list-style: none; counter-reset: step; }
|
||||
.sm-steps__item { position: relative; flex: 1; display: flex; flex-direction: column; align-items: center; gap: var(--space-2); font-size: 13px; line-height: 20px; font-weight: 500; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-muted); text-align: center; }
|
||||
.sm-steps__item::before { counter-increment: step; content: counter(step); display: grid; place-content: center; width: 32px; height: 32px; border-radius: var(--radius-pill); border: var(--hairline) solid var(--line-strong); background: var(--surface-raised); color: var(--ink-muted); font-size: 14px; letter-spacing: 0; z-index: 1; }
|
||||
.sm-steps__item + .sm-steps__item::after { content: ""; position: absolute; top: 16px; right: 50%; width: 100%; height: var(--hairline); background: var(--line-strong); }
|
||||
.sm-steps__item.is-done { color: var(--ink); }
|
||||
.sm-steps__item.is-done::before { content: "✓"; background: var(--noir); border-color: var(--noir); color: var(--on-noir); font-size: 15px; }
|
||||
.sm-steps__item.is-done + .sm-steps__item::after, .sm-steps__item.is-current + .sm-steps__item::after { background: var(--line-strong); }
|
||||
.sm-steps__item.is-done + .sm-steps__item.is-done::after, .sm-steps__item.is-done + .sm-steps__item.is-current::after { background: var(--noir); }
|
||||
.sm-steps__item.is-current { color: var(--ink); }
|
||||
.sm-steps__item.is-current::before { border: 2px solid var(--noir); color: var(--ink); font-weight: 500; }
|
||||
@media (max-width: 479px) { .sm-steps__item span { font-size: 11px; letter-spacing: 0.04em; } }
|
||||
|
||||
/* ---------- Vertrauensleiste ---------- */
|
||||
.sm-trust { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-4); padding: var(--space-5) 0; border-top: var(--hairline) solid var(--line); border-bottom: var(--hairline) solid var(--line); }
|
||||
@media (min-width: 768px) { .sm-trust { grid-template-columns: repeat(4, 1fr); gap: var(--space-5); } }
|
||||
.sm-trust__item { display: flex; gap: var(--space-3); align-items: flex-start; }
|
||||
.sm-trust__item .sm-icon { color: var(--gold-deep); }
|
||||
.sm-trust__title { margin: 0; font-size: 14px; line-height: 20px; font-weight: 500; }
|
||||
.sm-trust__text { margin: 2px 0 0; font-size: 14px; line-height: 22px; color: var(--ink-muted); }
|
||||
|
||||
/* ---------- Hinweis / Alert ---------- */
|
||||
.sm-alert { display: flex; gap: var(--space-3); align-items: flex-start; padding: var(--space-4); border-radius: var(--radius-sm); background: var(--gold-soft); color: var(--gold-deep); font-size: 14px; line-height: 22px; }
|
||||
.sm-alert--success { background: var(--success-soft); color: var(--success); }
|
||||
.sm-alert--danger { background: var(--danger-soft); color: var(--danger); }
|
||||
.sm-alert .sm-icon { width: 20px; height: 20px; margin-top: 1px; }
|
||||
.sm-alert__title { display: block; font-weight: 500; }
|
||||
.sm-alert a { color: inherit; }
|
||||
|
||||
/* ---------- Footer ---------- */
|
||||
.sm-footer { background: var(--surface-sunken); color: var(--ink); padding: var(--space-7) 0 var(--space-5); margin-top: var(--space-9); }
|
||||
.sm-footer__grid { display: grid; gap: var(--space-6); grid-template-columns: 1fr 1fr; }
|
||||
@media (min-width: 768px) { .sm-footer__grid { grid-template-columns: 1.6fr 1fr 1fr 1fr; } }
|
||||
.sm-footer__brand { grid-column: 1 / -1; }
|
||||
@media (min-width: 768px) { .sm-footer__brand { grid-column: auto; } }
|
||||
.sm-footer__logo { display: inline-block; font-size: 22px; line-height: 28px; letter-spacing: 0.32em; text-transform: uppercase; color: var(--ink); text-decoration: none; }
|
||||
.sm-footer__logo img { height: 160px; width: auto; margin-left: calc(-1 * var(--space-3)); }
|
||||
.sm-footer__claim { margin: var(--space-3) 0 0; max-width: 32ch; color: var(--ink-muted); font-size: 14px; line-height: 22px; }
|
||||
.sm-footer__title { margin: 0 0 var(--space-3); font-size: 13px; line-height: 20px; font-weight: 500; letter-spacing: 0.14em; text-transform: uppercase; }
|
||||
.sm-footer__links { margin: 0; padding: 0; list-style: none; }
|
||||
.sm-footer__links a { display: inline-block; padding: var(--space-1) 0; font-size: 14px; line-height: 22px; color: var(--ink-muted); text-decoration: none; }
|
||||
.sm-footer__links a:hover { color: var(--gold-deep); text-decoration: underline; text-underline-offset: 3px; }
|
||||
.sm-footer__news { display: flex; margin-top: var(--space-3); }
|
||||
.sm-footer__bottom { display: flex; flex-wrap: wrap; justify-content: space-between; gap: var(--space-3); margin-top: var(--space-7); padding-top: var(--space-4); border-top: var(--hairline) solid var(--line); font-size: 12px; line-height: 16px; color: var(--ink-muted); }
|
||||
.sm-footer__pay { display: flex; gap: var(--space-2); }
|
||||
.sm-footer__pay span { display: inline-grid; place-content: center; height: 24px; padding: 0 var(--space-2); border: var(--hairline) solid var(--line-strong); border-radius: var(--radius-sm); font-size: 11px; letter-spacing: 0.04em; color: var(--ink-muted); }
|
||||
|
||||
/* ---------- Hero ---------- */
|
||||
.sm-hero { background: var(--surface); color: var(--ink); padding: var(--space-8) 0; }
|
||||
@media (min-width: 1024px) { .sm-hero { padding: var(--space-10) 0; } }
|
||||
.sm-hero__inner { display: grid; gap: var(--space-6); align-items: center; }
|
||||
@media (min-width: 1024px) { .sm-hero__inner { grid-template-columns: 1fr 1fr; gap: var(--space-8); } }
|
||||
.sm-hero__eyebrow { display: block; color: var(--gold-deep); text-transform: uppercase; margin-bottom: var(--space-4); }
|
||||
.sm-hero__title { margin: 0; }
|
||||
.sm-hero__text { margin: var(--space-5) 0 0; max-width: 44ch; color: var(--ink-muted); font-size: 18px; line-height: 28px; }
|
||||
.sm-hero__actions { margin-top: var(--space-6); }
|
||||
.sm-hero__media { border-radius: var(--radius-lg); overflow: hidden; }
|
||||
.sm-hero__logo { width: min(100%, 420px); height: auto; margin: 0 auto; }
|
||||
.sm-hero__rule { width: 48px; height: var(--hairline); background: var(--gold); margin-top: var(--space-5); }
|
||||
|
||||
/* ---------- Produktseite ---------- */
|
||||
.sm-pdp { display: grid; gap: var(--space-6); }
|
||||
@media (min-width: 1024px) { .sm-pdp { grid-template-columns: 7fr 5fr; gap: var(--space-8); align-items: start; } }
|
||||
.sm-pdp__gallery { display: grid; gap: var(--space-3); }
|
||||
.sm-pdp__thumbs { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-3); }
|
||||
.sm-pdp__thumb { border: var(--hairline) solid var(--line); border-radius: var(--radius-md); overflow: hidden; background: var(--surface-sunken); cursor: pointer; padding: 0; }
|
||||
.sm-pdp__thumb.is-active { border: 2px solid var(--ink); }
|
||||
.sm-pdp__buy { position: sticky; top: calc(var(--header-height) + var(--space-5)); }
|
||||
.sm-pdp__title { margin: var(--space-2) 0 var(--space-3); }
|
||||
.sm-pdp__options { margin-top: var(--space-6); }
|
||||
.sm-pdp__option-label { display: flex; justify-content: space-between; margin-bottom: var(--space-2); font-size: 14px; line-height: 20px; font-weight: 500; }
|
||||
.sm-pdp__option-label span { color: var(--ink-muted); font-weight: 400; }
|
||||
.sm-pdp__sizes { display: flex; flex-wrap: wrap; gap: var(--space-2); }
|
||||
.sm-pdp__size { min-width: 56px; min-height: var(--control-height); padding: 0 var(--space-4); border: var(--hairline) solid var(--line-strong); border-radius: var(--radius-sm); background: var(--surface-raised); color: var(--ink); font-size: 14px; font-weight: 500; cursor: pointer; }
|
||||
.sm-pdp__size:hover { border-color: var(--ink); }
|
||||
.sm-pdp__size.is-active { border: 2px solid var(--noir); }
|
||||
.sm-pdp__size[disabled] { color: var(--ink-subtle); border-color: var(--line); text-decoration: line-through; cursor: not-allowed; background: var(--surface); }
|
||||
.sm-pdp__cta { display: flex; gap: var(--space-3); margin-top: var(--space-6); }
|
||||
.sm-pdp__cta .sm-btn--primary { flex: 1; }
|
||||
.sm-pdp__facts { margin: var(--space-5) 0 0; padding: 0; list-style: none; display: grid; gap: var(--space-2); font-size: 14px; line-height: 22px; color: var(--ink-muted); }
|
||||
.sm-pdp__facts li { display: flex; gap: var(--space-2); align-items: center; }
|
||||
.sm-pdp__facts .sm-icon { width: 18px; height: 18px; color: var(--gold-deep); }
|
||||
.sm-acc { border-top: var(--hairline) solid var(--line); }
|
||||
.sm-acc:last-child { border-bottom: var(--hairline) solid var(--line); }
|
||||
.sm-acc summary { display: flex; justify-content: space-between; align-items: center; min-height: 56px; padding: var(--space-3) 0; cursor: pointer; list-style: none; font-family: var(--font-serif); font-size: 20px; font-weight: 500; }
|
||||
.sm-acc summary::-webkit-details-marker { display: none; }
|
||||
.sm-acc summary::after { content: "+"; font-family: var(--font-sans); font-size: 22px; font-weight: 300; color: var(--gold-deep); }
|
||||
.sm-acc[open] summary::after { content: "–"; }
|
||||
.sm-acc__body { padding: 0 0 var(--space-4); color: var(--ink-muted); font-size: 16px; line-height: 26px; }
|
||||
.sm-sticky-cta { display: none; }
|
||||
@media (max-width: 1023px) { .sm-sticky-cta { display: block; position: fixed; left: 0; right: 0; bottom: 0; padding: var(--space-3) var(--space-4); background: var(--surface-raised); border-top: var(--hairline) solid var(--line); box-shadow: var(--shadow-lg); z-index: 20; } }
|
||||
|
||||
/* ---------- Kollektions-Teaser ---------- */
|
||||
.sm-tiles { display: grid; gap: var(--space-4); grid-template-columns: 1fr; }
|
||||
@media (min-width: 768px) { .sm-tiles { grid-template-columns: repeat(3, 1fr); gap: var(--space-5); } }
|
||||
.sm-tile { position: relative; display: block; border-radius: var(--radius-lg); overflow: hidden; text-decoration: none; color: var(--ink); }
|
||||
.sm-tile .sm-ph { aspect-ratio: 3 / 4; }
|
||||
.sm-tile__label { position: absolute; left: var(--space-4); right: var(--space-4); bottom: var(--space-4); display: flex; align-items: center; justify-content: space-between; padding: var(--space-3) var(--space-4); background: var(--surface-raised); border-radius: var(--radius-sm); font-size: 14px; line-height: 20px; font-weight: 500; letter-spacing: 0.08em; text-transform: uppercase; }
|
||||
.sm-tile__label .sm-icon { width: 18px; height: 18px; color: var(--gold-deep); }
|
||||
87
src/styles/shop.css
Normal file
87
src/styles/shop.css
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
/* Ergänzungen für den Shop, auf den Tokens des Design Systems. */
|
||||
html { scroll-behavior: smooth; }
|
||||
body { min-height: 100vh; display: flex; flex-direction: column; }
|
||||
main { flex: 1; }
|
||||
h1, h2, h3 { margin: 0; }
|
||||
.sm-section { padding-top: var(--space-8); }
|
||||
@media (min-width: 1024px) { .sm-section { padding-top: var(--space-9); } }
|
||||
.sm-page { padding-top: var(--space-6); padding-bottom: var(--space-9); }
|
||||
.sm-page__title { margin: 0 0 var(--space-2); }
|
||||
.sm-page__lead { margin: 0 0 var(--space-6); color: var(--ink-muted); }
|
||||
.sm-prose { max-width: var(--container-text); }
|
||||
.sm-prose p, .sm-prose ul, .sm-prose ol { margin: 0 0 var(--space-4); }
|
||||
.sm-prose h2 { font-family: var(--font-serif); font-weight: 500; font-size: 24px; line-height: 1.2; margin: var(--space-6) 0 var(--space-3); }
|
||||
.sm-prose h3 { font-size: 18px; font-weight: 500; margin: var(--space-5) 0 var(--space-2); }
|
||||
|
||||
/* Bilder in Karten und Kacheln */
|
||||
.sm-card__media img, .sm-tile img, .sm-pdp__gallery img, .sm-cartline__media img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.sm-tile img { aspect-ratio: 3 / 4; }
|
||||
.sm-pdp__main { aspect-ratio: var(--product-image-ratio); border-radius: var(--radius-md); overflow: hidden; background: var(--surface-sunken); }
|
||||
.sm-card__title a { color: inherit; text-decoration: none; }
|
||||
.sm-card__title a::after { content: ""; position: absolute; inset: 0; }
|
||||
.sm-card { position: relative; }
|
||||
.sm-card__quick, .sm-card__wish { z-index: 2; }
|
||||
|
||||
/* Mobilmenü (details/summary, ohne JavaScript) */
|
||||
.sm-mnav { position: relative; }
|
||||
.sm-mnav > summary { list-style: none; }
|
||||
.sm-mnav > summary::-webkit-details-marker { display: none; }
|
||||
.sm-mnav__panel { position: fixed; inset: 0 auto 0 0; z-index: 30; width: min(86vw, 360px); background: var(--surface-raised); box-shadow: var(--shadow-lg); padding: var(--space-5); display: flex; flex-direction: column; gap: var(--space-2); overflow-y: auto; }
|
||||
.sm-mnav__overlay { position: fixed; inset: 0; z-index: 29; background: var(--overlay); }
|
||||
.sm-mnav__panel a { display: flex; align-items: center; min-height: var(--touch-target); font-size: 13px; letter-spacing: 0.14em; text-transform: uppercase; font-weight: 500; color: var(--ink); text-decoration: none; border-bottom: var(--hairline) solid var(--line); }
|
||||
.sm-mnav__panel a[aria-current="page"] { color: var(--gold-deep); }
|
||||
.sm-mnav__close { align-self: flex-end; }
|
||||
@media (min-width: 1024px) { .sm-mnav { display: none; } }
|
||||
|
||||
/* Suche im Header */
|
||||
.sm-search { display: flex; gap: var(--space-2); max-width: 560px; }
|
||||
|
||||
/* Warenkorb und Kasse */
|
||||
.sm-cart-layout { display: grid; gap: var(--space-6); align-items: start; }
|
||||
@media (min-width: 1024px) { .sm-cart-layout { grid-template-columns: 1fr 400px; gap: var(--space-8); } }
|
||||
.sm-checkout { display: grid; gap: var(--space-6); align-items: start; }
|
||||
@media (min-width: 1024px) { .sm-checkout { grid-template-columns: 1fr 400px; gap: var(--space-8); } }
|
||||
.sm-checkout__form { max-width: 640px; }
|
||||
.sm-checkout__steps { margin: var(--space-5) 0 var(--space-7); }
|
||||
.sm-steps__item a { color: inherit; text-decoration: none; }
|
||||
.sm-option { display: flex; gap: var(--space-3); align-items: flex-start; padding: var(--space-4); border: var(--hairline) solid var(--line-strong); border-radius: var(--radius-sm); background: var(--surface-raised); cursor: pointer; }
|
||||
.sm-option + .sm-option { margin-top: var(--space-3); }
|
||||
.sm-option:has(input:checked) { border-color: var(--ink); box-shadow: inset 0 0 0 1px var(--ink); }
|
||||
.sm-option input { appearance: none; -webkit-appearance: none; flex: none; width: 22px; height: 22px; margin: 2px 0 0; border: var(--hairline) solid var(--line-strong); border-radius: var(--radius-pill); display: grid; place-content: center; background: var(--surface-raised); }
|
||||
.sm-option input::before { content: ""; width: 10px; height: 10px; border-radius: 50%; background: var(--on-noir); transform: scale(0); transition: transform 150ms; }
|
||||
.sm-option input:checked { background: var(--noir); border-color: var(--noir); }
|
||||
.sm-option input:checked::before { transform: scale(1); }
|
||||
.sm-option__body { flex: 1; }
|
||||
.sm-option__title { display: flex; justify-content: space-between; gap: var(--space-3); font-weight: 500; }
|
||||
.sm-option__text { display: block; color: var(--ink-muted); font-size: 14px; line-height: 22px; }
|
||||
.sm-summary__lines { margin-bottom: var(--space-4); }
|
||||
.sm-summary__line { display: flex; justify-content: space-between; gap: var(--space-3); font-size: 14px; line-height: 22px; padding: var(--space-2) 0; }
|
||||
.sm-summary__line span:first-child { color: var(--ink-muted); }
|
||||
.sm-review { display: grid; gap: var(--space-4); }
|
||||
@media (min-width: 768px) { .sm-review { grid-template-columns: 1fr 1fr; } }
|
||||
.sm-review__box { border: var(--hairline) solid var(--line); border-radius: var(--radius-md); padding: var(--space-4); background: var(--surface-raised); }
|
||||
.sm-review__box h3 { font-size: 14px; letter-spacing: 0.08em; text-transform: uppercase; font-weight: 500; margin-bottom: var(--space-2); display: flex; justify-content: space-between; }
|
||||
.sm-review__box h3 a { text-transform: none; letter-spacing: 0; font-weight: 400; }
|
||||
.sm-review__box p { margin: 0; }
|
||||
|
||||
/* Konto */
|
||||
.sm-auth { max-width: 440px; margin: 0 auto; }
|
||||
.sm-box { border: var(--hairline) solid var(--line); border-radius: var(--radius-md); background: var(--surface-raised); padding: var(--space-5); }
|
||||
.sm-table { width: 100%; border-collapse: collapse; font-size: 14px; line-height: 22px; }
|
||||
.sm-table th { text-align: left; font-weight: 500; color: var(--ink-muted); padding: var(--space-3); border-bottom: var(--hairline) solid var(--line); }
|
||||
.sm-table td { padding: var(--space-3); border-bottom: var(--hairline) solid var(--line); font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* Filter im Shop */
|
||||
.sm-shop-toolbar { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: var(--space-4); margin-bottom: var(--space-6); }
|
||||
.sm-chips { display: flex; flex-wrap: wrap; gap: var(--space-2); }
|
||||
.sm-chip { text-decoration: none; }
|
||||
.sm-empty { text-align: center; padding: var(--space-8) var(--space-4); color: var(--ink-muted); }
|
||||
.sm-empty h2 { color: var(--ink); margin-bottom: var(--space-3); }
|
||||
.sm-maintenance { min-height: 100vh; display: grid; place-content: center; text-align: center; padding: var(--space-5); }
|
||||
.sm-pdp__sizes input { position: absolute; opacity: 0; pointer-events: none; }
|
||||
.sm-pdp__sizes label.sm-pdp__size { display: inline-flex; align-items: center; justify-content: center; }
|
||||
.sm-pdp__sizes input:checked + label.sm-pdp__size { border: 2px solid var(--noir); }
|
||||
.sm-pdp__sizes input:focus-visible + label.sm-pdp__size { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
|
||||
.sm-pdp__sizes input:disabled + label.sm-pdp__size { color: var(--ink-subtle); border-color: var(--line); text-decoration: line-through; cursor: not-allowed; background: var(--surface); }
|
||||
.sm-pdp__thumb img { aspect-ratio: var(--product-image-ratio); object-fit: cover; width: 100%; }
|
||||
@media (max-width: 1023px) { .sm-pdp__buy { position: static; } .sm-pdp__cta .sm-btn--primary { min-height: var(--control-height-lg); } }
|
||||
104
src/styles/tokens.css
Normal file
104
src/styles/tokens.css
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
/* Sanamare — generated from design/tokens.json (npm run tokens) */
|
||||
:root {
|
||||
--font-serif: "Cormorant Garamond", Cormorant, Georgia, "Times New Roman", serif;
|
||||
--font-sans: Jost, Futura, "Avenir Next", "Century Gothic", "Segoe UI", system-ui, sans-serif;
|
||||
--space-1: 4px;
|
||||
--space-2: 8px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
--space-5: 24px;
|
||||
--space-6: 32px;
|
||||
--space-7: 48px;
|
||||
--space-8: 64px;
|
||||
--space-9: 96px;
|
||||
--space-10: 128px;
|
||||
--radius-none: 0px;
|
||||
--radius-sm: 2px;
|
||||
--radius-md: 6px;
|
||||
--radius-lg: 12px;
|
||||
--radius-pill: 999px;
|
||||
--container-max: 1280px;
|
||||
--container-text: 720px;
|
||||
--control-height: 48px;
|
||||
--control-height-sm: 40px;
|
||||
--control-height-lg: 56px;
|
||||
--touch-target: 44px;
|
||||
--header-height: 72px;
|
||||
--product-image-ratio: 4 / 5;
|
||||
--hairline: 1px;
|
||||
--bp-sm: 480px;
|
||||
--bp-md: 768px;
|
||||
--bp-lg: 1024px;
|
||||
--bp-xl: 1280px;
|
||||
--surface: #f7f4ee;
|
||||
--surface-raised: #ffffff;
|
||||
--surface-sunken: #efeadf;
|
||||
--line: #e2dbcd;
|
||||
--line-strong: #8c8270;
|
||||
--ink: #161411;
|
||||
--ink-muted: #5d574d;
|
||||
--ink-subtle: #7d766b;
|
||||
--gold: #c6a24c;
|
||||
--gold-deep: #7a5e1a;
|
||||
--gold-soft: #f4ebd3;
|
||||
--on-gold: #161411;
|
||||
--noir: #161411;
|
||||
--on-noir: #f7f4ee;
|
||||
--success: #1e6a5c;
|
||||
--success-soft: #e0f1ec;
|
||||
--danger: #a8322b;
|
||||
--danger-soft: #f9e4e2;
|
||||
--link: var(--gold-deep);
|
||||
--focus-ring: var(--gold-deep);
|
||||
--overlay: #161411a6;
|
||||
--shadow-sm: 0 1px 2px #16141114;
|
||||
--shadow-md: 0 4px 12px #1614111a, 0 1px 2px #1614110f;
|
||||
--shadow-lg: 0 16px 48px #16141126;
|
||||
color-scheme: light;
|
||||
}
|
||||
[data-theme="dark"] {
|
||||
--surface: #0d0d0f;
|
||||
--surface-raised: #17171a;
|
||||
--surface-sunken: #070708;
|
||||
--line: #2a2926;
|
||||
--line-strong: #6d6960;
|
||||
--ink: #f2ede3;
|
||||
--ink-muted: #b1a999;
|
||||
--ink-subtle: #8a8275;
|
||||
--gold: #d4ae5e;
|
||||
--gold-deep: #e4c47c;
|
||||
--gold-soft: #2a2211;
|
||||
--on-gold: #161411;
|
||||
--noir: #f2ede3;
|
||||
--on-noir: #0d0d0f;
|
||||
--success: #7fd3c0;
|
||||
--success-soft: #11292a;
|
||||
--danger: #f29a92;
|
||||
--danger-soft: #3a1715;
|
||||
--link: var(--gold-deep);
|
||||
--focus-ring: var(--gold-deep);
|
||||
--overlay: #000000b3;
|
||||
--shadow-sm: 0 1px 2px #00000080;
|
||||
--shadow-md: 0 4px 12px #00000099, 0 1px 2px #00000080;
|
||||
--shadow-lg: 0 16px 48px #000000bf;
|
||||
color-scheme: dark;
|
||||
background-color: var(--surface);
|
||||
color: var(--ink);
|
||||
}
|
||||
.display-xl { font-family: var(--font-serif); font-size: 64px; line-height: 1.0; font-weight: 500; letter-spacing: -0.01em; }
|
||||
.display-lg { font-family: var(--font-serif); font-size: 44px; line-height: 1.05; font-weight: 500; letter-spacing: -0.005em; }
|
||||
.display-md { font-family: var(--font-serif); font-size: 32px; line-height: 1.15; font-weight: 500; }
|
||||
.display-sm { font-family: var(--font-serif); font-size: 24px; line-height: 1.2; font-weight: 500; }
|
||||
.quote { font-family: var(--font-serif); font-size: 26px; line-height: 1.3; font-weight: 400; font-style: italic; }
|
||||
.title { font-family: var(--font-sans); font-size: 18px; line-height: 26px; font-weight: 500; }
|
||||
.body { font-family: var(--font-sans); font-size: 16px; line-height: 26px; font-weight: 400; }
|
||||
.body-sm { font-family: var(--font-sans); font-size: 14px; line-height: 22px; font-weight: 400; }
|
||||
.label { font-family: var(--font-sans); font-size: 14px; line-height: 20px; font-weight: 500; }
|
||||
.button { font-family: var(--font-sans); font-size: 14px; line-height: 20px; font-weight: 500; letter-spacing: 0.08em; text-transform: uppercase; }
|
||||
.nav { font-family: var(--font-sans); font-size: 13px; line-height: 20px; font-weight: 500; letter-spacing: 0.14em; text-transform: uppercase; }
|
||||
.eyebrow { font-family: var(--font-sans); font-size: 12px; line-height: 16px; font-weight: 500; letter-spacing: 0.2em; text-transform: uppercase; color: var(--gold-deep); }
|
||||
.caption { font-family: var(--font-sans); font-size: 12px; line-height: 16px; font-weight: 400; }
|
||||
.price { font-family: var(--font-sans); font-size: 18px; line-height: 24px; font-weight: 500; font-variant-numeric: tabular-nums; }
|
||||
.price-lg { font-family: var(--font-sans); font-size: 28px; line-height: 32px; font-weight: 500; font-variant-numeric: tabular-nums; }
|
||||
.wordmark { font-family: var(--font-sans); font-size: 22px; line-height: 28px; font-weight: 400; letter-spacing: 0.32em; text-transform: uppercase; }
|
||||
@media (max-width: 767px) { .display-xl { font-size: 44px; line-height: 1.05; } .display-lg { font-size: 34px; } }
|
||||
21
tsconfig.json
Normal file
21
tsconfig.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"plugins": [{ "name": "next" }],
|
||||
"paths": { "@/*": ["./src/*"] }
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
0
uploads/.gitkeep
Normal file
0
uploads/.gitkeep
Normal file
Loading…
Reference in a new issue