import "server-only"; import { cache } from "react"; import type { Category } from "@prisma/client"; import { db } from "./db"; export type CategoryNode = Category & { children: Category[] }; /** Alle Kategorien als Baum (Ober- mit Unterkategorien), sortiert. Einmal pro Anfrage geladen. */ export const getCategoryTree = cache(async (onlyActive = false): Promise => { const all = await db.category.findMany({ where: onlyActive ? { active: true } : undefined, orderBy: [{ sort: "asc" }, { name: "asc" }] }); const ids = new Set(all.map((c) => c.id)); // Unterkategorien einer ausgeblendeten Oberkategorie rutschen nicht nach oben, sie fallen mit weg const roots = all.filter((c) => !c.parentId || (!ids.has(c.parentId) && !onlyActive)); return roots.map((r) => ({ ...r, children: all.filter((c) => c.parentId === r.id) })); }); /** Die Kategorie selbst und alle ihre Unterkategorien. */ export async function withSubcategories(id: string) { const children = await db.category.findMany({ where: { parentId: id }, select: { id: true } }); return [id, ...children.map((c) => c.id)]; } /** "Matten › Reformer" für Auswahllisten im Admin. */ export function categoryLabels(all: Pick[]) { const byId = new Map(all.map((c) => [c.id, c])); return new Map(all.map((c) => [c.id, c.parentId && byId.get(c.parentId) ? `${byId.get(c.parentId)!.name} › ${c.name}` : c.name])); } /** Kategorien in Baum-Reihenfolge (Oberkategorie, dann ihre Unterkategorien) mit Anzeigenamen. */ export function sortedForSelect>(all: T[]) { const labels = categoryLabels(all); const roots = all.filter((c) => !c.parentId || !all.some((p) => p.id === c.parentId)).sort((a, b) => a.sort - b.sort); return roots.flatMap((r) => [r, ...all.filter((c) => c.parentId === r.id).sort((a, b) => a.sort - b.sort)]).map((c) => ({ ...c, label: labels.get(c.id)! })); }