feat: Admin-Dashboard — Verteilung der Tiere nach Tierart und Rasse
- 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
efc82d636d
commit
9adba560a7
5 files changed
+188
No files matched your search
@@ -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(),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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() {
|
||||
</>
|
||||
)}
|
||||
|
||||
<SpeciesDistributionCard />
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
@@ -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<string | null>(null);
|
||||
const [hoverId, setHoverId] = useState<string | null>(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 (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Tierarten</CardTitle>
|
||||
<CardDescription>
|
||||
{isLoading
|
||||
? "Wird geladen…"
|
||||
: `${total} Tiere · ${represented} von ${species.length} Tierarten vertreten. Klick auf eine Art zeigt die Rassen.`}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<Loader2 className="mx-auto my-8 h-5 w-5 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<ul className="space-y-0.5" aria-label="Verteilung der Tiere nach Tierart">
|
||||
{species.map((s) => {
|
||||
const isOpen = openId === s.id;
|
||||
const share = percent(s.count, total);
|
||||
return (
|
||||
<li key={s.id}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={s.count === 0}
|
||||
aria-expanded={s.count > 0 ? isOpen : undefined}
|
||||
aria-label={`${s.name}: ${s.count} Tiere, ${share}`}
|
||||
onClick={() => setOpenId(isOpen ? null : s.id)}
|
||||
onMouseEnter={() => setHoverId(s.id)}
|
||||
onMouseLeave={() => setHoverId(null)}
|
||||
onFocus={() => setHoverId(s.id)}
|
||||
onBlur={() => setHoverId(null)}
|
||||
className="group relative grid w-full grid-cols-[8.5rem_1fr_5.5rem] items-center gap-3 rounded-md px-1 py-1.5 text-left text-sm hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-orange-500 disabled:cursor-default disabled:hover:bg-transparent"
|
||||
>
|
||||
<span className={cn("flex items-center gap-1 truncate", s.count === 0 && "text-muted-foreground")}>
|
||||
{s.count > 0 && (
|
||||
<ChevronDown className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform", !isOpen && "-rotate-90")} aria-hidden="true" />
|
||||
)}
|
||||
{s.name}
|
||||
</span>
|
||||
<span className="h-3 w-full" aria-hidden="true">
|
||||
{s.count > 0 && (
|
||||
<span
|
||||
className="block h-full rounded-r bg-orange-500 transition-opacity group-hover:opacity-85"
|
||||
style={{ width: `${(s.count / max) * 100}%`, minWidth: 3 }}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<span className="text-right tabular-nums text-muted-foreground">
|
||||
<span className="font-medium text-foreground">{s.count}</span> · {share}
|
||||
</span>
|
||||
{hoverId === s.id && s.count > 0 && (
|
||||
<span
|
||||
role="tooltip"
|
||||
className="pointer-events-none absolute left-[9.5rem] top-full z-10 mt-1 whitespace-nowrap rounded-md border bg-popover px-2.5 py-1.5 text-xs text-popover-foreground shadow-md"
|
||||
>
|
||||
<strong>{s.name}</strong>: {s.count} {s.count === 1 ? "Tier" : "Tiere"} · {share} aller Tiere ·{" "}
|
||||
{s.breeds.length} {s.breeds.length === 1 ? "Rasse/Angabe" : "Rassen/Angaben"}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<ul className="mb-2 ml-[1.1rem] space-y-0.5 border-l pl-3" aria-label={`Rassen bei ${s.name}`}>
|
||||
{s.breeds.map((b) => (
|
||||
<li key={b.name} className="grid grid-cols-[8.5rem_1fr_5.5rem] items-center gap-3 py-1 text-xs">
|
||||
<span className="truncate text-muted-foreground">{b.name}</span>
|
||||
<span className="h-2 w-full" aria-hidden="true">
|
||||
<span className="block h-full rounded-r bg-orange-500/55" style={{ width: `${(b.count / s.count) * 100}%`, minWidth: 3 }} />
|
||||
</span>
|
||||
<span className="text-right tabular-nums text-muted-foreground">
|
||||
<span className="font-medium text-foreground">{b.count}</span> · {percent(b.count, s.count)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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 }) => {
|
||||
|
||||
Reference in new issue
Block a user