From 9adba560a74dcac62aa1d3e4609004ee0f3559f8 Mon Sep 17 00:00:00 2001 From: neodk2004 Date: Fri, 2 Oct 2026 21:17:21 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20Admin-Dashboard=20=E2=80=94=20Verteilun?= =?UTF-8?q?g=20der=20Tiere=20nach=20Tierart=20und=20Rasse?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - petAdmin.speciesDistribution: Anzahl pro Tierart (auch Arten ohne Tiere) und pro Rasse, deutsche Namen, ohne das Kurator-Tier „PawFeed Team“ - Karte "Tierarten" auf dem Dashboard: sortiertes Balkendiagramm (eine Reihe, Markenorange), Anzahl + Anteil als Text, Tooltip bei Hover/Fokus, Klick klappt die Rassen der Art auf Co-Authored-By: Claude Opus 5.5 --- src/__tests__/helpers/prisma-mock.ts | 2 + src/__tests__/pet-admin.test.ts | 30 +++++ src/app/p/[secret]/page.tsx | 3 + .../admin/SpeciesDistributionCard.tsx | 112 ++++++++++++++++++ src/trpc/routers/pet-admin.ts | 41 +++++++ 5 files changed, 188 insertions(+) create mode 100644 src/components/admin/SpeciesDistributionCard.tsx diff --git a/src/__tests__/helpers/prisma-mock.ts b/src/__tests__/helpers/prisma-mock.ts index dd1ae7a..b8d58a2 100644 --- a/src/__tests__/helpers/prisma-mock.ts +++ b/src/__tests__/helpers/prisma-mock.ts @@ -23,6 +23,7 @@ interface MockPetClient { delete: MockFn; deleteMany: MockFn; count: MockFn; + groupBy: MockFn; } interface MockOwnerClient { @@ -424,6 +425,7 @@ export function createMockPrisma(): MockPrismaClient { delete: vi.fn(), deleteMany: vi.fn(), count: vi.fn(), + groupBy: vi.fn().mockResolvedValue([]), }, owner: { upsert: vi.fn(), diff --git a/src/__tests__/pet-admin.test.ts b/src/__tests__/pet-admin.test.ts index 2e4793e..5162f54 100644 --- a/src/__tests__/pet-admin.test.ts +++ b/src/__tests__/pet-admin.test.ts @@ -99,6 +99,36 @@ describe("petAdmin.delete", () => { }); }); +describe("petAdmin.speciesDistribution", () => { + it("counts pets per species and breed, includes empty species and excludes the curator pet", async () => { + const prisma = createMockPrisma(); + mockAssertAdmin.mockResolvedValue("MODERATOR"); + prisma.species.findMany.mockResolvedValue([ + { id: "cat", name: "Cat", translations: [{ name: "Katze" }], breeds: [{ id: "bengal", name: "Bengal", translations: [] }] }, + { id: "dog", name: "Dog", translations: [{ name: "Hund" }], breeds: [] }, + { id: "spider", name: "Spider", translations: [{ name: "Spinne" }], breeds: [] }, + ]); + prisma.pet.groupBy + .mockResolvedValueOnce([ + { speciesId: "cat", _count: { _all: 3 } }, + { speciesId: "dog", _count: { _all: 1 } }, + ]) + .mockResolvedValueOnce([ + { speciesId: "cat", breedId: "bengal", _count: { _all: 2 } }, + { speciesId: "cat", breedId: null, _count: { _all: 1 } }, + { speciesId: "dog", breedId: null, _count: { _all: 1 } }, + ]); + const { c } = await createCaller(prisma); + + const result = await c.petAdmin.speciesDistribution(); + + expect(result.total).toBe(4); + expect(result.species.map((s) => [s.name, s.count])).toEqual([["Katze", 3], ["Hund", 1], ["Spinne", 0]]); + expect(result.species[0].breeds).toEqual([{ name: "Bengal", count: 2 }, { name: "Ohne Rassenangabe", count: 1 }]); + expect(prisma.pet.groupBy.mock.calls[0][0].where).toEqual({ id: { not: "pet-team" } }); + }); +}); + describe("petAdmin.clearContent", () => { it("clears the chosen fields, removes the avatar file and logs it", async () => { const prisma = createMockPrisma(); diff --git a/src/app/p/[secret]/page.tsx b/src/app/p/[secret]/page.tsx index fcbb0d2..f66c53e 100644 --- a/src/app/p/[secret]/page.tsx +++ b/src/app/p/[secret]/page.tsx @@ -7,6 +7,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useTRPC } from "@/trpc/client"; import { Flag, Clock, TriangleAlert, TrendingUp, ShieldAlert, Info, ChevronRight } from "lucide-react"; import { TimeSeriesChart } from "@/components/admin/TimeSeriesChart"; +import { SpeciesDistributionCard } from "@/components/admin/SpeciesDistributionCard"; import { GranularityToggle, type Granularity } from "@/components/admin/GranularityToggle"; import { Button } from "@/components/ui/button"; import { Card, CardHeader, CardTitle, CardDescription, CardAction, CardContent } from "@/components/ui/card"; @@ -162,6 +163,8 @@ export default function AdminDashboard() { )} + +
diff --git a/src/components/admin/SpeciesDistributionCard.tsx b/src/components/admin/SpeciesDistributionCard.tsx new file mode 100644 index 0000000..be3017f --- /dev/null +++ b/src/components/admin/SpeciesDistributionCard.tsx @@ -0,0 +1,112 @@ +"use client"; + +import { useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { ChevronDown, Loader2 } from "lucide-react"; +import { useTRPC } from "@/trpc/client"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { cn } from "@/lib/utils"; + +const percent = (part: number, total: number) => + total > 0 ? (part / total).toLocaleString("de-DE", { style: "percent", maximumFractionDigits: 1 }) : "0 %"; + +/** + * Admin-Dashboard: Verteilung der angelegten Tiere nach Tierart. Eine Reihe, + * daher ein Farbton (Markenorange); Werte stehen als Text daneben, Tooltip bei + * Hover/Fokus, Klick klappt die Rassen der Art auf. Daten: petAdmin.speciesDistribution. + */ +export function SpeciesDistributionCard() { + const trpc = useTRPC(); + const { data, isLoading } = useQuery(trpc.petAdmin.speciesDistribution.queryOptions()); + const [openId, setOpenId] = useState(null); + const [hoverId, setHoverId] = useState(null); + + const species = data?.species ?? []; + const total = data?.total ?? 0; + const max = Math.max(1, ...species.map((s) => s.count)); + const represented = species.filter((s) => s.count > 0).length; + + return ( + + + Tierarten + + {isLoading + ? "Wird geladen…" + : `${total} Tiere · ${represented} von ${species.length} Tierarten vertreten. Klick auf eine Art zeigt die Rassen.`} + + + + {isLoading ? ( + + ) : ( +
    + {species.map((s) => { + const isOpen = openId === s.id; + const share = percent(s.count, total); + return ( +
  • + + + {isOpen && ( +
      + {s.breeds.map((b) => ( +
    • + {b.name} +
    • + ))} +
    + )} +
  • + ); + })} +
+ )} +
+
+ ); +} diff --git a/src/trpc/routers/pet-admin.ts b/src/trpc/routers/pet-admin.ts index 55e8d83..b35e115 100644 --- a/src/trpc/routers/pet-admin.ts +++ b/src/trpc/routers/pet-admin.ts @@ -168,6 +168,47 @@ export const petAdminRouter = router({ return { pet, ranks }; }), + /** + * Verteilung der angelegten Tiere nach Tierart (inkl. Arten ohne Tiere) und + * innerhalb jeder Art nach Rasse — für das Admin-Dashboard. Das Kurator-Tier + * „PawFeed Team“ zählt nicht mit. + */ + speciesDistribution: protectedProcedure.query(async ({ ctx }) => { + await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR); + const teamPet = await ensureTeamPet(ctx.prisma).catch(() => null); + const excludeTeam: Prisma.PetWhereInput = teamPet ? { id: { not: teamPet.id } } : {}; + + const [species, bySpecies, byBreed] = await Promise.all([ + ctx.prisma.species.findMany({ + select: { + id: true, + name: true, + translations: { where: { locale: "de" }, select: { name: true } }, + breeds: { select: { id: true, name: true, translations: { where: { locale: "de" }, select: { name: true } } } }, + }, + }), + ctx.prisma.pet.groupBy({ by: ["speciesId"], where: excludeTeam, _count: { _all: true } }), + ctx.prisma.pet.groupBy({ by: ["speciesId", "breedId"], where: excludeTeam, _count: { _all: true } }), + ]); + + const countBySpecies = new Map(bySpecies.map((row) => [row.speciesId, row._count._all])); + const total = bySpecies.reduce((sum, row) => sum + row._count._all, 0); + + const rows = species.map((s) => { + const breedName = new Map(s.breeds.map((b) => [b.id, b.translations[0]?.name ?? b.name])); + const breeds = byBreed + .filter((row) => row.speciesId === s.id) + .map((row) => ({ + name: row.breedId ? (breedName.get(row.breedId) ?? "Unbekannt") : "Ohne Rassenangabe", + count: row._count._all, + })) + .sort((a, b) => b.count - a.count); + return { id: s.id, name: s.translations[0]?.name ?? s.name, count: countBySpecies.get(s.id) ?? 0, breeds }; + }); + + return { total, species: rows.sort((a, b) => b.count - a.count || a.name.localeCompare(b.name, "de")) }; + }), + setFoundingMember: protectedProcedure .input(z.object({ petId: z.string().min(1), value: z.boolean() })) .mutation(async ({ ctx, input }) => {