feat: add admin operations suite
Local Build and Deploy / deploy (push) Successful in 50s

This commit is contained in:
Simo committed 2026-07-12 20:11:28 +02:00
1 parent 21a61068fb
commit 60278b9e71
38 files changed
+3452

No files matched your search

+206
View File
@@ -0,0 +1,206 @@
'use server'
import { z } from 'zod'
import { PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { adminAction } from '@/lib/safe-action'
import { ActionError, actionOk } from '@/lib/safe-action-shared'
import { logAudit } from '@/lib/services/audit'
import { rcon } from '@/lib/services/rcon'
// ── CFH Ticket Actions ──────────────────────────────────────────────
const cfhIdSchema = z.object({ ticketId: z.coerce.number().int().positive() })
export const assignCfhTicket = adminAction(
{ permission: PERMS.MODERATION_EDIT, schema: cfhIdSchema },
async (ctx) => {
const ticket = await prisma.supportTickets.findUnique({ where: { id: ctx.data.ticketId } })
if (!ticket) throw new ActionError('Ticket not found')
await prisma.supportTickets.update({
where: { id: ctx.data.ticketId },
data: { modId: ctx.session.user.id, state: 1 },
})
logAudit({
userId: ctx.session.user.id,
action: 'cfh_assign',
target: 'support_tickets',
targetId: ctx.data.ticketId,
})
return actionOk()
},
)
const cfhStateSchema = z.object({
ticketId: z.coerce.number().int().positive(),
state: z.coerce.number().int().min(0).max(3),
})
export const updateCfhState = adminAction(
{ permission: PERMS.MODERATION_EDIT, schema: cfhStateSchema },
async (ctx) => {
const ticket = await prisma.supportTickets.findUnique({ where: { id: ctx.data.ticketId } })
if (!ticket) throw new ActionError('Ticket not found')
await prisma.supportTickets.update({
where: { id: ctx.data.ticketId },
data: { state: ctx.data.state, modId: ctx.session.user.id },
})
logAudit({
userId: ctx.session.user.id,
action: 'cfh_state_change',
target: 'support_tickets',
targetId: ctx.data.ticketId,
before: { state: ticket.state },
after: { state: ctx.data.state },
})
return actionOk()
},
)
export const closeCfhTicket = adminAction(
{ permission: PERMS.MODERATION_EDIT, schema: cfhIdSchema },
async (ctx) => {
await prisma.supportTickets.update({
where: { id: ctx.data.ticketId },
data: { state: 2, modId: ctx.session.user.id },
})
logAudit({
userId: ctx.session.user.id,
action: 'cfh_close',
target: 'support_tickets',
targetId: ctx.data.ticketId,
})
return actionOk()
},
)
// ── Quick Mod Actions ────────────────────────────────────────────────
const userIdSchema = z.object({ userId: z.coerce.number().int().positive() })
export const quickKick = adminAction(
{ permission: PERMS.MODERATION_EDIT, schema: userIdSchema },
async (ctx) => {
await rcon.disconnectUser(ctx.data.userId)
logAudit({
userId: ctx.session.user.id,
action: 'mod_kick',
target: 'User',
targetId: ctx.data.userId,
})
return actionOk()
},
)
const muteSchema = z.object({
userId: z.coerce.number().int().positive(),
duration: z.coerce.number().int().min(0).max(525600), // max 1 year in minutes
})
export const quickMute = adminAction(
{ permission: PERMS.MODERATION_EDIT, schema: muteSchema },
async (ctx) => {
await rcon.muteUser(ctx.data.userId, ctx.data.duration)
logAudit({
userId: ctx.session.user.id,
action: 'mod_mute',
target: 'User',
targetId: ctx.data.userId,
after: { duration: ctx.data.duration },
})
return actionOk()
},
)
export const quickUnmute = adminAction(
{ permission: PERMS.MODERATION_EDIT, schema: userIdSchema },
async (ctx) => {
await rcon.unmuteUser(ctx.data.userId)
logAudit({
userId: ctx.session.user.id,
action: 'mod_unmute',
target: 'User',
targetId: ctx.data.userId,
})
return actionOk()
},
)
const alertSchema = z.object({
userId: z.coerce.number().int().positive(),
message: z.string().min(1).max(500),
})
export const quickAlert = adminAction(
{ permission: PERMS.MODERATION_EDIT, schema: alertSchema },
async (ctx) => {
await rcon.alertUser(ctx.data.userId, ctx.data.message)
logAudit({
userId: ctx.session.user.id,
action: 'mod_alert',
target: 'User',
targetId: ctx.data.userId,
after: { message: ctx.data.message },
})
return actionOk()
},
)
const roomIdSchema = z.object({ roomId: z.coerce.number().int().positive() })
export const quickRoomKick = adminAction(
{ permission: PERMS.MODERATION_EDIT, schema: roomIdSchema },
async (ctx) => {
await rcon.kickAll(ctx.data.roomId)
logAudit({
userId: ctx.session.user.id,
action: 'mod_room_kick',
target: 'Room',
targetId: ctx.data.roomId,
})
return actionOk()
},
)
const broadcastSchema = z.object({
message: z.string().min(1).max(500),
type: z.enum(['hotel', 'staff']),
})
export const broadcastAlert = adminAction(
{ permission: PERMS.MODERATION_EDIT, schema: broadcastSchema },
async (ctx) => {
if (ctx.data.type === 'hotel') {
await rcon.hotelAlert(ctx.data.message)
} else {
await rcon.staffAlert(ctx.data.message)
}
logAudit({
userId: ctx.session.user.id,
action: `mod_broadcast_${ctx.data.type}`,
target: 'broadcast',
after: { message: ctx.data.message },
})
return actionOk()
},
)
+197
View File
@@ -0,0 +1,197 @@
import { MessageSquare, Shield, Terminal, Users } from 'lucide-react'
import { redirect } from 'next/navigation'
import { StatsCard } from '@/components/admin/stats-card'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
async function getActivityData() {
const now = Math.floor(Date.now() / 1000)
const todayStart = now - (now % 86400)
const weekAgo = now - 7 * 86400
// Daily activity breakdown — 4 GROUP BY queries instead of 28 sequential queries
const rangeStart = todayStart - 6 * 86400
const [chatRows, cmdRows, banRows, regRows] = await Promise.all([
prisma.$queryRaw<{ day_bucket: bigint; count: bigint }[]>`
SELECT FLOOR(timestamp / 86400) AS day_bucket, COUNT(*) AS count
FROM chatlogs_room WHERE timestamp >= ${rangeStart} GROUP BY day_bucket`,
prisma.$queryRaw<{ day_bucket: bigint; count: bigint }[]>`
SELECT FLOOR(timestamp / 86400) AS day_bucket, COUNT(*) AS count
FROM commandlogs WHERE timestamp >= ${rangeStart} GROUP BY day_bucket`,
prisma.$queryRaw<{ day_bucket: bigint; count: bigint }[]>`
SELECT FLOOR(timestamp / 86400) AS day_bucket, COUNT(*) AS count
FROM bans WHERE timestamp >= ${rangeStart} GROUP BY day_bucket`,
prisma.$queryRaw<{ day_bucket: bigint; count: bigint }[]>`
SELECT FLOOR(account_created / 86400) AS day_bucket, COUNT(*) AS count
FROM users WHERE account_created >= ${rangeStart} GROUP BY day_bucket`,
])
const toMap = (rows: { day_bucket: bigint; count: bigint }[]) =>
new Map(rows.map((r) => [Number(r.day_bucket), Number(r.count)]))
const chatMap = toMap(chatRows)
const cmdMap = toMap(cmdRows)
const banMap = toMap(banRows)
const regMap = toMap(regRows)
const dailyData = []
for (let i = 6; i >= 0; i--) {
const dayStart = todayStart - i * 86400
const bucket = Math.floor(dayStart / 86400)
const date = new Date(dayStart * 1000)
dailyData.push({
label: date.toLocaleDateString('en', { weekday: 'short', month: 'short', day: 'numeric' }),
chats: chatMap.get(bucket) ?? 0,
commands: cmdMap.get(bucket) ?? 0,
bans: banMap.get(bucket) ?? 0,
registrations: regMap.get(bucket) ?? 0,
})
}
// Totals
const [weekChatRows, weekCommandRows, weekBans, weekRegistrations] = await Promise.all([
prisma.$queryRaw<{ count: bigint }[]>`SELECT COUNT(*) AS count FROM chatlogs_room WHERE timestamp >= ${weekAgo}`,
prisma.$queryRaw<{ count: bigint }[]>`SELECT COUNT(*) AS count FROM commandlogs WHERE timestamp >= ${weekAgo}`,
prisma.ban.count({ where: { timestamp: { gte: weekAgo } } }),
prisma.user.count({ where: { accountCreated: { gte: weekAgo } } }),
])
const weekChats = Number(weekChatRows[0]?.count ?? 0)
const weekCommands = Number(weekCommandRows[0]?.count ?? 0)
// Most active users (by chat messages)
const topChatters = await prisma.$queryRaw<{ userId: number; messages: bigint }[]>`
SELECT user_from_id AS userId, COUNT(*) AS messages
FROM chatlogs_room WHERE timestamp >= ${weekAgo}
GROUP BY user_from_id ORDER BY messages DESC LIMIT 10
`
const userIds = topChatters.map((c) => c.userId)
const users = await prisma.user.findMany({
where: { id: { in: userIds } },
select: { id: true, username: true },
})
const userMap = new Map(users.map((u) => [u.id, u.username]))
const topChattersWithNames = topChatters.map((c) => ({
userId: c.userId,
username: userMap.get(c.userId) ?? `User #${c.userId}`,
messages: Number(c.messages),
}))
return {
dailyData,
weekChats,
weekCommands,
weekBans,
weekRegistrations,
topChatters: topChattersWithNames,
}
}
export default async function ActivityPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.ANALYTICS_VIEW, session.user.rank)) {
redirect('/admin')
}
const data = await getActivityData()
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Activity</h1>
<p className="text-muted-foreground">User activity breakdown and engagement metrics</p>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<StatsCard
title="Chat Messages"
value={data.weekChats.toLocaleString()}
description="Last 7 days"
icon={<MessageSquare className="h-4 w-4" />}
/>
<StatsCard
title="Commands"
value={data.weekCommands.toLocaleString()}
description="Last 7 days"
icon={<Terminal className="h-4 w-4" />}
/>
<StatsCard
title="Bans"
value={data.weekBans.toLocaleString()}
description="Last 7 days"
icon={<Shield className="h-4 w-4" />}
/>
<StatsCard
title="Registrations"
value={data.weekRegistrations.toLocaleString()}
description="Last 7 days"
icon={<Users className="h-4 w-4" />}
/>
</div>
<div className="grid gap-6 md:grid-cols-2">
{/* Daily breakdown table */}
<Card>
<CardHeader>
<CardTitle>Daily Breakdown (7 days)</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-muted-foreground">
<th className="text-left py-2 font-medium">Day</th>
<th className="text-right py-2 font-medium">Chats</th>
<th className="text-right py-2 font-medium">Cmds</th>
<th className="text-right py-2 font-medium">Bans</th>
<th className="text-right py-2 font-medium">Regs</th>
</tr>
</thead>
<tbody>
{data.dailyData.map((day) => (
<tr key={day.label} className="border-b last:border-0">
<td className="py-2">{day.label}</td>
<td className="text-right tabular-nums">{day.chats.toLocaleString()}</td>
<td className="text-right tabular-nums">{day.commands.toLocaleString()}</td>
<td className="text-right tabular-nums">{day.bans}</td>
<td className="text-right tabular-nums">{day.registrations}</td>
</tr>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
{/* Top chatters */}
<Card>
<CardHeader>
<CardTitle>Most Active Users (7 days)</CardTitle>
</CardHeader>
<CardContent>
{data.topChatters.length === 0 ? (
<p className="text-sm text-muted-foreground">No chat activity</p>
) : (
<div className="divide-y">
{data.topChatters.map((user, i) => (
<div
key={user.userId}
className="flex items-center gap-3 py-2.5 first:pt-0 last:pb-0"
>
<span className="flex h-6 w-6 items-center justify-center rounded-full bg-accent text-xs font-bold">
{i + 1}
</span>
<span className="flex-1 text-sm font-medium">{user.username}</span>
<span className="text-sm tabular-nums text-muted-foreground">
{user.messages.toLocaleString()} msgs
</span>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
</div>
)
}
+200
View File
@@ -0,0 +1,200 @@
import { ArrowLeftRight, Coins, TrendingDown, TrendingUp } from 'lucide-react'
import dynamic from 'next/dynamic'
import { redirect } from 'next/navigation'
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 RevenueChart = dynamic(
() => import('@/components/admin/revenue-chart').then((m) => ({ default: m.RevenueChart })),
{ loading: () => <Skeleton className="h-[300px] w-full rounded-xl" /> },
)
async function getEconomyData() {
const now = Math.floor(Date.now() / 1000)
const todayStart = now - (now % 86400)
const weekAgo = now - 7 * 86400
// Total currency in circulation — parallel instead of sequential
const [creditsAgg, pixelsAgg, pointsAgg] = await Promise.all([
prisma.user.aggregate({ _sum: { credits: true } }),
prisma.user.aggregate({ _sum: { pixels: true } }),
prisma.user.aggregate({ _sum: { points: true } }),
])
const totalCredits = creditsAgg._sum.credits ?? 0
const totalPixels = pixelsAgg._sum.pixels ?? 0
const totalPoints = pointsAgg._sum.points ?? 0
// Shop revenue (7 days)
const shopRevenue = await prisma.logsShopPurchases.aggregate({
where: { timestamp: { gte: weekAgo } },
_sum: { costCredits: true, costPoints: true },
_count: true,
})
// Marketplace stats
const marketplaceActive = await prisma.marketplaceItems.count({ where: { state: 1 } })
const marketplaceSold = await prisma.marketplaceItems.count({
where: { state: 2, soldTimestamp: { gte: weekAgo } },
})
// Revenue chart (7 days) — single GROUP BY query instead of 7 sequential queries
const rangeStart = todayStart - 6 * 86400
const revRows = await prisma.$queryRaw<{ day_bucket: bigint; credits: number; points: number }[]>`
SELECT FLOOR(timestamp / 86400) AS day_bucket,
COALESCE(SUM(cost_credits), 0) AS credits,
COALESCE(SUM(cost_points), 0) AS points
FROM logs_shop_purchases
WHERE timestamp >= ${rangeStart}
GROUP BY day_bucket ORDER BY day_bucket
`
const revMap = new Map(
revRows.map((r) => [
Number(r.day_bucket),
{ credits: Number(r.credits), points: Number(r.points) },
]),
)
const revenueData = []
for (let i = 6; i >= 0; i--) {
const dayStart = todayStart - i * 86400
const bucket = Math.floor(dayStart / 86400)
const date = new Date(dayStart * 1000)
const entry = revMap.get(bucket)
revenueData.push({
label: date.toLocaleDateString('en', { weekday: 'short' }),
credits: entry?.credits ?? 0,
points: entry?.points ?? 0,
})
}
// Trades (7 days)
const weekTrades = await prisma.roomTradeLog.count({
where: { timestamp: { gte: weekAgo } },
})
return {
totalCredits,
totalPixels,
totalPoints,
shopPurchases: typeof shopRevenue._count === 'number' ? shopRevenue._count : 0,
shopCreditsSpent: shopRevenue._sum?.costCredits ?? 0,
shopPointsSpent: shopRevenue._sum?.costPoints ?? 0,
marketplaceActive,
marketplaceSold,
weekTrades,
revenueData,
}
}
export default async function EconomyPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.ANALYTICS_VIEW, session.user.rank)) {
redirect('/admin')
}
const data = await getEconomyData()
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Economy</h1>
<p className="text-muted-foreground">
Currency circulation, shop revenue and marketplace activity
</p>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<StatsCard
title="Credits in Circulation"
value={data.totalCredits.toLocaleString()}
description="Total credits across all users"
icon={<Coins className="h-4 w-4" />}
/>
<StatsCard
title="Pixels in Circulation"
value={data.totalPixels.toLocaleString()}
description="Total pixels across all users"
icon={<TrendingUp className="h-4 w-4" />}
/>
<StatsCard
title="Points in Circulation"
value={data.totalPoints.toLocaleString()}
description="Total points across all users"
icon={<TrendingDown className="h-4 w-4" />}
/>
<StatsCard
title="Weekly Trades"
value={data.weekTrades.toLocaleString()}
description={`${data.marketplaceActive} marketplace listings`}
icon={<ArrowLeftRight className="h-4 w-4" />}
/>
</div>
<RevenueChart data={data.revenueData} />
<div className="grid gap-6 md:grid-cols-3">
<Card>
<CardHeader>
<CardTitle>Shop Revenue (7d)</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-muted-foreground">Purchases</span>
<span className="font-medium">{data.shopPurchases}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Credits spent</span>
<span className="font-medium">{data.shopCreditsSpent.toLocaleString()}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Points spent</span>
<span className="font-medium">{data.shopPointsSpent.toLocaleString()}</span>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Marketplace</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-muted-foreground">Active listings</span>
<span className="font-medium">{data.marketplaceActive}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Sold (7d)</span>
<span className="font-medium">{data.marketplaceSold}</span>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Currency Distribution</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-muted-foreground">Credits</span>
<span className="font-medium">{data.totalCredits.toLocaleString()}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Pixels</span>
<span className="font-medium">{data.totalPixels.toLocaleString()}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Points</span>
<span className="font-medium">{data.totalPoints.toLocaleString()}</span>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
)
}
+191
View File
@@ -0,0 +1,191 @@
import { ArrowLeftRight, Clock, DoorOpen, MessageSquare, TrendingUp, Users } from 'lucide-react'
import dynamic from 'next/dynamic'
import { redirect } from 'next/navigation'
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" /> },
)
const PeakHoursHeatmap = dynamic(
() =>
import('@/components/admin/peak-hours-heatmap').then((m) => ({ default: m.PeakHoursHeatmap })),
{ loading: () => <Skeleton className="h-[250px] w-full rounded-xl" /> },
)
async function getAnalyticsData() {
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 } } }),
])
// 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,
})
}
// 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() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.ANALYTICS_VIEW, session.user.rank)) {
redirect('/admin')
}
const data = await getAnalyticsData()
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Analytics</h1>
<p className="text-muted-foreground">Hotel performance overview and trends</p>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<StatsCard
title="Total Users"
value={data.totalUsers.toLocaleString()}
description={`${data.onlineUsers} online now`}
icon={<Users className="h-4 w-4" />}
/>
<StatsCard
title="Week Registrations"
value={data.weekRegistrations.toLocaleString()}
description={`${data.monthRegistrations} this month`}
icon={<TrendingUp className="h-4 w-4" />}
/>
<StatsCard
title="Active Rooms"
value={data.activeRooms.toLocaleString()}
description={`${data.totalRooms} total rooms`}
icon={<DoorOpen className="h-4 w-4" />}
/>
<StatsCard
title="Weekly Activity"
value={data.weekChatMessages.toLocaleString()}
description={`${data.weekTrades} trades, ${data.weekBans} bans`}
icon={<MessageSquare className="h-4 w-4" />}
/>
</div>
<div className="grid gap-6 md:grid-cols-2">
<DashboardChart
title="Registrations (30 days)"
data={data.registrationChart}
color="hsl(262, 83%, 58%)"
description="New user registrations over the last 30 days"
/>
<PeakHoursHeatmap data={data.peakHours} />
</div>
<div className="grid gap-6 md:grid-cols-3">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<MessageSquare className="h-4 w-4" /> Chat Activity
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">{data.weekChatMessages.toLocaleString()}</div>
<p className="text-sm text-muted-foreground">Messages in the last 7 days</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ArrowLeftRight className="h-4 w-4" /> Trades
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">{data.weekTrades.toLocaleString()}</div>
<p className="text-sm text-muted-foreground">Trades in the last 7 days</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Clock className="h-4 w-4" /> Retention
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">
{data.totalUsers > 0 ? Math.round((data.onlineUsers / data.totalUsers) * 100) : 0}%
</div>
<p className="text-sm text-muted-foreground">Users online / total</p>
</CardContent>
</Card>
</div>
</div>
)
}
+83
View File
@@ -0,0 +1,83 @@
import { redirect } from 'next/navigation'
import { Card, CardContent } from '@/components/ui/card'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
export default async function EmulatorErrorsPage({
searchParams,
}: {
searchParams: Promise<Record<string, string>>
}) {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.DEVOPS_VIEW, session.user.rank)) {
redirect('/admin')
}
const params = await searchParams
const page = Math.max(1, Number(params.page) || 1)
const perPage = 50
const [errors, total] = await Promise.all([
prisma.emulatorErrors.findMany({
orderBy: { id: 'desc' },
skip: (page - 1) * perPage,
take: perPage,
}),
prisma.emulatorErrors.count(),
])
const lastPage = Math.ceil(total / perPage)
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Emulator Errors</h1>
<p className="text-muted-foreground">
{total} total errors — showing page {page} of {lastPage}
</p>
</div>
<Card>
<CardContent className="p-0">
{errors.length === 0 ? (
<div className="p-6 text-center text-muted-foreground">No emulator errors found</div>
) : (
<div className="divide-y">
{errors.map((error) => (
<div key={error.id} className="p-4">
<div className="flex items-center justify-between mb-2">
<span className="font-mono text-xs text-muted-foreground">#{error.id}</span>
<span className="text-xs text-muted-foreground">
{new Date(error.timestamp * 1000).toLocaleString()}
</span>
</div>
<pre className="text-xs whitespace-pre-wrap break-all font-mono bg-muted p-2 rounded">
{Buffer.from(error.stacktrace).toString('utf-8')}
</pre>
</div>
))}
</div>
)}
</CardContent>
</Card>
{lastPage > 1 && (
<div className="flex justify-center gap-2">
{page > 1 && (
<a href={`?page=${page - 1}`} className="text-sm text-primary hover:underline">
Previous
</a>
)}
<span className="text-sm text-muted-foreground">
Page {page} of {lastPage}
</span>
{page < lastPage && (
<a href={`?page=${page + 1}`} className="text-sm text-primary hover:underline">
Next
</a>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,55 @@
'use client'
import { RefreshCw } from 'lucide-react'
import { useEffect, useState } from 'react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
export function HealthCheckClient() {
const [status, setStatus] = useState<'checking' | 'online' | 'offline'>('checking')
const [checking, setChecking] = useState(false)
async function checkEmulator() {
setChecking(true)
setStatus('checking')
try {
const res = await fetch('/api/admin/devops/health')
if (res.ok) {
const data = await res.json()
setStatus(data.emulator ? 'online' : 'offline')
} else {
setStatus('offline')
}
} catch {
setStatus('offline')
} finally {
setChecking(false)
}
}
// biome-ignore lint/correctness/useExhaustiveDependencies: explicitly chosen here, see surrounding code
useEffect(() => {
checkEmulator()
}, [])
return (
<div className="flex items-center gap-2">
<Badge
variant={
status === 'online' ? 'default' : status === 'offline' ? 'destructive' : 'secondary'
}
>
{status === 'checking' ? 'Checking...' : status === 'online' ? 'Online' : 'Offline'}
</Badge>
<Button
variant="ghost"
size="icon"
className="h-6 w-6"
onClick={checkEmulator}
disabled={checking}
>
<RefreshCw className={`h-3 w-3 ${checking ? 'animate-spin' : ''}`} />
</Button>
</div>
)
}
+147
View File
@@ -0,0 +1,147 @@
import { AlertTriangle, Database, HeartPulse, Server } from 'lucide-react'
import { redirect } from 'next/navigation'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { HealthCheckClient } from './health-check-client'
async function getDevOpsData() {
const now = Math.floor(Date.now() / 1000)
const dayAgo = now - 86400
// DB health — simple count query
let dbStatus: 'healthy' | 'error' = 'healthy'
let dbLatency = 0
try {
const start = Date.now()
await prisma.user.count({ take: 1 })
dbLatency = Date.now() - start
} catch {
dbStatus = 'error'
}
// Recent emulator errors
const recentErrors = await prisma.emulatorErrors.findMany({
orderBy: { id: 'desc' },
take: 20,
})
const errorsToday = await prisma.emulatorErrors.count({
where: { timestamp: { gte: dayAgo } },
})
// Emulator settings (version info)
const emuVersion = await prisma.emulatorSettings.findFirst({
where: { key: 'version' },
})
// Online user count as proxy for emulator health
const onlineUsers = await prisma.user.count({ where: { online: '1' } })
return {
dbStatus,
dbLatency,
recentErrors,
errorsToday,
emuVersion: emuVersion?.value ?? 'Unknown',
onlineUsers,
}
}
export default async function DevOpsPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.DEVOPS_VIEW, session.user.rank)) {
redirect('/admin')
}
const data = await getDevOpsData()
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Health Status</h1>
<p className="text-muted-foreground">System health, emulator status and error monitoring</p>
</div>
{/* Status cards */}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Database</CardTitle>
<Database className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<Badge variant={data.dbStatus === 'healthy' ? 'default' : 'destructive'}>
{data.dbStatus === 'healthy' ? 'Healthy' : 'Error'}
</Badge>
<p className="text-xs text-muted-foreground mt-1">Latency: {data.dbLatency}ms</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Emulator</CardTitle>
<Server className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<HealthCheckClient />
<p className="text-xs text-muted-foreground mt-1">Version: {data.emuVersion}</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Online Users</CardTitle>
<HeartPulse className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{data.onlineUsers}</div>
<p className="text-xs text-muted-foreground">Current active connections</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Errors (24h)</CardTitle>
<AlertTriangle className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{data.errorsToday}</div>
<p className="text-xs text-muted-foreground">Emulator errors today</p>
</CardContent>
</Card>
</div>
{/* Recent errors */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<AlertTriangle className="h-4 w-4" /> Recent Emulator Errors
</CardTitle>
</CardHeader>
<CardContent>
{data.recentErrors.length === 0 ? (
<p className="text-sm text-muted-foreground">No recent errors</p>
) : (
<div className="space-y-2 max-h-[500px] overflow-y-auto">
{data.recentErrors.map((error) => (
<div key={error.id} className="rounded-md border p-3 text-sm">
<div className="flex items-center justify-between mb-1">
<span className="font-mono text-xs text-muted-foreground">#{error.id}</span>
<span className="text-xs text-muted-foreground">
{new Date(error.timestamp * 1000).toLocaleString()}
</span>
</div>
<pre className="text-xs whitespace-pre-wrap break-all font-mono text-destructive">
{Buffer.from(error.stacktrace).toString('utf-8')}
</pre>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
)
}
+5
View File
@@ -89,6 +89,8 @@ function getNavGroups(t: (key: string) => string) {
{ href: "/admin/applications", label: t("applications"), icon: <ClipboardList size={16} /> },
{ href: "/admin/teams", label: t("teams"), icon: <Group size={16} /> },
{ href: "/admin/permissions", label: t("permissions"), icon: <Key size={16} /> },
{ href: "/admin/online", label: "Online Users", icon: <Users size={16} /> },
{ href: "/admin/moderation", label: "Moderation", icon: <Shield size={16} /> },
],
},
{
@@ -131,6 +133,9 @@ function getNavGroups(t: (key: string) => string) {
{ href: "/admin/emulator", label: t("emulator"), icon: <Monitor size={16} /> },
{ href: "/admin/alerts", label: t("alerts"), icon: <Bell size={16} /> },
{ href: "/admin/logs", label: t("logs"), icon: <FileText size={16} /> },
{ href: "/admin/logs/audit", label: "Audit Log", icon: <FileText size={16} /> },
{ href: "/admin/analytics", label: "Analytics", icon: <LayoutDashboard size={16} /> },
{ href: "/admin/devops", label: "DevOps", icon: <Monitor size={16} /> },
{ href: "/admin/wordfilter", label: t("wordFilter"), icon: <Filter size={16} /> },
{ href: "/admin/maintenance", label: t("maintenance"), icon: <Wrench size={16} /> },
{ href: "/admin/housekeeping", label: t("housekeeping"), icon: <Settings size={16} /> },
+111
View File
@@ -0,0 +1,111 @@
'use client'
import { useState } from 'react'
import { DataTable } from '@/components/admin/data-table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import type { DataTableColumn, PaginatedResult } from '@/types'
interface AuditRow {
id: number
username: string
action: string
target: string
targetId: number | null
diff: string | null
createdAt: string
}
function DiffCell({ diff }: { diff: string | null }) {
const [open, setOpen] = useState(false)
if (!diff) return <span className="text-muted-foreground">-</span>
let parsed: Record<string, { from: unknown; to: unknown }>
try {
parsed = JSON.parse(diff)
} catch {
return <span className="text-muted-foreground">-</span>
}
const keys = Object.keys(parsed)
if (keys.length === 0) return <span className="text-muted-foreground">-</span>
const summary =
keys.length === 1
? `${keys[0]}: ${String(parsed[keys[0]].from ?? '∅')} → ${String(parsed[keys[0]].to ?? '∅')}`
: `${keys.length} changes`
return (
<div>
<Button
variant="ghost"
size="sm"
className="h-auto p-0 text-xs font-normal"
onClick={() => setOpen(!open)}
>
{summary}
</Button>
{open && (
<div className="mt-1 space-y-0.5 text-xs">
{keys.map((k) => (
<div key={k} className="flex gap-1">
<span className="font-medium">{k}:</span>
<span className="text-[var(--admin-error)] line-through">{String(parsed[k].from ?? '∅')}</span>
<span>→</span>
<span className="text-[var(--admin-success)]">{String(parsed[k].to ?? '∅')}</span>
</div>
))}
</div>
)}
</div>
)
}
const columns: DataTableColumn<AuditRow>[] = [
{ key: 'id', label: 'ID', sortable: true },
{ key: 'username', label: 'User', sortable: true },
{
key: 'action',
label: 'Action',
sortable: true,
render: (value) => {
const v = String(value)
let variant: 'default' | 'secondary' | 'destructive' = 'secondary'
if (v.includes('create') || v.includes('add')) variant = 'default'
if (v.includes('delete') || v.includes('remove') || v.includes('ban')) variant = 'destructive'
return <Badge variant={variant}>{v}</Badge>
},
},
{ key: 'target', label: 'Target', sortable: true },
{
key: 'targetId',
label: 'Target ID',
render: (value) => <span>{value != null ? String(value) : '-'}</span>,
},
{
key: 'diff',
label: 'Details',
render: (_value, row) => <DiffCell diff={row.diff} />,
},
{
key: 'createdAt',
label: 'Date',
sortable: true,
render: (value) => <span>{String(value) || 'N/A'}</span>,
},
]
interface AuditTableProps {
data: PaginatedResult<AuditRow>
}
export function AuditTable({ data }: AuditTableProps) {
return (
<DataTable
data={data}
columns={columns}
searchPlaceholder="Search by action or target..."
exportUrl="/api/admin/export?type=audit"
/>
)
}
+28
View File
@@ -0,0 +1,28 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function AuditLogsLoading() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<Skeleton className="h-9 w-40" />
<Skeleton className="h-5 w-64 mt-2" />
</div>
</div>
<div className="flex items-center gap-3">
<Skeleton className="h-10 w-64" />
<Skeleton className="h-10 w-24" />
</div>
<div className="rounded-md border">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="flex items-center gap-6 px-4 py-3 border-b last:border-0">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-5 w-16 rounded-full" />
</div>
))}
</div>
</div>
)
}
+48
View File
@@ -0,0 +1,48 @@
import { redirect } from 'next/navigation'
import { calcPagination, parseListParams } from '@/lib/admin-helpers'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { getAuditLogs } from '@/lib/services/audit'
import { AuditTable } from './audit-table'
export default async function AuditLogsPage({
params: paramsPromise,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
await paramsPromise
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.LOGS_VIEW, session.user.rank)) {
redirect('/admin')
}
const params = await searchParams
const sp = new URLSearchParams(params)
const { search, perPage, page } = parseListParams(sp)
const result = await getAuditLogs({ search, page, perPage })
const pagination = calcPagination(result.total, result.page, result.perPage)
const rows = result.rows.map((r) => ({
id: r.id,
username: r.username,
action: r.action,
target: r.target,
targetId: r.targetId,
diff: r.diff,
createdAt: r.createdAt,
}))
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Audit Logs</h1>
<p className="text-muted-foreground">Track admin actions and changes</p>
</div>
<AuditTable data={{ rows, ...pagination }} />
</div>
)
}
+45
View File
@@ -0,0 +1,45 @@
'use client'
import { DataTable } from '@/components/admin/data-table'
import { formatTimestamp } from '@/lib/admin-helpers'
import type { DataTableColumn, PaginatedResult } from '@/types'
interface ChatLogRow {
id: number
username: string
message: string
timestamp: number
roomId: number
}
const columns: DataTableColumn<ChatLogRow>[] = [
{ key: 'id', label: 'ID', sortable: true },
{ key: 'username', label: 'User' },
{
key: 'message',
label: 'Message',
render: (value) => <span className="max-w-[300px] truncate block">{String(value)}</span>,
},
{
key: 'timestamp',
label: 'Time',
sortable: true,
render: (value) => <span>{formatTimestamp(Number(value))}</span>,
},
{ key: 'roomId', label: 'Room ID', sortable: true },
]
interface ChatTableProps {
data: PaginatedResult<ChatLogRow>
}
export function ChatTable({ data }: ChatTableProps) {
return (
<DataTable
data={data}
columns={columns}
searchPlaceholder="Search by username or message..."
exportUrl="/api/admin/export?type=chatlogs"
/>
)
}
+28
View File
@@ -0,0 +1,28 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function ChatLogsLoading() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<Skeleton className="h-9 w-40" />
<Skeleton className="h-5 w-64 mt-2" />
</div>
</div>
<div className="flex items-center gap-3">
<Skeleton className="h-10 w-64" />
<Skeleton className="h-10 w-24" />
</div>
<div className="rounded-md border">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="flex items-center gap-6 px-4 py-3 border-b last:border-0">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-5 w-16 rounded-full" />
</div>
))}
</div>
</div>
)
}
+49
View File
@@ -0,0 +1,49 @@
import { fetchAdminList } from '@/lib/admin-list'
import { PERMS } from '@/lib/permissions'
import { ChatTable } from './chat-table'
export default async function ChatLogsPage({
params: paramsPromise,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
const result = await fetchAdminList(
{
permission: PERMS.LOGS_VIEW,
model: 'chatLog',
searchFields: ['message', 'user.username'],
defaultPerPage: 50,
include: { user: { select: { username: true } } },
mapRow: (l) => ({
id: l.id,
username: l.user.username,
message: l.message,
timestamp: l.timestamp,
roomId: l.roomId,
}),
},
paramsPromise,
searchParams,
)
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Chat Logs</h1>
<p className="text-muted-foreground">View in-game chat messages</p>
</div>
<ChatTable
data={{
rows: result.rows,
total: result.total,
page: result.page,
perPage: result.perPage,
lastPage: result.lastPage,
}}
/>
</div>
)
}
@@ -0,0 +1,47 @@
'use client'
import { DataTable } from '@/components/admin/data-table'
import { formatTimestamp } from '@/lib/admin-helpers'
import type { DataTableColumn, PaginatedResult } from '@/types'
interface CommandLogRow {
id: number
username: string
command: string
params: string
timestamp: number
}
const columns: DataTableColumn<CommandLogRow>[] = [
{ key: 'id', label: 'ID', sortable: true },
{ key: 'username', label: 'User' },
{ key: 'command', label: 'Command', sortable: true },
{
key: 'params',
label: 'Params',
render: (value) => (
<span className="max-w-[200px] truncate block font-mono text-sm">{String(value) || '-'}</span>
),
},
{
key: 'timestamp',
label: 'Time',
sortable: true,
render: (value) => <span>{formatTimestamp(Number(value))}</span>,
},
]
interface CommandsTableProps {
data: PaginatedResult<CommandLogRow>
}
export function CommandsTable({ data }: CommandsTableProps) {
return (
<DataTable
data={data}
columns={columns}
searchPlaceholder="Search by username, command, or params..."
exportUrl="/api/admin/export?type=commands"
/>
)
}
+28
View File
@@ -0,0 +1,28 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function CommandLogsLoading() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<Skeleton className="h-9 w-40" />
<Skeleton className="h-5 w-64 mt-2" />
</div>
</div>
<div className="flex items-center gap-3">
<Skeleton className="h-10 w-64" />
<Skeleton className="h-10 w-24" />
</div>
<div className="rounded-md border">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="flex items-center gap-6 px-4 py-3 border-b last:border-0">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-5 w-16 rounded-full" />
</div>
))}
</div>
</div>
)
}
+49
View File
@@ -0,0 +1,49 @@
import { fetchAdminList } from '@/lib/admin-list'
import { PERMS } from '@/lib/permissions'
import { CommandsTable } from './commands-table'
export default async function CommandLogsPage({
params: paramsPromise,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
const result = await fetchAdminList(
{
permission: PERMS.LOGS_VIEW,
model: 'commandLog',
searchFields: ['command', 'params', 'user.username'],
defaultPerPage: 50,
include: { user: { select: { username: true } } },
mapRow: (l) => ({
id: l.id,
username: l.user.username,
command: l.command,
params: l.params,
timestamp: l.timestamp,
}),
},
paramsPromise,
searchParams,
)
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Command Logs</h1>
<p className="text-muted-foreground">View in-game command usage</p>
</div>
<CommandsTable
data={{
rows: result.rows,
total: result.total,
page: result.page,
perPage: result.perPage,
lastPage: result.lastPage,
}}
/>
</div>
)
}
+28
View File
@@ -0,0 +1,28 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function TradeLogsLoading() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<Skeleton className="h-9 w-40" />
<Skeleton className="h-5 w-64 mt-2" />
</div>
</div>
<div className="flex items-center gap-3">
<Skeleton className="h-10 w-64" />
<Skeleton className="h-10 w-24" />
</div>
<div className="rounded-md border">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="flex items-center gap-6 px-4 py-3 border-b last:border-0">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-5 w-16 rounded-full" />
</div>
))}
</div>
</div>
)
}
+52
View File
@@ -0,0 +1,52 @@
import { fetchAdminList } from '@/lib/admin-list'
import { PERMS } from '@/lib/permissions'
import { TradesTable } from './trades-table'
export default async function TradeLogsPage({
params: paramsPromise,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
const result = await fetchAdminList(
{
permission: PERMS.LOGS_VIEW,
model: 'trade',
searchFields: ['userOne.username', 'userTwo.username'],
defaultPerPage: 50,
include: {
userOne: { select: { username: true } },
userTwo: { select: { username: true } },
},
mapRow: (t) => ({
id: t.id,
userOneName: t.userOne.username,
userTwoName: t.userTwo.username,
status: t.status,
timestamp: t.timestamp,
}),
},
paramsPromise,
searchParams,
)
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Trade Logs</h1>
<p className="text-muted-foreground">View in-game trade history</p>
</div>
<TradesTable
data={{
rows: result.rows,
total: result.total,
page: result.page,
perPage: result.perPage,
lastPage: result.lastPage,
}}
/>
</div>
)
}
@@ -0,0 +1,45 @@
'use client'
import { DataTable } from '@/components/admin/data-table'
import { Badge } from '@/components/ui/badge'
import { formatTimestamp } from '@/lib/admin-helpers'
import type { DataTableColumn, PaginatedResult } from '@/types'
interface TradeLogRow {
id: number
userOneName: string
userTwoName: string
status: string
timestamp: number
}
const columns: DataTableColumn<TradeLogRow>[] = [
{ key: 'id', label: 'ID', sortable: true },
{ key: 'userOneName', label: 'User One' },
{ key: 'userTwoName', label: 'User Two' },
{
key: 'status',
label: 'Status',
sortable: true,
render: (value) => {
const v = String(value)
const variant =
v === 'completed' ? 'default' : v === 'cancelled' ? 'destructive' : 'secondary'
return <Badge variant={variant}>{v || 'unknown'}</Badge>
},
},
{
key: 'timestamp',
label: 'Time',
sortable: true,
render: (value) => <span>{formatTimestamp(Number(value))}</span>,
},
]
interface TradesTableProps {
data: PaginatedResult<TradeLogRow>
}
export function TradesTable({ data }: TradesTableProps) {
return <DataTable data={data} columns={columns} searchPlaceholder="Search by username..." />
}
@@ -0,0 +1,228 @@
'use client'
import {
DoorOpen,
Loader2,
Megaphone,
MessageSquare,
Shield,
Volume2,
VolumeX,
Zap,
} from 'lucide-react'
import { useState } from 'react'
import {
broadcastAlert,
quickAlert,
quickKick,
quickMute,
quickRoomKick,
quickUnmute,
} from '@/actions/moderation'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { useServerAction } from '@/hooks/use-server-action'
export function ModActionsClient() {
const { run, isPending } = useServerAction()
// User actions
const [userId, setUserId] = useState('')
const [muteDuration, setMuteDuration] = useState('10')
const [alertMessage, setAlertMessage] = useState('')
// Room actions
const [roomId, setRoomId] = useState('')
// Broadcast
const [broadcastMsg, setBroadcastMsg] = useState('')
const uid = parseInt(userId, 10)
const rid = parseInt(roomId, 10)
return (
<div className="grid gap-6 lg:grid-cols-2">
{/* User Actions */}
<Card>
<CardHeader>
<CardTitle className="text-sm flex items-center gap-2">
<Zap className="h-4 w-4 text-[var(--admin-warning)]" />
User Actions
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<span className="text-xs text-muted-foreground mb-1 block">User ID</span>
<Input
type="number"
value={userId}
onChange={(e) => setUserId(e.target.value)}
placeholder="Enter user ID"
/>
</div>
<div className="grid grid-cols-2 gap-2">
<Button
variant="destructive"
size="sm"
disabled={isPending || !uid}
onClick={() =>
run(() => quickKick({ userId: uid }), { successMessage: 'User disconnected' })
}
>
{isPending ? (
<Loader2 className="mr-1 h-3 w-3 animate-spin" />
) : (
<Zap className="mr-1 h-3 w-3" />
)}
Kick / Disconnect
</Button>
<Button
variant="outline"
size="sm"
disabled={isPending || !uid}
onClick={() =>
run(() => quickUnmute({ userId: uid }), { successMessage: 'User unmuted' })
}
>
<Volume2 className="mr-1 h-3 w-3" /> Unmute
</Button>
</div>
<div className="flex gap-2">
<Input
type="number"
min={1}
max={1440}
value={muteDuration}
onChange={(e) => setMuteDuration(e.target.value)}
className="w-24"
placeholder="Min"
/>
<Button
variant="outline"
size="sm"
className="flex-1"
disabled={isPending || !uid || !parseInt(muteDuration, 10)}
onClick={() =>
run(() => quickMute({ userId: uid, duration: parseInt(muteDuration, 10) }), {
successMessage: `Muted for ${muteDuration} min`,
})
}
>
<VolumeX className="mr-1 h-3 w-3" /> Mute
</Button>
</div>
<div className="flex gap-2">
<Textarea
value={alertMessage}
onChange={(e) => setAlertMessage(e.target.value)}
placeholder="Alert message to user..."
rows={2}
className="resize-none text-xs"
/>
<Button
variant="outline"
size="sm"
className="shrink-0 h-auto"
disabled={isPending || !uid || !alertMessage.trim()}
onClick={() => {
run(() => quickAlert({ userId: uid, message: alertMessage.trim() }), {
successMessage: 'Alert sent',
onSuccess: () => setAlertMessage(''),
})
}}
>
<MessageSquare className="h-4 w-4" />
</Button>
</div>
</CardContent>
</Card>
{/* Room Actions */}
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-sm flex items-center gap-2">
<DoorOpen className="h-4 w-4 text-[var(--admin-warning)]" />
Room Actions
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div>
<span className="text-xs text-muted-foreground mb-1 block">Room ID</span>
<Input
type="number"
value={roomId}
onChange={(e) => setRoomId(e.target.value)}
placeholder="Enter room ID"
/>
</div>
<Button
variant="destructive"
size="sm"
className="w-full"
disabled={isPending || !rid}
onClick={() =>
run(() => quickRoomKick({ roomId: rid }), {
successMessage: 'All users kicked from room',
})
}
>
<Zap className="mr-1 h-3 w-3" /> Kick All From Room
</Button>
</CardContent>
</Card>
{/* Broadcast */}
<Card>
<CardHeader>
<CardTitle className="text-sm flex items-center gap-2">
<Megaphone className="h-4 w-4 text-primary" />
Broadcast Alert
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<Textarea
value={broadcastMsg}
onChange={(e) => setBroadcastMsg(e.target.value)}
placeholder="Type broadcast message..."
rows={3}
className="resize-none"
/>
<div className="grid grid-cols-2 gap-2">
<Button
size="sm"
disabled={isPending || !broadcastMsg.trim()}
onClick={() => {
run(() => broadcastAlert({ message: broadcastMsg.trim(), type: 'hotel' }), {
successMessage: 'Hotel alert sent!',
onSuccess: () => setBroadcastMsg(''),
})
}}
>
<Megaphone className="mr-1 h-3 w-3" /> Hotel Alert
</Button>
<Button
variant="secondary"
size="sm"
disabled={isPending || !broadcastMsg.trim()}
onClick={() => {
run(() => broadcastAlert({ message: broadcastMsg.trim(), type: 'staff' }), {
successMessage: 'Staff alert sent!',
onSuccess: () => setBroadcastMsg(''),
})
}}
>
<Shield className="mr-1 h-3 w-3" /> Staff Alert
</Button>
</div>
</CardContent>
</Card>
</div>
</div>
)
}
+20
View File
@@ -0,0 +1,20 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { ModActionsClient } from './mod-actions-client'
export default async function QuickActionsPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.MODERATION_EDIT, session.user.rank)) redirect('/admin')
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Quick Actions</h1>
<p className="text-muted-foreground">
Fast moderation tools — kick, mute, alert, broadcast
</p>
</div>
<ModActionsClient />
</div>
)
}
@@ -0,0 +1,408 @@
'use client'
import {
AlertTriangle,
ArrowLeft,
Ban,
CheckCircle2,
MessageSquare,
Shield,
User,
VolumeX,
Zap,
} from 'lucide-react'
import Link from 'next/link'
import { useState } from 'react'
import {
assignCfhTicket,
closeCfhTicket,
quickAlert,
quickKick,
quickMute,
updateCfhState,
} from '@/actions/moderation'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { useServerAction } from '@/hooks/use-server-action'
const CFH_STATES: Record<number, { label: string; class: string }> = {
0: { label: 'Open', class: 'bg-[var(--admin-error-subtle)] text-[var(--admin-error)]' },
1: { label: 'Picked', class: 'bg-[var(--admin-warning-subtle)] text-[var(--admin-warning)]' },
2: { label: 'Closed', class: 'bg-muted text-muted-foreground' },
}
interface UserInfo {
id: number
username: string
look: string
rank: number
online: string
ipRegister: string
mail: string | null
}
interface BanRecord {
id: number
reason: string
type: string
staff: string
timestamp: number
}
export function CfhDetail({
ticket,
sender,
reported,
moderator,
banHistory,
canEdit,
// biome-ignore lint/correctness/noUnusedFunctionParameters: part of the public component API
currentUserId,
}: {
ticket: {
id: number
state: number
type: number
timestamp: number
issue: string
roomId: number
category: number
score: number
}
sender: UserInfo | null
reported: UserInfo | null
moderator: UserInfo | null
banHistory: { count: number; recent: BanRecord[] }
canEdit: boolean
currentUserId: number
}) {
const { run, isPending } = useServerAction()
const [alertMsg, setAlertMsg] = useState('')
const [muteDuration, setMuteDuration] = useState(10)
const state = CFH_STATES[ticket.state] ?? CFH_STATES[0]
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-start gap-4">
<Link href="/admin/moderation/cfh">
<Button variant="ghost" size="icon">
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<span className="text-sm text-muted-foreground font-mono">CFH #{ticket.id}</span>
<Badge className={state.class}>{state.label}</Badge>
<span className="text-xs text-muted-foreground">
Type {ticket.type} · Category {ticket.category}
</span>
</div>
<h1 className="text-xl font-bold">Call For Help Report</h1>
<p className="text-xs text-muted-foreground">
{new Date(ticket.timestamp * 1000).toLocaleString()} · Room #{ticket.roomId}
</p>
</div>
</div>
<div className="grid gap-6 lg:grid-cols-[1fr_300px]">
{/* Main content */}
<div className="space-y-4">
{/* Issue */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm flex items-center gap-2">
<MessageSquare className="h-4 w-4" />
Report Message
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm leading-relaxed whitespace-pre-wrap">
{ticket.issue || 'No description provided.'}
</p>
</CardContent>
</Card>
{/* Users involved */}
<div className="grid gap-4 sm:grid-cols-2">
{/* Sender */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm text-[var(--admin-info)]">Reporter</CardTitle>
</CardHeader>
<CardContent>
{sender ? (
<Link
href={`/admin/users/show/${sender.id}`}
className="flex items-center gap-3 hover:text-primary no-underline"
>
<User className="h-4 w-4" />
<div>
<p className="text-sm font-bold">{sender.username}</p>
<p className="text-xs text-muted-foreground">
Rank {sender.rank} · {sender.online === '1' ? 'Online' : 'Offline'}
</p>
</div>
</Link>
) : (
<p className="text-sm text-muted-foreground">Unknown user</p>
)}
</CardContent>
</Card>
{/* Reported */}
<Card className="border-[var(--admin-error-border)]">
<CardHeader className="pb-2">
<CardTitle className="text-sm text-[var(--admin-error)]">Reported User</CardTitle>
</CardHeader>
<CardContent>
{reported ? (
<div>
<Link
href={`/admin/users/show/${reported.id}`}
className="flex items-center gap-3 hover:text-primary no-underline"
>
<AlertTriangle className="h-4 w-4 text-[var(--admin-error)]" />
<div>
<p className="text-sm font-bold">{reported.username}</p>
<p className="text-xs text-muted-foreground">
Rank {reported.rank} · {reported.online === '1' ? 'Online' : 'Offline'} ·{' '}
{banHistory.count} bans
</p>
</div>
</Link>
{/* Quick actions on reported user */}
{canEdit && (
<div className="mt-3 pt-3 border-t space-y-2">
<div className="flex gap-2">
<Button
size="sm"
variant="destructive"
className="flex-1"
disabled={isPending}
onClick={() =>
run(() => quickKick({ userId: reported.id }), {
successMessage: 'User kicked',
})
}
>
<Zap className="mr-1 h-3 w-3" /> Kick
</Button>
<Button
size="sm"
variant="outline"
className="flex-1"
disabled={isPending}
onClick={() =>
run(
() => quickMute({ userId: reported.id, duration: muteDuration }),
{ successMessage: `Muted for ${muteDuration}min` },
)
}
>
<VolumeX className="mr-1 h-3 w-3" /> Mute
</Button>
</div>
<Input
type="number"
min={1}
max={1440}
value={muteDuration}
onChange={(e) => setMuteDuration(Number(e.target.value))}
className="h-7 text-xs"
placeholder="Mute duration (min)"
/>
<div className="flex gap-2">
<Textarea
value={alertMsg}
onChange={(e) => setAlertMsg(e.target.value)}
placeholder="Alert message..."
rows={2}
className="text-xs resize-none"
/>
<Button
size="sm"
variant="outline"
className="shrink-0"
disabled={isPending || !alertMsg.trim()}
onClick={() => {
run(
() => quickAlert({ userId: reported.id, message: alertMsg.trim() }),
{
successMessage: 'Alert sent',
onSuccess: () => setAlertMsg(''),
},
)
}}
>
Alert
</Button>
</div>
</div>
)}
</div>
) : (
<p className="text-sm text-muted-foreground">Unknown user</p>
)}
</CardContent>
</Card>
</div>
{/* Ban history */}
{banHistory.recent.length > 0 && (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm flex items-center gap-2">
<Ban className="h-4 w-4 text-[var(--admin-error)]" />
Ban History ({banHistory.count})
</CardTitle>
</CardHeader>
<CardContent>
<div className="divide-y divide-border">
{banHistory.recent.map((ban) => (
<div key={ban.id} className="py-2 first:pt-0 last:pb-0 text-xs">
<p className="font-medium">{ban.reason || 'No reason'}</p>
<p className="text-muted-foreground">
{ban.type} · by {ban.staff} ·{' '}
{new Date(ban.timestamp * 1000).toLocaleDateString()}
</p>
</div>
))}
</div>
</CardContent>
</Card>
)}
</div>
{/* Sidebar */}
<div className="space-y-4">
{/* Actions */}
{canEdit && (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">Actions</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div>
<span className="text-xs text-muted-foreground mb-1 block">Status</span>
<Select
value={String(ticket.state)}
onValueChange={(v) =>
run(() => updateCfhState({ ticketId: ticket.id, state: Number(v) }), {
successMessage: 'Status updated',
})
}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="0" className="text-xs">
Open
</SelectItem>
<SelectItem value="1" className="text-xs">
Picked
</SelectItem>
<SelectItem value="2" className="text-xs">
Closed
</SelectItem>
</SelectContent>
</Select>
</div>
<Button
variant="outline"
size="sm"
className="w-full"
disabled={isPending}
onClick={() =>
run(() => assignCfhTicket({ ticketId: ticket.id }), {
successMessage: 'Assigned to you',
})
}
>
<Shield className="mr-1.5 h-3.5 w-3.5" /> Assign to me
</Button>
<Button
variant="outline"
size="sm"
className="w-full text-[var(--admin-success)]"
disabled={isPending || ticket.state === 2}
onClick={() =>
run(() => closeCfhTicket({ ticketId: ticket.id }), {
successMessage: 'Ticket closed',
})
}
>
<CheckCircle2 className="mr-1.5 h-3.5 w-3.5" /> Close Ticket
</Button>
</CardContent>
</Card>
)}
{/* Moderator */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">Assigned Moderator</CardTitle>
</CardHeader>
<CardContent>
{moderator ? (
<Link
href={`/admin/users/show/${moderator.id}`}
className="flex items-center gap-2 text-sm hover:text-primary no-underline"
>
<Shield className="h-3.5 w-3.5 text-primary" />
{moderator.username}
</Link>
) : (
<p className="text-xs text-muted-foreground">Unassigned</p>
)}
</CardContent>
</Card>
{/* Details */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">Details</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-xs text-muted-foreground">
<div className="flex justify-between">
<span>Created</span>
<span>{new Date(ticket.timestamp * 1000).toLocaleString()}</span>
</div>
<div className="flex justify-between">
<span>Room</span>
<span>#{ticket.roomId}</span>
</div>
<div className="flex justify-between">
<span>Type</span>
<span>{ticket.type}</span>
</div>
<div className="flex justify-between">
<span>Category</span>
<span>{ticket.category}</span>
</div>
<div className="flex justify-between">
<span>Score</span>
<span>{ticket.score}</span>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
)
}
@@ -0,0 +1,80 @@
import { notFound, redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { CfhDetail } from './cfh-detail'
export default async function CfhDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.MODERATION_VIEW, session.user.rank)) redirect('/admin')
const { id } = await params
const ticketId = Number(id)
if (Number.isNaN(ticketId)) notFound()
const ticket = await prisma.supportTickets.findUnique({ where: { id: ticketId } })
if (!ticket) notFound()
const canEdit = canAccess(permissions, PERMS.MODERATION_EDIT, session.user.rank)
// Fetch sender, reported, mod info
const userIds = [ticket.senderId, ticket.reportedId, ticket.modId].filter(Boolean)
const users =
userIds.length > 0
? await prisma.user.findMany({
where: { id: { in: userIds } },
select: {
id: true,
username: true,
look: true,
rank: true,
online: true,
ipRegister: true,
mail: true,
},
})
: []
const userMap = Object.fromEntries(users.map((u) => [u.id, u]))
// Get ban/mute history for reported user
const reportedId = ticket.reportedId
const [banCount, recentBans] = reportedId
? await Promise.all([
prisma.ban.count({ where: { userId: reportedId } }),
prisma.ban.findMany({
where: { userId: reportedId },
orderBy: { id: 'desc' },
take: 5,
}),
])
: [0, []]
return (
<CfhDetail
ticket={{
id: ticket.id,
state: ticket.state,
type: ticket.type,
timestamp: ticket.timestamp,
issue: ticket.issue,
roomId: ticket.roomId,
category: ticket.category,
score: ticket.score,
}}
sender={userMap[ticket.senderId] ?? null}
reported={userMap[ticket.reportedId] ?? null}
moderator={userMap[ticket.modId] ?? null}
banHistory={{
count: banCount,
recent: recentBans.map((b) => ({
id: b.id,
reason: b.banReason,
type: b.type,
staff: `Staff #${b.userStaffId}`,
timestamp: b.timestamp,
})),
}}
canEdit={canEdit}
currentUserId={session.user.id}
/>
)
}
+161
View File
@@ -0,0 +1,161 @@
import { AlertTriangle, CheckCircle2, Clock, Radio } from 'lucide-react'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { Badge } from '@/components/ui/badge'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
const CFH_STATES: Record<number, { label: string; class: string; icon: typeof AlertTriangle }> = {
0: { label: 'Open', class: 'bg-[var(--admin-error-subtle)] text-[var(--admin-error)]', icon: AlertTriangle },
1: { label: 'Picked', class: 'bg-[var(--admin-warning-subtle)] text-[var(--admin-warning)]', icon: Clock },
2: { label: 'Closed', class: 'bg-muted text-muted-foreground', icon: CheckCircle2 },
}
interface PageProps {
searchParams: Promise<{ state?: string; page?: string }>
}
export default async function CfhListPage({ searchParams }: PageProps) {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.MODERATION_VIEW, session.user.rank)) redirect('/admin')
const sp = await searchParams
const stateFilter = sp.state !== undefined ? Number(sp.state) : -1
const page = Math.max(1, Number(sp.page) || 1)
const perPage = 25
const where = stateFilter >= 0 ? { state: stateFilter } : {}
const [tickets, total] = await Promise.all([
prisma.supportTickets.findMany({
where,
orderBy: { id: 'desc' },
skip: (page - 1) * perPage,
take: perPage,
}),
prisma.supportTickets.count({ where }),
])
// Fetch all related users
const userIds = [
...new Set([
...tickets.map((t) => t.senderId),
...tickets.map((t) => t.reportedId),
...tickets.map((t) => t.modId),
]),
].filter(Boolean)
const users =
userIds.length > 0
? await prisma.user.findMany({
where: { id: { in: userIds } },
select: { id: true, username: true },
})
: []
const userMap = new Map(users.map((u) => [u.id, u.username]))
const totalPages = Math.ceil(total / perPage)
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">CFH Tickets</h1>
<p className="text-muted-foreground">In-game Call For Help reports</p>
</div>
{/* Filters */}
<div className="flex gap-2">
{[
{ key: -1, label: 'All' },
{ key: 0, label: 'Open' },
{ key: 1, label: 'Picked' },
{ key: 2, label: 'Closed' },
].map(({ key, label }) => (
<Link key={key} href={`/admin/moderation/cfh${key >= 0 ? `?state=${key}` : ''}`}>
<Badge variant={stateFilter === key ? 'default' : 'outline'} className="cursor-pointer">
{label}
</Badge>
</Link>
))}
</div>
{/* Table */}
<div className="rounded-lg border">
<div className="grid grid-cols-[auto_1fr_auto_auto_auto_auto] gap-4 p-3 bg-muted/50 text-xs font-medium text-muted-foreground border-b">
<span>#</span>
<span>Issue</span>
<span>Sender</span>
<span>Reported</span>
<span>Mod</span>
<span>Status</span>
</div>
{tickets.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">
<Radio className="h-8 w-8 mx-auto mb-2" />
No tickets found.
</div>
) : (
tickets.map((ticket) => {
const state = CFH_STATES[ticket.state] ?? CFH_STATES[0]
const StateIcon = state.icon
return (
<Link
key={ticket.id}
href={`/admin/moderation/cfh/${ticket.id}`}
className="grid grid-cols-[auto_1fr_auto_auto_auto_auto] gap-4 p-3 items-center hover:bg-accent/50 transition-all duration-150 border-b last:border-0 hover:pl-4"
>
<span className="text-xs font-mono text-muted-foreground">{ticket.id}</span>
<div className="min-w-0">
<p className="text-sm truncate">{ticket.issue || 'No description'}</p>
<p className="text-[10px] text-muted-foreground">
Room #{ticket.roomId} · {new Date(ticket.timestamp * 1000).toLocaleString()}
</p>
</div>
<span className="text-xs whitespace-nowrap">
{userMap.get(ticket.senderId) ?? '—'}
</span>
<span className="text-xs whitespace-nowrap font-medium">
{userMap.get(ticket.reportedId) ?? '—'}
</span>
<span className="text-xs text-muted-foreground whitespace-nowrap">
{userMap.get(ticket.modId) ?? '—'}
</span>
<span
className={`inline-flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded-full whitespace-nowrap ${state.class}`}
>
<StateIcon className="h-3 w-3" />
{state.label}
</span>
</Link>
)
})
)}
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-center gap-2">
{page > 1 && (
<Link href={`/admin/moderation/cfh?state=${stateFilter}&page=${page - 1}`}>
<Badge variant="outline" className="cursor-pointer">
Previous
</Badge>
</Link>
)}
<span className="text-sm text-muted-foreground">
Page {page} of {totalPages}
</span>
{page < totalPages && (
<Link href={`/admin/moderation/cfh?state=${stateFilter}&page=${page + 1}`}>
<Badge variant="outline" className="cursor-pointer">
Next
</Badge>
</Link>
)}
</div>
)}
</div>
)
}
+184
View File
@@ -0,0 +1,184 @@
import { AlertTriangle, Ban, Clock, Gavel, Radio, Shield, User } from 'lucide-react'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { StatsCard } from '@/components/admin/stats-card'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
const CFH_STATES: Record<number, { label: string; class: string }> = {
0: { label: 'Open', class: 'bg-[var(--admin-error-subtle)] text-[var(--admin-error)]' },
1: { label: 'Picked', class: 'bg-[var(--admin-warning-subtle)] text-[var(--admin-warning)]' },
2: { label: 'Closed', class: 'bg-muted text-muted-foreground' },
}
export default async function ModerationDashboard() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.MODERATION_VIEW, session.user.rank)) redirect('/admin')
const now = Math.floor(Date.now() / 1000)
const todayStart = now - (now % 86400)
const [openCfh, pickedCfh, todayBans, modsOnline, recentCfh, recentModActions] =
await Promise.all([
prisma.supportTickets.count({ where: { state: 0 } }),
prisma.supportTickets.count({ where: { state: 1 } }),
prisma.ban.count({ where: { timestamp: { gte: todayStart } } }),
prisma.user.count({ where: { online: '1', rank: { gte: 4 } } }),
prisma.supportTickets.findMany({
orderBy: { id: 'desc' },
take: 10,
}),
prisma.adminAuditLog.findMany({
where: {
action: { startsWith: 'mod_' },
},
orderBy: { id: 'desc' },
take: 10,
include: { user: { select: { username: true } } },
}),
])
// Fetch usernames for CFH tickets
const userIds = [
...new Set([
...recentCfh.map((t) => t.senderId),
...recentCfh.map((t) => t.reportedId),
...recentCfh.map((t) => t.modId),
]),
].filter(Boolean)
const users =
userIds.length > 0
? await prisma.user.findMany({
where: { id: { in: userIds } },
select: { id: true, username: true },
})
: []
const userMap = new Map(users.map((u) => [u.id, u.username]))
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Moderation</h1>
<p className="text-muted-foreground">In-game moderation dashboard</p>
</div>
{/* Stats */}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<StatsCard
title="Open CFH"
value={openCfh}
description={`${pickedCfh} picked`}
icon={<Radio className="h-4 w-4" />}
href="/admin/moderation/cfh"
/>
<StatsCard
title="Bans Today"
value={todayBans}
icon={<Ban className="h-4 w-4" />}
href="/admin/bans"
/>
<StatsCard
title="Mods Online"
value={modsOnline}
icon={<Shield className="h-4 w-4" />}
href="/admin/moderation/team"
/>
<StatsCard
title="Quick Actions"
value="→"
description="Kick, mute, alert"
icon={<Gavel className="h-4 w-4" />}
href="/admin/moderation/actions"
/>
</div>
<div className="grid gap-6 lg:grid-cols-2">
{/* Recent CFH */}
<Card>
<CardHeader>
<CardTitle className="flex items-center justify-between">
<span className="flex items-center gap-2">
<AlertTriangle className="h-4 w-4 text-[var(--admin-error)]" />
Recent CFH Tickets
</span>
<Link
href="/admin/moderation/cfh"
className="text-xs font-normal text-primary hover:underline"
>
View all
</Link>
</CardTitle>
</CardHeader>
<CardContent>
{recentCfh.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">No CFH tickets</p>
) : (
<div className="divide-y divide-border">
{recentCfh.map((ticket) => {
const state = CFH_STATES[ticket.state] ?? CFH_STATES[0]
return (
<Link
key={ticket.id}
href={`/admin/moderation/cfh/${ticket.id}`}
className="flex items-center gap-3 py-2.5 first:pt-0 last:pb-0 hover:bg-accent/50 -mx-2 px-2 rounded transition-colors"
>
<span className="text-xs font-mono text-muted-foreground w-8">
#{ticket.id}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm truncate">{ticket.issue || 'No description'}</p>
<p className="text-xs text-muted-foreground">
{userMap.get(ticket.senderId) ?? '?'} →{' '}
{userMap.get(ticket.reportedId) ?? '?'}
</p>
</div>
<Badge className={`text-[10px] ${state.class}`}>{state.label}</Badge>
</Link>
)
})}
</div>
)}
</CardContent>
</Card>
{/* Recent Mod Actions */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Clock className="h-4 w-4" />
Recent Mod Actions
</CardTitle>
</CardHeader>
<CardContent>
{recentModActions.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">No recent actions</p>
) : (
<div className="divide-y divide-border">
{recentModActions.map((log) => (
<div key={log.id} className="flex items-center gap-3 py-2.5 first:pt-0 last:pb-0">
<User className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{log.action.replace('mod_', '').replace(/_/g, ' ')}
</p>
<p className="text-xs text-muted-foreground">
by {log.user?.username ?? '?'} · {log.target}{' '}
{log.targetId ? `#${log.targetId}` : ''}
</p>
</div>
<span className="text-[10px] text-muted-foreground whitespace-nowrap">
{log.createdAt}
</span>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
</div>
)
}
+149
View File
@@ -0,0 +1,149 @@
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { AvatarImage } from '@/components/shared/avatar-image'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
export default async function ModTeamPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.MODERATION_VIEW, session.user.rank)) redirect('/admin')
// Get all staff (rank >= 4)
const staff = await prisma.user.findMany({
where: { rank: { gte: 4 } },
select: {
id: true,
username: true,
look: true,
rank: true,
online: true,
lastLogin: true,
lastOnline: true,
},
orderBy: [{ online: 'desc' }, { rank: 'desc' }],
})
// Get CFH ticket counts per mod and web ticket counts
const [cfhCounts, webTicketCounts, modActionCounts] = await Promise.all([
prisma.supportTickets.groupBy({
by: ['modId'],
where: { modId: { in: staff.map((s) => s.id) } },
_count: { _all: true },
}),
prisma.websiteTicket.groupBy({
by: ['assigneeId'],
where: { assigneeId: { in: staff.map((s) => s.id) } },
_count: { _all: true },
}),
prisma.adminAuditLog.groupBy({
by: ['userId'],
where: {
userId: { in: staff.map((s) => s.id) },
action: { startsWith: 'mod_' },
},
_count: { _all: true },
}),
])
const cfhMap = new Map(cfhCounts.map((c) => [c.modId, c._count._all]))
const webMap = new Map(webTicketCounts.map((c) => [c.assigneeId, c._count._all]))
const actionMap = new Map(modActionCounts.map((c) => [c.userId, c._count._all]))
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Mod Team</h1>
<p className="text-muted-foreground">Staff performance and status</p>
</div>
{/* Summary */}
<div className="grid gap-4 grid-cols-3">
<Card>
<CardContent className="pt-4 text-center">
<p className="text-2xl font-bold text-[var(--admin-success)]">
{staff.filter((s) => s.online === '1').length}
</p>
<p className="text-xs text-muted-foreground">Online Now</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-4 text-center">
<p className="text-2xl font-bold">{staff.length}</p>
<p className="text-xs text-muted-foreground">Total Staff</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-4 text-center">
<p className="text-2xl font-bold text-primary">
{staff.filter((s) => s.rank >= 7).length}
</p>
<p className="text-xs text-muted-foreground">Super Admins</p>
</CardContent>
</Card>
</div>
{/* Staff list */}
<div className="rounded-lg border">
<div className="grid grid-cols-[auto_1fr_auto_auto_auto_auto_auto] gap-4 p-3 bg-muted/50 text-xs font-medium text-muted-foreground border-b">
<span></span>
<span>Name</span>
<span>Rank</span>
<span>CFH</span>
<span>Tickets</span>
<span>Actions</span>
<span>Last Seen</span>
</div>
{staff.map((member) => (
<Link
key={member.id}
href={`/admin/users/show/${member.id}`}
className="grid grid-cols-[auto_1fr_auto_auto_auto_auto_auto] gap-4 p-3 items-center hover:bg-accent/50 transition-all duration-150 border-b last:border-0"
>
<div className="relative">
<AvatarImage
figure={member.look}
options={{ headOnly: true, size: 'l' }}
alt={member.username}
width={32}
height={32}
/>
<span
className={`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-background ${
member.online === '1' ? 'bg-[var(--admin-success)]' : 'bg-[var(--admin-text-muted)]'
}`}
/>
</div>
<div>
<p className="text-sm font-medium">{member.username}</p>
</div>
<Badge variant="outline" className="text-[10px]">
Rank {member.rank}
</Badge>
<div className="text-center">
<p className="text-sm font-bold">{cfhMap.get(member.id) ?? 0}</p>
<p className="text-[9px] text-muted-foreground">CFH</p>
</div>
<div className="text-center">
<p className="text-sm font-bold">{webMap.get(member.id) ?? 0}</p>
<p className="text-[9px] text-muted-foreground">Web</p>
</div>
<div className="text-center">
<p className="text-sm font-bold">{actionMap.get(member.id) ?? 0}</p>
<p className="text-[9px] text-muted-foreground">Mod</p>
</div>
<span className="text-xs text-muted-foreground whitespace-nowrap">
{member.online === '1'
? 'Online'
: member.lastOnline
? new Date(member.lastOnline * 1000).toLocaleDateString()
: '—'}
</span>
</Link>
))}
</div>
</div>
)
}
+28
View File
@@ -0,0 +1,28 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function OnlineLoading() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<Skeleton className="h-9 w-40" />
<Skeleton className="h-5 w-64 mt-2" />
</div>
</div>
<div className="flex items-center gap-3">
<Skeleton className="h-10 w-64" />
<Skeleton className="h-10 w-24" />
</div>
<div className="rounded-md border">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="flex items-center gap-6 px-4 py-3 border-b last:border-0">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-5 w-16 rounded-full" />
</div>
))}
</div>
</div>
)
}
+120
View File
@@ -0,0 +1,120 @@
'use client'
import { Pause, Play, RefreshCw } from 'lucide-react'
import { useRouter } from 'next/navigation'
import { useCallback, useEffect, useState } from 'react'
import { DataTable } from '@/components/admin/data-table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { getAvatarUrl } from '@/lib/imager'
import type { DataTableColumn, PaginatedResult } from '@/types'
interface OnlineUserRow {
id: number
username: string
motto: string
look: string
}
const columns: DataTableColumn<OnlineUserRow>[] = [
{ key: 'id', label: 'ID', sortable: true },
{
key: 'username',
label: 'Username',
sortable: true,
render: (_, row) => (
<div className="flex items-center gap-2">
<img
src={getAvatarUrl(row.look, { size: 's', headOnly: true })}
alt=""
className="h-8 w-8 rounded"
/>
<span className="font-medium">{row.username}</span>
<span className="relative flex h-2 w-2">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-[var(--admin-success)]/70 opacity-75" />
<span className="relative inline-flex rounded-full h-2 w-2 bg-[var(--admin-success)]" />
</span>
</div>
),
},
{
key: 'motto',
label: 'Motto',
render: (value) => <span className="max-w-[250px] truncate block">{String(value) || '-'}</span>,
},
{
key: 'look',
label: 'Avatar',
render: (_, row) => <img src={getAvatarUrl(row.look)} alt={row.username} className="h-16" />,
},
]
interface OnlineTableProps {
data: PaginatedResult<OnlineUserRow>
}
const REFRESH_INTERVAL = 15_000 // 15 seconds
export function OnlineTable({ data }: OnlineTableProps) {
const router = useRouter()
const [autoRefresh, setAutoRefresh] = useState(false)
const [lastUpdated, setLastUpdated] = useState(() => new Date())
const [isRefreshing, setIsRefreshing] = useState(false)
const doRefresh = useCallback(() => {
setIsRefreshing(true)
router.refresh()
setLastUpdated(new Date())
// Small delay to show spinner
setTimeout(() => setIsRefreshing(false), 500)
}, [router])
useEffect(() => {
if (!autoRefresh) return
const timer = setInterval(doRefresh, REFRESH_INTERVAL)
return () => clearInterval(timer)
}, [autoRefresh, doRefresh])
// Update lastUpdated when data changes
// biome-ignore lint/correctness/useExhaustiveDependencies: explicitly chosen here, see surrounding code
useEffect(() => {
setLastUpdated(new Date())
}, [data.total])
return (
<div className="space-y-4">
{/* Auto-refresh controls */}
<div className="flex items-center gap-3 text-sm">
<Button variant="outline" size="sm" onClick={doRefresh} disabled={isRefreshing}>
<RefreshCw className={`mr-1.5 h-3.5 w-3.5 ${isRefreshing ? 'animate-spin' : ''}`} />
Refresh
</Button>
<Button
variant={autoRefresh ? 'default' : 'outline'}
size="sm"
onClick={() => setAutoRefresh(!autoRefresh)}
>
{autoRefresh ? (
<>
<Pause className="mr-1.5 h-3.5 w-3.5" /> Auto-refresh ON
</>
) : (
<>
<Play className="mr-1.5 h-3.5 w-3.5" /> Auto-refresh OFF
</>
)}
</Button>
{autoRefresh && (
<Badge variant="secondary" className="text-xs">
Every {REFRESH_INTERVAL / 1000}s
</Badge>
)}
<span className="text-xs text-muted-foreground ml-auto">
Last updated: {lastUpdated.toLocaleTimeString()}
</span>
</div>
<DataTable data={data} columns={columns} searchPlaceholder="Search by username or motto..." />
</div>
)
}
+48
View File
@@ -0,0 +1,48 @@
import { fetchAdminList } from '@/lib/admin-list'
import { PERMS } from '@/lib/permissions'
import { OnlineTable } from './online-table'
export default async function OnlineUsersPage({
params: paramsPromise,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
const result = await fetchAdminList(
{
permission: PERMS.USERS_VIEW,
model: 'user',
searchFields: ['username', 'motto'],
baseWhere: { online: '1' },
defaultPerPage: 50,
select: {
id: true,
username: true,
motto: true,
look: true,
},
},
paramsPromise,
searchParams,
)
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Online Users</h1>
<p className="text-muted-foreground">Currently online users ({result.total} connected)</p>
</div>
<OnlineTable
data={{
rows: result.rows,
total: result.total,
page: result.page,
perPage: result.perPage,
lastPage: result.lastPage,
}}
/>
</div>
)
}
+101
View File
@@ -0,0 +1,101 @@
import { withAdmin } from '@/lib/api-handler'
import { apiError } from '@/lib/api-response'
import { PERMS } from '@/lib/permission-slugs'
import { prisma } from '@/lib/prisma'
const VALID_REPORTS = new Set(['registrations', 'online-by-hour', 'economy'])
function csvEscape(value: unknown): string {
if (value == null) return ''
const str = String(value)
if (/[",\n\r]/.test(str)) {
return `"${str.replace(/"/g, '""')}"`
}
return str
}
function csvRow(values: unknown[]): string {
return `${values.map(csvEscape).join(',')}\n`
}
async function streamRegistrations(): Promise<ReadableStream<Uint8Array>> {
const rows = await prisma.$queryRaw<{ day: string; cnt: bigint }[]>`
SELECT FROM_UNIXTIME(account_created, '%Y-%m-%d') AS day, COUNT(*) AS cnt
FROM users
WHERE account_created > UNIX_TIMESTAMP(NOW() - INTERVAL 90 DAY)
GROUP BY day
ORDER BY day ASC
`
const encoder = new TextEncoder()
return new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(csvRow(['day', 'registrations'])))
for (const r of rows) {
controller.enqueue(encoder.encode(csvRow([r.day, Number(r.cnt)])))
}
controller.close()
},
})
}
async function streamOnlineByHour(): Promise<ReadableStream<Uint8Array>> {
const rows = await prisma.$queryRaw<{ hour: number; cnt: bigint }[]>`
SELECT HOUR(FROM_UNIXTIME(last_online)) AS hour, COUNT(*) AS cnt
FROM users
WHERE last_online > UNIX_TIMESTAMP(NOW() - INTERVAL 30 DAY)
GROUP BY hour
ORDER BY hour ASC
`
const encoder = new TextEncoder()
return new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(csvRow(['hour', 'active_users'])))
for (const r of rows) {
controller.enqueue(encoder.encode(csvRow([Number(r.hour), Number(r.cnt)])))
}
controller.close()
},
})
}
async function streamEconomy(): Promise<ReadableStream<Uint8Array>> {
const [totals] = await prisma.$queryRaw<{ total_credits: bigint; total_pixels: bigint }[]>`
SELECT SUM(credits) AS total_credits, SUM(pixels) AS total_pixels FROM users
`
const encoder = new TextEncoder()
return new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(csvRow(['metric', 'value'])))
controller.enqueue(
encoder.encode(csvRow(['total_credits', Number(totals?.total_credits ?? 0)])),
)
controller.enqueue(
encoder.encode(csvRow(['total_pixels', Number(totals?.total_pixels ?? 0)])),
)
controller.close()
},
})
}
export const GET = withAdmin({ permission: PERMS.ANALYTICS_EXPORT }, async (request) => {
const url = new URL(request.url)
const report = url.searchParams.get('report') ?? ''
if (!VALID_REPORTS.has(report)) {
return apiError(`Unknown report. Use one of: ${[...VALID_REPORTS].join(', ')}`, 400)
}
const stream =
report === 'registrations'
? await streamRegistrations()
: report === 'online-by-hour'
? await streamOnlineByHour()
: await streamEconomy()
return new Response(stream, {
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="${report}.csv"`,
'Cache-Control': 'no-store',
},
})
})
+59
View File
@@ -0,0 +1,59 @@
import net from 'node:net'
import { NextResponse } from 'next/server'
import { env } from '@/env'
import { withAdmin } from '@/lib/api-handler'
import { PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
function checkRcon(): Promise<boolean> {
return new Promise((resolve) => {
const host = env.RCON_HOST
const port = env.RCON_PORT
const socket = new net.Socket()
const timeout = setTimeout(() => {
socket.destroy()
resolve(false)
}, 3000)
socket.connect(port, host, () => {
clearTimeout(timeout)
socket.destroy()
resolve(true)
})
socket.on('error', () => {
clearTimeout(timeout)
socket.destroy()
resolve(false)
})
})
}
export const GET = withAdmin({ permission: PERMS.DEVOPS_VIEW }, async () => {
// DB health
let dbOk = false
let dbLatency = 0
try {
const start = Date.now()
await prisma.$queryRaw`SELECT 1`
dbLatency = Date.now() - start
dbOk = true
} catch {
dbOk = false
}
// Emulator health (RCON TCP check)
const emulator = await checkRcon()
// Online users
const onlineUsers = await prisma.user.count({ where: { online: '1' } })
return NextResponse.json({
database: dbOk,
dbLatency,
emulator,
onlineUsers,
timestamp: new Date().toISOString(),
})
})
+15
View File
@@ -0,0 +1,15 @@
'use client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
interface ChartDataPoint { label: string; value: number }
export function DashboardChart({ title, data, description }: { title: string; data: ChartDataPoint[]; color?: string; description?: string }) {
const max = Math.max(1, ...data.map((point) => point.value))
return (
<Card>
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium">{title}</CardTitle>{description && <p className="text-xs text-muted-foreground">{description}</p>}</CardHeader>
<CardContent><div className="flex h-[200px] items-end gap-1" aria-label={title}>{data.map((point) => <div key={point.label} className="flex min-w-0 flex-1 flex-col items-center gap-1"><span className="text-[10px] text-muted-foreground">{point.value}</span><div className="w-full rounded-t bg-[var(--admin-accent)]" style={{ height: `${Math.max(2, (point.value / max) * 150)}px` }} title={`${point.label}: ${point.value}`} /><span className="max-w-full truncate text-[9px] text-muted-foreground">{point.label}</span></div>)}</div></CardContent>
</Card>
)
}
@@ -0,0 +1,84 @@
'use client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
interface PeakHoursData {
/** [dayOfWeek (0=Mon..6=Sun)][hour (0..23)] = count */
grid: number[][]
max: number
}
const DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
const HOURS = Array.from({ length: 24 }, (_, i) => i)
function getColor(value: number, max: number) {
if (max === 0 || value === 0) return 'bg-muted'
const ratio = value / max
if (ratio < 0.25) return 'bg-[var(--admin-success)]/20'
if (ratio < 0.5) return 'bg-[var(--admin-success)]/55'
if (ratio < 0.75) return 'bg-[var(--admin-success)] dark:bg-[var(--admin-success)]'
return 'bg-[var(--admin-success-strong,var(--admin-success))]'
}
export function PeakHoursHeatmap({ data }: { data: PeakHoursData }) {
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Peak Hours</CardTitle>
<p className="text-xs text-muted-foreground">
User activity by day &amp; hour (last 7 days)
</p>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<div className="min-w-[500px]">
{/* Hour labels */}
<div className="flex gap-px ml-10 mb-1">
{HOURS.map((h) => (
<div key={h} className="flex-1 text-center text-[10px] text-muted-foreground">
{h % 3 === 0 ? `${h}` : ''}
</div>
))}
</div>
{/* Rows */}
{DAYS.map((day, dayIdx) => (
<div key={day} className="flex items-center gap-px mb-px">
<span className="w-10 text-xs text-muted-foreground text-right pr-2 shrink-0">
{day}
</span>
<TooltipProvider delayDuration={0}>
{HOURS.map((hour) => {
const count = data.grid[dayIdx]?.[hour] ?? 0
return (
<Tooltip key={hour}>
<TooltipTrigger asChild>
<div
className={`flex-1 aspect-square rounded-sm ${getColor(count, data.max)} transition-colors min-w-[14px]`}
/>
</TooltipTrigger>
<TooltipContent side="top" className="text-xs">
{day} {hour}:00 — {count} users
</TooltipContent>
</Tooltip>
)
})}
</TooltipProvider>
</div>
))}
{/* Legend */}
<div className="flex items-center gap-2 mt-3 ml-10">
<span className="text-[10px] text-muted-foreground">Less</span>
<div className="h-3 w-3 rounded-sm bg-muted" />
<div className="h-3 w-3 rounded-sm bg-[var(--admin-success)]/20" />
<div className="h-3 w-3 rounded-sm bg-[var(--admin-success)]/55" />
<div className="h-3 w-3 rounded-sm bg-[var(--admin-success)] dark:bg-[var(--admin-success)]" />
<div className="h-3 w-3 rounded-sm bg-[var(--admin-success-strong,var(--admin-success))]" />
<span className="text-[10px] text-muted-foreground">More</span>
</div>
</div>
</div>
</CardContent>
</Card>
)
}
+10
View File
@@ -0,0 +1,10 @@
'use client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
interface RevenueDataPoint { label: string; credits: number; points: number }
export function RevenueChart({ data }: { data: RevenueDataPoint[] }) {
const max = Math.max(1, ...data.flatMap((point) => [point.credits, point.points]))
return <Card><CardHeader className="pb-2"><CardTitle className="text-sm font-medium">Catalog Spending</CardTitle></CardHeader><CardContent><div className="space-y-3">{data.map((point) => <div key={point.label} className="grid grid-cols-[3rem_1fr] items-center gap-2 text-xs"><span>{point.label}</span><div className="space-y-1"><div className="h-2 rounded bg-[var(--admin-warning)]" style={{ width: `${Math.max(2, point.credits / max * 100)}%` }} title={`${point.credits} credits`} /><div className="h-2 rounded bg-[var(--admin-accent)]" style={{ width: `${Math.max(2, point.points / max * 100)}%` }} title={`${point.points} points`} /></div></div>)}</div></CardContent></Card>
}
+67
View File
@@ -0,0 +1,67 @@
import { Minus, TrendingDown, TrendingUp } from 'lucide-react'
import Link from 'next/link'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
interface StatsCardProps {
title: string
value: string | number
description?: string
icon?: React.ReactNode
href?: string
/** Percentage change vs previous period. Positive = up, negative = down, undefined = no trend */
trend?: number
}
export function StatsCard({ title, value, description, icon, href, trend }: StatsCardProps) {
const content = (
<Card
className={
href
? 'transition-all duration-200 hover:border-primary/50 hover:shadow-lg hover:shadow-primary/5 hover:-translate-y-0.5 cursor-pointer'
: ''
}
>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{title}</CardTitle>
{icon && <div className="text-muted-foreground">{icon}</div>}
</CardHeader>
<CardContent>
<div className="flex items-baseline gap-2">
<div className="text-2xl font-bold">{value}</div>
{trend !== undefined && <TrendBadge value={trend} />}
</div>
{description && <p className="text-xs text-muted-foreground">{description}</p>}
</CardContent>
</Card>
)
if (href) {
return <Link href={href}>{content}</Link>
}
return content
}
function TrendBadge({ value }: { value: number }) {
if (value === 0) {
return (
<span className="inline-flex items-center gap-0.5 text-xs text-muted-foreground">
<Minus className="h-3 w-3" />
0%
</span>
)
}
const isUp = value > 0
return (
<span
className={`inline-flex items-center gap-0.5 text-xs font-medium ${
isUp ? 'text-[var(--admin-success)]' : 'text-[var(--admin-error)]'
}`}
>
{isUp ? <TrendingUp className="h-3 w-3" /> : <TrendingDown className="h-3 w-3" />}
{isUp ? '+' : ''}
{value}%
</span>
)
}
+39
View File
@@ -0,0 +1,39 @@
import { type AvatarOptions, getAvatarUrl } from '@/lib/imager'
interface AvatarImageProps {
figure: string
options?: AvatarOptions
width: number
height: number
alt: string
className?: string
}
export function AvatarImage({
figure,
options,
width,
height,
alt,
className = '',
}: AvatarImageProps) {
// Auto-pick the smallest size that still looks crisp at the requested
// dimensions, unless the caller passed an explicit size.
const max = Math.max(width, height)
const autoSize: 's' | 'm' | 'l' =
options?.size ?? (options?.headOnly ? 'l' : max <= 40 ? 's' : max <= 80 ? 'm' : 'l')
return (
// eslint-disable-next-line @next/next/no-img-element
<img
src={getAvatarUrl(figure, { ...options, size: autoSize })}
alt={alt}
width={width}
height={height}
loading="lazy"
decoding="async"
style={{ maxWidth: width, maxHeight: height }}
className={`image-pixelated object-contain ${className}`}
/>
)
}
+9
View File
@@ -101,6 +101,15 @@ export class RconClient {
forwardUser(userId: number, roomId: number) {
return this.send("forwarduser", { user_id: userId, room_id: roomId });
}
kickAll(roomId: number) {
return this.send("kickall", { room_id: roomId });
}
hotelAlert(message: string) {
return this.send("hotelalert", { message });
}
staffAlert(message: string) {
return this.send("staffalert", { message });
}
executeCommand(userId: number, command: string) {
return this.send("executecommand", { user_id: userId, command });
}