diff --git a/src/__tests__/admin.test.ts b/src/__tests__/admin.test.ts index 9e7c20b..ea7601c 100644 --- a/src/__tests__/admin.test.ts +++ b/src/__tests__/admin.test.ts @@ -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 + }); +}); diff --git a/src/__tests__/helpers/prisma-mock.ts b/src/__tests__/helpers/prisma-mock.ts index 0167298..f569748 100644 --- a/src/__tests__/helpers/prisma-mock.ts +++ b/src/__tests__/helpers/prisma-mock.ts @@ -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. diff --git a/src/app/p/[secret]/page.tsx b/src/app/p/[secret]/page.tsx index f42e462..2672363 100644 --- a/src/app/p/[secret]/page.tsx +++ b/src/app/p/[secret]/page.tsx @@ -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("day"); + const [ownerGranularity, setOwnerGranularity] = useState("day"); + + const { data: postsOverTime } = useQuery( + trpc.admin.getPostsOverTime.queryOptions({ granularity: postsGranularity }) + ); + const { data: ownerGrowth } = useQuery( + trpc.admin.getOwnerGrowth.queryOptions({ granularity: ownerGranularity }) + ); + return (
@@ -27,6 +40,40 @@ export default function AdminDashboard() {
)} + +
+
+
+
+

Posts over time

+

New posts per {postsGranularity}

+
+ +
+ +
+ +
+
+
+

Owner growth

+

Total registered owners

+
+ +
+ +
+
); } diff --git a/src/components/admin/GranularityToggle.tsx b/src/components/admin/GranularityToggle.tsx new file mode 100644 index 0000000..43ada08 --- /dev/null +++ b/src/components/admin/GranularityToggle.tsx @@ -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 ( +
+ {OPTIONS.map((opt) => ( + + ))} +
+ ); +} diff --git a/src/components/admin/TimeSeriesChart.tsx b/src/components/admin/TimeSeriesChart.tsx new file mode 100644 index 0000000..1a43981 --- /dev/null +++ b/src/components/admin/TimeSeriesChart.tsx @@ -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(null); + + if (data.length === 0) { + return
No data yet
; + } + + 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 ( +
+ setHoverIdx(null)} + > + + + + + + + + {/* Recessive gridlines */} + {yTickVals.map((v, i) => { + const y = yOf(v); + return ( + + + + {Math.round(v)} + + + ); + })} + + {/* 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 ( + setHoverIdx(i)} + style={{ cursor: "pointer" }} + /> + ); + })} + + {/* Line + area */} + {variant === "line" && ( + <> + + + {data.map((d, i) => { + const isHovered = hoverIdx === i; + return ( + + {/* wide invisible hit target */} + setHoverIdx(i)} + /> + + + ); + })} + + )} + + {/* Hover crosshair */} + {hovered && ( + + )} + + {/* X-axis labels */} + {data.map((d, i) => { + if (!xLabelIndices.has(i)) return null; + return ( + + {formatBucketLabel(d.date, granularity)} + + ); + })} + + + {/* Tooltip */} + {hovered && hoverIdx !== null && ( +
+

{formatBucketLabel(hovered.date, granularity)}

+

+ {hovered.value.toLocaleString()} {valueLabel} +

+
+ )} +
+ ); +} diff --git a/src/trpc/routers/admin.ts b/src/trpc/routers/admin.ts index ff83d8c..034ba0a 100644 --- a/src/trpc/routers/admin.ts +++ b/src/trpc/routers/admin.ts @@ -33,6 +33,49 @@ export async function assertAdmin( } } +type Granularity = "day" | "week" | "month"; +const BUCKET_COUNT: Record = { 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(); + 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(