From 4187a1a51994fb475ecb95bca13d6d55483f0d9b Mon Sep 17 00:00:00 2001 From: neodk2004 Date: Mon, 5 Oct 2026 08:05:41 +0200 Subject: [PATCH] feat(admin): Protokoll in Klartext und Halter als Tabelle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/__tests__/admin-audit.test.ts | 122 +++ src/__tests__/helpers/prisma-mock.ts | 2 + src/app/p/[secret]/log/page.tsx | 352 +++---- src/app/p/[secret]/users/page.tsx | 884 ++++++------------ .../admin/users/UserActionDialogs.tsx | 240 +++++ src/lib/admin/audit-format.test.ts | 67 ++ src/lib/admin/audit-format.ts | 270 ++++++ src/lib/admin/format.test.ts | 12 +- src/lib/admin/format.ts | 24 + src/trpc/routers/_app.ts | 2 + src/trpc/routers/admin-audit.ts | 126 +++ src/trpc/routers/admin.ts | 42 - 12 files changed, 1352 insertions(+), 791 deletions(-) create mode 100644 src/__tests__/admin-audit.test.ts create mode 100644 src/components/admin/users/UserActionDialogs.tsx create mode 100644 src/lib/admin/audit-format.test.ts create mode 100644 src/lib/admin/audit-format.ts create mode 100644 src/trpc/routers/admin-audit.ts diff --git a/src/__tests__/admin-audit.test.ts b/src/__tests__/admin-audit.test.ts new file mode 100644 index 0000000..064bf59 --- /dev/null +++ b/src/__tests__/admin-audit.test.ts @@ -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; +const ctx = (prisma: MockPrisma) => ({ userId: "admin-1", prisma: prisma as never, locale: "de", ip: "127.0.0.1" }); +const row = (over: Record) => ({ + 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); + }); +}); diff --git a/src/__tests__/helpers/prisma-mock.ts b/src/__tests__/helpers/prisma-mock.ts index 4629ca9..3137450 100644 --- a/src/__tests__/helpers/prisma-mock.ts +++ b/src/__tests__/helpers/prisma-mock.ts @@ -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(), diff --git a/src/app/p/[secret]/log/page.tsx b/src/app/p/[secret]/log/page.tsx index 5ef787d..0404eff 100644 --- a/src/app/p/[secret]/log/page.tsx +++ b/src/app/p/[secret]/log/page.tsx @@ -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["adminAudit"]["list"]["entries"][number]; -const TARGET_TYPES = ["POST", "COMMENT", "USER", "REPORT", "AD", "SYSTEM"] as const; - -const ROLE_BADGE_CLASS: Record = { - 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> = { + 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 ( +
  • + + + +
    +

    + {actor}{" "} + {view.parts.map((part, i) => (typeof part === "string" ? {part} : {part.strong}))} +

    + {view.details.map((line) => ( +

    + {line} +

    + ))} +
    + {AUDIT_CATEGORY_LABEL[view.category as AuditCategory] ?? "Sonstiges"} + {role && · {role}} + +
    + {isOpen && ( +
    +
    Aktion
    +
    {entry.action}
    +
    Ziel
    +
    + {entry.targetType} · {entry.targetId} +
    +
    Von
    +
    {entry.moderatorId}
    + {entry.ipAddress && ( + <> +
    IP
    +
    {entry.ipAddress}
    + + )} + {entry.reason && ( + <> +
    Rohtext
    +
    {entry.reason}
    + + )} +
    + )} +
    + +
  • + ); +} + +/** + * 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("all"); - const [targetType, setTargetType] = useState("all"); - const [moderatorId, setModeratorId] = useState(""); + const [category, setCategory] = useState(ALL); + const [moderatorId, setModeratorId] = useState(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 (
    - +

    - {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."}

    ); } return ( -
    -
    -

    Protokoll

    -
    - setModeratorId(e.target.value)} - className="w-56 bg-card border-border text-foreground placeholder:text-muted-foreground font-mono text-sm" - /> - - -
    + } + /> + +
    + {[ALL, ...CATEGORIES].map((c) => ( + + ))}
    {isLoading ? ( -
    - +
    +
    - ) : entries.length === 0 ? ( -

    No entries match these filters

    + ) : days.length === 0 ? ( +

    + Für diese Auswahl gibt es keine Einträge. +

    ) : ( -
    - {/* 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. */} -
    -
    -
    - Action - Target - Moderator - IP - Time -
    - {entries.map((entry) => ( -
    -
    - - {entry.action} - -

    - {entry.targetType} · {entry.targetId} -

    -
    -

    - - {entry.moderatorName ?? unnamed} - - {entry.moderatorRole && ( - - {entry.moderatorRole} - - )} -

    -

    - {entry.moderatorId} -

    -
    -

    - {entry.ipAddress ?? "—"} -

    -

    - {new Date(entry.createdAt).toLocaleString()} -

    -
    - {entry.reason && ( -

    - Reason: {entry.reason} -

    - )} -
    - ))} -
    -
    - +
    + {days.map((day) => ( +
    +

    {day.heading}

    +
      + {day.entries.map((entry) => ( + + ))} +
    +
    + ))} {hasNextPage && ( -
    - + {isFetchingNextPage && } + Ältere Einträge laden +
    )}
    diff --git a/src/app/p/[secret]/users/page.tsx b/src/app/p/[secret]/users/page.tsx index e30dbc6..8d44cb8 100644 --- a/src/app/p/[secret]/users/page.tsx +++ b/src/app/p/[secret]/users/page.tsx @@ -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["admin"]["listUsers"]["users"][number]; +const BAN_STATUS_LABEL: Record = { all: "Alle Status", banned: "Nur gesperrte", active: "Nur aktive" }; +const ROLE_FILTER_LABEL: Record = { + 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 && Gesperrt, + user.shadowban && Shadowban, + user._count.warnings > 0 && ( + + {user._count.warnings === 1 ? "1 Verwarnung" : `${user._count.warnings} Verwarnungen`} + + ), + sponsor && Sponsor, + ].filter(Boolean); + return
    {badges.length > 0 ? badges : Aktiv}
    ; +} + +/** + * 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(null); - const [unbanTarget, setUnbanTarget] = useState(null); - const [banReason, setBanReason] = useState(""); - const [banExpiry, setBanExpiry] = useState(""); - const [shadowbanTarget, setShadowbanTarget] = useState(null); - const [unshadowbanTarget, setUnshadowbanTarget] = useState(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("all"); const [role, setRole] = useState("all"); - const [warnTarget, setWarnTarget] = useState(null); - const [warnReason, setWarnReason] = useState(""); - const [deleteTarget, setDeleteTarget] = useState(null); - const [deleteConfirmation, setDeleteConfirmation] = useState(""); + const [expandedId, setExpandedId] = useState(null); + const [actionTarget, setActionTarget] = useState(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 ( -
    -
    -

    Halter

    -
    - + + +
    +
    + + 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" /> -
    - - -
    +
    +
    + +
    {isLoading ? ( -
    - +
    +
    + ) : users.length === 0 ? ( +

    Keine Halter für diese Suche.

    ) : ( -
    - {users.map((user) => ( -
    -
    -
    -

    {user.id}

    - {isActiveSponsor({ - sponsorSince: user.sponsorSince ? new Date(user.sponsorSince) : null, - sponsorPeriodEnd: user.sponsorPeriodEnd ? new Date(user.sponsorPeriodEnd) : null, - }) && ( - +
    + Halter + Tiere + Status + Rolle + Aktionen +
    +
      + {users.map((user) => { + const name = displayName(user); + const isExpanded = expandedId === user.id; + const firstPet = user.pets[0]; + return ( +
    • +
      +
      - {user.clerk && ( -

      - {user.clerk.name ? `${user.clerk.name} · ` : ""} - {user.clerk.email ?? "no email on file"} -

      - )} -

      - {user._count.pets} pet{user._count.pets !== 1 ? "s" : ""} - {user._count.warnings > 0 && - ` · ${user._count.warnings} warning${user._count.warnings !== 1 ? "s" : ""}`} -

      - {user.pets.length > 0 && ( -
      - {user.pets.map((pet) => ( - - ))} -
      - )} - {user.ban?.reason && ( -

      Reason: {user.ban.reason}

      - )} - {user.shadowban?.reason && ( -

      Shadowban: {user.shadowban.reason}

      - )} -
    -
    - {user.pets[0] && ( - - )} - - - {canDeleteAccounts && ( - - )} - {user.shadowban ? ( - - ) : ( - - )} - {user.ban ? ( - - ) : ( - - )} -
    -
    - ))} + + {initials(name)} + + + {name} + {user.clerk?.name ? user.clerk.email : "Keine E-Mail hinterlegt"} + + + - {hasNextPage && ( -
    - -
    - )} +
    + {user.pets.length === 0 && Noch kein Tier} + {user.pets.map((pet) => ( + + ))} + {user._count.pets > user.pets.length && ( + +{user._count.pets - user.pets.length} weitere + )} +
    + +
    + +
    + + {user.adminRole ? ADMIN_ROLE_LABEL[user.adminRole.role] : "–"} + +
    + {firstPet && ( + + )} + + + + + + exportData.mutate({ ownerId: user.id })} disabled={exportData.isPending}> + Daten exportieren (DSGVO) + + openAction("WARN", user)}> + Verwarnungen … + + + openAction(user.shadowban ? "UNSHADOWBAN" : "SHADOWBAN", user)}> + {user.shadowban ? "Shadowban aufheben" : "Shadowban setzen …"} + + {user.ban ? ( + openAction("UNBAN", user)}> + Sperre aufheben + + ) : ( + openAction("BAN", user)}> + Sperren … + + )} + {canDeleteAccounts && ( + <> + + openAction("DELETE", user)}> + Konto löschen … + + + )} + + + +
    +
    + + {isExpanded && ( +
    +
    +
    Registriert
    +
    {user.clerk?.createdAt ? formatEventTime(new Date(user.clerk.createdAt)) : "–"}
    +
    +
    +
    Tiere gesamt
    +
    {user._count.pets}
    +
    +
    +
    Rolle
    +
    {user.adminRole ? ADMIN_ROLE_LABEL[user.adminRole.role] : "Keine"}
    +
    + {user.ban && ( +
    +
    Gesperrt
    +
    + {user.ban.reason || "Ohne Begründung"} + {user.ban.expiresAt ? ` · bis ${formatEventTime(new Date(user.ban.expiresAt))}` : " · dauerhaft"} +
    +
    + )} + {user.shadowban && ( +
    +
    Shadowban
    +
    {user.shadowban.reason}
    +
    + )} +
    +
    Konto-ID
    +
    {user.id}
    +
    +
    + )} + + ); + })} +
    )} - {/* Ban dialog */} - { if (!o) { setBanTarget(null); setBanReason(""); setBanExpiry(""); } }} - > - - - Ban user - -

    {banTarget}

    - setBanReason(e.target.value)} - className="bg-muted border-border text-foreground placeholder:text-muted-foreground" - /> -
    - - setBanExpiry(e.target.value)} - className="bg-muted border-border text-foreground" - /> -
    - - - - -
    -
    + {hasNextPage && ( +
    + +
    + )} - {/* Unban confirm */} - { if (!o) setUnbanTarget(null); }}> - - - Unban user - -

    Remove the ban for this user?

    - - - - -
    -
    - - {/* Shadowban dialog */} - { if (!o) { setShadowbanTarget(null); setShadowbanReason(""); } }} - > - - - Shadowban user - -

    {shadowbanTarget}

    -

    - Their posts quietly stop reaching anyone else — feed, explore, search, hashtags, - profile view. They keep posting normally and are never told. -

    - setShadowbanReason(e.target.value)} - className="bg-muted border-border text-foreground placeholder:text-muted-foreground" - /> - - - - -
    -
    - - {/* Un-shadowban confirm */} - { if (!o) setUnshadowbanTarget(null); }}> - - - Remove shadowban - -

    - Restore normal visibility for this user's posts? -

    - - - - -
    -
    - - {/* Warnings history + issue new */} - { if (!o) { setWarnTarget(null); setWarnReason(""); } }} - > - - - Warnings - -

    {warnTarget}

    -
    - {warningHistory.length === 0 ? ( -

    No warnings yet.

    - ) : ( - warningHistory.map((w) => ( -
    -

    {w.reason}

    -

    - {new Date(w.createdAt).toLocaleString()} -

    -
    - )) - )} -
    - setWarnReason(e.target.value)} - className="bg-muted border-border text-foreground placeholder:text-muted-foreground" - /> - - - - -
    -
    - - {/* Delete account (GDPR erasure, super-admin only) */} - { if (!o) { setDeleteTarget(null); setDeleteConfirmation(""); } }} - > - - - Delete account permanently - -

    - This permanently deletes the owner, all their pets, posts, and storage files, and - revokes their login. This cannot be undone. -

    -

    - Type the user ID to confirm:{" "} - {deleteTarget} -

    - setDeleteConfirmation(e.target.value)} - className="bg-muted border-border text-foreground placeholder:text-muted-foreground font-mono text-sm" - /> - - - - -
    -
    + setActionTarget(null)} />
    ); } diff --git a/src/components/admin/users/UserActionDialogs.tsx b/src/components/admin/users/UserActionDialogs.tsx new file mode 100644 index 0000000..211633e --- /dev/null +++ b/src/components/admin/users/UserActionDialogs.tsx @@ -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 && ; + const who = {target?.label}; + + return ( + <> + + + + Halter sperren + {who} kann sich danach nicht mehr anmelden. Alle Tiere des Halters sind betroffen. + + + + + + + + + + + + + + Sperre aufheben + {who} kann sich danach wieder anmelden. + + + + + + + + + + + + Shadowban setzen + + Beiträge von {who} erreichen niemanden mehr (Feed, Explore, Suche, Hashtags, Profil). Der Halter postet normal weiter und erfährt nichts davon. + + + + + + + + + + + + + + Shadowban aufheben + Beiträge von {who} sind danach wieder normal sichtbar. + + + + + + + + + + + + Verwarnungen + Bisherige Verwarnungen von {who} und eine neue aussprechen. + +
    + {isLoadingWarnings ? ( + + ) : warnings.length === 0 ? ( +

    Noch keine Verwarnungen.

    + ) : ( + warnings.map((w) => ( +
    +

    {w.reason}

    +

    {formatEventTime(new Date(w.createdAt))}

    +
    + )) + )} +
    +