sanamare/src/lib/categories.ts

34 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<CategoryNode[]> => {
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<Category, "id" | "name" | "parentId">[]) {
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<T extends Pick<Category, "id" | "name" | "parentId" | "sort">>(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)! }));
}