feat(admin): Protokoll in Klartext und Halter als Tabelle
Protokoll (/log): - Jeder Eintrag als deutscher Satz mit Namen statt Codes/IDs, z. B. „Daniel hat Jessi den Rang Botschafter verliehen“; Begründungen bereinigt (Rang-IDs, Feldlisten, JSON, true/false übersetzt) - Nach Tagen gruppiert, Filter nach Bereich (Chips) und Teammitglied (Auswahl mit Namen); Codes, IDs und IP unter „Technische Details“ - Neuer Router adminAudit (list, moderators) löst Tiere, Halter (Clerk), Beitrags-Autoren, Werbung, Musik und Ränge auf; formatAuditEntry übersetzt alle rund 50 Aktionen. admin.getModerationLog entfernt (ungenutzt) Halter (/users): - Tabelle mit Name/E-Mail, Tieren, Status-Abzeichen und Rolle statt Clerk-ID und sechs Knöpfen pro Zeile; Eingriffe im Menü „…“, Details (Registrierung, Sperrgrund, Konto-ID) zum Aufklappen - Dialoge deutsch und in eigener Komponente UserActionDialogs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e42831cfa9
commit
4187a1a519
12 files changed
+1352
-791
No files matched your search
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Lesbares Moderations-Protokoll (admin-audit.ts): Namen statt IDs, Filter nach
|
||||
* Kategorie und Moderator.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
vi.mock("server-only", () => ({}));
|
||||
vi.mock("@/lib/prisma", () => ({ prisma: {} }));
|
||||
const mockGetUserList = vi.fn();
|
||||
vi.mock("@clerk/nextjs/server", () => ({
|
||||
auth: vi.fn().mockResolvedValue({ userId: "admin-1" }),
|
||||
clerkClient: vi.fn().mockResolvedValue({ users: { getUserList: (...a: unknown[]) => mockGetUserList(...a) } }),
|
||||
}));
|
||||
const mockAssertAdmin = vi.fn();
|
||||
vi.mock("@/trpc/routers/admin", () => ({ assertAdmin: (...a: unknown[]) => mockAssertAdmin(...a) }));
|
||||
|
||||
import { createMockPrisma } from "@/__tests__/helpers/prisma-mock";
|
||||
import { adminAuditRouter } from "@/trpc/routers/admin-audit";
|
||||
|
||||
type MockPrisma = ReturnType<typeof createMockPrisma>;
|
||||
const ctx = (prisma: MockPrisma) => ({ userId: "admin-1", prisma: prisma as never, locale: "de", ip: "127.0.0.1" });
|
||||
const row = (over: Record<string, unknown>) => ({
|
||||
id: "log-1",
|
||||
action: "BAN_USER",
|
||||
targetType: "USER",
|
||||
targetId: "user_target",
|
||||
reason: null,
|
||||
moderatorId: "user_mod",
|
||||
moderatorRole: "MODERATOR",
|
||||
ipAddress: "1.2.3.4",
|
||||
createdAt: new Date("2026-10-05T08:00:00Z"),
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("adminAudit", () => {
|
||||
let prisma: MockPrisma;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockAssertAdmin.mockResolvedValue("MODERATOR");
|
||||
prisma = createMockPrisma();
|
||||
prisma.pet.findMany.mockResolvedValue([]);
|
||||
prisma.post.findMany.mockResolvedValue([]);
|
||||
prisma.advertisement.findMany.mockResolvedValue([]);
|
||||
prisma.musicTrack.findMany.mockResolvedValue([]);
|
||||
mockGetUserList.mockResolvedValue({ data: [] });
|
||||
});
|
||||
|
||||
it("resolves moderator, user, pet, post and rank names", async () => {
|
||||
prisma.moderationLog.findMany.mockResolvedValue([
|
||||
row({ id: "a" }),
|
||||
row({ id: "b", action: "VERIFY_PET", targetType: "PET", targetId: "pet-1" }),
|
||||
row({ id: "c", action: "DELETE_POST", targetType: "POST", targetId: "post-1" }),
|
||||
row({ id: "d", action: "GRANT_REFERRAL_RANK", targetType: "USER", targetId: "user_target", reason: "rank-1: Test" }),
|
||||
row({ id: "e", action: "HIDE_POST", targetType: "POST", targetId: "post-x", moderatorId: "SYSTEM", moderatorRole: null }),
|
||||
]);
|
||||
mockGetUserList.mockResolvedValue({
|
||||
data: [
|
||||
{ id: "user_mod", firstName: "Daniel", lastName: null, emailAddresses: [] },
|
||||
{ id: "user_target", firstName: null, lastName: null, primaryEmailAddress: { emailAddress: "jessi@example.com" }, emailAddresses: [] },
|
||||
],
|
||||
});
|
||||
prisma.pet.findMany.mockResolvedValue([{ id: "pet-1", name: "Bello" }]);
|
||||
prisma.post.findMany.mockResolvedValue([{ id: "post-1", pet: { name: "Bianca" } }]);
|
||||
prisma.referralRank.findMany.mockResolvedValue([{ id: "rank-1", nameDe: "Botschafter" }]);
|
||||
|
||||
const { entries, nextCursor } = await adminAuditRouter.createCaller(ctx(prisma)).list({});
|
||||
|
||||
expect(nextCursor).toBeNull();
|
||||
expect(entries.map((e) => [e.moderatorName, e.targetLabel, e.rankName])).toEqual([
|
||||
["Daniel", "jessi@example.com", null],
|
||||
["Daniel", "Bello", null],
|
||||
["Daniel", "Bianca", null],
|
||||
["Daniel", "jessi@example.com", "Botschafter"],
|
||||
[null, null, null],
|
||||
]);
|
||||
expect(entries[4]!.isAutomatic).toBe(true);
|
||||
expect(mockGetUserList).toHaveBeenCalledWith({ userId: ["user_target", "user_mod"], limit: 100 });
|
||||
});
|
||||
|
||||
it("filters by category and moderator and paginates", async () => {
|
||||
prisma.moderationLog.findMany.mockResolvedValue([row({ id: "a" }), row({ id: "b" }), row({ id: "c" })]);
|
||||
|
||||
const result = await adminAuditRouter.createCaller(ctx(prisma)).list({ limit: 2, category: "LOST", moderatorId: "user_mod" });
|
||||
|
||||
expect(prisma.moderationLog.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { action: { in: ["CLOSE_LOST_REPORT", "DELETE_LOST_REPORT"] }, moderatorId: "user_mod" }, take: 3 })
|
||||
);
|
||||
expect(result.entries).toHaveLength(2);
|
||||
expect(result.nextCursor).toBe("b");
|
||||
});
|
||||
|
||||
it("still returns entries when Clerk is unreachable", async () => {
|
||||
prisma.moderationLog.findMany.mockResolvedValue([row({})]);
|
||||
mockGetUserList.mockRejectedValue(new Error("clerk down"));
|
||||
|
||||
const { entries } = await adminAuditRouter.createCaller(ctx(prisma)).list({});
|
||||
|
||||
expect(entries[0]!.moderatorName).toBeNull();
|
||||
});
|
||||
|
||||
it("lists moderators by activity with names", async () => {
|
||||
prisma.moderationLog.groupBy.mockResolvedValue([
|
||||
{ moderatorId: "SYSTEM", _count: { _all: 2 } },
|
||||
{ moderatorId: "user_mod", _count: { _all: 9 } },
|
||||
]);
|
||||
mockGetUserList.mockResolvedValue({ data: [{ id: "user_mod", firstName: "Daniel", lastName: "B", emailAddresses: [] }] });
|
||||
|
||||
const list = await adminAuditRouter.createCaller(ctx(prisma)).moderators();
|
||||
|
||||
expect(list).toEqual([
|
||||
{ id: "user_mod", name: "Daniel B", count: 9 },
|
||||
{ id: "SYSTEM", name: "Automatik", count: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("is moderator-only", async () => {
|
||||
mockAssertAdmin.mockRejectedValue(new TRPCError({ code: "FORBIDDEN" }));
|
||||
await expect(adminAuditRouter.createCaller(ctx(prisma)).list({})).rejects.toThrow(TRPCError);
|
||||
});
|
||||
});
|
||||
@@ -247,6 +247,7 @@ interface MockAdRepostClient {
|
||||
interface MockModerationLogClient {
|
||||
create: MockFn;
|
||||
findMany: MockFn;
|
||||
groupBy: MockFn;
|
||||
}
|
||||
|
||||
interface MockAdminRoleClient {
|
||||
@@ -652,6 +653,7 @@ export function createMockPrisma(): MockPrismaClient {
|
||||
moderationLog: {
|
||||
create: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
groupBy: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
adminRole: {
|
||||
findUnique: vi.fn(),
|
||||
|
||||
+191
-161
@@ -1,204 +1,234 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
|
||||
import type { inferRouterOutputs } from "@trpc/server";
|
||||
import {
|
||||
Bot,
|
||||
ChevronDown,
|
||||
CircleDot,
|
||||
FileText,
|
||||
Flag,
|
||||
Gift,
|
||||
Loader2,
|
||||
Megaphone,
|
||||
PawPrint,
|
||||
Settings2,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
Siren,
|
||||
Users,
|
||||
} from "lucide-react";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { Loader2, ChevronDown, ShieldAlert } from "lucide-react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { AppRouter } from "@/trpc/routers/_app";
|
||||
import { AdminPageHeader } from "@/components/admin/AdminSection";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { ADMIN_ROLE_LABEL, type AdminRoleName } from "@/components/admin/admin-nav";
|
||||
import { AUDIT_CATEGORY_LABEL, formatAuditEntry, type AuditCategory } from "@/lib/admin/audit-format";
|
||||
import { berlinDayKey, formatClockTime, formatDayHeading } from "@/lib/admin/format";
|
||||
|
||||
// Free-text VarChar columns in ModerationLog, not DB enums — this list mirrors
|
||||
// every value actually written in admin.ts / legal.ts (see schema comments).
|
||||
const ACTIONS = [
|
||||
"DELETE_POST",
|
||||
"DELETE_COMMENT",
|
||||
"BAN_USER",
|
||||
"UNBAN_USER",
|
||||
"DISMISS_REPORT",
|
||||
"DATA_EXPORT",
|
||||
"CREATE_AD",
|
||||
"UPDATE_AD",
|
||||
"DELETE_AD",
|
||||
"GRANT_ROLE",
|
||||
"REVOKE_ROLE",
|
||||
"PIN_POST",
|
||||
"UNPIN_POST",
|
||||
"ENABLE_MAINTENANCE_MODE",
|
||||
"DISABLE_MAINTENANCE_MODE",
|
||||
"SEND_BROADCAST",
|
||||
] as const;
|
||||
type Entry = inferRouterOutputs<AppRouter>["adminAudit"]["list"]["entries"][number];
|
||||
|
||||
const TARGET_TYPES = ["POST", "COMMENT", "USER", "REPORT", "AD", "SYSTEM"] as const;
|
||||
|
||||
const ROLE_BADGE_CLASS: Record<string, string> = {
|
||||
BOOTSTRAP: "bg-orange-700 text-orange-100",
|
||||
SUPER_ADMIN: "bg-orange-700 text-orange-100",
|
||||
MODERATOR: "bg-secondary text-foreground",
|
||||
SUPPORT: "bg-blue-700 text-blue-100",
|
||||
const CATEGORY_ICON: Record<AuditCategory | "OTHER", React.ComponentType<{ className?: string }>> = {
|
||||
CONTENT: FileText,
|
||||
OWNERS: Users,
|
||||
PETS: PawPrint,
|
||||
REPORTS: Flag,
|
||||
MEDIA: Megaphone,
|
||||
TEAM: ShieldCheck,
|
||||
SYSTEM: Settings2,
|
||||
REFERRALS: Gift,
|
||||
LOST: Siren,
|
||||
OTHER: CircleDot,
|
||||
};
|
||||
|
||||
/** Eingriffe, die etwas wegnehmen — bekommen ein rotes statt oranges Symbol. */
|
||||
const isRemoval = (action: string) => /^(DELETE|BAN|SHADOWBAN|REVOKE|REJECT|DEACTIVATE|CLEAR|HIDE|DISABLE)_/.test(action);
|
||||
|
||||
const ALL = "all";
|
||||
const CATEGORIES = Object.keys(AUDIT_CATEGORY_LABEL) as AuditCategory[];
|
||||
|
||||
function EntryRow({ entry }: { entry: Entry }) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const view = formatAuditEntry(entry);
|
||||
const Icon = entry.isAutomatic ? Bot : CATEGORY_ICON[view.category];
|
||||
const removal = isRemoval(entry.action);
|
||||
const actor = entry.isAutomatic ? "Automatik" : (entry.moderatorName ?? "Unbekannt");
|
||||
const role = entry.moderatorRole ? ADMIN_ROLE_LABEL[entry.moderatorRole as AdminRoleName] : null;
|
||||
|
||||
return (
|
||||
<li className="flex gap-3 px-5 py-3.5 md:px-6">
|
||||
<span
|
||||
className={`mt-0.5 grid h-8 w-8 shrink-0 place-items-center rounded-full ${removal ? "bg-destructive/10 text-destructive" : "bg-accent text-primary"}`}
|
||||
aria-hidden
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm leading-relaxed text-card-foreground">
|
||||
<span className="font-semibold">{actor}</span>{" "}
|
||||
{view.parts.map((part, i) => (typeof part === "string" ? <span key={i}>{part}</span> : <strong key={i} className="font-semibold">{part.strong}</strong>))}
|
||||
</p>
|
||||
{view.details.map((line) => (
|
||||
<p key={line} className="mt-0.5 break-words text-sm text-muted-foreground">
|
||||
{line}
|
||||
</p>
|
||||
))}
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
|
||||
<span>{AUDIT_CATEGORY_LABEL[view.category as AuditCategory] ?? "Sonstiges"}</span>
|
||||
{role && <span>· {role}</span>}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen((v) => !v)}
|
||||
aria-expanded={isOpen}
|
||||
className="inline-flex cursor-pointer items-center gap-0.5 rounded hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
Technische Details
|
||||
<ChevronDown className={`h-3 w-3 transition-transform ${isOpen ? "rotate-180" : ""}`} aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
{isOpen && (
|
||||
<dl className="mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-lg bg-muted px-3 py-2 font-mono text-[11px] text-muted-foreground">
|
||||
<dt>Aktion</dt>
|
||||
<dd className="break-all">{entry.action}</dd>
|
||||
<dt>Ziel</dt>
|
||||
<dd className="break-all">
|
||||
{entry.targetType} · {entry.targetId}
|
||||
</dd>
|
||||
<dt>Von</dt>
|
||||
<dd className="break-all">{entry.moderatorId}</dd>
|
||||
{entry.ipAddress && (
|
||||
<>
|
||||
<dt>IP</dt>
|
||||
<dd>{entry.ipAddress}</dd>
|
||||
</>
|
||||
)}
|
||||
{entry.reason && (
|
||||
<>
|
||||
<dt>Rohtext</dt>
|
||||
<dd className="break-all">{entry.reason}</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
</div>
|
||||
<time dateTime={new Date(entry.createdAt).toISOString()} className="shrink-0 pt-0.5 text-xs tabular-nums text-muted-foreground">
|
||||
{formatClockTime(new Date(entry.createdAt))}
|
||||
</time>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Protokoll aller Moderations-Eingriffe als lesbare Sätze, nach Tagen gruppiert.
|
||||
* Codes, IDs und IP stehen nur noch unter „Technische Details“.
|
||||
*/
|
||||
export default function AdminAuditLogPage() {
|
||||
const trpc = useTRPC();
|
||||
const [action, setAction] = useState<string>("all");
|
||||
const [targetType, setTargetType] = useState<string>("all");
|
||||
const [moderatorId, setModeratorId] = useState("");
|
||||
const [category, setCategory] = useState<AuditCategory | typeof ALL>(ALL);
|
||||
const [moderatorId, setModeratorId] = useState<string>(ALL);
|
||||
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, isError, error } =
|
||||
useInfiniteQuery(
|
||||
trpc.admin.getModerationLog.infiniteQueryOptions(
|
||||
{
|
||||
limit: 50,
|
||||
action: action === "all" ? undefined : action,
|
||||
targetType: targetType === "all" ? undefined : targetType,
|
||||
moderatorId: moderatorId.trim() || undefined,
|
||||
},
|
||||
{ getNextPageParam: (p) => p.nextCursor, initialCursor: undefined }
|
||||
)
|
||||
);
|
||||
const { data: moderators } = useQuery(trpc.adminAudit.moderators.queryOptions());
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, isError, error } = useInfiniteQuery(
|
||||
trpc.adminAudit.list.infiniteQueryOptions(
|
||||
{ limit: 40, category: category === ALL ? undefined : category, moderatorId: moderatorId === ALL ? undefined : moderatorId },
|
||||
{ getNextPageParam: (p) => p.nextCursor, initialCursor: undefined }
|
||||
)
|
||||
);
|
||||
|
||||
const entries = data?.pages.flatMap((p) => p.entries) ?? [];
|
||||
const days: { key: string; heading: string; entries: Entry[] }[] = [];
|
||||
for (const entry of entries) {
|
||||
const date = new Date(entry.createdAt);
|
||||
const key = berlinDayKey(date);
|
||||
const last = days[days.length - 1];
|
||||
if (last?.key === key) last.entries.push(entry);
|
||||
else days.push({ key, heading: formatDayHeading(date), entries: [entry] });
|
||||
}
|
||||
const moderatorName = (id: string) => (id === ALL ? "Alle aus dem Team" : (moderators?.find((m) => m.id === id)?.name ?? "…"));
|
||||
|
||||
if (isError) {
|
||||
const isForbidden = error?.data?.code === "FORBIDDEN";
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-20 text-center">
|
||||
<ShieldAlert className="h-8 w-8 text-muted-foreground/70" />
|
||||
<ShieldAlert className="h-8 w-8 text-muted-foreground" aria-hidden />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{isForbidden
|
||||
? "Keine Berechtigung — das Audit Log ist ab Moderator-Rolle sichtbar."
|
||||
: "Log konnte nicht geladen werden."}
|
||||
{isForbidden ? "Das Protokoll ist ab der Moderator-Rolle sichtbar." : "Das Protokoll konnte nicht geladen werden."}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-2xl font-bold text-foreground">Protokoll</h1>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
placeholder="Moderator user_ID…"
|
||||
value={moderatorId}
|
||||
onChange={(e) => setModeratorId(e.target.value)}
|
||||
className="w-56 bg-card border-border text-foreground placeholder:text-muted-foreground font-mono text-sm"
|
||||
/>
|
||||
<Select value={action} onValueChange={(v) => setAction(v ?? "all")}>
|
||||
<SelectTrigger className="w-44 bg-card border-border text-foreground">
|
||||
<SelectValue />
|
||||
<div className="mx-auto max-w-5xl space-y-6">
|
||||
<AdminPageHeader
|
||||
title="Protokoll"
|
||||
description="Wer im Team wann was getan hat – jede Moderations-Aktion wird hier festgehalten."
|
||||
actions={
|
||||
<Select value={moderatorId} onValueChange={(v) => setModeratorId(v ?? ALL)}>
|
||||
<SelectTrigger className="h-9 min-w-48 bg-card" aria-label="Nach Teammitglied filtern">
|
||||
<SelectValue>{(v: string) => moderatorName(v)}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-muted border-border">
|
||||
<SelectItem value="all">All actions</SelectItem>
|
||||
{ACTIONS.map((a) => (
|
||||
<SelectItem key={a} value={a}>
|
||||
{a}
|
||||
<SelectContent>
|
||||
<SelectItem value={ALL}>Alle aus dem Team</SelectItem>
|
||||
{moderators?.map((m) => (
|
||||
<SelectItem key={m.id} value={m.id}>
|
||||
{m.name} ({m.count})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={targetType} onValueChange={(v) => setTargetType(v ?? "all")}>
|
||||
<SelectTrigger className="w-36 bg-card border-border text-foreground">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-muted border-border">
|
||||
<SelectItem value="all">All targets</SelectItem>
|
||||
{TARGET_TYPES.map((t) => (
|
||||
<SelectItem key={t} value={t}>
|
||||
{t}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<div role="tablist" aria-label="Nach Bereich filtern" className="flex flex-wrap gap-1.5">
|
||||
{[ALL, ...CATEGORIES].map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={category === c}
|
||||
onClick={() => setCategory(c as AuditCategory | typeof ALL)}
|
||||
className={`cursor-pointer rounded-full px-3 py-1.5 text-xs font-semibold transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${
|
||||
category === c ? "bg-primary text-primary-foreground" : "border border-border bg-card text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{c === ALL ? "Alle Bereiche" : AUDIT_CATEGORY_LABEL[c as AuditCategory]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center py-12">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
<div className="flex justify-center py-16">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" aria-label="Wird geladen" />
|
||||
</div>
|
||||
) : entries.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-12">No entries match these filters</p>
|
||||
) : days.length === 0 ? (
|
||||
<p className="rounded-2xl border border-dashed border-border px-4 py-12 text-center text-sm text-muted-foreground">
|
||||
Für diese Auswahl gibt es keine Einträge.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{/* Fixed-width grid columns instead of flex-wrap — long IDs/IPs used
|
||||
to force rows to overflow the viewport instead of wrapping. The
|
||||
outer scroll wrapper lets the whole table scroll as one unit on
|
||||
narrow screens rather than clipping individual cells. */}
|
||||
<div className="overflow-x-auto rounded-xl border border-border">
|
||||
<div className="min-w-[1000px]">
|
||||
<div className="grid grid-cols-[150px_190px_1fr_130px_170px] gap-3 border-b border-border bg-card/90 px-4 py-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
<span>Action</span>
|
||||
<span>Target</span>
|
||||
<span>Moderator</span>
|
||||
<span>IP</span>
|
||||
<span>Time</span>
|
||||
</div>
|
||||
{entries.map((entry) => (
|
||||
<div key={entry.id} className="border-b border-border bg-card last:border-b-0">
|
||||
<div className="grid grid-cols-[150px_190px_1fr_130px_170px] items-center gap-3 px-4 py-3">
|
||||
<Badge variant="secondary" className="w-fit text-[10px]">
|
||||
{entry.action}
|
||||
</Badge>
|
||||
<p className="min-w-0 truncate text-xs text-muted-foreground" title={entry.targetId}>
|
||||
{entry.targetType} · <span className="font-mono">{entry.targetId}</span>
|
||||
</p>
|
||||
<div className="min-w-0">
|
||||
<p className="flex items-center gap-2 truncate text-sm text-foreground">
|
||||
<span className="truncate">
|
||||
{entry.moderatorName ?? <span className="text-muted-foreground">unnamed</span>}
|
||||
</span>
|
||||
{entry.moderatorRole && (
|
||||
<Badge
|
||||
className={`shrink-0 text-[10px] ${
|
||||
ROLE_BADGE_CLASS[entry.moderatorRole] ?? "bg-secondary text-foreground"
|
||||
}`}
|
||||
>
|
||||
{entry.moderatorRole}
|
||||
</Badge>
|
||||
)}
|
||||
</p>
|
||||
<p
|
||||
className="truncate font-mono text-xs text-muted-foreground/70"
|
||||
title={entry.moderatorId}
|
||||
>
|
||||
{entry.moderatorId}
|
||||
</p>
|
||||
</div>
|
||||
<p className="truncate font-mono text-xs text-muted-foreground">
|
||||
{entry.ipAddress ?? "—"}
|
||||
</p>
|
||||
<p className="truncate text-xs text-muted-foreground/70">
|
||||
{new Date(entry.createdAt).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
{entry.reason && (
|
||||
<p className="truncate px-4 pb-3 text-xs text-muted-foreground">
|
||||
Reason: {entry.reason}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{days.map((day) => (
|
||||
<section key={day.key} aria-label={day.heading}>
|
||||
<h2 className="mb-2 px-1 text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground">{day.heading}</h2>
|
||||
<ul className="divide-y divide-border overflow-hidden rounded-2xl border border-border bg-card">
|
||||
{day.entries.map((entry) => (
|
||||
<EntryRow key={entry.id} entry={entry} />
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
{hasNextPage && (
|
||||
<div className="flex justify-center pt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
<div className="flex justify-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void fetchNextPage()}
|
||||
disabled={isFetchingNextPage}
|
||||
className="bg-card border-border text-foreground hover:bg-muted hover:text-foreground"
|
||||
className="inline-flex cursor-pointer items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-semibold text-card-foreground hover:bg-muted disabled:opacity-60"
|
||||
>
|
||||
{isFetchingNextPage ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
Load more
|
||||
</Button>
|
||||
{isFetchingNextPage && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||
Ältere Einträge laden
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
+297
-587
@@ -1,49 +1,88 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { formatPetName } from "@/lib/pet-display-name";
|
||||
import { useRouter, useParams, useSearchParams } from "next/navigation";
|
||||
import { toast } from "sonner";
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import {
|
||||
ShieldOff,
|
||||
ShieldCheck,
|
||||
Loader2,
|
||||
ChevronDown,
|
||||
MessageCircle,
|
||||
Download,
|
||||
BadgeCheck,
|
||||
TriangleAlert,
|
||||
Trash2,
|
||||
Ghost,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import type { inferRouterOutputs } from "@trpc/server";
|
||||
import { AdminRoleType } from "@prisma/client";
|
||||
import {
|
||||
BadgeCheck,
|
||||
ChevronDown,
|
||||
Download,
|
||||
Ghost,
|
||||
Loader2,
|
||||
MessageCircle,
|
||||
MoreHorizontal,
|
||||
Search,
|
||||
ShieldCheck,
|
||||
ShieldOff,
|
||||
Trash2,
|
||||
TriangleAlert,
|
||||
} from "lucide-react";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import type { AppRouter } from "@/trpc/routers/_app";
|
||||
import { formatPetName } from "@/lib/pet-display-name";
|
||||
import { isActiveSponsor } from "@/lib/sponsor";
|
||||
import { formatEventTime } from "@/lib/admin/format";
|
||||
import { AdminPageHeader } from "@/components/admin/AdminSection";
|
||||
import { StatusBadge } from "@/components/admin/StatusBadge";
|
||||
import { ADMIN_ROLE_LABEL } from "@/components/admin/admin-nav";
|
||||
import { UserActionDialogs, type UserAction, type UserActionTarget } from "@/components/admin/users/UserActionDialogs";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
|
||||
type BanStatusFilter = "all" | "banned" | "active";
|
||||
type RoleFilter = "all" | "none" | AdminRoleType;
|
||||
type User = inferRouterOutputs<AppRouter>["admin"]["listUsers"]["users"][number];
|
||||
|
||||
const BAN_STATUS_LABEL: Record<BanStatusFilter, string> = { all: "Alle Status", banned: "Nur gesperrte", active: "Nur aktive" };
|
||||
const ROLE_FILTER_LABEL: Record<RoleFilter, string> = {
|
||||
all: "Alle Rollen",
|
||||
none: "Ohne Rolle",
|
||||
SUPPORT: "Support",
|
||||
MODERATOR: "Moderator",
|
||||
SUPER_ADMIN: "Super-Admin",
|
||||
};
|
||||
|
||||
const displayName = (u: User) => u.clerk?.name ?? u.clerk?.email ?? "Unbekannter Halter";
|
||||
const initials = (text: string) =>
|
||||
text
|
||||
.split(/[\s@.]+/)
|
||||
.filter(Boolean)
|
||||
.slice(0, 2)
|
||||
.map((p) => p[0]!.toUpperCase())
|
||||
.join("");
|
||||
|
||||
function UserStatus({ user }: { user: User }) {
|
||||
const sponsor = isActiveSponsor({
|
||||
sponsorSince: user.sponsorSince ? new Date(user.sponsorSince) : null,
|
||||
sponsorPeriodEnd: user.sponsorPeriodEnd ? new Date(user.sponsorPeriodEnd) : null,
|
||||
});
|
||||
const badges = [
|
||||
user.ban && <StatusBadge key="ban" tone="danger">Gesperrt</StatusBadge>,
|
||||
user.shadowban && <StatusBadge key="shadow" tone="neutral">Shadowban</StatusBadge>,
|
||||
user._count.warnings > 0 && (
|
||||
<StatusBadge key="warn" tone="warning">
|
||||
{user._count.warnings === 1 ? "1 Verwarnung" : `${user._count.warnings} Verwarnungen`}
|
||||
</StatusBadge>
|
||||
),
|
||||
sponsor && <StatusBadge key="sponsor" tone="info">Sponsor</StatusBadge>,
|
||||
].filter(Boolean);
|
||||
return <div className="flex flex-wrap gap-1">{badges.length > 0 ? badges : <StatusBadge tone="success">Aktiv</StatusBadge>}</div>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Halter-Übersicht als Tabelle: wer, welche Tiere, welcher Status, welche Rolle.
|
||||
* Seltene und heikle Eingriffe liegen im Menü „…“ statt als Knopfreihe in jeder Zeile.
|
||||
*/
|
||||
export default function AdminUsersPage() {
|
||||
const trpc = useTRPC();
|
||||
const qc = useQueryClient();
|
||||
const router = useRouter();
|
||||
const params = useParams<{ secret: string }>();
|
||||
const [banTarget, setBanTarget] = useState<string | null>(null);
|
||||
const [unbanTarget, setUnbanTarget] = useState<string | null>(null);
|
||||
const [banReason, setBanReason] = useState("");
|
||||
const [banExpiry, setBanExpiry] = useState("");
|
||||
const [shadowbanTarget, setShadowbanTarget] = useState<string | null>(null);
|
||||
const [unshadowbanTarget, setUnshadowbanTarget] = useState<string | null>(null);
|
||||
const [shadowbanReason, setShadowbanReason] = useState("");
|
||||
// ?q= kommt von der globalen Suche in der Kopfzeile; ein neuer Treffer ersetzt die Suche.
|
||||
const searchParams = useSearchParams();
|
||||
const urlQuery = searchParams.get("q");
|
||||
const urlQuery = useSearchParams().get("q");
|
||||
const [search, setSearch] = useState(urlQuery ?? "");
|
||||
const [appliedUrlQuery, setAppliedUrlQuery] = useState(urlQuery);
|
||||
if (urlQuery !== appliedUrlQuery) {
|
||||
@@ -52,10 +91,8 @@ export default function AdminUsersPage() {
|
||||
}
|
||||
const [banStatus, setBanStatus] = useState<BanStatusFilter>("all");
|
||||
const [role, setRole] = useState<RoleFilter>("all");
|
||||
const [warnTarget, setWarnTarget] = useState<string | null>(null);
|
||||
const [warnReason, setWarnReason] = useState("");
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
|
||||
const [deleteConfirmation, setDeleteConfirmation] = useState("");
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
const [actionTarget, setActionTarget] = useState<UserActionTarget | null>(null);
|
||||
|
||||
const { data: myRole } = useQuery(trpc.admin.getMyRole.queryOptions());
|
||||
const canDeleteAccounts = myRole === "BOOTSTRAP" || myRole === "SUPER_ADMIN";
|
||||
@@ -66,593 +103,266 @@ export default function AdminUsersPage() {
|
||||
{ getNextPageParam: (p) => p.nextCursor, initialCursor: undefined }
|
||||
)
|
||||
);
|
||||
|
||||
const users = data?.pages.flatMap((p) => p.users) ?? [];
|
||||
|
||||
const banMutation = useMutation(
|
||||
trpc.admin.banUser.mutationOptions({
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: trpc.admin.listUsers.queryKey() });
|
||||
setBanTarget(null);
|
||||
setBanReason("");
|
||||
setBanExpiry("");
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const unbanMutation = useMutation(
|
||||
trpc.admin.unbanUser.mutationOptions({
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: trpc.admin.listUsers.queryKey() });
|
||||
setUnbanTarget(null);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const shadowbanMutation = useMutation(
|
||||
trpc.admin.shadowbanOwner.mutationOptions({
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: trpc.admin.listUsers.queryKey() });
|
||||
setShadowbanTarget(null);
|
||||
setShadowbanReason("");
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const removeShadowbanMutation = useMutation(
|
||||
trpc.admin.removeShadowban.mutationOptions({
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: trpc.admin.listUsers.queryKey() });
|
||||
setUnshadowbanTarget(null);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const startConversationMutation = useMutation(
|
||||
const startConversation = useMutation(
|
||||
trpc.admin.startTeamConversation.mutationOptions({
|
||||
onSuccess: ({ conversationId }) => {
|
||||
router.push(`/p/${params.secret}/messages?conversation=${conversationId}`);
|
||||
},
|
||||
onSuccess: ({ conversationId }) => router.push(`/p/${params.secret}/messages?conversation=${conversationId}`),
|
||||
onError: (err) => toast.error(`Nachricht konnte nicht geöffnet werden: ${err.message}`),
|
||||
})
|
||||
);
|
||||
|
||||
const exportDataMutation = useMutation(
|
||||
const exportData = useMutation(
|
||||
trpc.admin.exportUserData.mutationOptions({
|
||||
onSuccess: ({ sentTo }) => {
|
||||
toast.success(`Datenauskunft an ${sentTo} verschickt.`);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Export fehlgeschlagen: ${err.message}`);
|
||||
},
|
||||
onSuccess: ({ sentTo }) => toast.success(`Datenauskunft an ${sentTo} verschickt.`),
|
||||
onError: (err) => toast.error(`Export fehlgeschlagen: ${err.message}`),
|
||||
})
|
||||
);
|
||||
|
||||
const verifyMutation = useMutation(
|
||||
const verify = useMutation(
|
||||
trpc.admin.setPetVerified.mutationOptions({
|
||||
onSuccess: (pet) => {
|
||||
void qc.invalidateQueries({ queryKey: trpc.admin.listUsers.queryKey() });
|
||||
toast.success(pet.isVerified ? `${formatPetName(pet)} verified.` : `${formatPetName(pet)} un-verified.`);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Verification failed: ${err.message}`);
|
||||
toast.success(pet.isVerified ? `${formatPetName(pet)} ist jetzt verifiziert.` : `Verifizierung von ${formatPetName(pet)} entfernt.`);
|
||||
},
|
||||
onError: (err) => toast.error(`Verifizierung fehlgeschlagen: ${err.message}`),
|
||||
})
|
||||
);
|
||||
|
||||
const { data: warningHistory = [] } = useQuery(
|
||||
trpc.admin.listWarnings.queryOptions(
|
||||
{ ownerId: warnTarget ?? "" },
|
||||
{ enabled: !!warnTarget }
|
||||
)
|
||||
);
|
||||
|
||||
const issueWarningMutation = useMutation(
|
||||
trpc.admin.issueWarning.mutationOptions({
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: trpc.admin.listUsers.queryKey() });
|
||||
void qc.invalidateQueries({
|
||||
queryKey: trpc.admin.listWarnings.queryKey({ ownerId: warnTarget ?? "" }),
|
||||
});
|
||||
setWarnReason("");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Warning failed: ${err.message}`);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const deleteAccountMutation = useMutation(
|
||||
trpc.admin.deleteUserAccount.mutationOptions({
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: trpc.admin.listUsers.queryKey() });
|
||||
setDeleteTarget(null);
|
||||
setDeleteConfirmation("");
|
||||
toast.success("Account gelöscht.");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Löschen fehlgeschlagen: ${err.message}`);
|
||||
},
|
||||
})
|
||||
);
|
||||
const openAction = (action: UserAction, user: User) => setActionTarget({ action, ownerId: user.id, label: displayName(user) });
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h1 className="text-2xl font-bold text-foreground">Halter</h1>
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center">
|
||||
<Input
|
||||
placeholder="Search name or email…"
|
||||
<div className="mx-auto max-w-[1400px] space-y-6">
|
||||
<AdminPageHeader title="Halter" description="Alle Konten mit ihren Tieren, Status und Rollen." />
|
||||
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<div className="relative flex-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />
|
||||
<input
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="w-full bg-card border-border text-foreground placeholder:text-muted-foreground sm:w-64"
|
||||
placeholder="Name, E-Mail oder Tiername …"
|
||||
aria-label="Halter suchen"
|
||||
className="h-9 w-full rounded-lg border border-input bg-card pl-9 pr-3 text-sm text-foreground placeholder:text-muted-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/30"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Select value={banStatus} onValueChange={(v) => setBanStatus(v as BanStatusFilter)}>
|
||||
<SelectTrigger className="flex-1 bg-card border-border text-foreground sm:w-36 sm:flex-none">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-muted border-border">
|
||||
<SelectItem value="all">All statuses</SelectItem>
|
||||
<SelectItem value="banned">Banned</SelectItem>
|
||||
<SelectItem value="active">Active</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={role} onValueChange={(v) => setRole(v as RoleFilter)}>
|
||||
<SelectTrigger className="flex-1 bg-card border-border text-foreground sm:w-36 sm:flex-none">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-muted border-border">
|
||||
<SelectItem value="all">All roles</SelectItem>
|
||||
<SelectItem value="none">No role</SelectItem>
|
||||
<SelectItem value={AdminRoleType.SUPPORT}>Support</SelectItem>
|
||||
<SelectItem value={AdminRoleType.MODERATOR}>Moderator</SelectItem>
|
||||
<SelectItem value={AdminRoleType.SUPER_ADMIN}>Super Admin</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Select value={banStatus} onValueChange={(v) => setBanStatus((v ?? "all") as BanStatusFilter)}>
|
||||
<SelectTrigger className="h-9 flex-1 bg-card sm:w-40 sm:flex-none" aria-label="Nach Status filtern">
|
||||
<SelectValue>{(v: BanStatusFilter) => BAN_STATUS_LABEL[v]}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(Object.keys(BAN_STATUS_LABEL) as BanStatusFilter[]).map((v) => (
|
||||
<SelectItem key={v} value={v}>
|
||||
{BAN_STATUS_LABEL[v]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={role} onValueChange={(v) => setRole((v ?? "all") as RoleFilter)}>
|
||||
<SelectTrigger className="h-9 flex-1 bg-card sm:w-40 sm:flex-none" aria-label="Nach Rolle filtern">
|
||||
<SelectValue>{(v: RoleFilter) => ROLE_FILTER_LABEL[v]}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(Object.keys(ROLE_FILTER_LABEL) as RoleFilter[]).map((v) => (
|
||||
<SelectItem key={v} value={v}>
|
||||
{ROLE_FILTER_LABEL[v]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center py-12">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
<div className="flex justify-center py-16">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" aria-label="Wird geladen" />
|
||||
</div>
|
||||
) : users.length === 0 ? (
|
||||
<p className="rounded-2xl border border-dashed border-border px-4 py-12 text-center text-sm text-muted-foreground">Keine Halter für diese Suche.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{users.map((user) => (
|
||||
<div
|
||||
key={user.id}
|
||||
className="flex flex-col gap-3 rounded-xl border border-border bg-card px-4 py-3 sm:flex-row sm:items-center sm:gap-4"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm text-foreground font-mono truncate">{user.id}</p>
|
||||
{isActiveSponsor({
|
||||
sponsorSince: user.sponsorSince ? new Date(user.sponsorSince) : null,
|
||||
sponsorPeriodEnd: user.sponsorPeriodEnd ? new Date(user.sponsorPeriodEnd) : null,
|
||||
}) && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-[10px] shrink-0 bg-warning/10 text-warning"
|
||||
<div className="overflow-hidden rounded-2xl border border-border bg-card">
|
||||
<div className="hidden grid-cols-[minmax(0,2.2fr)_minmax(0,2fr)_minmax(0,1.4fr)_minmax(0,0.9fr)_auto] gap-4 border-b border-border px-5 py-2.5 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground lg:grid">
|
||||
<span>Halter</span>
|
||||
<span>Tiere</span>
|
||||
<span>Status</span>
|
||||
<span>Rolle</span>
|
||||
<span className="sr-only">Aktionen</span>
|
||||
</div>
|
||||
<ul className="divide-y divide-border">
|
||||
{users.map((user) => {
|
||||
const name = displayName(user);
|
||||
const isExpanded = expandedId === user.id;
|
||||
const firstPet = user.pets[0];
|
||||
return (
|
||||
<li key={user.id} className="transition-colors hover:bg-muted/40">
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 px-5 py-3.5 lg:grid-cols-[minmax(0,2.2fr)_minmax(0,2fr)_minmax(0,1.4fr)_minmax(0,0.9fr)_auto]">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpandedId(isExpanded ? null : user.id)}
|
||||
aria-expanded={isExpanded}
|
||||
className="flex min-w-0 cursor-pointer items-center gap-3 rounded-lg text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
SPONSOR
|
||||
</Badge>
|
||||
)}
|
||||
{user.adminRole && (
|
||||
<Badge variant="secondary" className="text-[10px] shrink-0">
|
||||
{user.adminRole.role}
|
||||
</Badge>
|
||||
)}
|
||||
{user.ban && (
|
||||
<Badge variant="destructive" className="text-[10px] shrink-0">
|
||||
BANNED
|
||||
</Badge>
|
||||
)}
|
||||
{user.shadowban && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-[10px] shrink-0 bg-violet-500/15 text-violet-700 dark:text-violet-300"
|
||||
>
|
||||
SHADOWBANNED
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{user.clerk && (
|
||||
<p className="text-xs text-muted-foreground mt-0.5 truncate">
|
||||
{user.clerk.name ? `${user.clerk.name} · ` : ""}
|
||||
{user.clerk.email ?? "no email on file"}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{user._count.pets} pet{user._count.pets !== 1 ? "s" : ""}
|
||||
{user._count.warnings > 0 &&
|
||||
` · ${user._count.warnings} warning${user._count.warnings !== 1 ? "s" : ""}`}
|
||||
</p>
|
||||
{user.pets.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-1.5 mt-1">
|
||||
{user.pets.map((pet) => (
|
||||
<button
|
||||
key={pet.id}
|
||||
type="button"
|
||||
onClick={() =>
|
||||
verifyMutation.mutate({ petId: pet.id, isVerified: !pet.isVerified })
|
||||
}
|
||||
disabled={verifyMutation.isPending}
|
||||
title={pet.isVerified ? "Verified — click to remove" : "Click to verify"}
|
||||
className={`flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] transition-colors ${
|
||||
pet.isVerified
|
||||
? "border-info/40 bg-info/10 text-info"
|
||||
: "border-border text-muted-foreground hover:border-border"
|
||||
}`}
|
||||
>
|
||||
{formatPetName(pet)}
|
||||
<BadgeCheck
|
||||
className={`h-3 w-3 ${pet.isVerified ? "fill-blue-400 text-background" : ""}`}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{user.ban?.reason && (
|
||||
<p className="text-xs text-destructive mt-0.5">Reason: {user.ban.reason}</p>
|
||||
)}
|
||||
{user.shadowban?.reason && (
|
||||
<p className="text-xs text-violet-600 dark:text-violet-400 mt-0.5">Shadowban: {user.shadowban.reason}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2 sm:max-w-md sm:shrink-0 sm:justify-end">
|
||||
{user.pets[0] && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="bg-card border-sky-800 text-info hover:bg-muted hover:opacity-80"
|
||||
onClick={() => startConversationMutation.mutate({ targetPetId: user.pets[0].id })}
|
||||
disabled={startConversationMutation.isPending}
|
||||
title={`Message ${user.pets[0].name} as PawFeed Team`}
|
||||
>
|
||||
{startConversationMutation.isPending &&
|
||||
startConversationMutation.variables?.targetPetId === user.pets[0].id ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<MessageCircle className="h-4 w-4 mr-1.5" />
|
||||
)}
|
||||
Message
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="bg-card border-blue-800 text-info hover:bg-muted hover:opacity-80"
|
||||
onClick={() => exportDataMutation.mutate({ ownerId: user.id })}
|
||||
disabled={exportDataMutation.isPending}
|
||||
title="Datenauskunft (Art. 15 DSGVO) per E-Mail versenden"
|
||||
>
|
||||
{exportDataMutation.isPending && exportDataMutation.variables?.ownerId === user.id ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Download className="h-4 w-4 mr-1.5" />
|
||||
)}
|
||||
Export
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="bg-card border-amber-800 text-warning hover:bg-muted hover:opacity-80"
|
||||
onClick={() => setWarnTarget(user.id)}
|
||||
title="Warnings"
|
||||
>
|
||||
<TriangleAlert className="h-4 w-4 mr-1.5" />
|
||||
Warn
|
||||
</Button>
|
||||
{canDeleteAccounts && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-500 hover:text-destructive"
|
||||
onClick={() => setDeleteTarget(user.id)}
|
||||
title="Delete account permanently (GDPR erasure)"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{user.shadowban ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="bg-card border-violet-800 text-violet-600 dark:text-violet-300 hover:bg-muted hover:opacity-80"
|
||||
onClick={() => setUnshadowbanTarget(user.id)}
|
||||
title="Remove shadowban"
|
||||
>
|
||||
<Ghost className="h-4 w-4 mr-1.5" />
|
||||
Un-shadowban
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-violet-600 dark:text-violet-400 hover:opacity-80"
|
||||
onClick={() => setShadowbanTarget(user.id)}
|
||||
title="Shadowban — content quietly stops reaching others, user isn't told"
|
||||
>
|
||||
<Ghost className="h-4 w-4 mr-1.5" />
|
||||
Shadowban
|
||||
</Button>
|
||||
)}
|
||||
{user.ban ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="bg-card border-border text-foreground hover:bg-muted hover:text-foreground"
|
||||
onClick={() => setUnbanTarget(user.id)}
|
||||
>
|
||||
<ShieldCheck className="h-4 w-4 mr-1.5" />
|
||||
Unban
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-destructive hover:opacity-80"
|
||||
onClick={() => setBanTarget(user.id)}
|
||||
>
|
||||
<ShieldOff className="h-4 w-4 mr-1.5" />
|
||||
Ban
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-accent text-xs font-bold text-accent-foreground" aria-hidden>
|
||||
{initials(name)}
|
||||
</span>
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-sm font-semibold text-card-foreground">{name}</span>
|
||||
<span className="block truncate text-xs text-muted-foreground">{user.clerk?.name ? user.clerk.email : "Keine E-Mail hinterlegt"}</span>
|
||||
</span>
|
||||
<ChevronDown className={`ml-auto h-4 w-4 shrink-0 text-muted-foreground transition-transform lg:hidden ${isExpanded ? "rotate-180" : ""}`} aria-hidden />
|
||||
</button>
|
||||
|
||||
{hasNextPage && (
|
||||
<div className="flex justify-center pt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => void fetchNextPage()}
|
||||
disabled={isFetchingNextPage}
|
||||
className="border-border text-foreground"
|
||||
>
|
||||
{isFetchingNextPage ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
Load more
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div className="col-span-2 flex flex-wrap gap-1.5 lg:col-span-1">
|
||||
{user.pets.length === 0 && <span className="text-xs text-muted-foreground">Noch kein Tier</span>}
|
||||
{user.pets.map((pet) => (
|
||||
<button
|
||||
key={pet.id}
|
||||
type="button"
|
||||
onClick={() => verify.mutate({ petId: pet.id, isVerified: !pet.isVerified })}
|
||||
disabled={verify.isPending}
|
||||
title={pet.isVerified ? "Verifiziert – klicken zum Entfernen" : "Klicken zum Verifizieren"}
|
||||
className={`inline-flex cursor-pointer items-center gap-1 rounded-full border px-2 py-0.5 text-xs transition-colors ${
|
||||
pet.isVerified ? "border-info/40 bg-info/10 text-info" : "border-border text-muted-foreground hover:border-ring/50 hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{formatPetName(pet)}
|
||||
<BadgeCheck className={`h-3 w-3 ${pet.isVerified ? "" : "opacity-40"}`} aria-hidden />
|
||||
</button>
|
||||
))}
|
||||
{user._count.pets > user.pets.length && (
|
||||
<span className="self-center text-xs text-muted-foreground">+{user._count.pets - user.pets.length} weitere</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="col-span-2 lg:col-span-1">
|
||||
<UserStatus user={user} />
|
||||
</div>
|
||||
|
||||
<span className="hidden text-sm text-muted-foreground lg:block">{user.adminRole ? ADMIN_ROLE_LABEL[user.adminRole.role] : "–"}</span>
|
||||
|
||||
<div className="col-start-2 row-start-1 flex items-center gap-1 lg:col-start-auto lg:row-start-auto">
|
||||
{firstPet && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => startConversation.mutate({ targetPetId: firstPet.id })}
|
||||
disabled={startConversation.isPending}
|
||||
title={`Als PawFeed Team an ${firstPet.name} schreiben`}
|
||||
className="inline-flex h-9 cursor-pointer items-center gap-1.5 rounded-lg border border-border px-3 text-sm font-medium text-card-foreground transition-colors hover:bg-muted disabled:opacity-60"
|
||||
>
|
||||
{startConversation.isPending && startConversation.variables?.targetPetId === firstPet.id ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" aria-hidden />
|
||||
) : (
|
||||
<MessageCircle className="h-4 w-4" aria-hidden />
|
||||
)}
|
||||
<span className="hidden sm:inline">Nachricht</span>
|
||||
</button>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
aria-label={`Weitere Aktionen für ${name}`}
|
||||
className="grid h-9 w-9 cursor-pointer place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" aria-hidden />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
<DropdownMenuItem onClick={() => exportData.mutate({ ownerId: user.id })} disabled={exportData.isPending}>
|
||||
<Download aria-hidden /> Daten exportieren (DSGVO)
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => openAction("WARN", user)}>
|
||||
<TriangleAlert aria-hidden /> Verwarnungen …
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => openAction(user.shadowban ? "UNSHADOWBAN" : "SHADOWBAN", user)}>
|
||||
<Ghost aria-hidden /> {user.shadowban ? "Shadowban aufheben" : "Shadowban setzen …"}
|
||||
</DropdownMenuItem>
|
||||
{user.ban ? (
|
||||
<DropdownMenuItem onClick={() => openAction("UNBAN", user)}>
|
||||
<ShieldCheck aria-hidden /> Sperre aufheben
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<DropdownMenuItem variant="destructive" onClick={() => openAction("BAN", user)}>
|
||||
<ShieldOff aria-hidden /> Sperren …
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canDeleteAccounts && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive" onClick={() => openAction("DELETE", user)}>
|
||||
<Trash2 aria-hidden /> Konto löschen …
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpandedId(isExpanded ? null : user.id)}
|
||||
aria-expanded={isExpanded}
|
||||
aria-label={isExpanded ? "Details ausblenden" : "Details anzeigen"}
|
||||
className="hidden h-9 w-9 cursor-pointer place-items-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground lg:grid"
|
||||
>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`} aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<dl className="mx-5 mb-4 grid grid-cols-1 gap-x-6 gap-y-2 rounded-xl bg-muted px-4 py-3 text-sm sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div>
|
||||
<dt className="text-xs text-muted-foreground">Registriert</dt>
|
||||
<dd className="text-foreground">{user.clerk?.createdAt ? formatEventTime(new Date(user.clerk.createdAt)) : "–"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs text-muted-foreground">Tiere gesamt</dt>
|
||||
<dd className="text-foreground">{user._count.pets}</dd>
|
||||
</div>
|
||||
<div className="lg:hidden">
|
||||
<dt className="text-xs text-muted-foreground">Rolle</dt>
|
||||
<dd className="text-foreground">{user.adminRole ? ADMIN_ROLE_LABEL[user.adminRole.role] : "Keine"}</dd>
|
||||
</div>
|
||||
{user.ban && (
|
||||
<div className="sm:col-span-2 lg:col-span-3">
|
||||
<dt className="text-xs text-muted-foreground">Gesperrt</dt>
|
||||
<dd className="text-destructive">
|
||||
{user.ban.reason || "Ohne Begründung"}
|
||||
{user.ban.expiresAt ? ` · bis ${formatEventTime(new Date(user.ban.expiresAt))}` : " · dauerhaft"}
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
{user.shadowban && (
|
||||
<div className="sm:col-span-2 lg:col-span-3">
|
||||
<dt className="text-xs text-muted-foreground">Shadowban</dt>
|
||||
<dd className="text-foreground">{user.shadowban.reason}</dd>
|
||||
</div>
|
||||
)}
|
||||
<div className="sm:col-span-2 lg:col-span-3">
|
||||
<dt className="text-xs text-muted-foreground">Konto-ID</dt>
|
||||
<dd className="break-all font-mono text-xs text-muted-foreground">{user.id}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Ban dialog */}
|
||||
<Dialog
|
||||
open={!!banTarget}
|
||||
onOpenChange={(o) => { if (!o) { setBanTarget(null); setBanReason(""); setBanExpiry(""); } }}
|
||||
>
|
||||
<DialogContent className="bg-card border-border text-foreground max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Ban user</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-xs text-muted-foreground font-mono break-all">{banTarget}</p>
|
||||
<Input
|
||||
placeholder="Reason (optional)"
|
||||
value={banReason}
|
||||
onChange={(e) => setBanReason(e.target.value)}
|
||||
className="bg-muted border-border text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs text-muted-foreground">
|
||||
Expires (optional — leave empty for permanent)
|
||||
</label>
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={banExpiry}
|
||||
onChange={(e) => setBanExpiry(e.target.value)}
|
||||
className="bg-muted border-border text-foreground"
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="ghost" className="text-muted-foreground" onClick={() => setBanTarget(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() =>
|
||||
banMutation.mutate({
|
||||
ownerId: banTarget!,
|
||||
reason: banReason || undefined,
|
||||
expiresAt: banExpiry ? new Date(banExpiry).toISOString() : undefined,
|
||||
})
|
||||
}
|
||||
disabled={banMutation.isPending}
|
||||
>
|
||||
{banMutation.isPending && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Confirm ban
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
{hasNextPage && (
|
||||
<div className="flex justify-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void fetchNextPage()}
|
||||
disabled={isFetchingNextPage}
|
||||
className="inline-flex cursor-pointer items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-semibold text-card-foreground hover:bg-muted disabled:opacity-60"
|
||||
>
|
||||
{isFetchingNextPage && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||
Weitere Halter laden
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Unban confirm */}
|
||||
<Dialog open={!!unbanTarget} onOpenChange={(o) => { if (!o) setUnbanTarget(null); }}>
|
||||
<DialogContent className="bg-card border-border text-foreground max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Unban user</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-muted-foreground">Remove the ban for this user?</p>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="ghost" className="text-muted-foreground" onClick={() => setUnbanTarget(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => unbanMutation.mutate({ ownerId: unbanTarget! })}
|
||||
disabled={unbanMutation.isPending}
|
||||
className="bg-secondary hover:bg-accent"
|
||||
>
|
||||
{unbanMutation.isPending && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Unban
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Shadowban dialog */}
|
||||
<Dialog
|
||||
open={!!shadowbanTarget}
|
||||
onOpenChange={(o) => { if (!o) { setShadowbanTarget(null); setShadowbanReason(""); } }}
|
||||
>
|
||||
<DialogContent className="bg-card border-border text-foreground max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Shadowban user</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-xs text-muted-foreground font-mono break-all">{shadowbanTarget}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Their posts quietly stop reaching anyone else — feed, explore, search, hashtags,
|
||||
profile view. They keep posting normally and are never told.
|
||||
</p>
|
||||
<Input
|
||||
placeholder="Reason (required)"
|
||||
value={shadowbanReason}
|
||||
onChange={(e) => setShadowbanReason(e.target.value)}
|
||||
className="bg-muted border-border text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="ghost" className="text-muted-foreground" onClick={() => setShadowbanTarget(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
className="bg-violet-700 hover:bg-violet-600"
|
||||
onClick={() =>
|
||||
shadowbanMutation.mutate({
|
||||
ownerId: shadowbanTarget!,
|
||||
reason: shadowbanReason.trim(),
|
||||
})
|
||||
}
|
||||
disabled={shadowbanMutation.isPending || !shadowbanReason.trim()}
|
||||
>
|
||||
{shadowbanMutation.isPending && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Confirm shadowban
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Un-shadowban confirm */}
|
||||
<Dialog open={!!unshadowbanTarget} onOpenChange={(o) => { if (!o) setUnshadowbanTarget(null); }}>
|
||||
<DialogContent className="bg-card border-border text-foreground max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Remove shadowban</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Restore normal visibility for this user's posts?
|
||||
</p>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="ghost" className="text-muted-foreground" onClick={() => setUnshadowbanTarget(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => removeShadowbanMutation.mutate({ ownerId: unshadowbanTarget! })}
|
||||
disabled={removeShadowbanMutation.isPending}
|
||||
className="bg-secondary hover:bg-accent"
|
||||
>
|
||||
{removeShadowbanMutation.isPending && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Remove shadowban
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Warnings history + issue new */}
|
||||
<Dialog
|
||||
open={!!warnTarget}
|
||||
onOpenChange={(o) => { if (!o) { setWarnTarget(null); setWarnReason(""); } }}
|
||||
>
|
||||
<DialogContent className="bg-card border-border text-foreground max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Warnings</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-xs text-muted-foreground font-mono break-all">{warnTarget}</p>
|
||||
<div className="max-h-48 space-y-2 overflow-y-auto">
|
||||
{warningHistory.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No warnings yet.</p>
|
||||
) : (
|
||||
warningHistory.map((w) => (
|
||||
<div key={w.id} className="rounded-lg border border-border px-3 py-2">
|
||||
<p className="text-sm text-foreground">{w.reason}</p>
|
||||
<p className="text-xs text-muted-foreground/70 mt-1">
|
||||
{new Date(w.createdAt).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
placeholder="New warning reason…"
|
||||
value={warnReason}
|
||||
onChange={(e) => setWarnReason(e.target.value)}
|
||||
className="bg-muted border-border text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="ghost" className="text-muted-foreground" onClick={() => setWarnTarget(null)}>
|
||||
Close
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() =>
|
||||
issueWarningMutation.mutate({ ownerId: warnTarget!, reason: warnReason.trim() })
|
||||
}
|
||||
disabled={issueWarningMutation.isPending || !warnReason.trim()}
|
||||
className="bg-secondary hover:bg-accent"
|
||||
>
|
||||
{issueWarningMutation.isPending && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Issue warning
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete account (GDPR erasure, super-admin only) */}
|
||||
<Dialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(o) => { if (!o) { setDeleteTarget(null); setDeleteConfirmation(""); } }}
|
||||
>
|
||||
<DialogContent className="bg-card border-border text-foreground max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-destructive">Delete account permanently</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This permanently deletes the owner, all their pets, posts, and storage files, and
|
||||
revokes their login. This cannot be undone.
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Type the user ID to confirm:{" "}
|
||||
<span className="font-mono text-foreground">{deleteTarget}</span>
|
||||
</p>
|
||||
<Input
|
||||
placeholder="user_…"
|
||||
value={deleteConfirmation}
|
||||
onChange={(e) => setDeleteConfirmation(e.target.value)}
|
||||
className="bg-muted border-border text-foreground placeholder:text-muted-foreground font-mono text-sm"
|
||||
/>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="ghost" className="text-muted-foreground" onClick={() => setDeleteTarget(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() =>
|
||||
deleteAccountMutation.mutate({
|
||||
ownerId: deleteTarget!,
|
||||
confirmation: deleteConfirmation,
|
||||
})
|
||||
}
|
||||
disabled={deleteAccountMutation.isPending || deleteConfirmation !== deleteTarget}
|
||||
>
|
||||
{deleteAccountMutation.isPending && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Delete permanently
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<UserActionDialogs target={actionTarget} onClose={() => setActionTarget(null)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { formatEventTime } from "@/lib/admin/format";
|
||||
|
||||
export type UserAction = "BAN" | "UNBAN" | "SHADOWBAN" | "UNSHADOWBAN" | "WARN" | "DELETE";
|
||||
|
||||
export interface UserActionTarget {
|
||||
action: UserAction;
|
||||
ownerId: string;
|
||||
/** Name oder E-Mail zur Orientierung im Dialog. */
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface UserActionDialogsProps {
|
||||
target: UserActionTarget | null;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Eingriffe der Halter-Seite in einem Dialog-Baustein: Sperren, Entsperren,
|
||||
* Shadowban (+ aufheben), Verwarnungen und Konto löschen. Die Rechte prüft der
|
||||
* Server (admin.ts), hier geht es nur um klare, deutsche Rückfragen.
|
||||
*/
|
||||
export function UserActionDialogs({ target, onClose }: UserActionDialogsProps) {
|
||||
const trpc = useTRPC();
|
||||
const qc = useQueryClient();
|
||||
const [reason, setReason] = useState("");
|
||||
const [banUntil, setBanUntil] = useState("");
|
||||
const [confirmation, setConfirmation] = useState("");
|
||||
const action = target?.action;
|
||||
const ownerId = target?.ownerId ?? "";
|
||||
|
||||
const close = () => {
|
||||
setReason("");
|
||||
setBanUntil("");
|
||||
setConfirmation("");
|
||||
onClose();
|
||||
};
|
||||
const refresh = () => void qc.invalidateQueries({ queryKey: trpc.admin.listUsers.queryKey() });
|
||||
const failed = (label: string) => (err: { message: string }) => toast.error(`${label} fehlgeschlagen: ${err.message}`);
|
||||
const done = (message: string) => () => {
|
||||
refresh();
|
||||
toast.success(message);
|
||||
close();
|
||||
};
|
||||
|
||||
const ban = useMutation(trpc.admin.banUser.mutationOptions({ onSuccess: done("Halter gesperrt."), onError: failed("Sperren") }));
|
||||
const unban = useMutation(trpc.admin.unbanUser.mutationOptions({ onSuccess: done("Sperre aufgehoben."), onError: failed("Entsperren") }));
|
||||
const shadowban = useMutation(trpc.admin.shadowbanOwner.mutationOptions({ onSuccess: done("Shadowban gesetzt."), onError: failed("Shadowban") }));
|
||||
const unshadowban = useMutation(trpc.admin.removeShadowban.mutationOptions({ onSuccess: done("Shadowban aufgehoben."), onError: failed("Aufheben") }));
|
||||
const deleteAccount = useMutation(trpc.admin.deleteUserAccount.mutationOptions({ onSuccess: done("Konto gelöscht."), onError: failed("Löschen") }));
|
||||
const warn = useMutation(
|
||||
trpc.admin.issueWarning.mutationOptions({
|
||||
onSuccess: () => {
|
||||
refresh();
|
||||
void qc.invalidateQueries({ queryKey: trpc.admin.listWarnings.queryKey({ ownerId }) });
|
||||
setReason("");
|
||||
toast.success("Verwarnung gespeichert.");
|
||||
},
|
||||
onError: failed("Verwarnen"),
|
||||
})
|
||||
);
|
||||
const { data: warnings = [], isLoading: isLoadingWarnings } = useQuery(
|
||||
trpc.admin.listWarnings.queryOptions({ ownerId }, { enabled: action === "WARN" })
|
||||
);
|
||||
|
||||
const isOpen = (a: UserAction) => action === a;
|
||||
const onOpenChange = (open: boolean) => !open && close();
|
||||
const spinner = (pending: boolean) => pending && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />;
|
||||
const who = <span className="font-semibold text-foreground">{target?.label}</span>;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen("BAN")} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Halter sperren</DialogTitle>
|
||||
<DialogDescription>{who} kann sich danach nicht mehr anmelden. Alle Tiere des Halters sind betroffen.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<label className="space-y-1.5 text-sm font-medium">
|
||||
<span>Grund (optional, nur intern sichtbar)</span>
|
||||
<Input value={reason} onChange={(e) => setReason(e.target.value)} placeholder="z. B. wiederholt Spam" maxLength={500} />
|
||||
</label>
|
||||
<label className="space-y-1.5 text-sm font-medium">
|
||||
<span>Gesperrt bis (leer lassen = dauerhaft)</span>
|
||||
<Input type="datetime-local" value={banUntil} onChange={(e) => setBanUntil(e.target.value)} />
|
||||
</label>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={close}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={ban.isPending}
|
||||
onClick={() => ban.mutate({ ownerId, reason: reason.trim() || undefined, expiresAt: banUntil ? new Date(banUntil).toISOString() : undefined })}
|
||||
>
|
||||
{spinner(ban.isPending)}
|
||||
Sperren
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={isOpen("UNBAN")} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Sperre aufheben</DialogTitle>
|
||||
<DialogDescription>{who} kann sich danach wieder anmelden.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={close}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button disabled={unban.isPending} onClick={() => unban.mutate({ ownerId })}>
|
||||
{spinner(unban.isPending)}
|
||||
Sperre aufheben
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={isOpen("SHADOWBAN")} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Shadowban setzen</DialogTitle>
|
||||
<DialogDescription>
|
||||
Beiträge von {who} erreichen niemanden mehr (Feed, Explore, Suche, Hashtags, Profil). Der Halter postet normal weiter und erfährt nichts davon.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<label className="space-y-1.5 text-sm font-medium">
|
||||
<span>Grund (Pflicht, nur intern sichtbar)</span>
|
||||
<Input value={reason} onChange={(e) => setReason(e.target.value)} placeholder="z. B. Werbe-Spam über mehrere Konten" maxLength={500} />
|
||||
</label>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={close}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button disabled={shadowban.isPending || !reason.trim()} onClick={() => shadowban.mutate({ ownerId, reason: reason.trim() })}>
|
||||
{spinner(shadowban.isPending)}
|
||||
Shadowban setzen
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={isOpen("UNSHADOWBAN")} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Shadowban aufheben</DialogTitle>
|
||||
<DialogDescription>Beiträge von {who} sind danach wieder normal sichtbar.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={close}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button disabled={unshadowban.isPending} onClick={() => unshadowban.mutate({ ownerId })}>
|
||||
{spinner(unshadowban.isPending)}
|
||||
Shadowban aufheben
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={isOpen("WARN")} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Verwarnungen</DialogTitle>
|
||||
<DialogDescription>Bisherige Verwarnungen von {who} und eine neue aussprechen.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="max-h-56 space-y-2 overflow-y-auto">
|
||||
{isLoadingWarnings ? (
|
||||
<Loader2 className="mx-auto h-5 w-5 animate-spin text-muted-foreground" aria-label="Wird geladen" />
|
||||
) : warnings.length === 0 ? (
|
||||
<p className="rounded-lg border border-dashed border-border px-3 py-4 text-center text-sm text-muted-foreground">Noch keine Verwarnungen.</p>
|
||||
) : (
|
||||
warnings.map((w) => (
|
||||
<div key={w.id} className="rounded-lg border border-border px-3 py-2">
|
||||
<p className="text-sm text-foreground">{w.reason}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{formatEventTime(new Date(w.createdAt))}</p>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<label className="space-y-1.5 text-sm font-medium">
|
||||
<span>Neue Verwarnung</span>
|
||||
<Textarea value={reason} onChange={(e) => setReason(e.target.value)} placeholder="Was ist passiert?" maxLength={500} rows={3} />
|
||||
</label>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={close}>
|
||||
Schließen
|
||||
</Button>
|
||||
<Button disabled={warn.isPending || !reason.trim()} onClick={() => warn.mutate({ ownerId, reason: reason.trim() })}>
|
||||
{spinner(warn.isPending)}
|
||||
Verwarnen
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={isOpen("DELETE")} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-destructive">Konto endgültig löschen</DialogTitle>
|
||||
<DialogDescription>
|
||||
Löscht {who} mit allen Tieren, Beiträgen und Dateien und beendet den Login. Das lässt sich nicht rückgängig machen (DSGVO-Löschung).
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<label className="space-y-1.5 text-sm font-medium">
|
||||
<span>
|
||||
Zur Bestätigung die Konto-ID eintippen: <span className="break-all font-mono text-xs text-muted-foreground">{ownerId}</span>
|
||||
</span>
|
||||
<Input value={confirmation} onChange={(e) => setConfirmation(e.target.value)} placeholder="user_…" className="font-mono text-sm" />
|
||||
</label>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={close}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={deleteAccount.isPending || confirmation !== ownerId}
|
||||
onClick={() => deleteAccount.mutate({ ownerId, confirmation })}
|
||||
>
|
||||
{spinner(deleteAccount.isPending)}
|
||||
Endgültig löschen
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { AUDIT_ACTIONS_BY_CATEGORY, auditRankId, formatAuditEntry, type AuditPart } from "@/lib/admin/audit-format";
|
||||
|
||||
const text = (parts: AuditPart[]) => parts.map((p) => (typeof p === "string" ? p : `**${p.strong}**`)).join("");
|
||||
const fmt = (action: string, reason: string | null = null, targetLabel: string | null = null, rankName: string | null = null) =>
|
||||
formatAuditEntry({ action, reason, targetLabel, rankName });
|
||||
|
||||
describe("formatAuditEntry", () => {
|
||||
it("names the target and strips the pet name the server stored in the reason", () => {
|
||||
const v = fmt("DELETE_PET", "Bello: Kein Account ist mit dem Tier verknüpft");
|
||||
expect(text(v.parts)).toBe("hat das Tier **Bello** gelöscht");
|
||||
expect(v.details).toEqual(["Grund: Kein Account ist mit dem Tier verknüpft"]);
|
||||
expect(v.category).toBe("PETS");
|
||||
});
|
||||
|
||||
it("describes posts by their author and falls back when the post is gone", () => {
|
||||
expect(text(fmt("DELETE_POST", "Spam", "Bianca").parts)).toBe("hat den Beitrag von **Bianca** gelöscht");
|
||||
expect(text(fmt("DELETE_POST", null, null).parts)).toBe("hat einen Beitrag gelöscht");
|
||||
});
|
||||
|
||||
it("explains automatic blacklist hides", () => {
|
||||
expect(fmt("HIDE_POST", "Auto-hidden: Wort „xyz“").details).toEqual(["Automatisch – Treffer auf der Sperrliste: Wort „xyz“"]);
|
||||
});
|
||||
|
||||
it("turns referral codes into rank names and readable field lists", () => {
|
||||
const grant = fmt("GRANT_REFERRAL_RANK", "cmuprcltd00042dmsyoxdol7q: Testzwecke", "Jessi Schober", "Botschafter");
|
||||
expect(text(grant.parts)).toBe("hat **Jessi Schober** den Rang **Botschafter** verliehen");
|
||||
expect(grant.details).toEqual(["Notiz: Testzwecke"]);
|
||||
|
||||
const update = fmt("UPDATE_REFERRAL_RANK", "goldene-pfote: nameDe, threshold, isActive", null, "Goldene Pfote");
|
||||
expect(text(update.parts)).toBe("hat den Rang **Goldene Pfote** bearbeitet");
|
||||
expect(update.details).toEqual(["Geändert: Name (DE), Schwelle, Aktiv"]);
|
||||
});
|
||||
|
||||
it("reads referral settings JSON", () => {
|
||||
const v = fmt("UPDATE_REFERRAL_SETTINGS", JSON.stringify({ redeemWindowDays: 14, programActive: true }));
|
||||
expect(v.details).toEqual(["Einlösefrist (Tage): 14", "Programm aktiv: an"]);
|
||||
});
|
||||
|
||||
it("translates founding member, cleared fields and roles", () => {
|
||||
expect(text(fmt("SET_FOUNDING_MEMBER", "false", "Odin").parts)).toBe("hat **Odin** das Gründungsmitglied-Abzeichen entzogen");
|
||||
expect(fmt("CLEAR_PET_CONTENT", "avatar, bio: unpassend", "Odin").details).toEqual(["Entfernt: Profilbild, Bio", "Grund: unpassend"]);
|
||||
expect(text(fmt("GRANT_ROLE", "MODERATOR", "Lea").parts)).toBe("hat **Lea** die Rolle **Moderator** gegeben");
|
||||
});
|
||||
|
||||
it("never shows a bare code for unknown actions", () => {
|
||||
const v = fmt("SOMETHING_NEW");
|
||||
expect(v.category).toBe("OTHER");
|
||||
expect(text(v.parts)).toBe("hat die Aktion **SOMETHING_NEW** ausgeführt");
|
||||
});
|
||||
|
||||
it("covers every action listed in the schema comment", () => {
|
||||
const all = Object.values(AUDIT_ACTIONS_BY_CATEGORY).flat();
|
||||
for (const action of all) {
|
||||
expect(fmt(action).category, action).not.toBe("OTHER");
|
||||
expect(text(fmt(action).parts), action).not.toContain(action);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("auditRankId", () => {
|
||||
it("finds the rank id in targetId or the reason prefix", () => {
|
||||
expect(auditRankId("UPDATE_REFERRAL_RANK", "rank-1", "key: x")).toBe("rank-1");
|
||||
expect(auditRankId("REVOKE_REFERRAL_RANK", "user_1", "rank-2: weil")).toBe("rank-2");
|
||||
expect(auditRankId("BAN_USER", "user_1", null)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
/**
|
||||
* Übersetzt Einträge des Moderations-Protokolls (ModerationLog) in lesbare
|
||||
* deutsche Sätze. Reine Funktion — Namen (Ziel, Rang) löst der Server vorher auf
|
||||
* (adminOverview.getAuditLog), hier wird nur formuliert.
|
||||
*
|
||||
* Beispiel: { action: "DELETE_PET", reason: "Bello: Fake-Profil" }
|
||||
* → „hat das Tier **Bello** gelöscht“, Details: ["Grund: Fake-Profil"]
|
||||
*/
|
||||
|
||||
export type AuditCategory = "CONTENT" | "OWNERS" | "PETS" | "REPORTS" | "MEDIA" | "TEAM" | "SYSTEM" | "REFERRALS" | "LOST";
|
||||
|
||||
export const AUDIT_CATEGORY_LABEL: Record<AuditCategory, string> = {
|
||||
CONTENT: "Beiträge",
|
||||
OWNERS: "Halter",
|
||||
PETS: "Tiere",
|
||||
REPORTS: "Meldungen",
|
||||
MEDIA: "Werbung & Musik",
|
||||
TEAM: "Team",
|
||||
SYSTEM: "System",
|
||||
REFERRALS: "Empfehlungen",
|
||||
LOST: "Vermisst",
|
||||
};
|
||||
|
||||
/** Welche Aktionen zu welcher Kategorie gehören — auch für den Kategorie-Filter des Servers. */
|
||||
export const AUDIT_ACTIONS_BY_CATEGORY: Record<AuditCategory, readonly string[]> = {
|
||||
CONTENT: ["DELETE_POST", "HIDE_POST", "UNHIDE_POST", "PIN_POST", "UNPIN_POST", "SET_AI_DISCLOSURE", "DELETE_COMMENT", "DELETE_IMAGE"],
|
||||
OWNERS: ["BAN_USER", "UNBAN_USER", "SHADOWBAN_USER", "UNSHADOWBAN_USER", "WARN_USER", "DELETE_ACCOUNT", "DATA_EXPORT"],
|
||||
PETS: ["VERIFY_PET", "UNVERIFY_PET", "APPROVE_VERIFICATION_REQUEST", "REJECT_VERIFICATION_REQUEST", "SET_FOUNDING_MEMBER", "CLEAR_PET_CONTENT", "DELETE_PET"],
|
||||
REPORTS: ["DISMISS_REPORT"],
|
||||
MEDIA: ["CREATE_AD", "UPDATE_AD", "DELETE_AD", "CREATE_MUSIC_TRACK", "UPDATE_MUSIC_TRACK", "DELETE_MUSIC_TRACK"],
|
||||
TEAM: ["GRANT_ROLE", "REVOKE_ROLE"],
|
||||
SYSTEM: [
|
||||
"ENABLE_MAINTENANCE_MODE",
|
||||
"DISABLE_MAINTENANCE_MODE",
|
||||
"ENABLE_STORY_EDITOR",
|
||||
"DISABLE_STORY_EDITOR",
|
||||
"SEND_BROADCAST",
|
||||
"DELETE_BROADCAST",
|
||||
"UPDATE_CURATOR_SETTINGS",
|
||||
],
|
||||
REFERRALS: [
|
||||
"CREATE_REFERRAL_RANK",
|
||||
"UPDATE_REFERRAL_RANK",
|
||||
"DEACTIVATE_REFERRAL_RANK",
|
||||
"UPDATE_REFERRAL_SETTINGS",
|
||||
"APPROVE_REFERRAL",
|
||||
"REVOKE_REFERRAL",
|
||||
"REVOKE_REFERRAL_RANK",
|
||||
"GRANT_REFERRAL_RANK",
|
||||
"RESTORE_REFERRAL_RANK",
|
||||
],
|
||||
LOST: ["CLOSE_LOST_REPORT", "DELETE_LOST_REPORT"],
|
||||
};
|
||||
|
||||
const CATEGORY_BY_ACTION = new Map<string, AuditCategory>(
|
||||
(Object.entries(AUDIT_ACTIONS_BY_CATEGORY) as [AuditCategory, readonly string[]][]).flatMap(([cat, actions]) =>
|
||||
actions.map((a) => [a, cat] as const)
|
||||
)
|
||||
);
|
||||
|
||||
export type AuditPart = string | { strong: string };
|
||||
|
||||
export interface AuditInput {
|
||||
action: string;
|
||||
reason: string | null;
|
||||
/** Vom Server aufgelöster Name des Ziels (Tier, Halter, Beitrags-Autor, Werbetitel …), null wenn unbekannt/gelöscht. */
|
||||
targetLabel: string | null;
|
||||
/** Vom Server aufgelöster Rangname bei Empfehlungs-Aktionen. */
|
||||
rankName?: string | null;
|
||||
}
|
||||
|
||||
export interface AuditView {
|
||||
category: AuditCategory | "OTHER";
|
||||
/** Satz ohne Handelnden, z. B. ["hat das Tier ", {strong: "Bello"}, " gelöscht"]. */
|
||||
parts: AuditPart[];
|
||||
/** Zusätzliche Zeilen (Grund, geänderte Felder …), schon übersetzt. */
|
||||
details: string[];
|
||||
}
|
||||
|
||||
const ROLE_LABEL: Record<string, string> = { SUPER_ADMIN: "Super-Admin", MODERATOR: "Moderator", SUPPORT: "Support" };
|
||||
const PET_FIELD_LABEL: Record<string, string> = { avatar: "Profilbild", bio: "Bio", adoptionStory: "Adoptionsgeschichte", nickname: "Rufname" };
|
||||
const RANK_FIELD_LABEL: Record<string, string> = {
|
||||
nameDe: "Name (DE)",
|
||||
nameEn: "Name (EN)",
|
||||
descriptionDe: "Beschreibung (DE)",
|
||||
descriptionEn: "Beschreibung (EN)",
|
||||
threshold: "Schwelle",
|
||||
icon: "Symbol",
|
||||
color: "Farbe",
|
||||
perks: "Vorteile",
|
||||
isActive: "Aktiv",
|
||||
};
|
||||
const SETTINGS_LABEL: Record<string, string> = {
|
||||
programActive: "Programm aktiv",
|
||||
redeemWindowDays: "Einlösefrist (Tage)",
|
||||
dailyQualifyCap: "Tageslimit",
|
||||
autoMutualFollow: "Gegenseitig folgen",
|
||||
};
|
||||
|
||||
/** „cmabc123: Text“ / „key: Text“ → ["cmabc123", "Text"]; ohne Doppelpunkt → [whole, null]. */
|
||||
function splitPrefix(reason: string | null): [string | null, string | null] {
|
||||
if (!reason) return [null, null];
|
||||
const i = reason.indexOf(": ");
|
||||
return i === -1 ? [reason, null] : [reason.slice(0, i), reason.slice(i + 2)];
|
||||
}
|
||||
|
||||
const reasonLine = (text: string | null | undefined) => (text && text.trim() ? [`Grund: ${text.trim()}`] : []);
|
||||
const formatValue = (v: unknown) => (v === true ? "an" : v === false ? "aus" : String(v));
|
||||
|
||||
export function formatAuditEntry({ action, reason, targetLabel, rankName }: AuditInput): AuditView {
|
||||
const category = CATEGORY_BY_ACTION.get(action) ?? "OTHER";
|
||||
const s = (label: string | null | undefined, fallback: string): AuditPart => (label ? { strong: label } : fallback);
|
||||
const view = (parts: AuditPart[], details: string[] = []): AuditView => ({ category, parts, details });
|
||||
|
||||
const post = targetLabel ? ["den Beitrag von ", { strong: targetLabel }] : ["einen Beitrag"];
|
||||
const owner = s(targetLabel, "einen Halter");
|
||||
const pet = s(targetLabel, "ein Tier");
|
||||
const rank = s(rankName, "einen Rang");
|
||||
|
||||
switch (action) {
|
||||
// Beiträge
|
||||
case "DELETE_POST":
|
||||
return view(["hat ", ...post, " gelöscht"], reasonLine(reason));
|
||||
case "HIDE_POST": {
|
||||
const auto = reason?.startsWith("Auto-hidden: ");
|
||||
return view(["hat ", ...post, " ausgeblendet"], auto ? [`Automatisch – Treffer auf der Sperrliste: ${reason!.slice(13)}`] : reasonLine(reason));
|
||||
}
|
||||
case "UNHIDE_POST":
|
||||
return view(["hat ", ...post, " wieder eingeblendet"]);
|
||||
case "PIN_POST":
|
||||
return view(["hat ", ...post, " angepinnt"]);
|
||||
case "UNPIN_POST":
|
||||
return view(["hat ", ...post, " nicht mehr angepinnt"]);
|
||||
case "SET_AI_DISCLOSURE":
|
||||
return view(["hat ", ...post, " als KI-generiert gekennzeichnet"], reasonLine(reason));
|
||||
case "DELETE_COMMENT":
|
||||
return view(["hat einen Kommentar gelöscht"], reasonLine(reason));
|
||||
case "DELETE_IMAGE":
|
||||
return view(["hat ein Bild gelöscht"], reasonLine(reason));
|
||||
|
||||
// Halter
|
||||
case "BAN_USER":
|
||||
return view(["hat ", owner, " gesperrt"], reasonLine(reason));
|
||||
case "UNBAN_USER":
|
||||
return view(["hat die Sperre von ", owner, " aufgehoben"]);
|
||||
case "SHADOWBAN_USER":
|
||||
return view(["hat ", owner, " unsichtbar geschaltet (Shadowban)"], reasonLine(reason));
|
||||
case "UNSHADOWBAN_USER":
|
||||
return view(["hat den Shadowban von ", owner, " aufgehoben"]);
|
||||
case "WARN_USER":
|
||||
return view(["hat ", owner, " verwarnt"], reasonLine(reason));
|
||||
case "DELETE_ACCOUNT":
|
||||
return view(["hat das Konto von ", owner, " gelöscht"], reasonLine(reason));
|
||||
case "DATA_EXPORT":
|
||||
return view(["hat die Daten von ", owner, " exportiert"]);
|
||||
|
||||
// Tiere
|
||||
case "VERIFY_PET":
|
||||
return view(["hat ", pet, " verifiziert"]);
|
||||
case "UNVERIFY_PET":
|
||||
return view(["hat die Verifizierung von ", pet, " entfernt"]);
|
||||
case "APPROVE_VERIFICATION_REQUEST":
|
||||
return view(["hat die Verifizierungs-Anfrage von ", pet, " angenommen"], reason ? [`Notiz: ${reason}`] : []);
|
||||
case "REJECT_VERIFICATION_REQUEST":
|
||||
return view(["hat die Verifizierungs-Anfrage von ", pet, " abgelehnt"], reason ? [`Notiz: ${reason}`] : []);
|
||||
case "SET_FOUNDING_MEMBER":
|
||||
return reason === "false"
|
||||
? view(["hat ", pet, " das Gründungsmitglied-Abzeichen entzogen"])
|
||||
: view(["hat ", pet, " zum Gründungsmitglied gemacht"]);
|
||||
case "CLEAR_PET_CONTENT": {
|
||||
const [fields, text] = splitPrefix(reason);
|
||||
const labels = (fields ?? "").split(", ").filter(Boolean).map((f) => PET_FIELD_LABEL[f] ?? f);
|
||||
return view(["hat bei ", pet, " Inhalte entfernt"], [...(labels.length ? [`Entfernt: ${labels.join(", ")}`] : []), ...reasonLine(text)]);
|
||||
}
|
||||
case "DELETE_PET": {
|
||||
const [name, text] = splitPrefix(reason);
|
||||
return view(["hat das Tier ", s(targetLabel ?? name, "ein Tier"), " gelöscht"], reasonLine(text));
|
||||
}
|
||||
|
||||
// Meldungen
|
||||
case "DISMISS_REPORT":
|
||||
return view(["hat eine Meldung abgewiesen"], reason ? [`Nachricht an den Melder: ${reason}`] : []);
|
||||
|
||||
// Werbung & Musik
|
||||
case "CREATE_AD":
|
||||
return view(["hat die Werbung ", s(targetLabel ?? reason, "(ohne Titel)"), " angelegt"]);
|
||||
case "UPDATE_AD":
|
||||
return view(["hat die Werbung ", s(targetLabel, "(gelöscht)"), " bearbeitet"]);
|
||||
case "DELETE_AD":
|
||||
return view(["hat eine Werbung gelöscht"]);
|
||||
case "CREATE_MUSIC_TRACK":
|
||||
return view(["hat den Musiktitel ", s(targetLabel ?? reason, "(ohne Titel)"), " hinzugefügt"]);
|
||||
case "UPDATE_MUSIC_TRACK":
|
||||
return view(["hat den Musiktitel ", s(targetLabel, "(gelöscht)"), " bearbeitet"]);
|
||||
case "DELETE_MUSIC_TRACK":
|
||||
return view(["hat einen Musiktitel gelöscht"]);
|
||||
|
||||
// Team
|
||||
case "GRANT_ROLE":
|
||||
return view(["hat ", owner, " die Rolle ", { strong: ROLE_LABEL[reason ?? ""] ?? reason ?? "?" }, " gegeben"]);
|
||||
case "REVOKE_ROLE":
|
||||
return view(["hat ", owner, " die Admin-Rolle entzogen"]);
|
||||
|
||||
// System
|
||||
case "ENABLE_MAINTENANCE_MODE":
|
||||
return view(["hat den ", { strong: "Wartungsmodus" }, " eingeschaltet"]);
|
||||
case "DISABLE_MAINTENANCE_MODE":
|
||||
return view(["hat den ", { strong: "Wartungsmodus" }, " ausgeschaltet"]);
|
||||
case "ENABLE_STORY_EDITOR":
|
||||
return view(["hat den ", { strong: "Story-Editor" }, " wieder eingeschaltet"]);
|
||||
case "DISABLE_STORY_EDITOR":
|
||||
return view(["hat den ", { strong: "Story-Editor" }, " abgeschaltet"]);
|
||||
case "SEND_BROADCAST":
|
||||
return view(["hat eine Mitteilung an alle gesendet"]);
|
||||
case "DELETE_BROADCAST":
|
||||
return view(["hat eine Mitteilung zurückgezogen"], reasonLine(reason));
|
||||
case "UPDATE_CURATOR_SETTINGS":
|
||||
return view(["hat die ", { strong: "Begrüßung" }, " neuer Tiere geändert"]);
|
||||
|
||||
// Empfehlungen
|
||||
case "CREATE_REFERRAL_RANK": {
|
||||
const threshold = reason?.match(/ab (\d+)$/)?.[1];
|
||||
return view(["hat den Rang ", rank, " angelegt"], threshold ? [`Ab ${threshold} Einladungen`] : []);
|
||||
}
|
||||
case "UPDATE_REFERRAL_RANK":
|
||||
case "DEACTIVATE_REFERRAL_RANK": {
|
||||
const [, fields] = splitPrefix(reason);
|
||||
const labels = (fields ?? "").split(", ").filter(Boolean).map((f) => RANK_FIELD_LABEL[f] ?? f);
|
||||
return action === "DEACTIVATE_REFERRAL_RANK"
|
||||
? view(["hat den Rang ", rank, " deaktiviert"])
|
||||
: view(["hat den Rang ", rank, " bearbeitet"], labels.length ? [`Geändert: ${labels.join(", ")}`] : []);
|
||||
}
|
||||
case "UPDATE_REFERRAL_SETTINGS": {
|
||||
let details: string[] = [];
|
||||
try {
|
||||
const settings = JSON.parse(reason ?? "{}") as Record<string, unknown>;
|
||||
details = Object.entries(settings).map(([k, v]) => `${SETTINGS_LABEL[k] ?? k}: ${formatValue(v)}`);
|
||||
} catch {
|
||||
details = [];
|
||||
}
|
||||
return view(["hat die Einstellungen des ", { strong: "Empfehlungsprogramms" }, " geändert"], details);
|
||||
}
|
||||
case "APPROVE_REFERRAL":
|
||||
return view(["hat die Einladung von ", owner, " freigegeben"]);
|
||||
case "REVOKE_REFERRAL":
|
||||
return view(["hat die Einladung von ", owner, " aberkannt"], reasonLine(reason));
|
||||
case "GRANT_REFERRAL_RANK":
|
||||
return view(["hat ", owner, " den Rang ", rank, " verliehen"], splitPrefix(reason)[1] ? [`Notiz: ${splitPrefix(reason)[1]}`] : []);
|
||||
case "RESTORE_REFERRAL_RANK":
|
||||
return view(["hat ", owner, " den Rang ", rank, " wieder freigegeben"], splitPrefix(reason)[1] ? [`Notiz: ${splitPrefix(reason)[1]}`] : []);
|
||||
case "REVOKE_REFERRAL_RANK":
|
||||
return view(["hat ", owner, " den Rang ", rank, " entzogen"], reasonLine(splitPrefix(reason)[1]));
|
||||
|
||||
// Vermisst
|
||||
case "CLOSE_LOST_REPORT":
|
||||
return view(["hat die Vermisst-Meldung von ", pet, " geschlossen"], reasonLine(reason));
|
||||
case "DELETE_LOST_REPORT":
|
||||
return view(["hat die Vermisst-Meldung von ", pet, " gelöscht"], reasonLine(reason));
|
||||
|
||||
default:
|
||||
return view(["hat die Aktion ", { strong: action }, " ausgeführt"], reasonLine(reason));
|
||||
}
|
||||
}
|
||||
|
||||
/** Rang-ID steckt bei Rang-Vergaben im Präfix der Begründung, bei Rang-Änderungen in targetId. */
|
||||
export function auditRankId(action: string, targetId: string, reason: string | null): string | null {
|
||||
if (action === "UPDATE_REFERRAL_RANK" || action === "DEACTIVATE_REFERRAL_RANK" || action === "CREATE_REFERRAL_RANK") return targetId;
|
||||
if (action === "GRANT_REFERRAL_RANK" || action === "RESTORE_REFERRAL_RANK" || action === "REVOKE_REFERRAL_RANK") return splitPrefix(reason)[0];
|
||||
return null;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { formatEventTime, formatTrend, formatWaitingSince, greetingFor } from "@/lib/admin/format";
|
||||
import { formatClockTime, formatDayHeading, formatEventTime, formatTrend, formatWaitingSince, greetingFor } from "@/lib/admin/format";
|
||||
|
||||
// 05.10.2026, 09:30 in Berlin (CEST = UTC+2)
|
||||
const NOW = new Date("2026-10-05T07:30:00Z");
|
||||
@@ -50,3 +50,13 @@ describe("formatTrend", () => {
|
||||
expect(formatTrend(0, 0)).toEqual({ label: "±0", direction: "flat" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatDayHeading", () => {
|
||||
it("names today and yesterday, otherwise weekday and date", () => {
|
||||
expect(formatDayHeading(new Date("2026-10-05T05:00:00Z"), NOW)).toBe("Heute");
|
||||
expect(formatDayHeading(new Date("2026-10-04T12:00:00Z"), NOW)).toBe("Gestern");
|
||||
expect(formatDayHeading(new Date("2026-10-02T12:00:00Z"), NOW)).toBe("Freitag, 2. Oktober");
|
||||
expect(formatDayHeading(new Date("2025-12-24T12:00:00Z"), NOW)).toBe("Mittwoch, 24. Dezember 2025");
|
||||
expect(formatClockTime(new Date("2026-10-05T07:42:00Z"))).toBe("09:42");
|
||||
});
|
||||
});
|
||||
@@ -59,3 +59,27 @@ export function formatTrend(current: number, previous: number): { label: string;
|
||||
if (pct === 0) return { label: "±0 %", direction: "flat" };
|
||||
return { label: `${pct > 0 ? "+" : "−"}${Math.abs(pct)} %`, direction: pct > 0 ? "up" : "down" };
|
||||
}
|
||||
|
||||
/** Überschrift für eine Tagesgruppe: „Heute“, „Gestern“, sonst „Freitag, 3. Oktober“ (anderes Jahr mit Jahreszahl). */
|
||||
export function formatDayHeading(date: Date, now: Date = new Date()): string {
|
||||
if (dayKey(date) === dayKey(now)) return "Heute";
|
||||
if (dayKey(date) === dayKey(new Date(now.getTime() - DAY_MS))) return "Gestern";
|
||||
const sameYear =
|
||||
date.toLocaleDateString("de-DE", { timeZone: TIME_ZONE, year: "numeric" }) ===
|
||||
now.toLocaleDateString("de-DE", { timeZone: TIME_ZONE, year: "numeric" });
|
||||
return date.toLocaleDateString("de-DE", {
|
||||
timeZone: TIME_ZONE,
|
||||
weekday: "long",
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
...(sameYear ? {} : { year: "numeric" }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Schlüssel für die Tagesgruppierung (Kalendertag in Berlin). */
|
||||
export const berlinDayKey = dayKey;
|
||||
|
||||
/** Uhrzeit „09:42“ in Berlin. */
|
||||
export function formatClockTime(date: Date): string {
|
||||
return date.toLocaleTimeString("de-DE", { timeZone: TIME_ZONE, hour: "2-digit", minute: "2-digit" });
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import { curatorAdminRouter } from "@/trpc/routers/curator-admin";
|
||||
import { lostReportsRouter } from "@/trpc/routers/lost-reports";
|
||||
import { lostReportAdminRouter } from "@/trpc/routers/lost-report-admin";
|
||||
import { adminOverviewRouter } from "@/trpc/routers/admin-overview";
|
||||
import { adminAuditRouter } from "@/trpc/routers/admin-audit";
|
||||
import { petAdminRouter } from "@/trpc/routers/pet-admin";
|
||||
|
||||
export const appRouter = router({
|
||||
@@ -67,6 +68,7 @@ export const appRouter = router({
|
||||
lostReports: lostReportsRouter,
|
||||
lostReportAdmin: lostReportAdminRouter,
|
||||
adminOverview: adminOverviewRouter,
|
||||
adminAudit: adminAuditRouter,
|
||||
petAdmin: petAdminRouter,
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { clerkClient } from "@clerk/nextjs/server";
|
||||
import { AdminRoleType, type PrismaClient } from "@prisma/client";
|
||||
import { router, protectedProcedure } from "@/trpc/init";
|
||||
import { assertAdmin } from "@/trpc/routers/admin";
|
||||
import { AUDIT_ACTIONS_BY_CATEGORY, auditRankId, type AuditCategory } from "@/lib/admin/audit-format";
|
||||
|
||||
const CATEGORIES = Object.keys(AUDIT_ACTIONS_BY_CATEGORY) as [AuditCategory, ...AuditCategory[]];
|
||||
const CLERK_LOOKUP_LIMIT = 100;
|
||||
/** Automatische Einträge (z. B. Sperrlisten-Treffer in posts.create) schreiben diese moderatorId. */
|
||||
const SYSTEM_MODERATOR = "SYSTEM";
|
||||
|
||||
const unique = <T,>(values: (T | null | undefined)[]) => [...new Set(values.filter((v): v is T => v != null))];
|
||||
|
||||
/** Anzeigenamen von Clerk-Usern (Vor- + Nachname, sonst E-Mail). Fehler bei Clerk → leere Map statt kaputtem Protokoll. */
|
||||
async function clerkNames(ids: string[]): Promise<Map<string, string>> {
|
||||
if (ids.length === 0) return new Map();
|
||||
try {
|
||||
const clerk = await clerkClient();
|
||||
const { data } = await clerk.users.getUserList({ userId: ids.slice(0, CLERK_LOOKUP_LIMIT), limit: CLERK_LOOKUP_LIMIT });
|
||||
return new Map(
|
||||
data.map((u) => [
|
||||
u.id,
|
||||
[u.firstName, u.lastName].filter(Boolean).join(" ") || u.primaryEmailAddress?.emailAddress || u.emailAddresses[0]?.emailAddress || u.id,
|
||||
])
|
||||
);
|
||||
} catch {
|
||||
return new Map();
|
||||
}
|
||||
}
|
||||
|
||||
type LogRow = { id: string; action: string; targetType: string; targetId: string; reason: string | null; moderatorId: string };
|
||||
|
||||
/** Löst Ziele (Tier, Halter, Beitrags-Autor, Werbung, Musik) und Rangnamen für eine Seite Protokoll auf. */
|
||||
async function resolveNames(prisma: PrismaClient, rows: LogRow[]) {
|
||||
const idsOf = (type: string) => unique(rows.filter((r) => r.targetType === type).map((r) => r.targetId));
|
||||
const rankIds = unique(rows.map((r) => auditRankId(r.action, r.targetId, r.reason)));
|
||||
const userIds = unique([...idsOf("USER"), ...rows.map((r) => r.moderatorId).filter((id) => id !== SYSTEM_MODERATOR)]);
|
||||
|
||||
const [people, pets, posts, ads, tracks, ranks] = await Promise.all([
|
||||
clerkNames(userIds),
|
||||
idsOf("PET").length ? prisma.pet.findMany({ where: { id: { in: idsOf("PET") } }, select: { id: true, name: true } }) : [],
|
||||
idsOf("POST").length ? prisma.post.findMany({ where: { id: { in: idsOf("POST") } }, select: { id: true, pet: { select: { name: true } } } }) : [],
|
||||
idsOf("AD").length ? prisma.advertisement.findMany({ where: { id: { in: idsOf("AD") } }, select: { id: true, title: true } }) : [],
|
||||
idsOf("MUSIC_TRACK").length ? prisma.musicTrack.findMany({ where: { id: { in: idsOf("MUSIC_TRACK") } }, select: { id: true, title: true } }) : [],
|
||||
rankIds.length ? prisma.referralRank.findMany({ where: { id: { in: rankIds } }, select: { id: true, nameDe: true } }) : [],
|
||||
]);
|
||||
|
||||
const targets = new Map<string, string>([
|
||||
...[...people].map(([id, name]) => [`USER:${id}`, name] as [string, string]),
|
||||
...pets.map((p) => [`PET:${p.id}`, p.name] as [string, string]),
|
||||
...posts.map((p) => [`POST:${p.id}`, p.pet.name] as [string, string]),
|
||||
...ads.map((a) => [`AD:${a.id}`, a.title] as [string, string]),
|
||||
...tracks.map((t) => [`MUSIC_TRACK:${t.id}`, t.title] as [string, string]),
|
||||
]);
|
||||
return { people, targets, rankNames: new Map(ranks.map((r) => [r.id, r.nameDe])) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Lesbares Moderations-Protokoll (/p/[secret]/log): Namen statt IDs, Filter nach
|
||||
* Kategorie und Moderator. Das Formulieren übernimmt formatAuditEntry im Client.
|
||||
*/
|
||||
export const adminAuditRouter = router({
|
||||
list: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
cursor: z.string().nullish(),
|
||||
limit: z.number().min(1).max(100).default(40),
|
||||
category: z.enum(CATEGORIES).optional(),
|
||||
moderatorId: z.string().min(1).optional(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
const rows = await ctx.prisma.moderationLog.findMany({
|
||||
where: {
|
||||
...(input.category ? { action: { in: [...AUDIT_ACTIONS_BY_CATEGORY[input.category]] } } : {}),
|
||||
...(input.moderatorId ? { moderatorId: input.moderatorId } : {}),
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: input.limit + 1,
|
||||
...(input.cursor ? { skip: 1, cursor: { id: input.cursor } } : {}),
|
||||
});
|
||||
const hasNext = rows.length > input.limit;
|
||||
const items = hasNext ? rows.slice(0, input.limit) : rows;
|
||||
const { people, targets, rankNames } = await resolveNames(ctx.prisma, items);
|
||||
|
||||
return {
|
||||
entries: items.map((e) => {
|
||||
const rankId = auditRankId(e.action, e.targetId, e.reason);
|
||||
return {
|
||||
id: e.id,
|
||||
action: e.action,
|
||||
targetType: e.targetType,
|
||||
targetId: e.targetId,
|
||||
reason: e.reason,
|
||||
createdAt: e.createdAt,
|
||||
ipAddress: e.ipAddress,
|
||||
moderatorId: e.moderatorId,
|
||||
moderatorRole: e.moderatorRole,
|
||||
moderatorName: e.moderatorId === SYSTEM_MODERATOR ? null : (people.get(e.moderatorId) ?? null),
|
||||
isAutomatic: e.moderatorId === SYSTEM_MODERATOR,
|
||||
targetLabel: targets.get(`${e.targetType}:${e.targetId}`) ?? null,
|
||||
rankName: rankId ? (rankNames.get(rankId) ?? null) : null,
|
||||
};
|
||||
}),
|
||||
nextCursor: hasNext ? items[items.length - 1]!.id : null,
|
||||
};
|
||||
}),
|
||||
|
||||
/** Alle, die je etwas im Protokoll getan haben — für den Moderator-Filter (Name statt Clerk-ID). */
|
||||
moderators: protectedProcedure.query(async ({ ctx }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
const grouped = await ctx.prisma.moderationLog.groupBy({ by: ["moderatorId"], _count: { _all: true } });
|
||||
const ids = grouped.map((g) => g.moderatorId).filter((id) => id !== SYSTEM_MODERATOR);
|
||||
const names = await clerkNames(ids);
|
||||
return grouped
|
||||
.map((g) => ({
|
||||
id: g.moderatorId,
|
||||
name: g.moderatorId === SYSTEM_MODERATOR ? "Automatik" : (names.get(g.moderatorId) ?? g.moderatorId),
|
||||
count: g._count._all,
|
||||
}))
|
||||
.sort((a, b) => b.count - a.count);
|
||||
}),
|
||||
});
|
||||
@@ -1743,48 +1743,6 @@ export const adminRouter = router({
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
getModerationLog: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
cursor: z.string().nullish(),
|
||||
limit: z.number().min(1).max(100).default(50),
|
||||
action: z.string().optional(),
|
||||
targetType: z.string().optional(),
|
||||
moderatorId: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
const entries = await ctx.prisma.moderationLog.findMany({
|
||||
where: {
|
||||
...(input.action ? { action: input.action } : {}),
|
||||
...(input.targetType ? { targetType: input.targetType } : {}),
|
||||
...(input.moderatorId ? { moderatorId: input.moderatorId } : {}),
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: input.limit + 1,
|
||||
...(input.cursor ? { skip: 1, cursor: { id: input.cursor } } : {}),
|
||||
});
|
||||
const hasNext = entries.length > input.limit;
|
||||
const items = hasNext ? entries.slice(0, input.limit) : entries;
|
||||
|
||||
// moderatorId is a raw ownerId — resolve a display name the same way
|
||||
// listModerators does, so the log doesn't just show opaque Clerk IDs.
|
||||
const moderatorIds = [...new Set(items.map((e) => e.moderatorId))];
|
||||
const owners = moderatorIds.length > 0
|
||||
? await ctx.prisma.owner.findMany({
|
||||
where: { id: { in: moderatorIds } },
|
||||
select: { id: true, pets: { select: { name: true, nickname: true }, take: 1 } },
|
||||
})
|
||||
: [];
|
||||
const nameByOwnerId = new Map(owners.map((o) => [o.id, o.pets[0]?.name ?? null]));
|
||||
|
||||
return {
|
||||
entries: items.map((e) => ({ ...e, moderatorName: nameByOwnerId.get(e.moderatorId) ?? null })),
|
||||
nextCursor: hasNext ? items[items.length - 1]!.id : null,
|
||||
};
|
||||
}),
|
||||
|
||||
/** Action count per moderator over the trailing window — throughput for the Moderators page. */
|
||||
getModeratorThroughput: protectedProcedure
|
||||
.input(z.object({ days: z.number().min(1).max(365).default(30) }))
|
||||
|
||||
Reference in new issue
Block a user