feat: add AI extraction frontend page (Phase 2M)

This commit is contained in:
m
2026-03-25 13:54:49 +01:00
7 changed files with 593 additions and 1 deletions

View File

@@ -13,6 +13,7 @@
"next": "15.5.14",
"react": "19.1.0",
"react-dom": "19.1.0",
"react-dropzone": "^15.0.0",
"sonner": "^2.0.7",
},
"devDependencies": {
@@ -315,6 +316,8 @@
"async-function": ["async-function@1.0.0", "", {}, "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA=="],
"attr-accept": ["attr-accept@2.2.5", "", {}, "sha512-0bDNnY/u6pPwHDMoF0FieU354oBi0a8rD9FcsLwzcGWbc8KS8KPIi7y+s13OlVY+gMWc/9xEMUgNE6Qm8ZllYQ=="],
"available-typed-arrays": ["available-typed-arrays@1.0.7", "", { "dependencies": { "possible-typed-array-names": "^1.0.0" } }, "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ=="],
"axe-core": ["axe-core@4.11.1", "", {}, "sha512-BASOg+YwO2C+346x3LZOeoovTIoTrRqEsqMa6fmfAV0P+U9mFr9NsyOEpiYvFjbc64NMrSswhV50WdXzdb/Z5A=="],
@@ -445,6 +448,8 @@
"file-entry-cache": ["file-entry-cache@8.0.0", "", { "dependencies": { "flat-cache": "^4.0.0" } }, "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ=="],
"file-selector": ["file-selector@2.1.2", "", { "dependencies": { "tslib": "^2.7.0" } }, "sha512-QgXo+mXTe8ljeqUFaX3QVHc5osSItJ/Km+xpocx0aSqWGMSCf6qYs/VnzZgS864Pjn5iceMRFigeAV7AfTlaig=="],
"fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
"find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="],
@@ -695,6 +700,8 @@
"react-dom": ["react-dom@19.1.0", "", { "dependencies": { "scheduler": "^0.26.0" }, "peerDependencies": { "react": "^19.1.0" } }, "sha512-Xs1hdnE+DyKgeHJeJznQmYMIBG3TKIHJJT95Q58nHLSrElKlGQqDTR2HQ9fx5CN/Gk6Vh/kupBTDLU11/nDk/g=="],
"react-dropzone": ["react-dropzone@15.0.0", "", { "dependencies": { "attr-accept": "^2.2.4", "file-selector": "^2.1.0", "prop-types": "^15.8.1" }, "peerDependencies": { "react": ">= 16.8 || 18.0.0" } }, "sha512-lGjYV/EoqEjEWPnmiSvH4v5IoIAwQM2W4Z1C0Q/Pw2xD0eVzKPS359BQTUMum+1fa0kH2nrKjuavmTPOGhpLPg=="],
"react-is": ["react-is@16.13.1", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
"reflect.getprototypeof": ["reflect.getprototypeof@1.0.10", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.9", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.7", "get-proto": "^1.0.1", "which-builtin-type": "^1.2.1" } }, "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw=="],

View File

@@ -17,6 +17,7 @@
"next": "15.5.14",
"react": "19.1.0",
"react-dom": "19.1.0",
"react-dropzone": "^15.0.0",
"sonner": "^2.0.7"
},
"devDependencies": {

View File

@@ -0,0 +1,142 @@
"use client";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Brain } from "lucide-react";
import { api } from "@/lib/api";
import type {
Case,
ExtractedDeadline,
ExtractionResponse,
PaginatedResponse,
} from "@/lib/types";
import { ExtractionForm } from "@/components/ai/ExtractionForm";
import { ExtractionResults } from "@/components/ai/ExtractionResults";
export default function AIExtractPage() {
const router = useRouter();
const [selectedCaseId, setSelectedCaseId] = useState("");
const [isExtracting, setIsExtracting] = useState(false);
const [isAdopting, setIsAdopting] = useState(false);
const [results, setResults] = useState<ExtractedDeadline[] | null>(null);
const { data: casesData } = useQuery({
queryKey: ["cases"],
queryFn: () => api.get<PaginatedResponse<Case>>("/api/cases"),
});
const cases = casesData?.data ?? [];
async function handleExtract(file: File | null, text: string) {
setIsExtracting(true);
setResults(null);
try {
let response: ExtractionResponse;
if (file) {
const formData = new FormData();
formData.append("file", file);
response = await api.postFormData<ExtractionResponse>(
"/api/ai/extract-deadlines",
formData,
);
} else {
response = await api.post<ExtractionResponse>(
"/api/ai/extract-deadlines",
{ text },
);
}
setResults(response.deadlines);
if (response.count === 0) {
toast.info("Keine Fristen im Dokument gefunden.");
} else {
toast.success(`${response.count} Frist(en) erkannt.`);
}
} catch (err: unknown) {
const message =
err && typeof err === "object" && "error" in err
? (err as { error: string }).error
: "Analyse fehlgeschlagen";
toast.error(message);
} finally {
setIsExtracting(false);
}
}
async function handleAdopt(deadlines: ExtractedDeadline[]) {
if (!selectedCaseId) return;
setIsAdopting(true);
try {
const promises = deadlines.map((d) =>
api.post(`/api/cases/${selectedCaseId}/deadlines`, {
title: d.title,
due_date: d.due_date ?? "",
source: "ai_extraction",
notes: [
d.rule_reference ? `Rechtsgrundlage: ${d.rule_reference}` : "",
d.source_quote ? `Quelle: "${d.source_quote}"` : "",
`Konfidenz: ${Math.round(d.confidence * 100)}%`,
]
.filter(Boolean)
.join("\n"),
}),
);
await Promise.all(promises);
toast.success(
`${deadlines.length} Frist(en) erfolgreich uebernommen.`,
);
router.push(`/akten/${selectedCaseId}`);
} catch (err: unknown) {
const message =
err && typeof err === "object" && "error" in err
? (err as { error: string }).error
: "Uebernahme fehlgeschlagen";
toast.error(message);
} finally {
setIsAdopting(false);
}
}
return (
<div className="mx-auto max-w-4xl">
<div className="mb-6 flex items-center gap-3">
<Brain className="h-5 w-5 text-neutral-500" />
<div>
<h1 className="text-lg font-semibold text-neutral-900">
AI Fristenanalyse
</h1>
<p className="text-sm text-neutral-500">
Fristen automatisch aus Dokumenten extrahieren
</p>
</div>
</div>
<div className="rounded-lg border border-neutral-200 bg-white p-6">
<ExtractionForm
cases={cases}
selectedCaseId={selectedCaseId}
onCaseChange={setSelectedCaseId}
onExtract={handleExtract}
isLoading={isExtracting}
/>
</div>
{results !== null && (
<div className="mt-6 rounded-lg border border-neutral-200 bg-white p-6">
<ExtractionResults
deadlines={results}
onAdopt={handleAdopt}
isAdopting={isAdopting}
/>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,169 @@
"use client";
import { useCallback, useState } from "react";
import { useDropzone } from "react-dropzone";
import { Upload, FileText, X, Loader2 } from "lucide-react";
import type { Case } from "@/lib/types";
interface ExtractionFormProps {
cases: Case[];
selectedCaseId: string;
onCaseChange: (caseId: string) => void;
onExtract: (file: File | null, text: string) => void;
isLoading: boolean;
}
export function ExtractionForm({
cases,
selectedCaseId,
onCaseChange,
onExtract,
isLoading,
}: ExtractionFormProps) {
const [file, setFile] = useState<File | null>(null);
const [text, setText] = useState("");
const onDrop = useCallback((acceptedFiles: File[]) => {
if (acceptedFiles.length > 0) {
setFile(acceptedFiles[0]);
setText("");
}
}, []);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
accept: { "application/pdf": [".pdf"] },
maxFiles: 1,
disabled: isLoading,
});
function removeFile() {
setFile(null);
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!selectedCaseId || (!file && !text.trim())) return;
onExtract(file, text.trim());
}
const hasInput = file !== null || text.trim().length > 0;
return (
<form onSubmit={handleSubmit} className="space-y-5">
{/* Case selector */}
<div>
<label
htmlFor="case-select"
className="mb-1.5 block text-sm font-medium text-neutral-700"
>
Akte
</label>
<select
id="case-select"
value={selectedCaseId}
onChange={(e) => onCaseChange(e.target.value)}
className="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 focus:border-neutral-500 focus:outline-none focus:ring-1 focus:ring-neutral-500"
disabled={isLoading}
>
<option value="">Akte auswaehlen...</option>
{cases.map((c) => (
<option key={c.id} value={c.id}>
{c.case_number} - {c.title}
</option>
))}
</select>
</div>
{/* PDF dropzone */}
<div>
<label className="mb-1.5 block text-sm font-medium text-neutral-700">
PDF hochladen
</label>
{file ? (
<div className="flex items-center gap-3 rounded-md border border-neutral-200 bg-neutral-50 px-4 py-3">
<FileText className="h-5 w-5 shrink-0 text-neutral-500" />
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-neutral-900">
{file.name}
</p>
<p className="text-xs text-neutral-500">
{(file.size / 1024).toFixed(0)} KB
</p>
</div>
<button
type="button"
onClick={removeFile}
disabled={isLoading}
className="rounded p-1 text-neutral-400 hover:bg-neutral-200 hover:text-neutral-600"
>
<X className="h-4 w-4" />
</button>
</div>
) : (
<div
{...getRootProps()}
className={`cursor-pointer rounded-md border-2 border-dashed px-6 py-8 text-center transition-colors ${
isDragActive
? "border-neutral-500 bg-neutral-50"
: "border-neutral-300 hover:border-neutral-400"
} ${isLoading ? "pointer-events-none opacity-50" : ""}`}
>
<input {...getInputProps()} />
<Upload className="mx-auto h-8 w-8 text-neutral-400" />
<p className="mt-2 text-sm text-neutral-600">
PDF hierher ziehen oder{" "}
<span className="font-medium text-neutral-900">durchsuchen</span>
</p>
<p className="mt-1 text-xs text-neutral-400">Nur PDF-Dateien</p>
</div>
)}
</div>
{/* Divider */}
<div className="flex items-center gap-3">
<div className="h-px flex-1 bg-neutral-200" />
<span className="text-xs text-neutral-400">oder</span>
<div className="h-px flex-1 bg-neutral-200" />
</div>
{/* Text input */}
<div>
<label
htmlFor="text-input"
className="mb-1.5 block text-sm font-medium text-neutral-700"
>
Text eingeben
</label>
<textarea
id="text-input"
value={text}
onChange={(e) => {
setText(e.target.value);
if (e.target.value.trim()) setFile(null);
}}
placeholder="Gerichtsschriftsatz, Beschluss oder sonstigen Text hier einfuegen..."
rows={6}
disabled={isLoading}
className="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm text-neutral-900 placeholder:text-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-1 focus:ring-neutral-500 disabled:opacity-50"
/>
</div>
{/* Submit */}
<button
type="submit"
disabled={isLoading || !hasInput || !selectedCaseId}
className="inline-flex items-center gap-2 rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-neutral-800 disabled:cursor-not-allowed disabled:opacity-50"
>
{isLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Analysiere...
</>
) : (
"Analysieren"
)}
</button>
</form>
);
}

View File

@@ -0,0 +1,238 @@
"use client";
import { useState } from "react";
import { Trash2, Check, Pencil, X, Loader2 } from "lucide-react";
import type { ExtractedDeadline } from "@/lib/types";
interface ExtractionResultsProps {
deadlines: ExtractedDeadline[];
onAdopt: (deadlines: ExtractedDeadline[]) => void;
isAdopting: boolean;
}
function confidenceColor(confidence: number): string {
if (confidence >= 0.8) return "bg-green-100 text-green-800";
if (confidence >= 0.5) return "bg-yellow-100 text-yellow-800";
return "bg-red-100 text-red-800";
}
function confidenceLabel(confidence: number): string {
if (confidence >= 0.8) return "Hoch";
if (confidence >= 0.5) return "Mittel";
return "Niedrig";
}
export function ExtractionResults({
deadlines: initialDeadlines,
onAdopt,
isAdopting,
}: ExtractionResultsProps) {
const [deadlines, setDeadlines] = useState(initialDeadlines);
const [editingIndex, setEditingIndex] = useState<number | null>(null);
const [editForm, setEditForm] = useState<ExtractedDeadline | null>(null);
function removeDeadline(index: number) {
setDeadlines((prev) => prev.filter((_, i) => i !== index));
}
function startEdit(index: number) {
setEditingIndex(index);
setEditForm({ ...deadlines[index] });
}
function cancelEdit() {
setEditingIndex(null);
setEditForm(null);
}
function saveEdit() {
if (editingIndex === null || !editForm) return;
setDeadlines((prev) =>
prev.map((d, i) => (i === editingIndex ? editForm : d)),
);
setEditingIndex(null);
setEditForm(null);
}
if (deadlines.length === 0) {
return (
<div className="rounded-md border border-neutral-200 bg-neutral-50 p-6 text-center">
<p className="text-sm text-neutral-500">
Keine Fristen gefunden. Alle extrahierten Fristen wurden entfernt.
</p>
</div>
);
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium text-neutral-900">
{deadlines.length} Frist{deadlines.length !== 1 ? "en" : ""} erkannt
</h3>
<button
onClick={() => onAdopt(deadlines)}
disabled={isAdopting || deadlines.length === 0}
className="inline-flex items-center gap-2 rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-neutral-800 disabled:cursor-not-allowed disabled:opacity-50"
>
{isAdopting ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Uebernehme...
</>
) : (
<>
<Check className="h-4 w-4" />
Fristen uebernehmen
</>
)}
</button>
</div>
<div className="overflow-hidden rounded-md border border-neutral-200">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-neutral-200 bg-neutral-50">
<th className="px-4 py-2.5 text-left font-medium text-neutral-700">
Frist
</th>
<th className="px-4 py-2.5 text-left font-medium text-neutral-700">
Faelligkeitsdatum
</th>
<th className="px-4 py-2.5 text-left font-medium text-neutral-700">
Rechtsgrundlage
</th>
<th className="px-4 py-2.5 text-left font-medium text-neutral-700">
Konfidenz
</th>
<th className="px-4 py-2.5 text-left font-medium text-neutral-700">
Quellenangabe
</th>
<th className="px-4 py-2.5 text-right font-medium text-neutral-700">
Aktionen
</th>
</tr>
</thead>
<tbody>
{deadlines.map((d, i) => (
<tr
key={i}
className="border-b border-neutral-100 last:border-b-0"
>
{editingIndex === i && editForm ? (
<>
<td className="px-4 py-2">
<input
value={editForm.title}
onChange={(e) =>
setEditForm({ ...editForm, title: e.target.value })
}
className="w-full rounded border border-neutral-300 px-2 py-1 text-sm"
/>
</td>
<td className="px-4 py-2">
<input
type="date"
value={editForm.due_date ?? ""}
onChange={(e) =>
setEditForm({
...editForm,
due_date: e.target.value || null,
})
}
className="rounded border border-neutral-300 px-2 py-1 text-sm"
/>
</td>
<td className="px-4 py-2">
<input
value={editForm.rule_reference}
onChange={(e) =>
setEditForm({
...editForm,
rule_reference: e.target.value,
})
}
className="w-full rounded border border-neutral-300 px-2 py-1 text-sm"
/>
</td>
<td className="px-4 py-2">
<span
className={`inline-block rounded-full px-2 py-0.5 text-xs font-medium ${confidenceColor(editForm.confidence)}`}
>
{confidenceLabel(editForm.confidence)}
</span>
</td>
<td className="px-4 py-2 text-xs text-neutral-500">
{editForm.source_quote}
</td>
<td className="px-4 py-2 text-right">
<div className="flex items-center justify-end gap-1">
<button
onClick={saveEdit}
className="rounded p-1 text-green-600 hover:bg-green-50"
title="Speichern"
>
<Check className="h-4 w-4" />
</button>
<button
onClick={cancelEdit}
className="rounded p-1 text-neutral-400 hover:bg-neutral-100"
title="Abbrechen"
>
<X className="h-4 w-4" />
</button>
</div>
</td>
</>
) : (
<>
<td className="px-4 py-2.5 font-medium text-neutral-900">
{d.title}
</td>
<td className="px-4 py-2.5 text-neutral-700">
{d.due_date
? new Date(d.due_date).toLocaleDateString("de-DE")
: `${d.duration_value} ${d.duration_unit}`}
</td>
<td className="px-4 py-2.5 text-neutral-600">
{d.rule_reference || "-"}
</td>
<td className="px-4 py-2.5">
<span
className={`inline-block rounded-full px-2 py-0.5 text-xs font-medium ${confidenceColor(d.confidence)}`}
>
{confidenceLabel(d.confidence)}{" "}
{Math.round(d.confidence * 100)}%
</span>
</td>
<td className="max-w-48 truncate px-4 py-2.5 text-xs text-neutral-500">
{d.source_quote || "-"}
</td>
<td className="px-4 py-2.5 text-right">
<div className="flex items-center justify-end gap-1">
<button
onClick={() => startEdit(i)}
className="rounded p-1 text-neutral-400 hover:bg-neutral-100 hover:text-neutral-600"
title="Bearbeiten"
>
<Pencil className="h-3.5 w-3.5" />
</button>
<button
onClick={() => removeDeadline(i)}
className="rounded p-1 text-neutral-400 hover:bg-red-50 hover:text-red-600"
title="Entfernen"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</td>
</>
)}
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -16,7 +16,7 @@ const navigation = [
{ name: "Akten", href: "/akten", icon: FolderOpen },
{ name: "Fristen", href: "/fristen", icon: Clock },
{ name: "Termine", href: "/termine", icon: Calendar },
{ name: "AI Analyse", href: "/ai", icon: Brain },
{ name: "AI Analyse", href: "/ai/extract", icon: Brain },
{ name: "Einstellungen", href: "/einstellungen", icon: Settings },
];

View File

@@ -79,6 +79,41 @@ class ApiClient {
delete<T>(path: string) {
return this.request<T>(path, { method: "DELETE" });
}
async postFormData<T>(path: string, formData: FormData): Promise<T> {
const supabase = createClient();
const {
data: { session },
} = await supabase.auth.getSession();
const headers: HeadersInit = {};
if (session?.access_token) {
headers["Authorization"] = `Bearer ${session.access_token}`;
}
const tenantId = typeof window !== "undefined"
? localStorage.getItem("kanzlai_tenant_id")
: null;
if (tenantId) {
headers["X-Tenant-ID"] = tenantId;
}
const res = await fetch(`${this.baseUrl}${path}`, {
method: "POST",
headers,
body: formData,
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
const err: ApiError = {
error: body.error || res.statusText,
status: res.status,
};
throw err;
}
return res.json();
}
}
export const api = new ApiClient();