feat(admin): add posts-over-time and owner-growth charts to the dashboard

Two new chart panels on the admin dashboard, each with a day/week/month
granularity toggle:
- "Posts over time" — bar chart of new posts per bucket (trailing 30
  days / 12 weeks / 12 months, zero-filled so gaps show as zero, not
  missing points).
- "Owner growth" — line+area chart of the cumulative total registered
  owners, seeded from a pre-window baseline count so the curve starts
  at the correct absolute total instead of zero.

Backend: admin.getPostsOverTime/getOwnerGrowth bucket timestamps in
plain JS (UTC-consistent day/ISO-week-Monday/month-1st truncation) —
deliberately not raw SQL date_trunc, to avoid DB-session-timezone
ambiguity and keep this testable without hitting Postgres. Data volume
is small enough (Alpha-stage app) that fetching bare createdAt columns
and bucketing in memory is the simpler, lower-risk choice over adding
the codebase's first raw-SQL query.

Frontend: new src/components/admin/ (TimeSeriesChart, GranularityToggle)
following the dataviz skill — thin 2px marks, rounded bar corners,
recessive gridlines, hover crosshair+tooltip on both variants, single
brand-orange hue since each chart is one series (no legend needed).
Admin surface is fixed dark (zinc-950), so colors are hardcoded rather
than light/dark-aware, unlike the app-wide WeightChart this borrows its
SVG approach from.

Added 2 regression tests covering zero-fill bucketing and the
cumulative-with-baseline math. prisma-mock.ts gained owner.findMany/
owner.count (previously missing).
This commit is contained in:
admin committed 2026-07-23 19:59:36 +02:00
1 parent bb1515cb93
commit 0e02d3da71
6 files changed
+415

No files matched your search

+34
View File
@@ -189,3 +189,37 @@ describe("admin transactional moderation actions", () => {
expect(result).toEqual({ success: true });
});
});
describe("admin dashboard time-series", () => {
it("getPostsOverTime returns a zero-filled 30-bucket series with today's posts counted correctly", async () => {
vi.stubEnv("ADMIN_OWNER_ID", "admin-1");
const { caller, mockPrisma } = await createAdminCaller();
const now = new Date();
mockPrisma.post.findMany.mockResolvedValue([
{ createdAt: now },
{ createdAt: now },
]);
const result = await caller.admin.getPostsOverTime({ granularity: "day" });
expect(result).toHaveLength(30);
expect(result[29]!.value).toBe(2); // today = last bucket
expect(result.slice(0, 29).every((b) => b.value === 0)).toBe(true);
});
it("getOwnerGrowth returns a cumulative total, starting from the pre-window baseline", async () => {
vi.stubEnv("ADMIN_OWNER_ID", "admin-1");
const { caller, mockPrisma } = await createAdminCaller();
mockPrisma.owner.count.mockResolvedValue(5); // owners registered before the window
const now = new Date();
mockPrisma.owner.findMany.mockResolvedValue([{ createdAt: now }]);
const result = await caller.admin.getOwnerGrowth({ granularity: "day" });
expect(result).toHaveLength(30);
expect(result[0]!.value).toBe(5); // baseline carried through empty leading buckets
expect(result[29]!.value).toBe(6); // baseline + 1 new owner today
});
});
+4
View File
@@ -26,8 +26,10 @@ interface MockPetClient {
interface MockOwnerClient {
upsert: MockFn;
findUnique: MockFn;
findMany: MockFn;
create: MockFn;
update: MockFn;
count: MockFn;
}
interface MockInviteCodeClient {
@@ -280,8 +282,10 @@ export function createMockPrisma(): MockPrismaClient {
owner: {
upsert: vi.fn(),
findUnique: vi.fn(),
findMany: vi.fn(),
create: vi.fn(),
update: vi.fn(),
count: vi.fn(),
},
// pets.create's idempotent starter-invite-code seeding runs on every call —
// default to "no codes yet" so tests unrelated to invites don't need to stub it.
+47
View File
@@ -1,13 +1,26 @@
"use client";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTRPC } from "@/trpc/client";
import { Users, PawPrint, FileText, ShieldOff, Megaphone, Flag } from "lucide-react";
import { TimeSeriesChart } from "@/components/admin/TimeSeriesChart";
import { GranularityToggle, type Granularity } from "@/components/admin/GranularityToggle";
export default function AdminDashboard() {
const trpc = useTRPC();
const { data: stats, isLoading } = useQuery(trpc.admin.getStats.queryOptions());
const [postsGranularity, setPostsGranularity] = useState<Granularity>("day");
const [ownerGranularity, setOwnerGranularity] = useState<Granularity>("day");
const { data: postsOverTime } = useQuery(
trpc.admin.getPostsOverTime.queryOptions({ granularity: postsGranularity })
);
const { data: ownerGrowth } = useQuery(
trpc.admin.getOwnerGrowth.queryOptions({ granularity: ownerGranularity })
);
return (
<div className="space-y-6">
<div>
@@ -27,6 +40,40 @@ export default function AdminDashboard() {
<StatCard icon={Flag} label="Open reports" value={stats?.reports ?? 0} color="text-yellow-400" />
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div className="rounded-xl border border-zinc-800 bg-zinc-900 p-5">
<div className="flex items-center justify-between mb-4">
<div>
<h2 className="text-sm font-semibold text-zinc-100">Posts over time</h2>
<p className="text-xs text-zinc-500 mt-0.5">New posts per {postsGranularity}</p>
</div>
<GranularityToggle value={postsGranularity} onChange={setPostsGranularity} />
</div>
<TimeSeriesChart
data={postsOverTime ?? []}
granularity={postsGranularity}
variant="bar"
valueLabel="posts"
/>
</div>
<div className="rounded-xl border border-zinc-800 bg-zinc-900 p-5">
<div className="flex items-center justify-between mb-4">
<div>
<h2 className="text-sm font-semibold text-zinc-100">Owner growth</h2>
<p className="text-xs text-zinc-500 mt-0.5">Total registered owners</p>
</div>
<GranularityToggle value={ownerGranularity} onChange={setOwnerGranularity} />
</div>
<TimeSeriesChart
data={ownerGrowth ?? []}
granularity={ownerGranularity}
variant="line"
valueLabel="owners"
/>
</div>
</div>
</div>
);
}
@@ -0,0 +1,36 @@
"use client";
export type Granularity = "day" | "week" | "month";
const OPTIONS: { value: Granularity; label: string }[] = [
{ value: "day", label: "Day" },
{ value: "week", label: "Week" },
{ value: "month", label: "Month" },
];
export function GranularityToggle({
value,
onChange,
}: {
value: Granularity;
onChange: (g: Granularity) => void;
}) {
return (
<div className="flex items-center gap-1 bg-zinc-950 border border-zinc-800 p-0.5 rounded-lg">
{OPTIONS.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => onChange(opt.value)}
className={`px-2.5 py-1 rounded-md text-xs font-medium transition-colors ${
value === opt.value
? "bg-zinc-800 text-zinc-100"
: "text-zinc-500 hover:text-zinc-300"
}`}
>
{opt.label}
</button>
))}
</div>
);
}
+218
View File
@@ -0,0 +1,218 @@
"use client";
import { useState } from "react";
export interface TimeSeriesPoint {
date: string;
value: number;
}
interface TimeSeriesChartProps {
data: TimeSeriesPoint[];
granularity: "day" | "week" | "month";
variant: "bar" | "line";
/** Single-hex accent — admin surface is fixed dark, so no light/dark variant needed. */
color?: string;
valueLabel: string;
}
const W = 640;
const H = 220;
const L = 40; // left axis gutter
const R = 12;
const T = 16;
const B = 32;
function formatBucketLabel(iso: string, granularity: TimeSeriesChartProps["granularity"]): string {
const d = new Date(iso);
if (granularity === "month") {
return d.toLocaleDateString("en-US", { month: "short", year: "2-digit", timeZone: "UTC" });
}
return d.toLocaleDateString("en-US", { day: "2-digit", month: "short", timeZone: "UTC" });
}
/**
* Single-series time-series chart (bar for per-bucket counts, line+area for a
* cumulative growth curve). Admin dashboard only — always rendered on the
* fixed zinc-950 dark surface, so colors are hardcoded rather than
* light/dark-aware. One series → no legend needed (dataviz skill: a single
* series needs no legend box, the chart title names it).
*/
export function TimeSeriesChart({
data,
granularity,
variant,
color = "#f97316", // orange-500 — the app's existing single-hue brand accent
valueLabel,
}: TimeSeriesChartProps) {
const [hoverIdx, setHoverIdx] = useState<number | null>(null);
if (data.length === 0) {
return <div className="h-[220px] flex items-center justify-center text-sm text-zinc-600">No data yet</div>;
}
const maxV = Math.max(...data.map((d) => d.value), 1);
const cW = W - L - R;
const cH = H - T - B;
const xOf = (i: number) =>
data.length === 1 ? L + cW / 2 : L + (i / (data.length - 1)) * cW;
const yOf = (v: number) => T + cH - (v / maxV) * cH;
const yTicks = 4;
const yTickVals = Array.from({ length: yTicks + 1 }, (_, i) => (maxV * i) / yTicks);
const maxLabels = variant === "bar" ? Math.min(data.length, 8) : 6;
const step = Math.max(1, Math.ceil(data.length / maxLabels));
const xLabelIndices = new Set(
data.map((_, i) => i).filter((i) => i % step === 0 || i === data.length - 1)
);
const barWidth = variant === "bar" ? Math.max((cW / data.length) * 0.6, 2) : 0;
const linePath =
variant === "line"
? data
.map((d, i) => `${i === 0 ? "M" : "L"} ${xOf(i)} ${yOf(d.value)}`)
.join(" ")
: "";
const areaPath =
variant === "line"
? `M ${xOf(0)} ${T + cH} L ` +
data.map((d, i) => `${xOf(i)} ${yOf(d.value)}`).join(" L ") +
` L ${xOf(data.length - 1)} ${T + cH} Z`
: "";
const hovered = hoverIdx !== null ? data[hoverIdx] : null;
return (
<div className="relative">
<svg
viewBox={`0 0 ${W} ${H}`}
className="w-full"
style={{ maxHeight: H }}
role="img"
aria-label={`${valueLabel} over time`}
onMouseLeave={() => setHoverIdx(null)}
>
<defs>
<linearGradient id="pf-admin-area" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={color} stopOpacity="0.25" />
<stop offset="100%" stopColor={color} stopOpacity="0" />
</linearGradient>
</defs>
{/* Recessive gridlines */}
{yTickVals.map((v, i) => {
const y = yOf(v);
return (
<g key={i}>
<line x1={L} y1={y} x2={W - R} y2={y} stroke="#3f3f46" strokeWidth="1" strokeDasharray={i === 0 ? "0" : "3 3"} opacity={i === 0 ? 0.5 : 0.3} />
<text x={L - 6} y={y} textAnchor="end" dominantBaseline="middle" fontSize="9" fill="#71717a">
{Math.round(v)}
</text>
</g>
);
})}
{/* Bars */}
{variant === "bar" &&
data.map((d, i) => {
const x = xOf(i) - barWidth / 2;
const y = yOf(d.value);
const h = T + cH - y;
const isHovered = hoverIdx === i;
return (
<rect
key={i}
x={x}
y={y}
width={barWidth}
height={Math.max(h, 0)}
rx={2}
fill={color}
opacity={isHovered ? 1 : 0.75}
onMouseEnter={() => setHoverIdx(i)}
style={{ cursor: "pointer" }}
/>
);
})}
{/* Line + area */}
{variant === "line" && (
<>
<path d={areaPath} fill="url(#pf-admin-area)" />
<path d={linePath} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
{data.map((d, i) => {
const isHovered = hoverIdx === i;
return (
<g key={i}>
{/* wide invisible hit target */}
<rect
x={xOf(i) - cW / data.length / 2}
y={T}
width={cW / data.length}
height={cH}
fill="transparent"
onMouseEnter={() => setHoverIdx(i)}
/>
<circle
cx={xOf(i)}
cy={yOf(d.value)}
r={isHovered ? 4 : 2.5}
fill={isHovered ? color : "#18181b"}
stroke={color}
strokeWidth={isHovered ? 0 : 1.5}
/>
</g>
);
})}
</>
)}
{/* Hover crosshair */}
{hovered && (
<line
x1={xOf(hoverIdx!)}
y1={T}
x2={xOf(hoverIdx!)}
y2={T + cH}
stroke={color}
strokeOpacity="0.3"
strokeWidth="1"
strokeDasharray="2 2"
pointerEvents="none"
/>
)}
{/* X-axis labels */}
{data.map((d, i) => {
if (!xLabelIndices.has(i)) return null;
return (
<text key={i} x={xOf(i)} y={H - 8} textAnchor="middle" fontSize="9" fill="#71717a">
{formatBucketLabel(d.date, granularity)}
</text>
);
})}
</svg>
{/* Tooltip */}
{hovered && hoverIdx !== null && (
<div
className="absolute pointer-events-none rounded-lg bg-zinc-800 border border-zinc-700 px-2.5 py-1.5 text-xs shadow-lg"
style={{
left: `${(xOf(hoverIdx) / W) * 100}%`,
top: 4,
transform: "translateX(-50%)",
}}
>
<p className="text-zinc-400">{formatBucketLabel(hovered.date, granularity)}</p>
<p className="font-semibold text-zinc-100">
{hovered.value.toLocaleString()} {valueLabel}
</p>
</div>
)}
</div>
);
}
+76
View File
@@ -33,6 +33,49 @@ export async function assertAdmin(
}
}
type Granularity = "day" | "week" | "month";
const BUCKET_COUNT: Record<Granularity, number> = { day: 30, week: 12, month: 12 };
/** Truncates a date down to the start of its bucket, in UTC (day/ISO-week-Monday/month-1st). */
function truncateUTC(date: Date, granularity: Granularity): Date {
const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
if (granularity === "month") return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1));
if (granularity === "week") {
const isoDow = d.getUTCDay() || 7; // Mon=1..Sun=7
d.setUTCDate(d.getUTCDate() - isoDow + 1);
}
return d;
}
function stepBackOneBucket(date: Date, granularity: Granularity): Date {
const d = new Date(date);
if (granularity === "month") d.setUTCMonth(d.getUTCMonth() - 1);
else if (granularity === "week") d.setUTCDate(d.getUTCDate() - 7);
else d.setUTCDate(d.getUTCDate() - 1);
return d;
}
/** Ordered bucket start-dates (oldest first) ending at the current bucket. */
function buildBuckets(granularity: Granularity): Date[] {
const buckets: Date[] = [];
let cursor = truncateUTC(new Date(), granularity);
for (let i = 0; i < BUCKET_COUNT[granularity]; i++) {
buckets.unshift(cursor);
cursor = stepBackOneBucket(cursor, granularity);
}
return buckets;
}
/** Counts how many timestamps fall in each bucket (zero-filled — no gaps). */
function countByBucket(timestamps: Date[], buckets: Date[], granularity: Granularity): number[] {
const counts = new Map<number, number>();
for (const ts of timestamps) {
const key = truncateUTC(ts, granularity).getTime();
counts.set(key, (counts.get(key) ?? 0) + 1);
}
return buckets.map((b) => counts.get(b.getTime()) ?? 0);
}
export const adminRouter = router({
// ─── Ban status check (no admin role required) ───────────────────────────────
getActiveBan: protectedProcedure
@@ -66,6 +109,39 @@ export const adminRouter = router({
return { owners, pets, posts, bans, activeAds: ads, reports };
}),
/** New posts per bucket over the trailing window (30 days / 12 weeks / 12 months). */
getPostsOverTime: protectedProcedure
.input(z.object({ granularity: z.enum(["day", "week", "month"]) }))
.query(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
const buckets = buildBuckets(input.granularity);
const posts = await ctx.prisma.post.findMany({
where: { createdAt: { gte: buckets[0] } },
select: { createdAt: true },
});
const counts = countByBucket(posts.map((p) => p.createdAt), buckets, input.granularity);
return buckets.map((date, i) => ({ date: date.toISOString(), value: counts[i]! }));
}),
/** Cumulative total owners per bucket — the growth curve, not just new signups. */
getOwnerGrowth: protectedProcedure
.input(z.object({ granularity: z.enum(["day", "week", "month"]) }))
.query(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
const buckets = buildBuckets(input.granularity);
const [baselineCount, owners] = await Promise.all([
ctx.prisma.owner.count({ where: { createdAt: { lt: buckets[0] } } }),
ctx.prisma.owner.findMany({
where: { createdAt: { gte: buckets[0] } },
select: { createdAt: true },
}),
]);
const newPerBucket = countByBucket(owners.map((o) => o.createdAt), buckets, input.granularity);
let running = baselineCount;
const cumulative = newPerBucket.map((n) => (running += n));
return buckets.map((date, i) => ({ date: date.toISOString(), value: cumulative[i]! }));
}),
// ─── Post moderation ─────────────────────────────────────────────────────────
listPosts: protectedProcedure
.input(