diff --git a/prisma/migrations/20261020200000_category_tree/migration.sql b/prisma/migrations/20261020200000_category_tree/migration.sql new file mode 100644 index 0000000..04f5806 --- /dev/null +++ b/prisma/migrations/20261020200000_category_tree/migration.sql @@ -0,0 +1,6 @@ +-- AlterTable +ALTER TABLE "Category" ADD COLUMN "parentId" TEXT; + +-- AddForeignKey +ALTER TABLE "Category" ADD CONSTRAINT "Category_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "Category"("id") ON DELETE SET NULL ON UPDATE CASCADE; + diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 0167566..221af4c 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -87,17 +87,21 @@ model Address { // ---------- Katalog ---------- model Category { - id String @id @default(cuid()) + 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) + slug String @unique + description String @default("") + image String @default("") + sort Int @default(0) + active Boolean @default(true) + showOnHome Boolean @default(true) + // Oberkategorie; leer = selbst Oberkategorie. Höchstens zwei Ebenen. + parentId String? + parent Category? @relation("CategoryTree", fields: [parentId], references: [id], onDelete: SetNull) + children Category[] @relation("CategoryTree") products Product[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt } model Product { diff --git a/src/app/(shop)/kategorie/[slug]/page.tsx b/src/app/(shop)/kategorie/[slug]/page.tsx index 862c6e4..527e662 100644 --- a/src/app/(shop)/kategorie/[slug]/page.tsx +++ b/src/app/(shop)/kategorie/[slug]/page.tsx @@ -9,6 +9,8 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str return { title: c?.name ?? "Kategorie" }; } +const activeChildren = { where: { active: true }, orderBy: [{ sort: "asc" as const }, { name: "asc" as const }] }; + export default async function CategoryPage({ params, searchParams, @@ -17,20 +19,54 @@ export default async function CategoryPage({ 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(); + const category = await db.category.findUnique({ where: { slug }, include: { children: activeChildren, parent: { include: { children: activeChildren } } } }); + if (!category || !category.active || (category.parent && !category.parent.active)) notFound(); + + // Eine Oberkategorie ist eine eigene Rubrik: Titelbild, Text und nur ihre Produkte samt Unterkategorien + const rubric = category.parent ?? category; + const subs = rubric.children; + const chips = subs.length + ? [{ label: "Alle", href: `/kategorie/${rubric.slug}`, active: !category.parent }, ...subs.map((c) => ({ label: c.name, href: `/kategorie/${c.slug}`, active: c.id === category.id }))] + : undefined; + const ids = category.parent ? [category.id] : [category.id, ...subs.map((c) => c.id)]; + const crumbs = ( + + ); + return ( -
- -

{category.name}

- {category.description &&

{category.description}

} - -
+ <> + {!category.parent && category.image ? ( +
+
+
+ {crumbs} +

{category.name}

+ +
+ {/* eslint-disable-next-line @next/next/no-img-element */} + +
+
+
+ ) : null} +
+ {(category.parent || !category.image) && ( + <> + {crumbs} +

{category.name}

+ {category.description &&

{category.description}

} + + )} + +
+ ); } diff --git a/src/app/(shop)/kollektionen/page.tsx b/src/app/(shop)/kollektionen/page.tsx index 52b06b3..88b922c 100644 --- a/src/app/(shop)/kollektionen/page.tsx +++ b/src/app/(shop)/kollektionen/page.tsx @@ -6,7 +6,7 @@ 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" } }); + const categories = await db.category.findMany({ where: { active: true, parentId: null }, orderBy: { sort: "asc" } }); return (
Kollektionen diff --git a/src/app/admin/(panel)/gestaltung/page.tsx b/src/app/admin/(panel)/gestaltung/page.tsx index c9c608a..520f37f 100644 --- a/src/app/admin/(panel)/gestaltung/page.tsx +++ b/src/app/admin/(panel)/gestaltung/page.tsx @@ -1,5 +1,6 @@ import { requireAdmin } from "@/lib/auth"; import { getSettings } from "@/lib/settings"; +import { getCategoryTree } from "@/lib/categories"; import { Field, TextareaField } from "@/components/Field"; import { AdminForm } from "@/components/admin/AdminForm"; import { NavEditor, TrustEditor } from "@/components/admin/ListEditors"; @@ -8,7 +9,9 @@ import { saveAppearance } from "./actions"; export default async function AppearancePage() { await requireAdmin("appearance.edit"); - const a = (await getSettings()).appearance; + const [settings, tree] = await Promise.all([getSettings(), getCategoryTree(true)]); + const a = settings.appearance; + const rubrics = tree.map((r) => ({ name: r.name, slug: r.slug })); return (
@@ -22,8 +25,8 @@ export default async function AppearancePage() {
- - + + diff --git a/src/app/admin/(panel)/kategorien/actions.ts b/src/app/admin/(panel)/kategorien/actions.ts index c73e728..398e3da 100644 --- a/src/app/admin/(panel)/kategorien/actions.ts +++ b/src/app/admin/(panel)/kategorien/actions.ts @@ -17,7 +17,16 @@ export async function saveCategory(_prev: ActionResult, fd: FormData): Promise
@@ -17,6 +18,14 @@ function CategoryFields({ c }: { c: C }) {
+ {hasChildren ? ( +

Oberkategorie mit Unterkategorien. Sie kann selbst keiner anderen Kategorie untergeordnet werden.

+ ) : ( + + + {parents.filter((p) => p.id !== c.id).map((p) => )} + + )} @@ -24,7 +33,7 @@ function CategoryFields({ c }: { c: C }) {
Kachelbild - +
); @@ -32,28 +41,46 @@ function CategoryFields({ c }: { c: C }) { export default async function CategoriesPage() { await requireAdmin("categories.edit"); - const categories = await db.category.findMany({ orderBy: { sort: "asc" }, include: { _count: { select: { products: true } } } }); + const categories = await db.category.findMany({ orderBy: [{ sort: "asc" }, { name: "asc" }], include: { _count: { select: { products: true } } } }); + const roots = categories.filter((c) => !c.parentId || !categories.some((p) => p.id === c.parentId)); + const childrenOf = (id: string) => categories.filter((c) => c.parentId === id); + const parents = roots.map((r) => ({ id: r.id, name: r.name })); + const card = (c: (typeof categories)[number], sub = false) => { + const kids = childrenOf(c.id); + const total = c._count.products + kids.reduce((n, k) => n + k._count.products, 0); + return ( +
+ +
+

{sub && }{c.name}

+

+ {kids.length ? `${total} Produkte, davon ${c._count.products} direkt · ${kids.length} Unterkategorie${kids.length === 1 ? "" : "n"}` : `${c._count.products} Produkte`} · /{c.slug}{c.active ? "" : " · versteckt"} +

+
+ Bearbeiten +
+
+ Löschen}> + 0} /> + +
+
+ ); + }; return (
- - {categories.map((c) => ( -
- -

{c.name}

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

- Bearbeiten -
-
- Löschen}> - - -
-
+ + {roots.map((r) => ( +
+ {card(r)} + {childrenOf(r.id).map((k) => card(k, true))} +
))}

Neue Kategorie

- +
diff --git a/src/app/admin/(panel)/produkte/[id]/page.tsx b/src/app/admin/(panel)/produkte/[id]/page.tsx index 9d1ef54..b34e342 100644 --- a/src/app/admin/(panel)/produkte/[id]/page.tsx +++ b/src/app/admin/(panel)/produkte/[id]/page.tsx @@ -1,5 +1,6 @@ import { notFound } from "next/navigation"; import { db } from "@/lib/db"; +import { sortedForSelect } from "@/lib/categories"; import { can, requireAdmin } from "@/lib/auth"; import { centsToInput, formatPrice } from "@/lib/money"; import { bestSale, getRunningSales, reduce } from "@/lib/sales"; @@ -46,7 +47,7 @@ export default async function EditProduct({ params, searchParams }: { params: Pr )}
diff --git a/src/app/admin/(panel)/produkte/page.tsx b/src/app/admin/(panel)/produkte/page.tsx index 9806f35..f10f2ca 100644 --- a/src/app/admin/(panel)/produkte/page.tsx +++ b/src/app/admin/(panel)/produkte/page.tsx @@ -2,6 +2,7 @@ import Link from "next/link"; import type { Prisma } from "@prisma/client"; import { db } from "@/lib/db"; +import { categoryLabels, sortedForSelect, withSubcategories } from "@/lib/categories"; import { can, requireAdmin } from "@/lib/auth"; import { formatPrice } from "@/lib/money"; import { Icon } from "@/components/Icon"; @@ -14,7 +15,8 @@ export default async function ProductsPage({ searchParams }: { searchParams: Pro const q = (sp.q ?? "").trim(); const where: Prisma.ProductWhereInput = { ...(q ? { OR: [{ name: { contains: q, mode: "insensitive" } }, { sku: { contains: q, mode: "insensitive" } }] } : {}), - ...(sp.kategorie ? { categoryId: sp.kategorie } : {}), + // Oberkategorie zeigt auch die Produkte ihrer Unterkategorien + ...(sp.kategorie ? { categoryId: { in: await withSubcategories(sp.kategorie) } } : {}), ...(sp.filter === "versteckt" ? { active: false } : sp.filter === "aktiv" ? { active: true } : {}), }; const [products, categories] = await Promise.all([ @@ -22,6 +24,7 @@ export default async function ProductsPage({ searchParams }: { searchParams: Pro db.category.findMany({ orderBy: { sort: "asc" } }), ]); const editable = can(user, "products.edit"); + const labels = categoryLabels(categories); return (
@@ -32,7 +35,7 @@ export default async function ProductsPage({ searchParams }: { searchParams: Pro i.label.trim()))} /> - + {rubrics.length > 0 && } {items.map((it, i) => ( + {rubrics.length > 0 && ( + + )}
TextZiel (z. B. /shop oder /kategorie/matten)
TextRubrikZiel (z. B. /shop oder /kategorie/matten)
set(i, "label", e.target.value)} aria-label="Text" /> + + + + set(i, "href", e.target.value)} aria-label="Ziel" /> {" "} diff --git a/src/components/admin/ProductForm.tsx b/src/components/admin/ProductForm.tsx index 2dd6dc6..afdb746 100644 --- a/src/components/admin/ProductForm.tsx +++ b/src/components/admin/ProductForm.tsx @@ -29,7 +29,7 @@ export type ProductFormValues = { variants: VariantRow[]; }; -export function ProductForm({ values, categories, canStock }: { values: ProductFormValues; categories: Category[]; canStock: boolean }) { +export function ProductForm({ values, categories, canStock }: { values: ProductFormValues; categories: (Pick & { label?: string })[]; canStock: boolean }) { return ( {(state) => { @@ -86,7 +86,7 @@ export function ProductForm({ values, categories, canStock }: { values: ProductF
- {categories.map((c) => )} + {categories.map((c) => )} diff --git a/src/components/shop/Footer.tsx b/src/components/shop/Footer.tsx index 1426e3c..d95942d 100644 --- a/src/components/shop/Footer.tsx +++ b/src/components/shop/Footer.tsx @@ -6,7 +6,7 @@ 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.category.findMany({ where: { active: true, parentId: null }, 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" } }), ]); diff --git a/src/components/shop/Header.tsx b/src/components/shop/Header.tsx index c4545a3..f7327c9 100644 --- a/src/components/shop/Header.tsx +++ b/src/components/shop/Header.tsx @@ -2,13 +2,19 @@ import Link from "next/link"; import { getCartCount } from "@/lib/cart"; import { getCurrentUser } from "@/lib/auth"; import { getSettings } from "@/lib/settings"; +import { getCategoryTree } from "@/lib/categories"; import { Icon } from "../Icon"; -import { MobileNav, NavLinks } from "./NavLinks"; +import { MobileNav, NavLinks, type NavItem } from "./NavLinks"; import { ThemeToggle } from "../ThemeToggle"; export async function Header() { - const [settings, count, user] = await Promise.all([getSettings(), getCartCount(), getCurrentUser()]); + const [settings, count, user, tree] = await Promise.all([getSettings(), getCartCount(), getCurrentUser(), getCategoryTree(true)]); const a = settings.appearance; + // Zeigt ein Menüpunkt auf eine Rubrik (Oberkategorie), klappen darunter ihre Unterkategorien auf + const nav: NavItem[] = a.navigation.map((l) => { + const rubric = tree.find((r) => l.href === `/kategorie/${r.slug}`); + return rubric?.children.length ? { ...l, children: rubric.children.map((c) => ({ label: c.name, href: `/kategorie/${c.slug}` })) } : l; + }); return (
{(a.promoText || a.promoLinkLabel) && ( @@ -21,7 +27,7 @@ export async function Header() {
{settings.general.shopName}.
- +
diff --git a/src/components/shop/NavLinks.tsx b/src/components/shop/NavLinks.tsx index f71b9c2..8dca816 100644 --- a/src/components/shop/NavLinks.tsx +++ b/src/components/shop/NavLinks.tsx @@ -1,29 +1,86 @@ "use client"; import Link from "next/link"; import { usePathname } from "next/navigation"; -import { useEffect, useRef } from "react"; +import { useEffect, useRef, useState } from "react"; import type { NavLink } from "@/lib/settings"; import { Icon } from "../Icon"; +/** Navigationspunkt, bei Rubriken mit ihren Unterkategorien als Menü. */ +export type NavItem = NavLink & { children?: NavLink[] }; + function isActive(pathname: string, href: string) { if (href === "/") return pathname === "/"; return pathname === href || pathname.startsWith(href + "/"); } -export function NavLinks({ links }: { links: NavLink[] }) { +export function NavLinks({ links }: { links: NavItem[] }) { const pathname = usePathname(); + const ref = useRef(null); + // Nach dem Klick auf einen Menüpunkt bleibt der Fokus im Menü und hielte es offen + useEffect(() => { + const el = document.activeElement; + if (el instanceof HTMLElement && ref.current?.contains(el)) el.blur(); + }, [pathname]); return ( - diff --git a/src/components/shop/ProductList.tsx b/src/components/shop/ProductList.tsx index 019a35c..9d964f9 100644 --- a/src/components/shop/ProductList.tsx +++ b/src/components/shop/ProductList.tsx @@ -17,17 +17,20 @@ export async function ProductList({ sort, showCategoryChips, activeCategory, + chips, }: { basePath: string; where: Prisma.ProductWhereInput; sort?: string; showCategoryChips?: boolean; activeCategory?: string; + // Eigene Filter-Chips, z. B. die Unterkategorien einer Rubrik + chips?: { label: string; href: string; active: boolean }[]; }) { 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 }).then(withSales), - showCategoryChips ? db.category.findMany({ where: { active: true }, orderBy: { sort: "asc" } }) : [], + showCategoryChips && !chips ? db.category.findMany({ where: { active: true, parentId: null }, orderBy: { sort: "asc" } }) : [], ]); // Nach Sale-Preis sortieren, nicht nach dem gespeicherten Preis if (s === "preis-auf") products.sort((a, b) => a.price - b.price); @@ -35,7 +38,15 @@ export async function ProductList({ return ( <>
- {showCategoryChips ? ( + {chips ? ( + + ) : showCategoryChips ? (