All files / pages AuditLogsPage.tsx

70.9% Statements 39/55
81.25% Branches 26/32
60% Functions 9/15
72.22% Lines 39/54

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265                                            66x 66x 66x     66x 66x 66x 66x     66x 66x 66x 66x     66x 66x   66x 30x 30x   30x 30x                   30x 25x   4x   29x       66x 28x     66x 1x 1x 1x     66x                 66x 2x 2x         2x           66x             66x                 1x       1x                                   4x                                   5x                                                                                                                                                                                                                            
/**
 * Audit logs viewer page
 */
 
import { useEffect, useState, useCallback } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { FileText, Search, RefreshCw, Download, Filter } from 'lucide-react';
import AuditLogsTable from '@/components/audit-logs/AuditLogsTable';
import AuditLogDetailDialog from '@/components/audit-logs/AuditLogDetailDialog';
import {
    getAuditLogs,
    exportAuditLogs,
    type AuditLogItem,
    type AuditLogListResponse,
    type AuditLogFilters,
} from '@/services/audit.service';
import { handleApiError } from '@/lib/api';
 
export default function AuditLogsPage() {
    const [data, setData] = useState<AuditLogListResponse | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
 
    // Pagination and filtering state
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [sortBy, setSortBy] = useState('occurred_at');
    const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
 
    // Filters
    const [tableName, setTableName] = useState('');
    const [operation, setOperation] = useState('all');
    const [recordId, setRecordId] = useState('');
    const [showFilters, setShowFilters] = useState(false);
 
    // Dialog state
    const [detailDialogOpen, setDetailDialogOpen] = useState(false);
    const [selectedLog, setSelectedLog] = useState<AuditLogItem | null>(null);
 
    const fetchLogs = useCallback(async () => {
        setLoading(true);
        setError(null);
 
        try {
            const filters: AuditLogFilters = {
                skip: (page - 1) * pageSize,
                limit: pageSize,
                sort_by: sortBy,
                sort_order: sortOrder,
                table_name: tableName || undefined,
                operation: operation !== 'all' ? operation : undefined,
                record_id: recordId || undefined,
            };
 
            const response = await getAuditLogs(filters);
            setData(response);
        } catch (err) {
            setError(handleApiError(err));
        } finally {
            setLoading(false);
        }
    }, [page, pageSize, sortBy, sortOrder, tableName, operation, recordId]);
 
    useEffect(() => {
        fetchLogs();
    }, [fetchLogs]);
 
    const handleSearch = (e?: React.FormEvent) => {
        e?.preventDefault();
        setPage(1);
        fetchLogs();
    };
 
    const handleSort = (column: string) => {
        if (sortBy === column) {
            setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
        } else {
            setSortBy(column);
            setSortOrder('desc');
        }
    };
 
    const handleExport = async (format: 'csv' | 'json') => {
        try {
            const filters: AuditLogFilters = {
                table_name: tableName || undefined,
                operation: operation !== 'all' ? operation : undefined,
                record_id: recordId || undefined,
            };
            await exportAuditLogs(format, filters);
        } catch (err) {
            alert('Failed to export: ' + handleApiError(err));
        }
    };
 
    const handleView = (log: AuditLogItem) => {
        setSelectedLog(log);
        setDetailDialogOpen(true);
    };
 
 
 
    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold">Audit Logs</h1>
                    <p className="text-muted-foreground mt-2">View and export GxP-compliant audit trails</p>
                </div>
                <div className="flex gap-2">
                    <Button variant="outline" onClick={() => handleExport('csv')} className="gap-2">
                        <Download className="h-4 w-4" />
                        Export CSV
                    </Button>
                    <Button variant="outline" onClick={() => handleExport('json')} className="gap-2">
                        <Download className="h-4 w-4" />
                        Export JSON
                    </Button>
                </div>
            </div>
 
            {/* Filters and Actions */}
            <Card>
                <CardHeader className="pb-3">
                    <div className="flex items-center justify-between">
                        <CardTitle className="flex items-center gap-2">
                            <FileText className="h-5 w-5 text-primary" />
                            Audit Log Viewer
                        </CardTitle>
                        <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => setShowFilters(!showFilters)}
                            className="gap-2"
                        >
                            <Filter className="h-4 w-4" />
                            {showFilters ? 'Hide Filters' : 'Show Filters'}
                        </Button>
                    </div>
                    <CardDescription>
                        Track all data changes with column-level granularity and integrity protection
                    </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    {/* Filter Bar */}
                    <form onSubmit={handleSearch} className={`grid gap-4 transition-all ${showFilters ? 'grid-cols-4' : 'hidden'}`}>
                        <div className="space-y-2">
                            <label className="text-xs font-medium text-muted-foreground uppercase">Collection</label>
                            <Input
                                value={tableName}
                                onChange={(e) => setTableName(e.target.value)}
                                placeholder="Filter by collection..."
                                size={1}
                            />
                        </div>
                        <div className="space-y-2">
                            <label className="text-xs font-medium text-muted-foreground uppercase">Operation</label>
                            <Select value={operation} onValueChange={setOperation}>
                                <SelectTrigger>
                                    <SelectValue placeholder="All Operations" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">All Operations</SelectItem>
                                    <SelectItem value="CREATE">CREATE</SelectItem>
                                    <SelectItem value="UPDATE">UPDATE</SelectItem>
                                    <SelectItem value="DELETE">DELETE</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                        <div className="space-y-2">
                            <label className="text-xs font-medium text-muted-foreground uppercase">Record ID</label>
                            <Input
                                value={recordId}
                                onChange={(e) => setRecordId(e.target.value)}
                                placeholder="Filter by record ID..."
                            />
                        </div>
                        <div className="flex items-end gap-2">
                            <Button type="submit" variant="secondary" className="flex-1">
                                <Search className="h-4 w-4 mr-2" />
                                Filter
                            </Button>
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => {
                                    setTableName('');
                                    setOperation('all');
                                    setRecordId('');
                                    setPage(1);
                                    setTimeout(() => handleSearch(), 0);
                                }}
                            >
                                Reset
                            </Button>
                        </div>
                    </form>
 
                    {!showFilters && (
                        <div className="flex justify-end">
                            <Button
                                type="button"
                                variant="outline"
                                size="icon"
                                onClick={fetchLogs}
                                disabled={loading}
                            >
                                <RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
                            </Button>
                        </div>
                    )}
 
                    {/* Error State */}
                    {error && (
                        <div className="bg-destructive/10 border border-destructive/20 rounded-lg p-4">
                            <p className="text-destructive font-medium">Failed to load audit logs</p>
                            <p className="text-sm text-muted-foreground mt-1">{error}</p>
                            <Button onClick={fetchLogs} className="mt-4" size="sm">
                                Try Again
                            </Button>
                        </div>
                    )}
 
                    {/* Loading State */}
                    {loading && !data && (
                        <div className="flex items-center justify-center py-12">
                            <RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
                        </div>
                    )}
 
                    {/* Table */}
                    {!loading && data && (
                        <AuditLogsTable
                            logs={data.items}
                            sortBy={sortBy}
                            sortOrder={sortOrder}
                            onSort={handleSort}
                            onView={handleView}
                            totalItems={data.total}
                            page={page}
                            pageSize={pageSize}
                            onPageChange={setPage}
                            onPageSizeChange={(size) => {
                                setPageSize(size);
                                setPage(1);
                            }}
                        />
                    )}
                </CardContent>
            </Card>
 
            {/* Detail Dialog */}
            <AuditLogDetailDialog
                open={detailDialogOpen}
                onOpenChange={setDetailDialogOpen}
                log={selectedLog}
            />
        </div>
    );
}