4c3880e07f
Moderator role existed in the schema and was already respected by
comment deletion, but every admin page/route treated moderator
identically to a regular user (403/redirect). Wires it up narrowly:
admin/layout.tsx now lets admin+moderator through and filters the
nav by role, while every admin-only page (users, tiers, settings,
webhooks, insights, etc.) explicitly redirects moderators away via a
new requireFullAdminPage() helper -- the nav filter is UX, this is
the actual gate. Moderators land on Reports and Recipes: reports
GET/PATCH now accept requireAdmin({allowModerator: true}), and a new
PATCH /api/v1/admin/recipes/[id] lets admin+moderator unpublish a
public recipe (flip to private) as a takedown action, audit-logged.
Also found and fixed a real bug while auditing the PWA push pipeline
for a "push click-through" gap: public/sw.js had no `push` event
listener at all, so incoming push messages never displayed anything
-- push was silently non-functional end-to-end despite the
subscribe/send plumbing all working. Added the push listener
(showNotification) and a notificationclick listener that focuses an
existing tab or opens one at the payload's url.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
185 lines
7.2 KiB
TypeScript
185 lines
7.2 KiB
TypeScript
import type { Metadata } from "next";
|
|
import { db, users, recipes, userUsage, supportTickets, gte, sql } from "@epicure/db";
|
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
|
import { BarChart } from "@/components/admin/charts/bar-chart";
|
|
import { TimeSeriesChart } from "@/components/admin/charts/time-series-chart";
|
|
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
|
|
|
export const metadata: Metadata = {};
|
|
|
|
const DAYS = 30;
|
|
|
|
function lastNDays(n: number): string[] {
|
|
const out: string[] = [];
|
|
const now = new Date();
|
|
for (let i = n - 1; i >= 0; i--) {
|
|
const d = new Date(now);
|
|
d.setDate(d.getDate() - i);
|
|
out.push(d.toISOString().slice(0, 10));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function formatShortDate(d: string) {
|
|
const date = new Date(`${d}T00:00:00Z`);
|
|
return date.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" });
|
|
}
|
|
|
|
function lastNMonths(n: number): string[] {
|
|
const out: string[] = [];
|
|
const now = new Date();
|
|
for (let i = n - 1; i >= 0; i--) {
|
|
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
|
out.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export default async function AdminInsightsPage() {
|
|
await requireFullAdminPage();
|
|
const since = new Date();
|
|
since.setDate(since.getDate() - DAYS);
|
|
|
|
// Promise.allSettled, not all — six independent aggregate queries feeding
|
|
// six independent charts; one query breaking (e.g. a table that's empty
|
|
// in a fresh install) shouldn't take down every chart on the page.
|
|
const results = await Promise.allSettled([
|
|
db
|
|
.select({ day: sql<string>`to_char(${users.createdAt}, 'YYYY-MM-DD')`.as("day"), n: sql<number>`count(*)::int` })
|
|
.from(users)
|
|
.where(gte(users.createdAt, since))
|
|
.groupBy(sql`to_char(${users.createdAt}, 'YYYY-MM-DD')`),
|
|
db
|
|
.select({
|
|
day: sql<string>`to_char(${recipes.createdAt}, 'YYYY-MM-DD')`.as("day"),
|
|
aiGenerated: recipes.aiGenerated,
|
|
n: sql<number>`count(*)::int`,
|
|
})
|
|
.from(recipes)
|
|
.where(gte(recipes.createdAt, since))
|
|
.groupBy(sql`to_char(${recipes.createdAt}, 'YYYY-MM-DD')`, recipes.aiGenerated),
|
|
db.select({ tier: users.tier, n: sql<number>`count(*)::int` }).from(users).groupBy(users.tier),
|
|
db.select({ visibility: recipes.visibility, n: sql<number>`count(*)::int` }).from(recipes).groupBy(recipes.visibility),
|
|
db
|
|
.select({ month: userUsage.month, n: sql<number>`coalesce(sum(${userUsage.aiCallsUsed}), 0)::int` })
|
|
.from(userUsage)
|
|
.groupBy(userUsage.month),
|
|
db.select({ status: supportTickets.status, n: sql<number>`count(*)::int` }).from(supportTickets).groupBy(supportTickets.status),
|
|
]);
|
|
|
|
for (const r of results) {
|
|
if (r.status === "rejected") console.error("[admin/insights] query failed", r.reason);
|
|
}
|
|
|
|
const [signupRows, recipeRows, tierRows, visibilityRows, usageRows, ticketRows] = results.map((r) =>
|
|
r.status === "fulfilled" ? r.value : []
|
|
) as [
|
|
{ day: string; n: number }[],
|
|
{ day: string; aiGenerated: boolean; n: number }[],
|
|
{ tier: "free" | "pro" | "family"; n: number }[],
|
|
{ visibility: "private" | "unlisted" | "public" | "followers"; n: number }[],
|
|
{ month: string; n: number }[],
|
|
{ status: "open" | "triaged" | "closed"; n: number }[],
|
|
];
|
|
|
|
const signupByDay = new Map(signupRows.map((r) => [r.day, r.n]));
|
|
const signupSeries = lastNDays(DAYS).map((day) => ({ date: day, value: signupByDay.get(day) ?? 0 }));
|
|
|
|
const recipesByDay = new Map<string, { manual: number; ai: number }>();
|
|
for (const r of recipeRows) {
|
|
const entry = recipesByDay.get(r.day) ?? { manual: 0, ai: 0 };
|
|
if (r.aiGenerated) entry.ai += r.n; else entry.manual += r.n;
|
|
recipesByDay.set(r.day, entry);
|
|
}
|
|
const recipesSeries = lastNDays(DAYS).map((day) => {
|
|
const entry = recipesByDay.get(day) ?? { manual: 0, ai: 0 };
|
|
return { label: formatShortDate(day), values: [entry.manual, entry.ai] };
|
|
});
|
|
|
|
const TIER_ORDER = ["free", "pro", "family"] as const;
|
|
const tierByKey = new Map(tierRows.map((r) => [r.tier, r.n]));
|
|
const tierData = TIER_ORDER.map((tier) => ({ label: tier, values: [tierByKey.get(tier) ?? 0] }));
|
|
|
|
const VISIBILITY_ORDER = ["private", "unlisted", "followers", "public"] as const;
|
|
const visByKey = new Map(visibilityRows.map((r) => [r.visibility, r.n]));
|
|
const visibilityData = VISIBILITY_ORDER.map((v) => ({ label: v, values: [visByKey.get(v) ?? 0] }));
|
|
|
|
const usageByMonth = new Map(usageRows.map((r) => [r.month, r.n]));
|
|
const usageSeries = lastNMonths(6).map((month) => ({ date: month, value: usageByMonth.get(month) ?? 0 }));
|
|
|
|
const STATUS_ORDER = ["open", "triaged", "closed"] as const;
|
|
const statusByKey = new Map(ticketRows.map((r) => [r.status, r.n]));
|
|
const statusData = STATUS_ORDER.map((s) => ({ label: s, values: [statusByKey.get(s) ?? 0] }));
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
<div>
|
|
<h1 className="text-2xl font-bold tracking-tight">Insights</h1>
|
|
<p className="text-muted-foreground text-sm mt-1">Trends and breakdowns across the last {DAYS} days (or 6 months for usage).</p>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">New signups</CardTitle>
|
|
<CardDescription>Daily, last {DAYS} days</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<TimeSeriesChart data={signupSeries} dateFormat="day" />
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">Recipes created</CardTitle>
|
|
<CardDescription>Daily, manual vs AI-generated</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<BarChart data={recipesSeries} seriesLabels={["Manual", "AI-generated"]} />
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">Users by tier</CardTitle>
|
|
<CardDescription>All-time</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<BarChart data={tierData} seriesLabels={["Users"]} />
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">Recipes by visibility</CardTitle>
|
|
<CardDescription>All-time</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<BarChart data={visibilityData} seriesLabels={["Recipes"]} />
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">AI calls</CardTitle>
|
|
<CardDescription>Monthly total across all users, last 6 months</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<TimeSeriesChart data={usageSeries} dateFormat="month" />
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">Support tickets by status</CardTitle>
|
|
<CardDescription>All-time</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<BarChart data={statusData} seriesLabels={["Tickets"]} />
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|