import { useCallback, useEffect, useMemo, useState } from 'react'; import { Activity, RefreshCw, Search, ChevronLeft, ChevronRight, Eye, User as UserIcon, Filter } from 'lucide-react'; import { toast } from 'sonner'; import { API } from '@/api/API'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { Input } from '@/components/ui/input'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; type SystemAuditLog = { id: string; module: string; moduleLabel: string; action: string; actionLabel: string; entityType: string; entityId: string | null; entityLabel: string | null; description: string; actor: { id: string | null; name: string; role: string | null; email: string | null; }; oldData: any; newData: any; metadata: any; ipAddress: string | null; userAgent: string | null; timestamp: string; }; type Summary = { totalEntries: number; byModule: { module: string; moduleLabel: string; total: number }[]; lastActivity: SystemAuditLog | null; }; const MODULE_OPTIONS = [ { value: '__all__', label: 'All Modules' }, { value: 'QUESTIONNAIRE', label: 'Questionnaire' }, { value: 'INTERVIEW_CONFIG', label: 'Interview Configuration' }, { value: 'SYSTEM_CONFIG', label: 'System Configuration' }, { value: 'SLA_CONFIG', label: 'SLA Configuration' }, { value: 'EMAIL_TEMPLATE', label: 'Email Template' }, { value: 'MASTER_HIERARCHY', label: 'Master Hierarchy' }, { value: 'ROLE_ASSIGNMENT', label: 'Role Assignment' }, { value: 'USER_ADMIN', label: 'User Administration' }, { value: 'DEALER_MAPPING', label: 'Dealer Mapping' } ]; const ACTION_OPTIONS = [ { value: '__all__', label: 'All Actions' }, { value: 'CREATED', label: 'Created' }, { value: 'UPDATED', label: 'Updated' }, { value: 'DELETED', label: 'Deleted' }, { value: 'ACTIVATED', label: 'Activated' }, { value: 'DEACTIVATED', label: 'Deactivated' }, { value: 'INITIALIZED', label: 'Initialized' }, { value: 'SUBMITTED', label: 'Submitted' }, { value: 'ASSIGNED', label: 'Assigned' }, { value: 'UNASSIGNED', label: 'Unassigned' }, { value: 'REORDERED', label: 'Reordered' } ]; const ACTION_BADGE_CLASS: Record = { CREATED: 'bg-emerald-100 text-emerald-700 border-emerald-200', UPDATED: 'bg-blue-100 text-blue-700 border-blue-200', DELETED: 'bg-rose-100 text-rose-700 border-rose-200', ACTIVATED: 'bg-emerald-100 text-emerald-700 border-emerald-200', DEACTIVATED: 'bg-slate-200 text-slate-700 border-slate-300', INITIALIZED: 'bg-amber-100 text-amber-700 border-amber-200', SUBMITTED: 'bg-indigo-100 text-indigo-700 border-indigo-200', ASSIGNED: 'bg-violet-100 text-violet-700 border-violet-200', UNASSIGNED: 'bg-slate-200 text-slate-700 border-slate-300', REORDERED: 'bg-sky-100 text-sky-700 border-sky-200' }; const formatTimestamp = (ts: string) => { try { const d = new Date(ts); return d.toLocaleString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }); } catch { return ts; } }; const JsonBlock = ({ value }: { value: any }) => { if (value === null || value === undefined) { return

; } return (
            {JSON.stringify(value, null, 2)}
        
); }; export const SystemLogsPage: React.FC = () => { const [logs, setLogs] = useState([]); const [summary, setSummary] = useState(null); const [loading, setLoading] = useState(false); const [page, setPage] = useState(1); const [limit] = useState(25); const [totalPages, setTotalPages] = useState(1); const [totalEntries, setTotalEntries] = useState(0); const [moduleFilter, setModuleFilter] = useState('__all__'); const [actionFilter, setActionFilter] = useState('__all__'); const [search, setSearch] = useState(''); const [dateFrom, setDateFrom] = useState(''); const [dateTo, setDateTo] = useState(''); const [appliedSearch, setAppliedSearch] = useState(''); const [selected, setSelected] = useState(null); const queryParams = useMemo( () => ({ module: moduleFilter !== '__all__' ? moduleFilter : undefined, action: actionFilter !== '__all__' ? actionFilter : undefined, search: appliedSearch || undefined, dateFrom: dateFrom || undefined, dateTo: dateTo || undefined, page, limit }), [moduleFilter, actionFilter, appliedSearch, dateFrom, dateTo, page, limit] ); const fetchLogs = useCallback(async () => { setLoading(true); try { const res = (await API.getSystemAuditLogs(queryParams)) as any; const body = res?.data; if (res?.ok && body?.success) { setLogs(body.data || []); setTotalPages(body.pagination?.totalPages || 1); setTotalEntries(body.pagination?.total || 0); } else { toast.error(body?.message || 'Unable to load system logs'); setLogs([]); } } catch (err) { console.error('[SystemLogsPage] fetchLogs error:', err); toast.error('Failed to load system logs'); setLogs([]); } finally { setLoading(false); } }, [queryParams]); const fetchSummary = useCallback(async () => { try { const res = (await API.getSystemAuditSummary()) as any; const body = res?.data; if (res?.ok && body?.success) { setSummary(body.data || null); } } catch (err) { console.error('[SystemLogsPage] fetchSummary error:', err); } }, []); useEffect(() => { fetchLogs(); }, [fetchLogs]); useEffect(() => { fetchSummary(); }, [fetchSummary]); const applySearch = () => { setPage(1); setAppliedSearch(search.trim()); }; const clearFilters = () => { setModuleFilter('__all__'); setActionFilter('__all__'); setSearch(''); setAppliedSearch(''); setDateFrom(''); setDateTo(''); setPage(1); }; return (

System Activity Logs

Configuration-level changes across questionnaires, interview configs, master hierarchy, system / SLA configs, and role assignments.

{/* Summary */}
Total Events

{summary?.totalEntries ?? '—'}

Lifetime

{(summary?.byModule || []).slice(0, 4).map((row) => ( {row.moduleLabel}

{row.total}

))}
{/* Filters */}
setSearch(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') applySearch(); }} />
{ setDateFrom(e.target.value); setPage(1); }} />
{ setDateTo(e.target.value); setPage(1); }} />
Showing {logs.length} of {totalEntries} matching event(s)
{/* Logs table */}
{loading && ( )} {!loading && logs.length === 0 && ( )} {!loading && logs.map((log) => ( setSelected(log)} > ))}
When Module Action Entity Actor Description
Loading system logs…
No events match the current filters.
{formatTimestamp(log.timestamp)} {log.moduleLabel} {log.actionLabel}
{log.entityLabel || `${log.entityType}`}
{log.entityId && (
{log.entityId}
)}
{(log.actor?.name || 'S').charAt(0).toUpperCase()}
{log.actor?.name || 'System'}
{log.actor?.role && (
{log.actor.role}
)}
{log.description}
{/* Pagination */}
Page {page} of {totalPages}
{/* Detail dialog */} !open && setSelected(null)}> {selected && ( <> {selected.moduleLabel} · {selected.actionLabel} {selected.description}

Entity

{selected.entityLabel || selected.entityType}

{selected.entityId && (

{selected.entityId}

)}

Actor

{selected.actor?.name || 'System'}

{selected.actor?.role && (

{selected.actor.role}

)} {selected.actor?.email && (

{selected.actor.email}

)}

When

{formatTimestamp(selected.timestamp)}

Source

{selected.ipAddress || '—'}

{selected.userAgent || ''}

Previous values

New values

{selected.metadata && (

Metadata

)} )}
); }; export default SystemLogsPage;