Harden analytics pages against missing tables and RSC dynamic imports.
Local Build and Deploy / deploy (push) Successful in 1m1s
Local Build and Deploy / deploy (push) Successful in 1m1s
Co-authored-by: Cursor <[email protected]>
This commit is contained in:
1 parent
63c7ff8570
commit
665d87cbf4
4 files changed
+420
-248
No files matched your search
@@ -6,117 +6,168 @@ import {
|
||||
TrendingUp,
|
||||
Users,
|
||||
} from "lucide-react";
|
||||
import dynamic from "next/dynamic";
|
||||
import { redirect } from "next/navigation";
|
||||
import { DashboardChart } from "@/components/admin/dashboard-chart";
|
||||
import { PeakHoursHeatmap } from "@/components/admin/peak-hours-heatmap";
|
||||
import { StatsCard } from "@/components/admin/stats-card";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const DashboardChart = dynamic(
|
||||
() =>
|
||||
import("@/components/admin/dashboard-chart").then((m) => ({
|
||||
default: m.DashboardChart,
|
||||
})),
|
||||
{ loading: () => <Skeleton className="h-[300px] w-full rounded-xl" /> },
|
||||
);
|
||||
type AnalyticsData = {
|
||||
totalUsers: number;
|
||||
onlineUsers: number;
|
||||
weekRegistrations: number;
|
||||
monthRegistrations: number;
|
||||
totalRooms: number;
|
||||
activeRooms: number;
|
||||
weekChatMessages: number;
|
||||
weekTrades: number;
|
||||
weekBans: number;
|
||||
registrationChart: { label: string; value: number }[];
|
||||
peakHours: { grid: number[][]; max: number };
|
||||
};
|
||||
|
||||
const PeakHoursHeatmap = dynamic(
|
||||
() =>
|
||||
import("@/components/admin/peak-hours-heatmap").then((m) => ({
|
||||
default: m.PeakHoursHeatmap,
|
||||
})),
|
||||
{ loading: () => <Skeleton className="h-[250px] w-full rounded-xl" /> },
|
||||
);
|
||||
const EMPTY: AnalyticsData = {
|
||||
totalUsers: 0,
|
||||
onlineUsers: 0,
|
||||
weekRegistrations: 0,
|
||||
monthRegistrations: 0,
|
||||
totalRooms: 0,
|
||||
activeRooms: 0,
|
||||
weekChatMessages: 0,
|
||||
weekTrades: 0,
|
||||
weekBans: 0,
|
||||
registrationChart: [],
|
||||
peakHours: {
|
||||
grid: Array.from({ length: 7 }, () => Array(24).fill(0)),
|
||||
max: 0,
|
||||
},
|
||||
};
|
||||
|
||||
async function getAnalyticsData() {
|
||||
async function safeCount(fn: () => Promise<number>): Promise<number> {
|
||||
try {
|
||||
return await fn();
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
async function getAnalyticsData(): Promise<AnalyticsData> {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const todayStart = now - (now % 86400);
|
||||
const weekAgo = now - 7 * 86400;
|
||||
const monthAgo = now - 30 * 86400;
|
||||
|
||||
const [
|
||||
totalUsers,
|
||||
onlineUsers,
|
||||
weekRegistrations,
|
||||
monthRegistrations,
|
||||
totalRooms,
|
||||
activeRooms,
|
||||
weekChatMessages,
|
||||
weekTrades,
|
||||
weekBans,
|
||||
] = await Promise.all([
|
||||
prisma.user.count(),
|
||||
prisma.user.count({ where: { online: "1" } }),
|
||||
prisma.user.count({ where: { accountCreated: { gte: weekAgo } } }),
|
||||
prisma.user.count({ where: { accountCreated: { gte: monthAgo } } }),
|
||||
prisma.rooms.count(),
|
||||
prisma.rooms.count({ where: { users: { gt: 0 } } }),
|
||||
prisma.$queryRaw<
|
||||
{ count: bigint }[]
|
||||
>`SELECT COUNT(*) AS count FROM chatlogs_room WHERE timestamp >= ${weekAgo}`,
|
||||
prisma.roomTradeLog.count({ where: { timestamp: { gte: weekAgo } } }),
|
||||
prisma.ban.count({ where: { timestamp: { gte: weekAgo } } }),
|
||||
]);
|
||||
try {
|
||||
const [
|
||||
totalUsers,
|
||||
onlineUsers,
|
||||
weekRegistrations,
|
||||
monthRegistrations,
|
||||
totalRooms,
|
||||
activeRooms,
|
||||
weekChatMessages,
|
||||
weekTrades,
|
||||
weekBans,
|
||||
] = await Promise.all([
|
||||
safeCount(() => prisma.user.count()),
|
||||
safeCount(() => prisma.user.count({ where: { online: "1" } })),
|
||||
safeCount(() =>
|
||||
prisma.user.count({ where: { accountCreated: { gte: weekAgo } } }),
|
||||
),
|
||||
safeCount(() =>
|
||||
prisma.user.count({ where: { accountCreated: { gte: monthAgo } } }),
|
||||
),
|
||||
safeCount(() => prisma.rooms.count()),
|
||||
safeCount(() => prisma.rooms.count({ where: { users: { gt: 0 } } })),
|
||||
(async () => {
|
||||
try {
|
||||
const rows = await prisma.$queryRaw<{ count: bigint }[]>`
|
||||
SELECT COUNT(*) AS count FROM chatlogs_room WHERE timestamp >= ${weekAgo}`;
|
||||
return Number(rows[0]?.count ?? 0);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
})(),
|
||||
safeCount(() =>
|
||||
prisma.roomTradeLog.count({ where: { timestamp: { gte: weekAgo } } }),
|
||||
),
|
||||
safeCount(() =>
|
||||
prisma.ban.count({ where: { timestamp: { gte: weekAgo } } }),
|
||||
),
|
||||
]);
|
||||
|
||||
// Registration chart (30 days) — single GROUP BY query instead of 30 sequential queries
|
||||
const regRows = await prisma.$queryRaw<
|
||||
{ day_bucket: bigint; count: bigint }[]
|
||||
>`
|
||||
SELECT FLOOR(account_created / 86400) AS day_bucket, COUNT(*) AS count
|
||||
FROM users
|
||||
WHERE account_created >= ${monthAgo}
|
||||
GROUP BY day_bucket ORDER BY day_bucket
|
||||
`;
|
||||
const regCountMap = new Map(
|
||||
regRows.map((r) => [Number(r.day_bucket), Number(r.count)]),
|
||||
);
|
||||
const registrationChart = [];
|
||||
for (let i = 29; i >= 0; i--) {
|
||||
const dayStart = todayStart - i * 86400;
|
||||
const bucket = Math.floor(dayStart / 86400);
|
||||
const date = new Date(dayStart * 1000);
|
||||
registrationChart.push({
|
||||
label: date.toLocaleDateString("en", { month: "short", day: "numeric" }),
|
||||
value: regCountMap.get(bucket) ?? 0,
|
||||
});
|
||||
let registrationChart: { label: string; value: number }[] = [];
|
||||
try {
|
||||
const regRows = await prisma.$queryRaw<
|
||||
{ day_bucket: bigint; count: bigint }[]
|
||||
>`
|
||||
SELECT FLOOR(account_created / 86400) AS day_bucket, COUNT(*) AS count
|
||||
FROM users
|
||||
WHERE account_created >= ${monthAgo}
|
||||
GROUP BY day_bucket ORDER BY day_bucket
|
||||
`;
|
||||
const regCountMap = new Map(
|
||||
regRows.map((r) => [Number(r.day_bucket), Number(r.count)]),
|
||||
);
|
||||
for (let i = 29; i >= 0; i--) {
|
||||
const dayStart = todayStart - i * 86400;
|
||||
const bucket = Math.floor(dayStart / 86400);
|
||||
const date = new Date(dayStart * 1000);
|
||||
registrationChart.push({
|
||||
label: date.toLocaleDateString("en", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
}),
|
||||
value: regCountMap.get(bucket) ?? 0,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
registrationChart = [];
|
||||
}
|
||||
|
||||
const grid: number[][] = Array.from({ length: 7 }, () => Array(24).fill(0));
|
||||
let max = 0;
|
||||
try {
|
||||
const peakRows = await prisma.$queryRaw<
|
||||
{ d: number; h: number; c: bigint }[]
|
||||
>`
|
||||
SELECT ((DAYOFWEEK(FROM_UNIXTIME(last_online)) + 5) % 7) AS d,
|
||||
HOUR(FROM_UNIXTIME(last_online)) AS h,
|
||||
COUNT(*) AS c
|
||||
FROM users
|
||||
WHERE last_online >= ${weekAgo}
|
||||
GROUP BY d, h
|
||||
`;
|
||||
for (const r of peakRows) {
|
||||
const day = Number(r.d);
|
||||
const hour = Number(r.h);
|
||||
if (day < 0 || day > 6 || hour < 0 || hour > 23) continue;
|
||||
const count = Number(r.c);
|
||||
grid[day][hour] = count;
|
||||
if (count > max) max = count;
|
||||
}
|
||||
} catch {
|
||||
/* keep empty grid */
|
||||
}
|
||||
|
||||
return {
|
||||
totalUsers,
|
||||
onlineUsers,
|
||||
weekRegistrations,
|
||||
monthRegistrations,
|
||||
totalRooms,
|
||||
activeRooms,
|
||||
weekChatMessages,
|
||||
weekTrades,
|
||||
weekBans,
|
||||
registrationChart,
|
||||
peakHours: { grid, max },
|
||||
};
|
||||
} catch {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
// Peak hours — single GROUP BY query instead of fetching all user rows
|
||||
const peakRows = await prisma.$queryRaw<
|
||||
{ d: number; h: number; c: bigint }[]
|
||||
>`
|
||||
SELECT ((DAYOFWEEK(FROM_UNIXTIME(last_online)) + 5) % 7) AS d,
|
||||
HOUR(FROM_UNIXTIME(last_online)) AS h,
|
||||
COUNT(*) AS c
|
||||
FROM users
|
||||
WHERE last_online >= ${weekAgo}
|
||||
GROUP BY d, h
|
||||
`;
|
||||
const grid: number[][] = Array.from({ length: 7 }, () => Array(24).fill(0));
|
||||
let max = 0;
|
||||
for (const r of peakRows) {
|
||||
const count = Number(r.c);
|
||||
grid[r.d][r.h] = count;
|
||||
if (count > max) max = count;
|
||||
}
|
||||
|
||||
return {
|
||||
totalUsers,
|
||||
onlineUsers,
|
||||
weekRegistrations,
|
||||
monthRegistrations,
|
||||
totalRooms,
|
||||
activeRooms,
|
||||
weekChatMessages: Array.isArray(weekChatMessages)
|
||||
? Number(weekChatMessages[0]?.count ?? 0)
|
||||
: 0,
|
||||
weekTrades,
|
||||
weekBans,
|
||||
registrationChart,
|
||||
peakHours: { grid, max },
|
||||
};
|
||||
}
|
||||
|
||||
export default async function AnalyticsPage() {
|
||||
|
||||
Reference in new issue
Block a user