import { useEffect, useState } from 'react' import { useInfiniteQuery, useQuery } from '@tanstack/react-query' import { useInView } from 'react-intersection-observer' import { client } from '@/ui/api/client' import { m } from '@/ui/paraglide/messages.js' import { AuditAction } from '@shumai/dtos' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@/ui/components/ui/table' import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar' import { Badge } from '@/ui/components/ui/badge' import { Input } from '@/ui/components/ui/input' import { Button } from '@/ui/components/ui/button' import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover' import { Checkbox } from '@/ui/components/ui/checkbox' import { Loader2, Search, Filter, Activity, X, Bot } from 'lucide-react' import { formatTimeAgo } from '@/ui/lib/time' const ALL_AUDIT_ACTIONS = Object.values(AuditAction) interface MemberInfo { id: string userId?: string name?: string image?: string user?: { id: string name?: string image?: string } } interface AuditLogsDashboardProps { teamId: string } export function AuditLogsDashboard({ teamId }: AuditLogsDashboardProps) { const [selectedActions, setSelectedActions] = useState([]) const [selectedUserIds, setSelectedUserIds] = useState([]) const [itemIdFilter, setItemIdFilter] = useState('') const { ref: loadMoreRef, inView } = useInView() // Fetch team members for user filter options const { data: membersData } = useQuery({ queryKey: ['teams', teamId, 'members'], queryFn: async () => { const res = await client.api.teams[':teamId'].members.$get({ param: { teamId }, query: {}, }) if (!res.ok) return [] return (await res.json()) as MemberInfo[] }, enabled: !!teamId, }) const teamMembers = membersData || [] // Infinite query for audit logs const { data, isLoading, isError, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({ queryKey: ['teams', teamId, 'audit-logs', selectedActions, selectedUserIds, itemIdFilter], queryFn: async ({ pageParam }) => { const res = await client.api.teams[':teamId']['audit-logs'].$get({ param: { teamId }, query: { first: '20', after: pageParam ? String(pageParam) : undefined, actions: selectedActions.length > 0 ? selectedActions : undefined, userIds: selectedUserIds.length > 0 ? selectedUserIds : undefined, itemId: itemIdFilter.trim() || undefined, }, }) if (!res.ok) throw new Error('Failed to fetch audit logs') return await res.json() }, initialPageParam: '', getNextPageParam: (lastPage) => lastPage.pageInfo.endCursor || undefined, enabled: !!teamId, }) useEffect(() => { if (inView && hasNextPage && !isFetchingNextPage) { fetchNextPage() } }, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]) const allLogs = data?.pages.flatMap((page) => page.nodes) || [] const totalCount = data?.pages[0]?.total ?? 0 const toggleAction = (action: AuditAction) => { setSelectedActions((prev) => prev.includes(action) ? prev.filter((a) => a !== action) : [...prev, action], ) } const toggleUser = (userId: string) => { setSelectedUserIds((prev) => prev.includes(userId) ? prev.filter((u) => u !== userId) : [...prev, userId], ) } const getActionBadge = (action: string) => { if (action.includes('delete') || action.includes('remove') || action.includes('revoke')) { return ( {action} ) } if (action.includes('create') || action.includes('add')) { return ( {action} ) } if (action.includes('update') || action.includes('reparent') || action.includes('copy')) { return ( {action} ) } return ( {action} ) } const memberMap = new Map(teamMembers.map((m) => [m.userId || m.id, m])) return (
{m.audit_logs()} {m.audit_logs_description()}
{totalCount > 0 && ( {totalCount} {m.audit_logs()} )}
{/* Filter Bar */}
{/* Action Multi-select */}
{m.select_actions()}
{ALL_AUDIT_ACTIONS.map((act) => ( ))}
{selectedActions.length > 0 && ( )}
{/* User Multi-select */}
{m.select_users()}
{teamMembers.map((member) => { const uId = member.userId || member.user?.id || member.id const uName = member.user?.name || member.name || uId const uImage = member.user?.image || member.image return ( ) })}
{selectedUserIds.length > 0 && ( )}
{/* Item ID Input */}
setItemIdFilter(e.target.value)} className="pl-8 pr-8 h-9 text-xs" /> {itemIdFilter && ( )}
{/* Reset All Filters */} {(selectedActions.length > 0 || selectedUserIds.length > 0 || itemIdFilter) && ( )}
{isLoading ? (
) : isError ? (
Failed to load audit logs.
) : allLogs.length === 0 ? (
{m.no_audit_logs()}
) : ( {m.action()} {m.user()} {m.item_id()} {m.project_id()} {m.timestamp()} {allLogs.map((log) => { const member = log.userId ? memberMap.get(log.userId) : null const userName = member?.user?.name || member?.name || log.userId || 'System' const userImage = member?.user?.image || member?.image return ( {getActionBadge(log.action)}
{userName.slice(0, 2).toUpperCase()} {log.agent ? m.user_via_agent({ user: userName, agent: log.agent.name, }) : userName} {log.agent && ( )}
{log.itemId || '-'} {log.projectId || '-'} {formatTimeAgo(log.createdAt)}
) })}
)} {/* Infinite Scroll sentinel */}
{isFetchingNextPage && ( )}
) }