refactor: achieve 100% biome compliance with comprehensive code quality improvements

- Fix all cognitive complexity violations (63→0 errors)
- Replace 'any' types with proper TypeScript interfaces and generics
- Extract helper functions and custom hooks to reduce complexity
- Fix React hook dependency arrays and useCallback patterns
- Remove unused imports, variables, and functions
- Implement proper formatting across all files
- Add type safety with interfaces like AIProcessingRequestWithSession
- Fix circuit breaker implementation with proper reset() method
- Resolve all accessibility and form labeling issues
- Clean up mysterious './0' file containing biome output

Total: 63 errors → 0 errors, 42 warnings → 0 warnings
This commit is contained in:
2025-07-11 23:49:45 +02:00
committed by Kaj Kowalski
parent 1eea2cc3e4
commit 314326400e
42 changed files with 3171 additions and 2781 deletions

View File

@ -2,7 +2,7 @@
import { formatDistanceToNow } from "date-fns";
import { useSession } from "next-auth/react";
import { useEffect, useState, useCallback } from "react";
import { useCallback, useEffect, useId, useState } from "react";
import { Alert, AlertDescription } from "../../../components/ui/alert";
import { Badge } from "../../../components/ui/badge";
import { Button } from "../../../components/ui/button";
@ -108,6 +108,11 @@ const severityColors: Record<string, string> = {
export default function AuditLogsPage() {
const { data: session } = useSession();
const eventTypeId = useId();
const outcomeId = useId();
const severityId = useId();
const startDateId = useId();
const endDateId = useId();
const [auditLogs, setAuditLogs] = useState<AuditLog[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@ -194,8 +199,8 @@ export default function AuditLogsPage() {
<div className="container mx-auto py-8">
<Alert>
<AlertDescription>
You don&apos;t have permission to view audit logs. Only administrators
can access this page.
You don&apos;t have permission to view audit logs. Only
administrators can access this page.
</AlertDescription>
</Alert>
</div>
@ -219,14 +224,16 @@ export default function AuditLogsPage() {
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<div>
<label className="text-sm font-medium">Event Type</label>
<label htmlFor={eventTypeId} className="text-sm font-medium">
Event Type
</label>
<Select
value={filters.eventType}
onValueChange={(value) =>
handleFilterChange("eventType", value)
}
>
<SelectTrigger>
<SelectTrigger id={eventTypeId}>
<SelectValue placeholder="All event types" />
</SelectTrigger>
<SelectContent>
@ -241,12 +248,14 @@ export default function AuditLogsPage() {
</div>
<div>
<label className="text-sm font-medium">Outcome</label>
<label htmlFor={outcomeId} className="text-sm font-medium">
Outcome
</label>
<Select
value={filters.outcome}
onValueChange={(value) => handleFilterChange("outcome", value)}
>
<SelectTrigger>
<SelectTrigger id={outcomeId}>
<SelectValue placeholder="All outcomes" />
</SelectTrigger>
<SelectContent>
@ -261,12 +270,14 @@ export default function AuditLogsPage() {
</div>
<div>
<label className="text-sm font-medium">Severity</label>
<label htmlFor={severityId} className="text-sm font-medium">
Severity
</label>
<Select
value={filters.severity}
onValueChange={(value) => handleFilterChange("severity", value)}
>
<SelectTrigger>
<SelectTrigger id={severityId}>
<SelectValue placeholder="All severities" />
</SelectTrigger>
<SelectContent>
@ -281,8 +292,11 @@ export default function AuditLogsPage() {
</div>
<div>
<label className="text-sm font-medium">Start Date</label>
<label htmlFor={startDateId} className="text-sm font-medium">
Start Date
</label>
<Input
id={startDateId}
type="datetime-local"
value={filters.startDate}
onChange={(e) =>
@ -292,8 +306,11 @@ export default function AuditLogsPage() {
</div>
<div>
<label className="text-sm font-medium">End Date</label>
<label htmlFor={endDateId} className="text-sm font-medium">
End Date
</label>
<Input
id={endDateId}
type="datetime-local"
value={filters.endDate}
onChange={(e) => handleFilterChange("endDate", e.target.value)}
@ -442,14 +459,14 @@ export default function AuditLogsPage() {
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="font-medium">Timestamp:</label>
<span className="font-medium">Timestamp:</span>
<p className="font-mono text-sm">
{new Date(selectedLog.timestamp).toLocaleString()}
</p>
</div>
<div>
<label className="font-medium">Event Type:</label>
<span className="font-medium">Event Type:</span>
<p>
{eventTypeLabels[selectedLog.eventType] ||
selectedLog.eventType}
@ -457,26 +474,26 @@ export default function AuditLogsPage() {
</div>
<div>
<label className="font-medium">Action:</label>
<span className="font-medium">Action:</span>
<p>{selectedLog.action}</p>
</div>
<div>
<label className="font-medium">Outcome:</label>
<span className="font-medium">Outcome:</span>
<Badge className={outcomeColors[selectedLog.outcome]}>
{selectedLog.outcome}
</Badge>
</div>
<div>
<label className="font-medium">Severity:</label>
<span className="font-medium">Severity:</span>
<Badge className={severityColors[selectedLog.severity]}>
{selectedLog.severity}
</Badge>
</div>
<div>
<label className="font-medium">IP Address:</label>
<span className="font-medium">IP Address:</span>
<p className="font-mono text-sm">
{selectedLog.ipAddress || "N/A"}
</p>
@ -484,7 +501,7 @@ export default function AuditLogsPage() {
{selectedLog.user && (
<div>
<label className="font-medium">User:</label>
<span className="font-medium">User:</span>
<p>
{selectedLog.user.email} ({selectedLog.user.role})
</p>
@ -493,7 +510,7 @@ export default function AuditLogsPage() {
{selectedLog.platformUser && (
<div>
<label className="font-medium">Platform User:</label>
<span className="font-medium">Platform User:</span>
<p>
{selectedLog.platformUser.email} (
{selectedLog.platformUser.role})
@ -503,21 +520,21 @@ export default function AuditLogsPage() {
{selectedLog.country && (
<div>
<label className="font-medium">Country:</label>
<span className="font-medium">Country:</span>
<p>{selectedLog.country}</p>
</div>
)}
{selectedLog.sessionId && (
<div>
<label className="font-medium">Session ID:</label>
<span className="font-medium">Session ID:</span>
<p className="font-mono text-sm">{selectedLog.sessionId}</p>
</div>
)}
{selectedLog.requestId && (
<div>
<label className="font-medium">Request ID:</label>
<span className="font-medium">Request ID:</span>
<p className="font-mono text-sm">{selectedLog.requestId}</p>
</div>
)}
@ -525,7 +542,7 @@ export default function AuditLogsPage() {
{selectedLog.errorMessage && (
<div className="mt-4">
<label className="font-medium">Error Message:</label>
<span className="font-medium">Error Message:</span>
<p className="text-red-600 bg-red-50 p-2 rounded text-sm">
{selectedLog.errorMessage}
</p>
@ -534,14 +551,14 @@ export default function AuditLogsPage() {
{selectedLog.userAgent && (
<div className="mt-4">
<label className="font-medium">User Agent:</label>
<span className="font-medium">User Agent:</span>
<p className="text-sm break-all">{selectedLog.userAgent}</p>
</div>
)}
{selectedLog.metadata && (
<div className="mt-4">
<label className="font-medium">Metadata:</label>
<span className="font-medium">Metadata:</span>
<pre className="bg-gray-100 p-2 rounded text-xs overflow-auto max-h-40">
{JSON.stringify(selectedLog.metadata, null, 2)}
</pre>

View File

@ -23,24 +23,24 @@ import MessageViewer from "../../../../components/MessageViewer";
import SessionDetails from "../../../../components/SessionDetails";
import type { ChatSession } from "../../../../lib/types";
export default function SessionViewPage() {
const params = useParams();
const router = useRouter(); // Initialize useRouter
const { status } = useSession(); // Get session status, removed unused sessionData
const id = params?.id as string;
/**
* Custom hook for managing session data fetching and state
*/
function useSessionData(id: string | undefined, authStatus: string) {
const [session, setSession] = useState<ChatSession | null>(null);
const [loading, setLoading] = useState(true); // This will now primarily be for data fetching
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const router = useRouter();
useEffect(() => {
if (status === "unauthenticated") {
if (authStatus === "unauthenticated") {
router.push("/login");
return;
}
if (status === "authenticated" && id) {
if (authStatus === "authenticated" && id) {
const fetchSession = async () => {
setLoading(true); // Always set loading before fetch
setLoading(true);
setError(null);
try {
const response = await fetch(`/api/dashboard/session/${id}`);
@ -63,222 +63,247 @@ export default function SessionViewPage() {
}
};
fetchSession();
} else if (status === "authenticated" && !id) {
} else if (authStatus === "authenticated" && !id) {
setError("Session ID is missing.");
setLoading(false);
}
}, [id, status, router]); // session removed from dependencies
}, [id, authStatus, router]);
if (status === "loading") {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8 text-muted-foreground">
Loading session...
</div>
</CardContent>
</Card>
</div>
);
}
if (status === "unauthenticated") {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8 text-muted-foreground">
Redirecting to login...
</div>
</CardContent>
</Card>
</div>
);
}
if (loading && status === "authenticated") {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8 text-muted-foreground">
Loading session details...
</div>
</CardContent>
</Card>
</div>
);
}
if (error) {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8">
<AlertCircle className="h-12 w-12 text-destructive mx-auto mb-4" />
<p className="text-destructive text-lg mb-4">Error: {error}</p>
<Link href="/dashboard/sessions">
<Button variant="outline" className="gap-2">
<ArrowLeft className="h-4 w-4" />
Back to Sessions List
</Button>
</Link>
</div>
</CardContent>
</Card>
</div>
);
}
if (!session) {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8">
<MessageSquare className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<p className="text-muted-foreground text-lg mb-4">
Session not found.
</p>
<Link href="/dashboard/sessions">
<Button variant="outline" className="gap-2">
<ArrowLeft className="h-4 w-4" />
Back to Sessions List
</Button>
</Link>
</div>
</CardContent>
</Card>
</div>
);
}
return { session, loading, error };
}
/**
* Component for rendering loading state
*/
function LoadingCard({ message }: { message: string }) {
return (
<div className="space-y-6 max-w-6xl mx-auto">
{/* Header */}
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<div className="text-center py-8 text-muted-foreground">
{message}
</div>
</CardContent>
</Card>
</div>
);
}
/**
* Component for rendering error state
*/
function ErrorCard({ error }: { error: string }) {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8">
<AlertCircle className="h-12 w-12 text-destructive mx-auto mb-4" />
<p className="text-destructive text-lg mb-4">Error: {error}</p>
<Link href="/dashboard/sessions">
<Button variant="outline" className="gap-2">
<ArrowLeft className="h-4 w-4" />
Back to Sessions List
</Button>
</Link>
</div>
</CardContent>
</Card>
</div>
);
}
/**
* Component for rendering session not found state
*/
function SessionNotFoundCard() {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8">
<MessageSquare className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<p className="text-muted-foreground text-lg mb-4">
Session not found.
</p>
<Link href="/dashboard/sessions">
<Button variant="outline" className="gap-2">
<ArrowLeft className="h-4 w-4" />
Back to Sessions List
</Button>
</Link>
</div>
</CardContent>
</Card>
</div>
);
}
/**
* Component for rendering session header with navigation and badges
*/
function SessionHeader({ session }: { session: ChatSession }) {
return (
<Card>
<CardContent className="pt-6">
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<div className="space-y-2">
<Link href="/dashboard/sessions">
<Button
variant="ghost"
className="gap-2 p-0 h-auto focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
aria-label="Return to sessions list"
>
<ArrowLeft className="h-4 w-4" aria-hidden="true" />
Back to Sessions List
</Button>
</Link>
<div className="space-y-2">
<Link href="/dashboard/sessions">
<Button
variant="ghost"
className="gap-2 p-0 h-auto focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
aria-label="Return to sessions list"
>
<ArrowLeft className="h-4 w-4" aria-hidden="true" />
Back to Sessions List
</Button>
</Link>
<div className="space-y-2">
<h1 className="text-3xl font-bold">Session Details</h1>
<div className="flex items-center gap-3">
<Badge variant="outline" className="font-mono text-xs">
ID
</Badge>
<code className="text-sm text-muted-foreground font-mono">
{(session.sessionId || session.id).slice(0, 8)}...
</code>
</div>
<h1 className="text-3xl font-bold">Session Details</h1>
<div className="flex items-center gap-3">
<Badge variant="outline" className="font-mono text-xs">
ID
</Badge>
<code className="text-sm text-muted-foreground font-mono">
{(session.sessionId || session.id).slice(0, 8)}...
</code>
</div>
</div>
<div className="flex flex-wrap gap-2">
{session.category && (
<Badge variant="secondary" className="gap-1">
<Activity className="h-3 w-3" />
{formatCategory(session.category)}
</Badge>
)}
{session.language && (
<Badge variant="outline" className="gap-1">
<Globe className="h-3 w-3" />
{session.language.toUpperCase()}
</Badge>
)}
{session.sentiment && (
<Badge
variant={
session.sentiment === "positive"
? "default"
: session.sentiment === "negative"
? "destructive"
: "secondary"
}
className="gap-1"
>
{session.sentiment.charAt(0).toUpperCase() +
session.sentiment.slice(1)}
</Badge>
)}
</div>
<div className="flex flex-wrap gap-2">
{session.category && (
<Badge variant="secondary" className="gap-1">
<Activity className="h-3 w-3" />
{formatCategory(session.category)}
</Badge>
)}
{session.language && (
<Badge variant="outline" className="gap-1">
<Globe className="h-3 w-3" />
{session.language.toUpperCase()}
</Badge>
)}
{session.sentiment && (
<Badge
variant={
session.sentiment === "positive"
? "default"
: session.sentiment === "negative"
? "destructive"
: "secondary"
}
className="gap-1"
>
{session.sentiment.charAt(0).toUpperCase() +
session.sentiment.slice(1)}
</Badge>
)}
</div>
</div>
</CardContent>
</Card>
);
}
/**
* Component for rendering session overview cards
*/
function SessionOverview({ session }: { session: ChatSession }) {
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<Clock className="h-8 w-8 text-blue-500" />
<div>
<p className="text-sm text-muted-foreground">Start Time</p>
<p className="font-semibold">
{new Date(session.startTime).toLocaleString()}
</p>
</div>
</div>
</CardContent>
</Card>
{/* Session Overview */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<Clock className="h-8 w-8 text-blue-500" />
<div>
<p className="text-sm text-muted-foreground">Start Time</p>
<p className="font-semibold">
{new Date(session.startTime).toLocaleString()}
</p>
</div>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<MessageSquare className="h-8 w-8 text-green-500" />
<div>
<p className="text-sm text-muted-foreground">Messages</p>
<p className="font-semibold">{session.messages?.length || 0}</p>
</div>
</CardContent>
</Card>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<MessageSquare className="h-8 w-8 text-green-500" />
<div>
<p className="text-sm text-muted-foreground">Messages</p>
<p className="font-semibold">{session.messages?.length || 0}</p>
</div>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<User className="h-8 w-8 text-purple-500" />
<div>
<p className="text-sm text-muted-foreground">User ID</p>
<p className="font-semibold truncate">
{session.userId || "N/A"}
</p>
</div>
</CardContent>
</Card>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<User className="h-8 w-8 text-purple-500" />
<div>
<p className="text-sm text-muted-foreground">User ID</p>
<p className="font-semibold truncate">
{session.userId || "N/A"}
</p>
</div>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<Activity className="h-8 w-8 text-orange-500" />
<div>
<p className="text-sm text-muted-foreground">Duration</p>
<p className="font-semibold">
{session.endTime && session.startTime
? `${Math.round(
(new Date(session.endTime).getTime() -
new Date(session.startTime).getTime()) /
60000
)} min`
: "N/A"}
</p>
</div>
</CardContent>
</Card>
</div>
</CardContent>
</Card>
</div>
);
}
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<Activity className="h-8 w-8 text-orange-500" />
<div>
<p className="text-sm text-muted-foreground">Duration</p>
<p className="font-semibold">
{session.endTime && session.startTime
? `${Math.round(
(new Date(session.endTime).getTime() -
new Date(session.startTime).getTime()) /
60000
)} min`
: "N/A"}
</p>
</div>
</div>
</CardContent>
</Card>
</div>
export default function SessionViewPage() {
const params = useParams();
const { status } = useSession();
const id = params?.id as string;
const { session, loading, error } = useSessionData(id, status);
if (status === "loading") {
return <LoadingCard message="Loading session..." />;
}
if (status === "unauthenticated") {
return <LoadingCard message="Redirecting to login..." />;
}
if (loading && status === "authenticated") {
return <LoadingCard message="Loading session details..." />;
}
if (error) {
return <ErrorCard error={error} />;
}
if (!session) {
return <SessionNotFoundCard />;
}
return (
<div className="space-y-6 max-w-6xl mx-auto">
<SessionHeader session={session} />
<SessionOverview session={session} />
{/* Session Details */}
<SessionDetails session={session} />

View File

@ -14,6 +14,7 @@ import {
} from "lucide-react";
import Link from "next/link";
import { useEffect, useId, useState } from "react";
import type { z } from "zod";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@ -21,8 +22,7 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { formatCategory } from "@/lib/format-enums";
import { trpc } from "@/lib/trpc-client";
import { sessionFilterSchema } from "@/lib/validation";
import type { z } from "zod";
import type { sessionFilterSchema } from "@/lib/validation";
import type { ChatSession } from "../../../lib/types";
interface FilterOptions {
@ -97,13 +97,13 @@ function FilterSection({
<CardHeader>
<div className="space-y-4">
<div className="relative">
<Label htmlFor="search-sessions" className="sr-only">
<Label htmlFor={searchId} className="sr-only">
Search sessions
</Label>
<div className="relative">
<Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
id="search-sessions"
id={searchId}
type="text"
placeholder="Search sessions..."
value={searchTerm}
@ -179,9 +179,9 @@ function FilterSection({
</div>
<div>
<Label htmlFor="start-date">Start Date</Label>
<Label htmlFor={startDateId}>Start Date</Label>
<Input
id="start-date"
id={startDateId}
type="date"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
@ -190,9 +190,9 @@ function FilterSection({
</div>
<div>
<Label htmlFor="end-date">End Date</Label>
<Label htmlFor={endDateId}>End Date</Label>
<Input
id="end-date"
id={endDateId}
type="date"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
@ -201,9 +201,9 @@ function FilterSection({
</div>
<div>
<Label htmlFor="sort-by">Sort By</Label>
<Label htmlFor={sortById}>Sort By</Label>
<select
id="sort-by"
id={sortById}
value={sortKey}
onChange={(e) => setSortKey(e.target.value)}
className="w-full mt-1 p-2 border border-gray-300 rounded-md"
@ -489,7 +489,9 @@ export default function SessionsPage() {
} = trpc.dashboard.getSessions.useQuery(
{
search: debouncedSearchTerm || undefined,
category: selectedCategory ? selectedCategory as z.infer<typeof sessionFilterSchema>["category"] : undefined,
category: selectedCategory
? (selectedCategory as z.infer<typeof sessionFilterSchema>["category"])
: undefined,
// language: selectedLanguage || undefined, // Not supported in schema yet
startDate: startDate || undefined,
endDate: endDate || undefined,