Kundenkonto ueberarbeitet: Uebersicht, Bestellungen, Adressbuch, Profil und Passwort

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:
Maaxxs 2026-10-19 19:33:14 +02:00
parent f38db8e837
commit 390b5f3f4f
14 changed files with 649 additions and 53 deletions

View file

@ -0,0 +1,109 @@
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { db } from "@/lib/db";
import { getCurrentUser, hashPassword, verifyPassword } from "@/lib/auth";
import { COUNTRIES } from "@/lib/settings";
export type AccountState = { ok?: string; error?: string; errors?: Record<string, string>; values?: Record<string, string> } | null;
const issues = (e: z.ZodError) => {
const errors: Record<string, string> = {};
for (const i of e.issues) errors[String(i.path[0])] ??= i.message;
return errors;
};
const profileSchema = z.object({
firstName: z.string().trim().min(1, "Bitte gib deinen Vornamen ein.").max(80),
lastName: z.string().trim().min(1, "Bitte gib deinen Nachnamen ein.").max(80),
phone: z.string().trim().max(40).regex(/^[0-9+()/ -]*$/, "Bitte gib eine gültige Telefonnummer ein."),
});
export async function updateProfile(_prev: AccountState, fd: FormData): Promise<AccountState> {
const user = await getCurrentUser();
if (!user) return { error: "Bitte melde dich erneut an." };
const parsed = profileSchema.safeParse({ firstName: fd.get("firstName"), lastName: fd.get("lastName"), phone: fd.get("phone") ?? "" });
if (!parsed.success) return { errors: issues(parsed.error), values: { firstName: String(fd.get("firstName") ?? ""), lastName: String(fd.get("lastName") ?? ""), phone: String(fd.get("phone") ?? "") } };
const newsletter = fd.get("newsletter") === "on";
await db.user.update({ where: { id: user.id }, data: { ...parsed.data, newsletter } });
if (newsletter) await db.newsletterSubscriber.upsert({ where: { email: user.email }, create: { email: user.email }, update: {} });
else await db.newsletterSubscriber.deleteMany({ where: { email: user.email } });
revalidatePath("/konto", "layout");
return { ok: "Deine Daten sind gespeichert." };
}
export async function changePassword(_prev: AccountState, fd: FormData): Promise<AccountState> {
const user = await getCurrentUser();
if (!user) return { error: "Bitte melde dich erneut an." };
const current = String(fd.get("current") ?? "");
const next = String(fd.get("next") ?? "");
const errors: Record<string, string> = {};
if (user.passwordHash && !(await verifyPassword(current, user.passwordHash))) errors.current = "Das aktuelle Passwort stimmt nicht.";
if (next.length < 8) errors.next = "Das neue Passwort braucht mindestens 8 Zeichen.";
else if (next !== String(fd.get("repeat") ?? "")) errors.repeat = "Die beiden Passwörter stimmen nicht überein.";
if (Object.keys(errors).length) return { errors };
await db.user.update({ where: { id: user.id }, data: { passwordHash: await hashPassword(next) } });
return { ok: user.passwordHash ? "Dein Passwort ist geändert." : "Dein Passwort ist gesetzt. Du kannst dich jetzt auch mit E-Mail und Passwort anmelden." };
}
const addressSchema = z.object({
firstName: z.string().trim().min(1, "Bitte gib den Vornamen ein.").max(80),
lastName: z.string().trim().min(1, "Bitte gib den Nachnamen ein.").max(80),
company: z.string().trim().max(120).default(""),
street: z.string().trim().min(3, "Bitte gib Straße und Hausnummer ein.").max(120),
extra: z.string().trim().max(120).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 den Ort ein.").max(80),
country: z.string().trim().refine((c) => c in COUNTRIES, "Bitte wähle ein Land."),
});
const MAX_ADDRESSES = 10;
export async function saveAddressBook(_prev: AccountState, fd: FormData): Promise<AccountState> {
const user = await getCurrentUser();
if (!user) return { error: "Bitte melde dich erneut an." };
const raw: Record<string, string> = {};
for (const k of ["firstName", "lastName", "company", "street", "extra", "zip", "city", "country"]) raw[k] = String(fd.get(k) ?? "");
const parsed = addressSchema.safeParse(raw);
// Eingaben zurückgeben, damit das Formular sie nach einem Fehler behält
if (!parsed.success) return { errors: issues(parsed.error), values: raw };
const id = String(fd.get("id") ?? "");
const count = await db.address.count({ where: { userId: user.id } });
if (!id && count >= MAX_ADDRESSES) return { error: `Du kannst höchstens ${MAX_ADDRESSES} Adressen speichern.`, values: raw };
if (id && !(await db.address.findFirst({ where: { id, userId: user.id } }))) return { error: "Diese Adresse gibt es nicht mehr." };
const makeDefault = fd.get("isDefault") === "on" || count === 0 || (count === 1 && Boolean(id));
await db.$transaction(async (tx) => {
if (makeDefault) await tx.address.updateMany({ where: { userId: user.id }, data: { isDefault: false } });
if (id) await tx.address.update({ where: { id }, data: { ...parsed.data, ...(makeDefault ? { isDefault: true } : {}) } });
else await tx.address.create({ data: { ...parsed.data, userId: user.id, isDefault: makeDefault } });
});
revalidatePath("/konto", "layout");
return { ok: id ? "Die Adresse ist gespeichert." : "Die Adresse ist hinzugefügt." };
}
export async function deleteAddress(fd: FormData) {
const user = await getCurrentUser();
if (!user) return;
const id = String(fd.get("id") ?? "");
const addr = await db.address.findFirst({ where: { id, userId: user.id } });
if (!addr) return;
await db.address.delete({ where: { id } });
if (addr.isDefault) {
const next = await db.address.findFirst({ where: { userId: user.id } });
if (next) await db.address.update({ where: { id: next.id }, data: { isDefault: true } });
}
revalidatePath("/konto", "layout");
}
export async function setDefaultAddress(fd: FormData) {
const user = await getCurrentUser();
if (!user) return;
const id = String(fd.get("id") ?? "");
const addr = await db.address.findFirst({ where: { id, userId: user.id } });
if (!addr) return;
await db.$transaction([
db.address.updateMany({ where: { userId: user.id }, data: { isDefault: false } }),
db.address.update({ where: { id }, data: { isDefault: true } }),
]);
revalidatePath("/konto", "layout");
}

View file

@ -0,0 +1,22 @@
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { COUNTRIES, getSettings } from "@/lib/settings";
import { AccountShell } from "@/components/shop/account/AccountShell";
import { AddressBook } from "@/components/shop/account/AddressBook";
export const metadata = { title: "Meine Adressen" };
export default async function AddressesPage() {
const user = await getCurrentUser();
if (!user) redirect("/konto/anmelden?weiter=/konto/adressen");
const [addresses, settings] = await Promise.all([
db.address.findMany({ where: { userId: user.id }, orderBy: [{ isDefault: "desc" }, { id: "asc" }] }),
getSettings(),
]);
return (
<AccountShell user={user} title="Adressen" lead="Die Standardadresse tragen wir an der Kasse automatisch für dich ein.">
<AddressBook addresses={addresses} countries={settings.checkout.countries.map((c) => [c, COUNTRIES[c] ?? c])} max={10} />
</AccountShell>
);
}

View file

@ -1,47 +1,67 @@
/* eslint-disable @next/next/no-img-element */
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 { PAYMENT_STATUS, dayFmt } from "@/lib/status";
import type { AddressData } from "@/lib/checkout";
import { AddressLines } from "@/components/shop/AddressLines";
import { DhlTracking } from "@/components/shop/DhlTracking";
import { AccountShell } from "@/components/shop/account/AccountShell";
import { StatusBadge } from "@/components/shop/account/OrderCard";
import { fetchTracking, getDhlConfig, syncDelivered } from "@/lib/dhl";
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 (!user) redirect(`/konto/anmelden?weiter=/konto/bestellung/${encodeURIComponent(number)}`);
const order = await db.order.findUnique({ where: { number }, include: { items: { include: { product: { select: { images: true, slug: true, active: true } } } } } });
if (!order || order.userId !== user.id) notFound();
const dhl = await getDhlConfig();
const tracking = order.trackingNumber ? await fetchTracking(dhl, order.trackingNumber) : null;
if (await syncDelivered(dhl, order, tracking)) order.status = "COMPLETED";
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}
</p>
{order.trackingNumber && <DhlTracking trackingNumber={order.trackingNumber} tracking={tracking} />}
<div className="sm-box" style={{ padding: 0, 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</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>
<AccountShell
user={user}
title={`Bestellung ${order.number}`}
lead={<>vom {dayFmt.format(order.createdAt)}</>}
>
<div className="sm-account__badges">
<StatusBadge status={order.status} />
<span className={`sm-badge sm-status sm-status--${PAYMENT_STATUS[order.paymentStatus].tone}`}><span className="sm-dot" />{PAYMENT_STATUS[order.paymentStatus].label}</span>
</div>
{order.trackingNumber && <DhlTracking trackingNumber={order.trackingNumber} tracking={tracking} />}
<section className="sm-box sm-account__panel">
<h2 className="display-sm">Artikel</h2>
<ul className="sm-orderitems">
{order.items.map((i) => {
const href = i.product?.active && i.product.slug ? `/produkt/${i.product.slug}` : null;
const img = i.product?.images[0];
return (
<li key={i.id}>
<span className="sm-ordercard__thumb">{img ? <img src={img} alt="" loading="lazy" /> : <span>{i.name.charAt(0)}</span>}</span>
<div>
{href ? <Link href={href}>{i.name}</Link> : <span>{i.name}</span>}
<small>{i.variantName ? `${i.variantName} · ` : ""}{i.quantity} × {formatPrice(i.unitPrice)}</small>
</div>
<strong>{formatPrice(i.total)}</strong>
</li>
);
})}
</ul>
<dl className="sm-ordersum">
<div><dt>Zwischensumme</dt><dd>{formatPrice(order.subtotal)}</dd></div>
<div><dt>Versand</dt><dd>{order.shippingCost === 0 ? "Kostenlos" : formatPrice(order.shippingCost)}</dd></div>
{order.discount > 0 && <div><dt>Gutschein</dt><dd>−{formatPrice(order.discount)}</dd></div>}
<div className="sm-ordersum__total"><dt>Gesamt</dt><dd>{formatPrice(order.total)}</dd></div>
</dl>
</section>
<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>
<p className="body-sm" style={{ marginTop: "var(--space-6)" }}><Link href="/konto/bestellungen">← Alle Bestellungen</Link></p>
</AccountShell>
);
}

View file

@ -0,0 +1,28 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { Icon } from "@/components/Icon";
import { AccountShell } from "@/components/shop/account/AccountShell";
import { OrderCard } from "@/components/shop/account/OrderCard";
export const metadata = { title: "Meine Bestellungen" };
export default async function OrdersPage() {
const user = await getCurrentUser();
if (!user) redirect("/konto/anmelden?weiter=/konto/bestellungen");
const orders = await db.order.findMany({ where: { userId: user.id }, orderBy: { createdAt: "desc" }, include: { items: { include: { product: { select: { images: true } } } } } });
return (
<AccountShell user={user} title="Bestellungen" lead="Alle deine Bestellungen mit Status und Sendungsverfolgung.">
{orders.length === 0 ? (
<div className="sm-box sm-account__empty">
<Icon name="box" />
<p className="body">Du hast noch nichts bestellt.</p>
<Link className="sm-btn sm-btn--primary" href="/shop">Zum Shop</Link>
</div>
) : (
<div className="sm-orderlist">{orders.map((o) => <OrderCard key={o.id} order={o} />)}</div>
)}
</AccountShell>
);
}

View file

@ -2,44 +2,80 @@ 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";
import { dayFmt } from "@/lib/status";
import { AddressLines } from "@/components/shop/AddressLines";
import { Icon } from "@/components/Icon";
import { AccountShell } from "@/components/shop/account/AccountShell";
import { OrderCard } from "@/components/shop/account/OrderCard";
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" } });
const [orders, orderCount, spent, address] = await Promise.all([
db.order.findMany({ where: { userId: user.id }, orderBy: { createdAt: "desc" }, take: 3, include: { items: { include: { product: { select: { images: true } } } } } }),
db.order.count({ where: { userId: user.id } }),
db.order.aggregate({ where: { userId: user.id, status: { notIn: ["CANCELLED", "REFUNDED"] } }, _sum: { total: true } }),
db.address.findFirst({ where: { userId: user.id }, orderBy: { isDefault: "desc" } }),
]);
const open = orders.find((o) => ["PENDING", "PAID", "PROCESSING", "SHIPPED"].includes(o.status));
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>
<AccountShell user={user} title={`Hallo${user.firstName ? ` ${user.firstName}` : ""}`} lead={`Schön, dass du da bist. Dabei seit ${dayFmt.format(user.createdAt)}.`}>
{open && (
<Link className="sm-account__highlight" href={`/konto/bestellung/${open.number}`}>
<Icon name={open.status === "SHIPPED" ? "truck" : "box"} />
<div>
<strong>{open.status === "SHIPPED" ? "Deine Bestellung ist unterwegs" : "Wir bereiten deine Bestellung vor"}</strong>
<span>Bestellung {open.number} vom {dayFmt.format(open.createdAt)}{open.trackingNumber ? " · Sendung verfolgen" : ""}</span>
</div>
<span aria-hidden="true">›</span>
</Link>
)}
</main>
<div className="sm-account__stats">
<div className="sm-box"><span>Bestellungen</span><strong>{orderCount}</strong></div>
<div className="sm-box"><span>Gesamtwert</span><strong>{formatPrice(spent._sum.total ?? 0)}</strong></div>
<div className="sm-box"><span>Newsletter</span><strong>{user.newsletter ? "Ja" : "Nein"}</strong></div>
</div>
<section className="sm-account__section">
<div className="sm-account__section-head">
<h2 className="display-sm">Letzte Bestellungen</h2>
{orderCount > 3 && <Link href="/konto/bestellungen" className="body-sm">Alle {orderCount} ansehen</Link>}
</div>
{orders.length === 0 ? (
<div className="sm-box sm-account__empty">
<Icon name="box" />
<p className="body">Du hast noch nichts bestellt.</p>
<Link className="sm-btn sm-btn--primary" href="/shop">Zum Shop</Link>
</div>
) : (
<div className="sm-orderlist">{orders.map((o) => <OrderCard key={o.id} order={o} />)}</div>
)}
</section>
<div className="sm-account__cards">
<section className="sm-box sm-account__card">
<div className="sm-account__section-head">
<h2 className="display-sm">Standardadresse</h2>
<Link href="/konto/adressen" className="body-sm">{address ? "Verwalten" : "Hinzufügen"}</Link>
</div>
{address ? <AddressLines a={address} /> : <p className="body sm-muted">Noch keine Adresse gespeichert. Mit einer gespeicherten Adresse geht die nächste Bestellung schneller.</p>}
</section>
<section className="sm-box sm-account__card">
<div className="sm-account__section-head">
<h2 className="display-sm">Persönliche Daten</h2>
<Link href="/konto/profil" className="body-sm">Bearbeiten</Link>
</div>
<p className="body">
{[user.firstName, user.lastName].filter(Boolean).join(" ") || "Kein Name hinterlegt"}<br />
{user.email}<br />
{user.phone || <span className="sm-muted">Keine Telefonnummer</span>}
</p>
</section>
</div>
</AccountShell>
);
}

View file

@ -0,0 +1,33 @@
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { AccountShell } from "@/components/shop/account/AccountShell";
import { PasswordForm, ProfileForm } from "@/components/shop/account/ProfileForms";
export const metadata = { title: "Profil & Sicherheit" };
const PROVIDERS: Record<string, string> = { google: "Google", apple: "Apple" };
export default async function ProfilePage() {
const user = await getCurrentUser();
if (!user) redirect("/konto/anmelden?weiter=/konto/profil");
const identities = await db.userIdentity.findMany({ where: { userId: user.id }, select: { provider: true } });
return (
<AccountShell user={user} title="Profil & Sicherheit">
<section className="sm-box sm-account__panel">
<h2 className="display-sm">Persönliche Daten</h2>
<ProfileForm user={user} />
</section>
<section className="sm-box sm-account__panel">
<h2 className="display-sm">{user.passwordHash ? "Passwort ändern" : "Passwort festlegen"}</h2>
{identities.length > 0 && (
<p className="body sm-muted">
Du meldest dich mit {identities.map((i) => PROVIDERS[i.provider] ?? i.provider).join(" und ")} an.
{!user.passwordHash && " Wenn du möchtest, kannst du zusätzlich ein Passwort festlegen."}
</p>
)}
<PasswordForm hasPassword={Boolean(user.passwordHash)} />
</section>
</AccountShell>
);
}

View file

@ -5,7 +5,7 @@ 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][] }) {
export 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 (
<>

View file

@ -0,0 +1,26 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Icon, type IconName } from "../../Icon";
const LINKS: { href: string; label: string; icon: IconName }[] = [
{ href: "/konto", label: "Übersicht", icon: "dashboard" },
{ href: "/konto/bestellungen", label: "Bestellungen", icon: "box" },
{ href: "/konto/adressen", label: "Adressen", icon: "truck" },
{ href: "/konto/profil", label: "Profil & Sicherheit", icon: "user" },
];
export function AccountNav() {
const path = usePathname();
const active = (href: string) => (href === "/konto" ? path === href : path.startsWith(href) || (href === "/konto/bestellungen" && path.startsWith("/konto/bestellung/")));
return (
<nav className="sm-account__nav" aria-label="Kontobereich">
{LINKS.map((l) => (
<Link key={l.href} href={l.href} aria-current={active(l.href) ? "page" : undefined}>
<Icon name={l.icon} />
<span>{l.label}</span>
</Link>
))}
</nav>
);
}

View file

@ -0,0 +1,32 @@
import Link from "next/link";
import type { CurrentUser } from "@/lib/auth";
import { logout } from "@/lib/auth-actions";
import { Icon } from "../../Icon";
import { AccountNav } from "./AccountNav";
export function AccountShell({ user, title, lead, children }: { user: CurrentUser; title: string; lead?: React.ReactNode; children: React.ReactNode }) {
const name = [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email;
return (
<main className="sm-container sm-page sm-account">
<aside className="sm-account__side">
<div className="sm-account__who">
<span className="sm-account__avatar" aria-hidden="true">{(user.firstName || user.email).charAt(0).toUpperCase()}</span>
<div>
<strong>{name}</strong>
<span>{user.email}</span>
</div>
</div>
<AccountNav />
<div className="sm-account__side-foot">
{user.role && <Link href="/admin"><Icon name="settings" /> Zum Admin-Bereich</Link>}
<form action={logout}><button type="submit"><Icon name="logout" /> Abmelden</button></form>
</div>
</aside>
<div className="sm-account__main">
<h1 className="display-lg sm-page__title">{title}</h1>
{lead && <p className="body sm-page__lead">{lead}</p>}
{children}
</div>
</main>
);
}

View file

@ -0,0 +1,93 @@
"use client";
import { useActionState, useEffect, useState } from "react";
import type { Address } from "@prisma/client";
import { deleteAddress, saveAddressBook, setDefaultAddress } from "@/app/(shop)/konto/actions";
import { AddressFields } from "../AddressForm";
import { Alert } from "../Blocks";
import { Icon } from "../../Icon";
function AddressEditor({ address, countries, onDone, first }: { address?: Address; countries: [string, string][]; onDone: () => void; first: boolean }) {
const [state, action, pending] = useActionState(saveAddressBook, null);
useEffect(() => {
if (state?.ok) onDone();
}, [state, onDone]);
return (
<form action={action} className="sm-box sm-account__editor" noValidate>
<h2 className="display-sm">{address ? "Adresse bearbeiten" : "Neue Adresse"}</h2>
{state?.error && <div className="sm-account__alert"><Alert kind="danger" title={state.error} /></div>}
{address && <input type="hidden" name="id" value={address.id} />}
<AddressFields prefix="" values={state?.values ?? address} errors={state?.errors ?? {}} countries={countries} />
{!first && !address?.isDefault && (
<label className="sm-check" style={{ marginTop: "var(--space-3)" }}>
<input type="checkbox" name="isDefault" />
<span className="sm-check__text">Als Standardadresse verwenden</span>
</label>
)}
<div className="sm-account__actions">
<button className="sm-btn sm-btn--primary" type="submit" disabled={pending}>{pending ? "Speichert …" : "Adresse speichern"}</button>
<button className="sm-btn sm-btn--ghost" type="button" onClick={onDone}>Abbrechen</button>
</div>
</form>
);
}
export function AddressBook({ addresses, countries, max }: { addresses: Address[]; countries: [string, string][]; max: number }) {
const [editing, setEditing] = useState<string | null>(addresses.length === 0 ? "new" : null);
const [saved, setSaved] = useState(false);
const [confirm, setConfirm] = useState<string | null>(null);
const names = Object.fromEntries(countries);
const done = () => {
setEditing(null);
setSaved(true);
};
return (
<div>
{saved && !editing && <div className="sm-account__alert"><Alert kind="success" title="Gespeichert." /></div>}
<div className="sm-addressgrid">
{addresses.map((a) =>
editing === a.id ? (
<AddressEditor key={a.id} address={a} countries={countries} onDone={done} first={false} />
) : (
<div key={a.id} className={`sm-box sm-addresscard${a.isDefault ? " is-default" : ""}`}>
{a.isDefault && <span className="sm-badge sm-badge--new">Standard</span>}
<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 />
{names[a.country] ?? a.country}
</p>
<div className="sm-addresscard__actions">
<button type="button" className="sm-linkbtn" onClick={() => { setSaved(false); setEditing(a.id); }}><Icon name="edit" size="sm" /> Bearbeiten</button>
{!a.isDefault && (
<form action={setDefaultAddress}><input type="hidden" name="id" value={a.id} /><button type="submit" className="sm-linkbtn"><Icon name="check" size="sm" /> Als Standard</button></form>
)}
{confirm === a.id ? (
<form action={deleteAddress} className="sm-addresscard__confirm">
<input type="hidden" name="id" value={a.id} />
<span>Wirklich löschen?</span>
<button type="submit" className="sm-linkbtn sm-linkbtn--danger">Ja, löschen</button>
<button type="button" className="sm-linkbtn" onClick={() => setConfirm(null)}>Nein</button>
</form>
) : (
<button type="button" className="sm-linkbtn sm-linkbtn--danger" onClick={() => setConfirm(a.id)}><Icon name="trash" size="sm" /> Löschen</button>
)}
</div>
</div>
),
)}
{editing === "new" ? (
<AddressEditor countries={countries} onDone={done} first={addresses.length === 0} />
) : (
addresses.length < max && (
<button type="button" className="sm-addresscard sm-addresscard--add" onClick={() => { setSaved(false); setEditing("new"); }}>
<Icon name="plus" />
<span>Adresse hinzufügen</span>
</button>
)
)}
</div>
</div>
);
}

View file

@ -0,0 +1,36 @@
/* eslint-disable @next/next/no-img-element */
import Link from "next/link";
import type { Order, OrderItem } from "@prisma/client";
import { formatPrice } from "@/lib/money";
import { ORDER_STATUS, dayFmt } from "@/lib/status";
export type OrderWithItems = Order & { items: (OrderItem & { product: { images: string[] } | null })[] };
export function StatusBadge({ status }: { status: Order["status"] }) {
const s = ORDER_STATUS[status];
return <span className={`sm-badge sm-status sm-status--${s.tone}`}><span className="sm-dot" />{s.label}</span>;
}
export function OrderCard({ order }: { order: OrderWithItems }) {
const count = order.items.reduce((n, i) => n + i.quantity, 0);
const thumbs = order.items.slice(0, 4);
return (
<Link className="sm-ordercard" href={`/konto/bestellung/${order.number}`}>
<div className="sm-ordercard__thumbs" aria-hidden="true">
{thumbs.map((i) => (
<span key={i.id} className="sm-ordercard__thumb">
{i.product?.images[0] ? <img src={i.product.images[0]} alt="" loading="lazy" /> : <span>{i.name.charAt(0)}</span>}
</span>
))}
{order.items.length > 4 && <span className="sm-ordercard__thumb sm-ordercard__more">+{order.items.length - 4}</span>}
</div>
<div className="sm-ordercard__info">
<span className="sm-ordercard__number">Bestellung {order.number}</span>
<span className="sm-ordercard__meta">{dayFmt.format(order.createdAt)} · {count} Artikel</span>
</div>
<StatusBadge status={order.status} />
<span className="sm-ordercard__total">{formatPrice(order.total)}</span>
<span className="sm-ordercard__go" aria-hidden="true">›</span>
</Link>
);
}

View file

@ -0,0 +1,49 @@
"use client";
import { useActionState } from "react";
import { changePassword, updateProfile } from "@/app/(shop)/konto/actions";
import { Field } from "../../Field";
import { Alert } from "../Blocks";
export function ProfileForm({ user }: { user: { firstName: string; lastName: string; email: string; phone: string; newsletter: boolean } }) {
const [state, action, pending] = useActionState(updateProfile, null);
const e = state?.errors ?? {};
const v = { ...user, ...state?.values };
return (
<form action={action} noValidate>
{state?.ok && <div className="sm-account__alert"><Alert kind="success" title={state.ok} /></div>}
{state?.error && <div className="sm-account__alert"><Alert kind="danger" title={state.error} /></div>}
<div className="sm-form-row">
<Field label="Vorname" name="firstName" autoComplete="given-name" defaultValue={v.firstName} error={e.firstName} required />
<Field label="Nachname" name="lastName" autoComplete="family-name" defaultValue={v.lastName} error={e.lastName} required />
</div>
<Field label="E-Mail-Adresse" name="email" type="email" defaultValue={user.email} readOnly hint="Zum Ändern der E-Mail-Adresse schreib uns kurz." />
<Field label="Telefon" optional name="phone" type="tel" autoComplete="tel" defaultValue={v.phone} error={e.phone} hint="Nur für Rückfragen zur Lieferung." />
<label className="sm-check" style={{ marginTop: "var(--space-3)" }}>
<input type="checkbox" name="newsletter" defaultChecked={user.newsletter} />
<span className="sm-check__text">Newsletter erhalten <small>Neuheiten und Studio-Termine, etwa zweimal im Monat. Jederzeit abbestellbar.</small></span>
</label>
<div className="sm-account__actions">
<button className="sm-btn sm-btn--primary" type="submit" disabled={pending}>{pending ? "Speichert …" : "Speichern"}</button>
</div>
</form>
);
}
export function PasswordForm({ hasPassword }: { hasPassword: boolean }) {
const [state, action, pending] = useActionState(changePassword, null);
const e = state?.errors ?? {};
return (
<form action={action} noValidate key={state?.ok ?? "form"}>
{state?.ok && <div className="sm-account__alert"><Alert kind="success" title={state.ok} /></div>}
{state?.error && <div className="sm-account__alert"><Alert kind="danger" title={state.error} /></div>}
{hasPassword && <Field label="Aktuelles Passwort" name="current" type="password" autoComplete="current-password" error={e.current} required />}
<div className="sm-form-row">
<Field label="Neues Passwort" name="next" type="password" autoComplete="new-password" error={e.next} hint="Mindestens 8 Zeichen." required />
<Field label="Neues Passwort wiederholen" name="repeat" type="password" autoComplete="new-password" error={e.repeat} required />
</div>
<div className="sm-account__actions">
<button className="sm-btn sm-btn--secondary" type="submit" disabled={pending}>{hasPassword ? "Passwort ändern" : "Passwort festlegen"}</button>
</div>
</form>
);
}

View file

@ -63,6 +63,7 @@ export async function register(_prev: AuthState, formData: FormData): Promise<Au
newsletter: formData.get("newsletter") === "on",
},
});
if (user.newsletter) await db.newsletterSubscriber.upsert({ where: { email: user.email }, create: { email: user.email }, update: {} });
// 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);

View file

@ -129,3 +129,114 @@ button.sm-pdp__main { display: block; width: 100%; padding: 0; border: 0; cursor
.sm-lightbox__nav--prev { left: 16px; }
.sm-lightbox__nav--next { right: 16px; }
.sm-lightbox__close:hover, .sm-lightbox__nav:hover { background: rgba(12, 11, 9, 0.85); }
/* Kundenkonto */
.sm-account { display: grid; gap: var(--space-6); align-items: start; width: 100%; box-sizing: border-box; }
@media (min-width: 900px) { .sm-account { grid-template-columns: 260px minmax(0, 1fr); gap: var(--space-7); } }
.sm-account__side { display: grid; gap: var(--space-4); }
@media (min-width: 900px) { .sm-account__side { position: sticky; top: calc(var(--space-6) + 72px); } }
.sm-account__who { display: flex; align-items: center; gap: var(--space-3); min-width: 0; }
.sm-account__who > div { display: grid; min-width: 0; }
.sm-account__who strong { font-weight: 500; font-size: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sm-account__who span:not(.sm-account__avatar) { font-size: 13px; color: var(--ink-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sm-account__avatar { flex: none; width: 44px; height: 44px; border-radius: 50%; display: grid; place-content: center; background: var(--noir); color: var(--gold); font-family: var(--font-serif); font-size: 20px; }
.sm-account__nav { display: flex; gap: var(--space-2); overflow-x: auto; scrollbar-width: none; margin-inline: calc(-1 * var(--space-4)); padding-inline: var(--space-4); }
.sm-account__nav::-webkit-scrollbar { display: none; }
.sm-account__nav a { display: flex; align-items: center; gap: var(--space-2); flex: none; min-height: 44px; padding: 0 var(--space-4); border: var(--hairline) solid var(--line); border-radius: var(--radius-pill); color: var(--ink); text-decoration: none; font-size: 14px; background: var(--surface-raised); }
.sm-account__nav a .sm-icon { width: 18px; height: 18px; color: var(--ink-muted); }
.sm-account__nav a[aria-current="page"] { background: var(--noir); border-color: var(--noir); color: var(--on-noir); }
.sm-account__nav a[aria-current="page"] .sm-icon { color: var(--gold); }
@media (min-width: 900px) {
.sm-account__nav { flex-direction: column; gap: 2px; margin: 0; padding: 0; overflow: visible; }
.sm-account__nav a { border: 0; border-radius: var(--radius-sm); background: transparent; }
.sm-account__nav a:hover { background: var(--surface-sunken); }
.sm-account__nav a[aria-current="page"] { background: var(--surface-sunken); color: var(--ink); font-weight: 500; box-shadow: inset 2px 0 0 var(--gold); }
}
.sm-account__side-foot { display: flex; flex-wrap: wrap; gap: var(--space-2) var(--space-4); padding-top: var(--space-3); border-top: var(--hairline) solid var(--line); }
.sm-account__side-foot a, .sm-account__side-foot button { display: inline-flex; align-items: center; gap: var(--space-2); min-height: 40px; padding: 0; border: 0; background: none; color: var(--ink-muted); font: inherit; font-size: 14px; text-decoration: none; cursor: pointer; }
.sm-account__side-foot a:hover, .sm-account__side-foot button:hover { color: var(--ink); }
.sm-account__side-foot .sm-icon { width: 18px; height: 18px; }
@media (min-width: 900px) { .sm-account__side-foot { flex-direction: column; gap: 0; } }
.sm-account__main { min-width: 0; }
.sm-account__main > .sm-page__lead { margin-bottom: var(--space-6); }
.sm-account__highlight { display: flex; align-items: center; gap: var(--space-4); padding: var(--space-4) var(--space-5); margin-bottom: var(--space-5); border-radius: var(--radius-md); background: var(--noir); color: var(--on-noir); text-decoration: none; }
.sm-account__highlight .sm-icon { flex: none; width: 26px; height: 26px; color: var(--gold); }
.sm-account__highlight div { display: grid; flex: 1; min-width: 0; }
.sm-account__highlight strong { font-weight: 500; }
.sm-account__highlight span { font-size: 14px; opacity: 0.8; }
.sm-account__highlight > span:last-child { font-size: 24px; opacity: 1; color: var(--gold); }
.sm-account__stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--space-3); margin-bottom: var(--space-7); }
.sm-account__stats .sm-box { display: grid; gap: var(--space-1); padding: var(--space-4); }
.sm-account__stats span { font-size: 12px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-muted); }
.sm-account__stats strong { font-family: var(--font-serif); font-variant-numeric: lining-nums; font-size: 24px; font-weight: 500; line-height: 1.2; }
@media (max-width: 599px) { .sm-account__stats strong { font-size: 17px; } .sm-account__stats .sm-box { padding: var(--space-3); } }
.sm-account__section { margin-bottom: var(--space-7); }
.sm-account__section-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-3); margin-bottom: var(--space-4); }
.sm-account__section-head h2 { margin: 0; }
.sm-account__cards { display: grid; gap: var(--space-4); }
@media (min-width: 700px) { .sm-account__cards { grid-template-columns: 1fr 1fr; } }
.sm-account__card .body { margin: 0; }
.sm-account__empty { display: grid; justify-items: center; gap: var(--space-3); text-align: center; padding: var(--space-7) var(--space-5); }
.sm-account__empty .sm-icon { width: 32px; height: 32px; color: var(--gold-deep); }
.sm-account__empty .body { margin: 0; color: var(--ink-muted); }
.sm-account__panel { margin-bottom: var(--space-5); }
.sm-account__panel > h2 { margin: 0 0 var(--space-4); }
.sm-account__panel > .body { margin: 0 0 var(--space-4); }
.sm-account__alert { margin-bottom: var(--space-4); }
.sm-account__actions { display: flex; flex-wrap: wrap; gap: var(--space-3); margin-top: var(--space-5); }
.sm-account__badges { display: flex; flex-wrap: wrap; gap: var(--space-2); margin: calc(-1 * var(--space-3)) 0 var(--space-5); }
.sm-status--gold { background: var(--gold-soft); color: var(--gold-deep); }
.sm-status--success { background: var(--success-soft); color: var(--success); }
.sm-status--danger { background: var(--danger-soft); color: var(--danger); }
.sm-status { text-transform: none; letter-spacing: 0; font-size: 13px; }
.sm-orderlist { display: grid; gap: var(--space-3); }
.sm-ordercard { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; grid-template-areas: "thumbs info go" "thumbs status total"; align-items: center; gap: var(--space-2) var(--space-4); padding: var(--space-4); border: var(--hairline) solid var(--line); border-radius: var(--radius-md); background: var(--surface-raised); color: var(--ink); text-decoration: none; transition: border-color 150ms, box-shadow 150ms; }
.sm-ordercard:hover { border-color: var(--line-strong); box-shadow: var(--shadow-sm); }
.sm-ordercard__thumbs { grid-area: thumbs; display: flex; }
.sm-ordercard__thumbs .sm-ordercard__thumb + .sm-ordercard__thumb { margin-left: -14px; }
.sm-ordercard__thumb { flex: none; width: 52px; height: 52px; border-radius: var(--radius-sm); overflow: hidden; background: var(--surface-sunken); border: 2px solid var(--surface-raised); display: grid; place-content: center; color: var(--ink-muted); font-size: 15px; }
.sm-ordercard__thumb img { width: 100%; height: 100%; object-fit: cover; }
.sm-ordercard__more { font-size: 13px; font-weight: 500; }
.sm-ordercard__info { grid-area: info; display: grid; min-width: 0; }
.sm-ordercard__number { font-weight: 500; }
.sm-ordercard__meta { font-size: 13px; color: var(--ink-muted); }
.sm-ordercard .sm-status { grid-area: status; justify-self: start; }
.sm-ordercard__total { grid-area: total; font-weight: 500; font-variant-numeric: tabular-nums; text-align: right; }
.sm-ordercard__go { grid-area: go; justify-self: end; font-size: 22px; color: var(--ink-muted); }
@media (min-width: 700px) {
.sm-ordercard { grid-template-columns: auto minmax(0, 1fr) auto auto auto; grid-template-areas: "thumbs info status total go"; gap: var(--space-5); }
.sm-ordercard__total { min-width: 90px; }
}
.sm-orderitems { list-style: none; margin: 0; padding: 0; }
.sm-orderitems li { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: var(--space-4); padding: var(--space-3) 0; border-bottom: var(--hairline) solid var(--line); }
.sm-orderitems li:first-child { padding-top: 0; }
.sm-orderitems li > div { display: grid; min-width: 0; }
.sm-orderitems a { color: var(--ink); text-decoration: none; font-weight: 500; }
.sm-orderitems a:hover { text-decoration: underline; }
.sm-orderitems small { font-size: 13px; color: var(--ink-muted); }
.sm-orderitems strong { font-weight: 500; font-variant-numeric: tabular-nums; }
.sm-ordersum { margin: var(--space-4) 0 0; display: grid; gap: var(--space-2); font-size: 14px; }
.sm-ordersum div { display: flex; justify-content: space-between; gap: var(--space-4); }
.sm-ordersum dt { color: var(--ink-muted); }
.sm-ordersum dd { margin: 0; font-variant-numeric: tabular-nums; }
.sm-ordersum__total { padding-top: var(--space-3); margin-top: var(--space-1); border-top: var(--hairline) solid var(--line); font-size: 16px; }
.sm-ordersum__total dt { color: var(--ink); font-weight: 500; }
.sm-ordersum__total dd { font-weight: 600; }
.sm-addressgrid { display: grid; gap: var(--space-4); align-items: start; }
@media (min-width: 700px) { .sm-addressgrid { grid-template-columns: 1fr 1fr; } }
.sm-addresscard { display: grid; gap: var(--space-3); align-content: start; }
.sm-addresscard.is-default { border-color: var(--gold); }
.sm-addresscard .sm-badge { justify-self: start; }
.sm-addresscard .body { margin: 0; }
.sm-addresscard__actions { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-1) var(--space-4); padding-top: var(--space-3); border-top: var(--hairline) solid var(--line); }
.sm-addresscard__confirm { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-3); font-size: 14px; }
.sm-addresscard--add { min-height: 180px; place-content: center; justify-items: center; border: 1px dashed var(--line-strong); border-radius: var(--radius-md); background: transparent; color: var(--ink-muted); font: inherit; font-size: 15px; cursor: pointer; }
.sm-addresscard--add:hover { border-color: var(--ink); color: var(--ink); }
.sm-account__editor { grid-column: 1 / -1; }
.sm-account__editor > h2 { margin: 0 0 var(--space-4); }
.sm-linkbtn { display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0; border: 0; background: none; color: var(--ink); font: inherit; font-size: 14px; cursor: pointer; text-decoration: underline; text-underline-offset: 3px; text-decoration-color: var(--line-strong); }
.sm-linkbtn:hover { text-decoration-color: currentColor; }
.sm-linkbtn--danger { color: var(--danger); }