refactor(admin): split compliance-hub, obligations, document-generator pages

Each page.tsx was >1000 LOC; extract components to _components/ and hooks
to _hooks/ so page files stay under 500 LOC (164 / 255 / 243 respectively).
Zero behavior changes — logic relocated verbatim.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Sharang Parnerkar
2026-04-16 17:10:14 +02:00
parent c43d9da6d0
commit 2ade65431a
15 changed files with 1607 additions and 2948 deletions

View File

@@ -0,0 +1,70 @@
'use client'
import type { ModuleStatusData } from './types'
import { MODULE_ICONS } from './types'
interface ModulesTabProps {
moduleStatus: ModuleStatusData | null
}
export function ModulesTab({ moduleStatus }: ModulesTabProps) {
if (!moduleStatus) {
return (
<div className="flex items-center justify-center h-48">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
</div>
)
}
return (
<>
{/* Summary */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
<div className="bg-white rounded-xl shadow-sm border p-6 text-center">
<p className="text-sm text-slate-500">Gesamt-Fortschritt</p>
<p className="text-3xl font-bold text-purple-600">{moduleStatus.overall_progress.toFixed(0)}%</p>
</div>
<div className="bg-white rounded-xl shadow-sm border p-6 text-center">
<p className="text-sm text-slate-500">Module gestartet</p>
<p className="text-3xl font-bold text-blue-600">{moduleStatus.started}/{moduleStatus.total}</p>
</div>
<div className="bg-white rounded-xl shadow-sm border p-6 text-center">
<p className="text-sm text-slate-500">Module abgeschlossen</p>
<p className="text-3xl font-bold text-green-600">{moduleStatus.complete}/{moduleStatus.total}</p>
</div>
</div>
{/* Module Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{moduleStatus.modules.map(mod => (
<div key={mod.key} className="bg-white rounded-xl shadow-sm border p-5">
<div className="flex items-center gap-3 mb-3">
<span className="text-2xl">{MODULE_ICONS[mod.key] || '📦'}</span>
<div>
<h4 className="font-medium text-slate-900">{mod.label}</h4>
<p className="text-xs text-slate-500">{mod.count} Eintraege</p>
</div>
<span className={`ml-auto px-2 py-0.5 text-xs rounded-full font-medium ${
mod.status === 'complete' ? 'bg-green-100 text-green-700' :
mod.status === 'in_progress' ? 'bg-yellow-100 text-yellow-700' :
'bg-slate-100 text-slate-500'
}`}>
{mod.status === 'complete' ? 'Fertig' :
mod.status === 'in_progress' ? 'In Arbeit' : 'Offen'}
</span>
</div>
<div className="h-2 bg-slate-200 rounded-full overflow-hidden">
<div
className={`h-full transition-all duration-500 ${
mod.status === 'complete' ? 'bg-green-500' :
mod.status === 'in_progress' ? 'bg-yellow-500' : 'bg-slate-300'
}`}
style={{ width: `${mod.progress}%` }}
/>
</div>
</div>
))}
</div>
</>
)
}

View File

@@ -0,0 +1,388 @@
'use client'
import Link from 'next/link'
import type { DashboardData, MappingsData, FindingsData, NextAction } from './types'
import { DOMAIN_LABELS } from './types'
interface OverviewTabProps {
dashboard: DashboardData | null
mappings: MappingsData | null
findings: FindingsData | null
nextActions: NextAction[]
evidenceDistribution: {
by_confidence: Record<string, number>
four_eyes_pending: number
total: number
} | null
score: number
scoreColor: string
scoreBgColor: string
loadData: () => void
regulations: Array<{ id: string; code: string; name: string; regulation_type: string; requirement_count: number }>
}
export function OverviewTab({
dashboard, mappings, findings, nextActions, evidenceDistribution,
score, scoreColor, scoreBgColor, loadData, regulations,
}: OverviewTabProps) {
return (
<>
{/* Quick Actions */}
<div className="bg-white rounded-xl shadow-sm border p-6">
<h3 className="text-lg font-semibold text-slate-900 mb-4">Schnellzugriff</h3>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-4">
{[
{ href: '/sdk/audit-checklist', icon: 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01', label: 'Audit Checkliste', sub: `${dashboard?.total_requirements || '...'} Anforderungen`, color: 'purple' },
{ href: '/sdk/controls', icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z', label: 'Controls', sub: `${dashboard?.total_controls || '...'} Massnahmen`, color: 'green' },
{ href: '/sdk/evidence', icon: 'M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z', label: 'Evidence', sub: 'Nachweise', color: 'blue' },
{ href: '/sdk/risks', icon: 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z', label: 'Risk Matrix', sub: '5x5 Risiken', color: 'red' },
{ href: '/sdk/process-tasks', icon: 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4', label: 'Prozesse', sub: 'Aufgaben', color: 'indigo' },
{ href: '/sdk/audit-report', icon: 'M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', label: 'Audit Report', sub: 'PDF Export', color: 'orange' },
].map(item => (
<Link
key={item.href}
href={item.href}
className={`p-4 rounded-lg border border-slate-200 hover:border-${item.color}-500 hover:bg-${item.color}-50 transition-colors text-center`}
>
<div className={`text-${item.color}-600 mb-2 flex justify-center`}>
<svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={item.icon} />
</svg>
</div>
<p className="font-medium text-slate-900 text-sm">{item.label}</p>
<p className="text-xs text-slate-500 mt-1">{item.sub}</p>
</Link>
))}
</div>
</div>
{/* Score and Stats Row */}
<div className="grid grid-cols-1 lg:grid-cols-5 gap-4">
<div className="bg-white rounded-xl shadow-sm border p-6">
<h3 className="text-sm font-medium text-slate-500 mb-4">Compliance Score</h3>
<div className={`text-5xl font-bold ${scoreColor}`}>
{score.toFixed(0)}%
</div>
<div className="mt-4 h-2 bg-slate-200 rounded-full overflow-hidden">
<div className={`h-full transition-all duration-500 ${scoreBgColor}`} style={{ width: `${score}%` }} />
</div>
<p className="mt-2 text-sm text-slate-500">
{dashboard?.controls_by_status?.pass || 0} von {dashboard?.total_controls || 0} Controls bestanden
</p>
</div>
{[
{ label: 'Verordnungen', value: dashboard?.total_regulations || 0, sub: `${dashboard?.total_requirements || 0} Anforderungen`, iconColor: 'blue', icon: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z' },
{ label: 'Controls', value: dashboard?.total_controls || 0, sub: `${dashboard?.controls_by_status?.pass || 0} bestanden`, iconColor: 'green', icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' },
{ label: 'Nachweise', value: dashboard?.total_evidence || 0, sub: `${dashboard?.evidence_by_status?.valid || 0} aktiv`, iconColor: 'purple', icon: 'M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z' },
{ label: 'Risiken', value: dashboard?.total_risks || 0, sub: `${(dashboard?.risks_by_level?.high || 0) + (dashboard?.risks_by_level?.critical || 0)} kritisch`, iconColor: 'red', icon: 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z' },
].map(stat => (
<div key={stat.label} className="bg-white rounded-xl shadow-sm border p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-slate-500">{stat.label}</p>
<p className="text-2xl font-bold text-slate-900">{stat.value}</p>
</div>
<div className={`w-10 h-10 bg-${stat.iconColor}-100 rounded-lg flex items-center justify-center`}>
<svg className={`w-5 h-5 text-${stat.iconColor}-600`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={stat.icon} />
</svg>
</div>
</div>
<p className="mt-2 text-sm text-slate-500">{stat.sub}</p>
</div>
))}
</div>
{/* Anti-Fake-Evidence Section (Phase 3) */}
{dashboard && (
<div className="bg-white rounded-xl shadow-sm border p-6">
<h3 className="text-lg font-semibold text-slate-900 mb-4">Anti-Fake-Evidence Status</h3>
{/* Confidence Distribution Bar */}
{evidenceDistribution && evidenceDistribution.total > 0 && (
<div className="mb-6">
<p className="text-sm text-slate-500 mb-2">Confidence-Verteilung ({evidenceDistribution.total} Nachweise)</p>
<div className="flex h-6 rounded-full overflow-hidden">
{(['E0', 'E1', 'E2', 'E3', 'E4'] as const).map(level => {
const count = evidenceDistribution.by_confidence[level] || 0
const pct = (count / evidenceDistribution.total) * 100
if (pct === 0) return null
const colors: Record<string, string> = {
E0: 'bg-red-400', E1: 'bg-yellow-400', E2: 'bg-blue-400', E3: 'bg-green-400', E4: 'bg-emerald-400'
}
return (
<div key={level} className={`${colors[level]} flex items-center justify-center text-xs text-white font-medium`}
style={{ width: `${pct}%` }} title={`${level}: ${count}`}>
{pct >= 10 ? `${level} (${count})` : ''}
</div>
)
})}
</div>
<div className="flex items-center gap-4 mt-2 text-xs text-slate-500">
{(['E0', 'E1', 'E2', 'E3', 'E4'] as const).map(level => {
const count = evidenceDistribution.by_confidence[level] || 0
const dotColors: Record<string, string> = {
E0: 'bg-red-400', E1: 'bg-yellow-400', E2: 'bg-blue-400', E3: 'bg-green-400', E4: 'bg-emerald-400'
}
return (
<span key={level} className="flex items-center gap-1">
<span className={`w-2 h-2 rounded-full ${dotColors[level]}`} />
{level}: {count}
</span>
)
})}
</div>
</div>
)}
{/* Multi-Score Dimensions */}
{dashboard.multi_score && (
<div className="mb-6">
<p className="text-sm text-slate-500 mb-2">Multi-dimensionaler Score</p>
<div className="space-y-2">
{([
{ key: 'requirement_coverage', label: 'Anforderungsabdeckung', color: 'bg-blue-500' },
{ key: 'evidence_strength', label: 'Evidence-Staerke', color: 'bg-green-500' },
{ key: 'validation_quality', label: 'Validierungsqualitaet', color: 'bg-purple-500' },
{ key: 'evidence_freshness', label: 'Aktualitaet', color: 'bg-yellow-500' },
{ key: 'control_effectiveness', label: 'Control-Wirksamkeit', color: 'bg-indigo-500' },
] as const).map(dim => {
const value = (dashboard.multi_score as Record<string, number>)[dim.key] || 0
return (
<div key={dim.key} className="flex items-center gap-3">
<span className="text-xs text-slate-600 w-44 truncate">{dim.label}</span>
<div className="flex-1 h-2 bg-slate-200 rounded-full overflow-hidden">
<div className={`h-full ${dim.color} rounded-full transition-all`} style={{ width: `${value}%` }} />
</div>
<span className="text-xs text-slate-600 w-12 text-right">{typeof value === 'number' ? value.toFixed(0) : value}%</span>
</div>
)
})}
<div className="flex items-center gap-3 pt-2 border-t border-slate-100">
<span className="text-xs font-semibold text-slate-700 w-44">Audit-Readiness</span>
<div className="flex-1 h-3 bg-slate-200 rounded-full overflow-hidden">
<div className={`h-full rounded-full transition-all ${
(dashboard.multi_score.overall_readiness || 0) >= 80 ? 'bg-green-500' :
(dashboard.multi_score.overall_readiness || 0) >= 60 ? 'bg-yellow-500' : 'bg-red-500'
}`} style={{ width: `${dashboard.multi_score.overall_readiness || 0}%` }} />
</div>
<span className="text-xs font-semibold text-slate-700 w-12 text-right">
{typeof dashboard.multi_score.overall_readiness === 'number' ? dashboard.multi_score.overall_readiness.toFixed(0) : 0}%
</span>
</div>
</div>
</div>
)}
{/* Bottom row: Four-Eyes + Hard Blocks */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="text-center p-3 rounded-lg bg-yellow-50">
<div className="text-2xl font-bold text-yellow-700">{evidenceDistribution?.four_eyes_pending || 0}</div>
<div className="text-xs text-yellow-600 mt-1">Four-Eyes Reviews ausstehend</div>
</div>
{dashboard.multi_score?.hard_blocks && dashboard.multi_score.hard_blocks.length > 0 ? (
<div className="p-3 rounded-lg bg-red-50">
<div className="text-xs font-medium text-red-700 mb-1">Hard Blocks ({dashboard.multi_score.hard_blocks.length})</div>
<ul className="space-y-1">
{dashboard.multi_score.hard_blocks.slice(0, 3).map((block: string, i: number) => (
<li key={i} className="text-xs text-red-600 flex items-start gap-1">
<span className="text-red-400 mt-0.5">&#8226;</span>
<span>{block}</span>
</li>
))}
</ul>
</div>
) : (
<div className="text-center p-3 rounded-lg bg-green-50">
<div className="text-2xl font-bold text-green-700">0</div>
<div className="text-xs text-green-600 mt-1">Keine Hard Blocks</div>
</div>
)}
</div>
</div>
)}
{/* Next Actions + Findings */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{/* Next Actions */}
<div className="bg-white rounded-xl shadow-sm border p-6">
<h3 className="text-lg font-semibold text-slate-900 mb-4">Naechste Aktionen</h3>
{nextActions.length === 0 ? (
<p className="text-sm text-slate-500">Keine offenen Aktionen.</p>
) : (
<div className="space-y-3">
{nextActions.map(action => (
<div key={action.id} className="flex items-center gap-3 p-3 rounded-lg bg-slate-50">
<div className={`w-2 h-2 rounded-full flex-shrink-0 ${
action.days_overdue > 0 ? 'bg-red-500' : 'bg-yellow-500'
}`} />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-slate-900 truncate">{action.title}</p>
<p className="text-xs text-slate-500">
{action.control_id} · {DOMAIN_LABELS[action.domain] || action.domain}
{action.days_overdue > 0 && <span className="text-red-600 ml-2">{action.days_overdue}d ueberfaellig</span>}
</p>
</div>
<span className={`px-2 py-0.5 text-xs rounded-full ${
action.status === 'partial' ? 'bg-yellow-100 text-yellow-700' : 'bg-slate-100 text-slate-600'
}`}>
{action.status}
</span>
</div>
))}
</div>
)}
</div>
{/* Audit Findings */}
<div className="bg-white rounded-xl shadow-sm border p-6">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-slate-900">Audit Findings</h3>
<Link href="/sdk/audit-checklist" className="text-sm text-purple-600 hover:text-purple-700">
Audit Checkliste
</Link>
</div>
<div className="grid grid-cols-2 gap-4 mb-4">
<div className="p-4 bg-red-50 border border-red-200 rounded-lg">
<div className="flex items-center gap-2 mb-1">
<div className="w-3 h-3 bg-red-500 rounded-full" />
<span className="text-sm font-medium text-red-800">Hauptabweichungen</span>
</div>
<p className="text-3xl font-bold text-red-600">{findings?.open_majors || 0}</p>
<p className="text-xs text-red-600">offen (blockiert Zertifizierung)</p>
</div>
<div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
<div className="flex items-center gap-2 mb-1">
<div className="w-3 h-3 bg-yellow-500 rounded-full" />
<span className="text-sm font-medium text-yellow-800">Nebenabweichungen</span>
</div>
<p className="text-3xl font-bold text-yellow-600">{findings?.open_minors || 0}</p>
<p className="text-xs text-yellow-600">offen (erfordert CAPA)</p>
</div>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-slate-500">
Gesamt: {findings?.total || 0} Findings ({findings?.major_count || 0} Major, {findings?.minor_count || 0} Minor, {findings?.ofi_count || 0} OFI)
</span>
{(findings?.open_majors || 0) === 0 ? (
<span className="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs font-medium">
Zertifizierung moeglich
</span>
) : (
<span className="px-2 py-1 bg-red-100 text-red-700 rounded-full text-xs font-medium">
Zertifizierung blockiert
</span>
)}
</div>
</div>
</div>
{/* Control-Mappings & Domain Chart */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div className="bg-white rounded-xl shadow-sm border p-6">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-slate-900">Control-Mappings</h3>
<Link href="/sdk/controls" className="text-sm text-purple-600 hover:text-purple-700">
Alle anzeigen
</Link>
</div>
<div className="flex items-center gap-6 mb-4">
<div>
<p className="text-4xl font-bold text-purple-600">{mappings?.total || 0}</p>
<p className="text-sm text-slate-500">Mappings gesamt</p>
</div>
<div className="flex-1 h-16 bg-slate-50 rounded-lg p-3">
<p className="text-xs text-slate-500 mb-1">Nach Verordnung</p>
<div className="flex gap-1 flex-wrap">
{mappings?.by_regulation && Object.entries(mappings.by_regulation).slice(0, 5).map(([reg, count]) => (
<span key={reg} className="px-2 py-0.5 bg-purple-100 text-purple-700 rounded text-xs">
{reg}: {count}
</span>
))}
{!mappings?.by_regulation && (
<span className="px-2 py-0.5 bg-slate-100 text-slate-500 rounded text-xs">Keine Mappings vorhanden</span>
)}
</div>
</div>
</div>
</div>
<div className="bg-white rounded-xl shadow-sm border p-6">
<h3 className="text-lg font-semibold text-slate-900 mb-4">Controls nach Domain</h3>
<div className="space-y-2">
{Object.entries(dashboard?.controls_by_domain || {}).slice(0, 6).map(([domain, stats]) => {
const total = stats.total || 0
const pass = stats.pass || 0
const partial = stats.partial || 0
const passPercent = total > 0 ? ((pass + partial * 0.5) / total) * 100 : 0
return (
<div key={domain} className="flex items-center gap-3">
<span className="text-xs font-medium text-slate-600 w-24 truncate">
{DOMAIN_LABELS[domain] || domain}
</span>
<div className="flex-1 h-2 bg-slate-200 rounded-full overflow-hidden flex">
<div className="bg-green-500 h-full" style={{ width: `${(pass / (total || 1)) * 100}%` }} />
<div className="bg-yellow-500 h-full" style={{ width: `${(partial / (total || 1)) * 100}%` }} />
</div>
<span className="text-xs text-slate-500 w-16 text-right">{passPercent.toFixed(0)}%</span>
</div>
)
})}
</div>
</div>
</div>
{/* Regulations Table */}
<div className="bg-white rounded-xl shadow-sm border overflow-hidden">
<div className="p-4 border-b flex items-center justify-between">
<h3 className="text-lg font-semibold text-slate-900">Verordnungen & Standards ({regulations.length})</h3>
<button onClick={loadData} className="text-sm text-purple-600 hover:text-purple-700">
Aktualisieren
</button>
</div>
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-slate-50">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Code</th>
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Name</th>
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Typ</th>
<th className="px-4 py-3 text-center text-xs font-medium text-slate-500 uppercase">Anforderungen</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-200">
{regulations.slice(0, 15).map((reg) => (
<tr key={reg.id} className="hover:bg-slate-50">
<td className="px-4 py-3">
<span className="font-mono font-medium text-purple-600">{reg.code}</span>
</td>
<td className="px-4 py-3">
<p className="font-medium text-slate-900">{reg.name}</p>
</td>
<td className="px-4 py-3">
<span className={`px-2 py-1 text-xs rounded-full ${
reg.regulation_type === 'eu_regulation' ? 'bg-blue-100 text-blue-700' :
reg.regulation_type === 'eu_directive' ? 'bg-purple-100 text-purple-700' :
reg.regulation_type === 'bsi_standard' ? 'bg-green-100 text-green-700' :
'bg-slate-100 text-slate-700'
}`}>
{reg.regulation_type === 'eu_regulation' ? 'EU-VO' :
reg.regulation_type === 'eu_directive' ? 'EU-RL' :
reg.regulation_type === 'bsi_standard' ? 'BSI' :
reg.regulation_type === 'de_law' ? 'DE' : reg.regulation_type}
</span>
</td>
<td className="px-4 py-3 text-center">
<span className="font-medium">{reg.requirement_count}</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</>
)
}

View File

@@ -0,0 +1,60 @@
'use client'
import type { RoadmapData } from './types'
import { BUCKET_LABELS, DOMAIN_LABELS } from './types'
interface RoadmapTabProps {
roadmap: RoadmapData | null
}
export function RoadmapTab({ roadmap }: RoadmapTabProps) {
if (!roadmap) {
return (
<div className="flex items-center justify-center h-48">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
</div>
)
}
return (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
{(['quick_wins', 'must_have', 'should_have', 'nice_to_have'] as const).map(bucketKey => {
const meta = BUCKET_LABELS[bucketKey]
const items = roadmap.buckets[bucketKey] || []
return (
<div key={bucketKey} className={`rounded-xl border p-4 ${meta.bg}`}>
<div className="flex items-center justify-between mb-3">
<h3 className={`font-semibold ${meta.color}`}>{meta.label}</h3>
<span className={`text-xs font-medium px-2 py-0.5 rounded-full bg-white ${meta.color}`}>
{items.length}
</span>
</div>
<div className="space-y-2 max-h-96 overflow-y-auto">
{items.length === 0 ? (
<p className="text-sm text-slate-400 text-center py-4">Keine Eintraege</p>
) : (
items.map(item => (
<div key={item.id} className="bg-white rounded-lg p-3 shadow-sm">
<p className="text-sm font-medium text-slate-900 truncate">{item.title}</p>
<div className="mt-1 flex items-center gap-2 text-xs text-slate-500">
<span className="font-mono">{item.control_id}</span>
<span>·</span>
<span>{DOMAIN_LABELS[item.domain] || item.domain}</span>
</div>
{item.days_overdue > 0 && (
<p className="mt-1 text-xs text-red-600">{item.days_overdue}d ueberfaellig</p>
)}
{item.owner && (
<p className="mt-1 text-xs text-slate-400">{item.owner}</p>
)}
</div>
))
)}
</div>
</div>
)
})}
</div>
)
}

View File

@@ -0,0 +1,253 @@
'use client'
import { ConfidenceLevelBadge } from '../../evidence/components/anti-fake-badges'
import type { TraceabilityMatrixData } from './types'
import { DOMAIN_LABELS } from './types'
interface TraceabilityTabProps {
traceabilityMatrix: TraceabilityMatrixData | null
traceabilityLoading: boolean
traceabilityFilter: 'all' | 'covered' | 'uncovered' | 'fully_verified'
setTraceabilityFilter: (f: 'all' | 'covered' | 'uncovered' | 'fully_verified') => void
traceabilityDomainFilter: string
setTraceabilityDomainFilter: (d: string) => void
expandedControls: Set<string>
expandedEvidence: Set<string>
toggleControlExpanded: (id: string) => void
toggleEvidenceExpanded: (id: string) => void
}
export function TraceabilityTab({
traceabilityMatrix, traceabilityLoading,
traceabilityFilter, setTraceabilityFilter,
traceabilityDomainFilter, setTraceabilityDomainFilter,
expandedControls, expandedEvidence,
toggleControlExpanded, toggleEvidenceExpanded,
}: TraceabilityTabProps) {
if (traceabilityLoading) {
return (
<div className="flex items-center justify-center py-12">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
<span className="ml-3 text-slate-500">Traceability Matrix wird geladen...</span>
</div>
)
}
if (!traceabilityMatrix) {
return (
<div className="text-center py-12 text-slate-500">
Keine Daten verfuegbar. Stellen Sie sicher, dass Controls und Evidence vorhanden sind.
</div>
)
}
const summary = traceabilityMatrix.summary
const totalControls = summary.total_controls || 0
const covered = summary.covered || 0
const fullyVerified = summary.fully_verified || 0
const uncovered = summary.uncovered || 0
const filteredControls = (traceabilityMatrix.controls || []).filter(ctrl => {
if (traceabilityFilter === 'covered' && !ctrl.coverage.has_evidence) return false
if (traceabilityFilter === 'uncovered' && ctrl.coverage.has_evidence) return false
if (traceabilityFilter === 'fully_verified' && !ctrl.coverage.all_assertions_verified) return false
if (traceabilityDomainFilter !== 'all' && ctrl.domain !== traceabilityDomainFilter) return false
return true
})
const domains = [...new Set(traceabilityMatrix.controls.map(c => c.domain))].sort()
return (
<div className="p-6 space-y-6">
{/* Summary Cards */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
<div className="text-2xl font-bold text-purple-700">{totalControls}</div>
<div className="text-sm text-purple-600">Total Controls</div>
</div>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<div className="text-2xl font-bold text-blue-700">{covered}</div>
<div className="text-sm text-blue-600">Abgedeckt</div>
</div>
<div className="bg-green-50 border border-green-200 rounded-lg p-4">
<div className="text-2xl font-bold text-green-700">{fullyVerified}</div>
<div className="text-sm text-green-600">Vollst. verifiziert</div>
</div>
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
<div className="text-2xl font-bold text-red-700">{uncovered}</div>
<div className="text-sm text-red-600">Unabgedeckt</div>
</div>
</div>
{/* Filter Bar */}
<div className="flex flex-wrap gap-4 items-center">
<div className="flex gap-1">
{([
{ key: 'all', label: 'Alle' },
{ key: 'covered', label: 'Abgedeckt' },
{ key: 'uncovered', label: 'Nicht abgedeckt' },
{ key: 'fully_verified', label: 'Vollst. verifiziert' },
] as const).map(f => (
<button
key={f.key}
onClick={() => setTraceabilityFilter(f.key)}
className={`px-3 py-1 text-xs rounded-full transition-colors ${
traceabilityFilter === f.key
? 'bg-purple-600 text-white'
: 'bg-slate-100 text-slate-600 hover:bg-slate-200'
}`}
>
{f.label}
</button>
))}
</div>
<div className="h-4 w-px bg-slate-300" />
<div className="flex gap-1 flex-wrap">
<button
onClick={() => setTraceabilityDomainFilter('all')}
className={`px-3 py-1 text-xs rounded-full transition-colors ${
traceabilityDomainFilter === 'all'
? 'bg-purple-600 text-white'
: 'bg-slate-100 text-slate-600 hover:bg-slate-200'
}`}
>
Alle Domains
</button>
{domains.map(d => (
<button
key={d}
onClick={() => setTraceabilityDomainFilter(d)}
className={`px-3 py-1 text-xs rounded-full transition-colors ${
traceabilityDomainFilter === d
? 'bg-purple-600 text-white'
: 'bg-slate-100 text-slate-600 hover:bg-slate-200'
}`}
>
{DOMAIN_LABELS[d] || d}
</button>
))}
</div>
</div>
{/* Controls List */}
<div className="space-y-2">
{filteredControls.length === 0 ? (
<div className="text-center py-8 text-slate-400">
Keine Controls fuer diesen Filter gefunden.
</div>
) : filteredControls.map(ctrl => {
const isExpanded = expandedControls.has(ctrl.id)
const coverageIcon = ctrl.coverage.all_assertions_verified
? { symbol: '\u2713', color: 'text-green-600 bg-green-50' }
: ctrl.coverage.has_evidence
? { symbol: '\u25D0', color: 'text-yellow-600 bg-yellow-50' }
: { symbol: '\u2717', color: 'text-red-600 bg-red-50' }
return (
<div key={ctrl.id} className="border rounded-lg overflow-hidden">
{/* Control Row */}
<button
onClick={() => toggleControlExpanded(ctrl.id)}
className="w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-slate-50 transition-colors"
>
<span className="text-slate-400 text-xs">{isExpanded ? '\u25BC' : '\u25B6'}</span>
<span className={`w-7 h-7 flex items-center justify-center rounded-full text-sm font-medium ${coverageIcon.color}`}>
{coverageIcon.symbol}
</span>
<code className="text-xs bg-slate-100 px-2 py-0.5 rounded text-slate-600 font-mono">{ctrl.control_id}</code>
<span className="text-sm text-slate-800 flex-1 truncate">{ctrl.title}</span>
<span className="text-xs bg-slate-100 text-slate-500 px-2 py-0.5 rounded">{DOMAIN_LABELS[ctrl.domain] || ctrl.domain}</span>
<span className={`text-xs px-2 py-0.5 rounded ${
ctrl.status === 'implemented' ? 'bg-green-100 text-green-700'
: ctrl.status === 'in_progress' ? 'bg-blue-100 text-blue-700'
: 'bg-slate-100 text-slate-600'
}`}>
{ctrl.status}
</span>
<ConfidenceLevelBadge level={ctrl.coverage.min_confidence_level} />
<span className="text-xs text-slate-400 min-w-[3rem] text-right">
{ctrl.evidence.length} Ev.
</span>
</button>
{/* Expanded: Evidence list */}
{isExpanded && (
<div className="border-t bg-slate-50">
{ctrl.evidence.length === 0 ? (
<div className="px-8 py-3 text-xs text-slate-400 italic">
Kein Evidence verknuepft.
</div>
) : ctrl.evidence.map(ev => {
const evExpanded = expandedEvidence.has(ev.id)
return (
<div key={ev.id} className="border-b last:border-b-0">
<button
onClick={() => toggleEvidenceExpanded(ev.id)}
className="w-full flex items-center gap-3 px-8 py-2 text-left hover:bg-slate-100 transition-colors"
>
<span className="text-slate-400 text-xs">{evExpanded ? '\u25BC' : '\u25B6'}</span>
<span className="text-sm text-slate-700 flex-1 truncate">{ev.title}</span>
<span className="text-xs bg-white border px-2 py-0.5 rounded text-slate-500">{ev.evidence_type}</span>
<ConfidenceLevelBadge level={ev.confidence_level} />
<span className={`text-xs px-2 py-0.5 rounded ${
ev.status === 'valid' ? 'bg-green-100 text-green-700'
: ev.status === 'expired' ? 'bg-red-100 text-red-700'
: 'bg-slate-100 text-slate-600'
}`}>
{ev.status}
</span>
<span className="text-xs text-slate-400 min-w-[3rem] text-right">
{ev.assertions.length} Ass.
</span>
</button>
{/* Expanded: Assertions list */}
{evExpanded && ev.assertions.length > 0 && (
<div className="bg-white border-t">
<table className="w-full text-xs">
<thead className="bg-slate-50">
<tr>
<th className="px-12 py-1.5 text-left text-slate-500 font-medium">Aussage</th>
<th className="px-3 py-1.5 text-center text-slate-500 font-medium w-20">Typ</th>
<th className="px-3 py-1.5 text-center text-slate-500 font-medium w-24">Konfidenz</th>
<th className="px-3 py-1.5 text-center text-slate-500 font-medium w-16">Status</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{ev.assertions.map(a => (
<tr key={a.id} className="hover:bg-slate-50">
<td className="px-12 py-1.5 text-slate-700">{a.sentence_text}</td>
<td className="px-3 py-1.5 text-center text-slate-500">{a.assertion_type}</td>
<td className="px-3 py-1.5 text-center">
<span className={`font-medium ${
a.confidence >= 0.8 ? 'text-green-600'
: a.confidence >= 0.5 ? 'text-yellow-600'
: 'text-red-600'
}`}>
{(a.confidence * 100).toFixed(0)}%
</span>
</td>
<td className="px-3 py-1.5 text-center">
{a.verified
? <span className="text-green-600 font-medium">{'\u2713'}</span>
: <span className="text-slate-400">{'\u2717'}</span>
}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)
})}
</div>
)}
</div>
)
})}
</div>
</div>
)
}

View File

@@ -0,0 +1,104 @@
'use client'
import type { ScoreSnapshot } from './types'
interface TrendTabProps {
scoreHistory: ScoreSnapshot[]
savingSnapshot: boolean
saveSnapshot: () => Promise<void>
}
export function TrendTab({ scoreHistory, savingSnapshot, saveSnapshot }: TrendTabProps) {
return (
<div className="bg-white rounded-xl shadow-sm border p-6">
<div className="flex items-center justify-between mb-6">
<h3 className="text-lg font-semibold text-slate-900">Score-Verlauf</h3>
<button
onClick={saveSnapshot}
disabled={savingSnapshot}
className="px-3 py-1.5 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50"
>
{savingSnapshot ? 'Speichere...' : 'Aktuellen Score speichern'}
</button>
</div>
{scoreHistory.length === 0 ? (
<div className="text-center py-12">
<p className="text-slate-500">Noch keine Score-Snapshots vorhanden.</p>
<p className="text-sm text-slate-400 mt-1">Klicken Sie auf "Aktuellen Score speichern", um den ersten Datenpunkt zu erstellen.</p>
</div>
) : (
<>
{/* Simple SVG Line Chart */}
<div className="relative h-64 mb-6">
<svg className="w-full h-full" viewBox="0 0 800 200" preserveAspectRatio="none">
{/* Grid lines */}
{[0, 25, 50, 75, 100].map(pct => (
<line key={pct} x1="0" y1={200 - pct * 2} x2="800" y2={200 - pct * 2}
stroke="#e2e8f0" strokeWidth="1" />
))}
{/* Score line */}
<polyline
fill="none"
stroke="#9333ea"
strokeWidth="3"
strokeLinejoin="round"
points={scoreHistory.map((s, i) => {
const x = scoreHistory.length === 1 ? 400 : (i / (scoreHistory.length - 1)) * 780 + 10
const y = 200 - (s.score / 100) * 200
return `${x},${y}`
}).join(' ')}
/>
{/* Points */}
{scoreHistory.map((s, i) => {
const x = scoreHistory.length === 1 ? 400 : (i / (scoreHistory.length - 1)) * 780 + 10
const y = 200 - (s.score / 100) * 200
return (
<circle key={i} cx={x} cy={y} r="5" fill="#9333ea" stroke="white" strokeWidth="2" />
)
})}
</svg>
{/* Y-axis labels */}
<div className="absolute left-0 top-0 h-full flex flex-col justify-between text-xs text-slate-400 -ml-2">
<span>100%</span>
<span>75%</span>
<span>50%</span>
<span>25%</span>
<span>0%</span>
</div>
</div>
{/* Snapshot Table */}
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="bg-slate-50">
<tr>
<th className="px-4 py-2 text-left text-xs font-medium text-slate-500 uppercase">Datum</th>
<th className="px-4 py-2 text-center text-xs font-medium text-slate-500 uppercase">Score</th>
<th className="px-4 py-2 text-center text-xs font-medium text-slate-500 uppercase">Controls</th>
<th className="px-4 py-2 text-center text-xs font-medium text-slate-500 uppercase">Bestanden</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-200">
{scoreHistory.slice().reverse().map(snap => (
<tr key={snap.id} className="hover:bg-slate-50">
<td className="px-4 py-2 text-slate-700">{new Date(snap.snapshot_date).toLocaleDateString('de-DE')}</td>
<td className="px-4 py-2 text-center">
<span className={`font-bold ${
snap.score >= 80 ? 'text-green-600' : snap.score >= 60 ? 'text-yellow-600' : 'text-red-600'
}`}>
{typeof snap.score === 'number' ? snap.score.toFixed(1) : snap.score}%
</span>
</td>
<td className="px-4 py-2 text-center text-slate-600">{snap.controls_total}</td>
<td className="px-4 py-2 text-center text-slate-600">{snap.controls_pass}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
)}
</div>
)
}

View File

@@ -0,0 +1,169 @@
// Shared types for Compliance Hub
export interface DashboardData {
compliance_score: number
total_regulations: number
total_requirements: number
total_controls: number
controls_by_status: Record<string, number>
controls_by_domain: Record<string, Record<string, number>>
total_evidence: number
evidence_by_status: Record<string, number>
total_risks: number
risks_by_level: Record<string, number>
multi_score?: {
requirement_coverage: number
evidence_strength: number
validation_quality: number
evidence_freshness: number
control_effectiveness: number
overall_readiness: number
hard_blocks: string[]
} | null
}
export interface Regulation {
id: string
code: string
name: string
full_name: string
regulation_type: string
effective_date: string | null
description: string
requirement_count: number
}
export interface MappingsData {
total: number
by_regulation: Record<string, number>
}
export interface FindingsData {
major_count: number
minor_count: number
ofi_count: number
total: number
open_majors: number
open_minors: number
}
export interface RoadmapItem {
id: string
control_id: string
title: string
status: string
domain: string
owner: string | null
next_review_at: string | null
days_overdue: number
weight: number
}
export interface RoadmapData {
buckets: Record<string, RoadmapItem[]>
counts: Record<string, number>
}
export interface ModuleInfo {
key: string
label: string
count: number
status: string
progress: number
}
export interface ModuleStatusData {
modules: ModuleInfo[]
total: number
started: number
complete: number
overall_progress: number
}
export interface NextAction {
id: string
control_id: string
title: string
status: string
domain: string
owner: string | null
days_overdue: number
urgency_score: number
reason: string
}
export interface ScoreSnapshot {
id: string
score: number
controls_total: number
controls_pass: number
snapshot_date: string
created_at: string
}
export interface TraceabilityAssertion {
id: string
sentence_text: string
assertion_type: string
confidence: number
verified: boolean
}
export interface TraceabilityEvidence {
id: string
title: string
evidence_type: string
confidence_level: string
status: string
assertions: TraceabilityAssertion[]
}
export interface TraceabilityCoverage {
has_evidence: boolean
has_assertions: boolean
all_assertions_verified: boolean
min_confidence_level: string | null
}
export interface TraceabilityControl {
id: string
control_id: string
title: string
status: string
domain: string
evidence: TraceabilityEvidence[]
coverage: TraceabilityCoverage
}
export interface TraceabilityMatrixData {
controls: TraceabilityControl[]
summary: Record<string, number>
}
export type TabKey = 'overview' | 'roadmap' | 'modules' | 'trend' | 'traceability'
export const DOMAIN_LABELS: Record<string, string> = {
gov: 'Governance',
priv: 'Datenschutz',
iam: 'Identity & Access',
crypto: 'Kryptografie',
sdlc: 'Secure Dev',
ops: 'Operations',
ai: 'KI-spezifisch',
cra: 'Supply Chain',
aud: 'Audit',
}
export const BUCKET_LABELS: Record<string, { label: string; color: string; bg: string }> = {
quick_wins: { label: 'Quick Wins', color: 'text-green-700', bg: 'bg-green-50 border-green-200' },
must_have: { label: 'Must Have', color: 'text-red-700', bg: 'bg-red-50 border-red-200' },
should_have: { label: 'Should Have', color: 'text-yellow-700', bg: 'bg-yellow-50 border-yellow-200' },
nice_to_have: { label: 'Nice to Have', color: 'text-slate-700', bg: 'bg-slate-50 border-slate-200' },
}
export const MODULE_ICONS: Record<string, string> = {
vvt: '📋', tom: '🔒', dsfa: '⚠️', loeschfristen: '🗑️', risks: '🎯',
controls: '✅', evidence: '📎', obligations: '📜', incidents: '🚨',
vendor: '🤝', legal_templates: '📄', training: '🎓', audit: '🔍',
security_backlog: '🛡️', quality: '⭐',
}

View File

@@ -1,84 +1,78 @@
'use client' 'use client'
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import type {
export interface DashboardData { DashboardData, Regulation, MappingsData, FindingsData,
compliance_score: number RoadmapData, ModuleStatusData, NextAction, ScoreSnapshot,
total_regulations: number TraceabilityMatrixData, TabKey,
total_requirements: number } from '../_components/types'
total_controls: number
controls_by_status: Record<string, number>
controls_by_domain: Record<string, Record<string, number>>
total_evidence: number
evidence_by_status: Record<string, number>
total_risks: number
risks_by_level: Record<string, number>
}
export interface Regulation {
id: string
code: string
name: string
full_name: string
regulation_type: string
effective_date: string | null
description: string
requirement_count: number
}
export interface MappingsData {
total: number
by_regulation: Record<string, number>
}
export interface FindingsData {
major_count: number
minor_count: number
ofi_count: number
total: number
open_majors: number
open_minors: number
}
export function useComplianceHub() { export function useComplianceHub() {
const [activeTab, setActiveTab] = useState<TabKey>('overview')
const [dashboard, setDashboard] = useState<DashboardData | null>(null) const [dashboard, setDashboard] = useState<DashboardData | null>(null)
const [regulations, setRegulations] = useState<Regulation[]>([]) const [regulations, setRegulations] = useState<Regulation[]>([])
const [mappings, setMappings] = useState<MappingsData | null>(null) const [mappings, setMappings] = useState<MappingsData | null>(null)
const [findings, setFindings] = useState<FindingsData | null>(null) const [findings, setFindings] = useState<FindingsData | null>(null)
const [roadmap, setRoadmap] = useState<RoadmapData | null>(null)
const [moduleStatus, setModuleStatus] = useState<ModuleStatusData | null>(null)
const [nextActions, setNextActions] = useState<NextAction[]>([])
const [scoreHistory, setScoreHistory] = useState<ScoreSnapshot[]>([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [seeding, setSeeding] = useState(false) const [seeding, setSeeding] = useState(false)
const [savingSnapshot, setSavingSnapshot] = useState(false)
const [evidenceDistribution, setEvidenceDistribution] = useState<{
by_confidence: Record<string, number>
four_eyes_pending: number
total: number
} | null>(null)
const [traceabilityMatrix, setTraceabilityMatrix] = useState<TraceabilityMatrixData | null>(null)
const [traceabilityLoading, setTraceabilityLoading] = useState(false)
const [traceabilityFilter, setTraceabilityFilter] = useState<'all' | 'covered' | 'uncovered' | 'fully_verified'>('all')
const [traceabilityDomainFilter, setTraceabilityDomainFilter] = useState<string>('all')
const [expandedControls, setExpandedControls] = useState<Set<string>>(new Set())
const [expandedEvidence, setExpandedEvidence] = useState<Set<string>>(new Set())
useEffect(() => { useEffect(() => {
loadData() loadData()
}, []) }, [])
useEffect(() => {
if (activeTab === 'roadmap' && !roadmap) loadRoadmap()
if (activeTab === 'modules' && !moduleStatus) loadModuleStatus()
if (activeTab === 'trend' && scoreHistory.length === 0) loadScoreHistory()
if (activeTab === 'traceability' && !traceabilityMatrix) loadTraceabilityMatrix()
}, [activeTab]) // eslint-disable-line react-hooks/exhaustive-deps
const loadData = async () => { const loadData = async () => {
setLoading(true) setLoading(true)
setError(null) setError(null)
try { try {
const [dashboardRes, regulationsRes, mappingsRes, findingsRes] = await Promise.all([ const [dashboardRes, regulationsRes, mappingsRes, findingsRes, actionsRes] = await Promise.all([
fetch('/api/sdk/v1/compliance/dashboard'), fetch('/api/sdk/v1/compliance/dashboard'),
fetch('/api/sdk/v1/compliance/regulations'), fetch('/api/sdk/v1/compliance/regulations'),
fetch('/api/sdk/v1/compliance/mappings'), fetch('/api/sdk/v1/compliance/mappings'),
fetch('/api/sdk/v1/isms/findings?status=open'), fetch('/api/sdk/v1/isms/findings?status=open'),
fetch('/api/sdk/v1/compliance/dashboard/next-actions?limit=5'),
]) ])
if (dashboardRes.ok) { if (dashboardRes.ok) setDashboard(await dashboardRes.json())
setDashboard(await dashboardRes.json())
}
if (regulationsRes.ok) { if (regulationsRes.ok) {
const data = await regulationsRes.json() const data = await regulationsRes.json()
setRegulations(data.regulations || []) setRegulations(data.regulations || [])
} }
if (mappingsRes.ok) { if (mappingsRes.ok) setMappings(await mappingsRes.json())
const data = await mappingsRes.json() if (findingsRes.ok) setFindings(await findingsRes.json())
setMappings(data) if (actionsRes.ok) {
} const data = await actionsRes.json()
if (findingsRes.ok) { setNextActions(data.actions || [])
const data = await findingsRes.json()
setFindings(data)
} }
// Evidence distribution (Anti-Fake-Evidence Phase 3)
try {
const evidenceDistRes = await fetch('/api/sdk/v1/compliance/dashboard/evidence-distribution')
if (evidenceDistRes.ok) setEvidenceDistribution(await evidenceDistRes.json())
} catch { /* silent */ }
} catch (err) { } catch (err) {
console.error('Failed to load compliance data:', err) console.error('Failed to load compliance data:', err)
setError('Verbindung zum Backend fehlgeschlagen') setError('Verbindung zum Backend fehlgeschlagen')
@@ -87,6 +81,66 @@ export function useComplianceHub() {
} }
} }
const loadRoadmap = async () => {
try {
const res = await fetch('/api/sdk/v1/compliance/dashboard/roadmap')
if (res.ok) setRoadmap(await res.json())
} catch { /* silent */ }
}
const loadModuleStatus = async () => {
try {
const res = await fetch('/api/sdk/v1/compliance/dashboard/module-status')
if (res.ok) setModuleStatus(await res.json())
} catch { /* silent */ }
}
const loadScoreHistory = async () => {
try {
const res = await fetch('/api/sdk/v1/compliance/dashboard/score-history?months=12')
if (res.ok) {
const data = await res.json()
setScoreHistory(data.snapshots || [])
}
} catch { /* silent */ }
}
const loadTraceabilityMatrix = async () => {
setTraceabilityLoading(true)
try {
const res = await fetch('/api/sdk/v1/compliance/dashboard/traceability-matrix')
if (res.ok) setTraceabilityMatrix(await res.json())
} catch { /* silent */ }
finally { setTraceabilityLoading(false) }
}
const toggleControlExpanded = (id: string) => {
setExpandedControls(prev => {
const next = new Set(prev)
if (next.has(id)) next.delete(id); else next.add(id)
return next
})
}
const toggleEvidenceExpanded = (id: string) => {
setExpandedEvidence(prev => {
const next = new Set(prev)
if (next.has(id)) next.delete(id); else next.add(id)
return next
})
}
const saveSnapshot = async () => {
setSavingSnapshot(true)
try {
const res = await fetch('/api/sdk/v1/compliance/dashboard/snapshot', { method: 'POST' })
if (res.ok) {
loadScoreHistory()
}
} catch { /* silent */ }
finally { setSavingSnapshot(false) }
}
const seedDatabase = async () => { const seedDatabase = async () => {
setSeeding(true) setSeeding(true)
try { try {
@@ -101,8 +155,8 @@ export function useComplianceHub() {
alert(`Datenbank erfolgreich initialisiert!\n\nRegulations: ${result.counts?.regulations || 0}\nControls: ${result.counts?.controls || 0}\nRequirements: ${result.counts?.requirements || 0}`) alert(`Datenbank erfolgreich initialisiert!\n\nRegulations: ${result.counts?.regulations || 0}\nControls: ${result.counts?.controls || 0}\nRequirements: ${result.counts?.requirements || 0}`)
loadData() loadData()
} else { } else {
const errorText = await res.text() const error = await res.text()
alert(`Fehler beim Seeding: ${errorText}`) alert(`Fehler beim Seeding: ${error}`)
} }
} catch (err) { } catch (err) {
console.error('Seeding failed:', err) console.error('Seeding failed:', err)
@@ -112,5 +166,16 @@ export function useComplianceHub() {
} }
} }
return { dashboard, regulations, mappings, findings, loading, error, seeding, loadData, seedDatabase } return {
activeTab, setActiveTab,
dashboard, regulations, mappings, findings,
roadmap, moduleStatus, nextActions, scoreHistory,
loading, error, seeding, savingSnapshot,
evidenceDistribution, traceabilityMatrix, traceabilityLoading,
traceabilityFilter, setTraceabilityFilter,
traceabilityDomainFilter, setTraceabilityDomainFilter,
expandedControls, expandedEvidence,
loadData, saveSnapshot, seedDatabase,
toggleControlExpanded, toggleEvidenceExpanded,
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -9,807 +9,10 @@ import { DataPointsPreview } from './components/DataPointsPreview'
import { DocumentValidation } from './components/DocumentValidation' import { DocumentValidation } from './components/DocumentValidation'
import { generateAllPlaceholders } from '@/lib/sdk/document-generator/datapoint-helpers' import { generateAllPlaceholders } from '@/lib/sdk/document-generator/datapoint-helpers'
import { loadAllTemplates } from './searchTemplates' import { loadAllTemplates } from './searchTemplates'
import { import { TemplateContext, EMPTY_CONTEXT } from './contextBridge'
TemplateContext, EMPTY_CONTEXT, import { CATEGORIES } from './_constants'
contextToPlaceholders, getRelevantSections, import TemplateLibrary from './_components/TemplateLibrary'
getUncoveredPlaceholders, getMissingRequired, import GeneratorSection from './_components/GeneratorSection'
} from './contextBridge'
import {
runRuleset, getDocType, applyBlockRemoval,
buildBoolContext, applyConditionalBlocks,
type RuleInput, type RuleEngineResult,
} from './ruleEngine'
// =============================================================================
// CATEGORY CONFIG
// =============================================================================
const CATEGORIES: { key: string; label: string; types: string[] | null }[] = [
{ key: 'all', label: 'Alle', types: null },
// Legal / Vertragsvorlagen
{ key: 'privacy_policy', label: 'Datenschutz', types: ['privacy_policy'] },
{ key: 'terms', label: 'AGB', types: ['terms_of_service', 'agb', 'clause'] },
{ key: 'impressum', label: 'Impressum', types: ['impressum'] },
{ key: 'dpa', label: 'AVV/DPA', types: ['dpa'] },
{ key: 'nda', label: 'NDA', types: ['nda'] },
{ key: 'sla', label: 'SLA', types: ['sla'] },
{ key: 'widerruf', label: 'Widerruf', types: ['widerruf'] },
{ key: 'cookie', label: 'Cookie', types: ['cookie_policy', 'cookie_banner'] },
{ key: 'cloud', label: 'Cloud', types: ['cloud_service_agreement'] },
{ key: 'misc', label: 'Weitere', types: ['community_guidelines', 'copyright_policy', 'data_usage_clause'] },
{ key: 'dsfa', label: 'DSFA', types: ['dsfa'] },
// Sicherheitskonzepte (Migration 051)
{ key: 'security', label: 'Sicherheitskonzepte', types: ['it_security_concept', 'data_protection_concept', 'backup_recovery_concept', 'logging_concept', 'incident_response_plan', 'access_control_concept', 'risk_management_concept', 'cybersecurity_policy'] },
// Policy-Bibliothek (Migration 071/072)
{ key: 'it_security_policies', label: 'IT-Sicherheit Policies', types: ['information_security_policy', 'access_control_policy', 'password_policy', 'encryption_policy', 'logging_policy', 'backup_policy', 'incident_response_policy', 'change_management_policy', 'patch_management_policy', 'asset_management_policy', 'cloud_security_policy', 'devsecops_policy', 'secrets_management_policy', 'vulnerability_management_policy'] },
{ key: 'data_policies', label: 'Daten-Policies', types: ['data_protection_policy', 'data_classification_policy', 'data_retention_policy', 'data_transfer_policy', 'privacy_incident_policy'] },
{ key: 'hr_policies', label: 'Personal-Policies', types: ['employee_security_policy', 'security_awareness_policy', 'acceptable_use', 'remote_work_policy', 'offboarding_policy'] },
{ key: 'vendor_policies', label: 'Lieferanten-Policies', types: ['vendor_risk_management_policy', 'third_party_security_policy', 'supplier_security_policy'] },
{ key: 'bcm_policies', label: 'BCM/Notfall', types: ['business_continuity_policy', 'disaster_recovery_policy', 'crisis_management_policy'] },
// Modul-Dokumente (Migration 073)
{ key: 'module_docs', label: 'DSGVO-Dokumente', types: ['vvt_register', 'tom_documentation', 'loeschkonzept', 'pflichtenregister'] },
]
// =============================================================================
// CONTEXT FORM CONFIG
// =============================================================================
const SECTION_LABELS: Record<keyof TemplateContext, string> = {
PROVIDER: 'Anbieter',
CUSTOMER: 'Kunde / Gegenpartei',
SERVICE: 'Dienst / Produkt',
LEGAL: 'Rechtliches',
PRIVACY: 'Datenschutz',
SLA: 'Service Level (SLA)',
PAYMENTS: 'Zahlungskonditionen',
SECURITY: 'Sicherheit & Logs',
NDA: 'Geheimhaltung (NDA)',
CONSENT: 'Cookie / Einwilligung',
HOSTING: 'Hosting-Provider',
FEATURES: 'Dokument-Features & Textbausteine',
}
type FieldType = 'text' | 'email' | 'number' | 'select' | 'textarea' | 'boolean'
interface FieldDef {
key: string
label: string
type?: FieldType
opts?: string[]
span?: boolean
nullable?: boolean
}
const SECTION_FIELDS: Record<keyof TemplateContext, FieldDef[]> = {
PROVIDER: [
{ key: 'LEGAL_NAME', label: 'Firmenname' },
{ key: 'EMAIL', label: 'Kontakt-E-Mail', type: 'email' },
{ key: 'LEGAL_FORM', label: 'Rechtsform' },
{ key: 'ADDRESS_LINE', label: 'Adresse' },
{ key: 'POSTAL_CODE', label: 'PLZ' },
{ key: 'CITY', label: 'Stadt' },
{ key: 'WEBSITE_URL', label: 'Website-URL' },
{ key: 'CEO_NAME', label: 'Geschäftsführer' },
{ key: 'REGISTER_COURT', label: 'Registergericht' },
{ key: 'REGISTER_NUMBER', label: 'HRB-Nummer' },
{ key: 'VAT_ID', label: 'USt-ID' },
{ key: 'PHONE', label: 'Telefon' },
],
CUSTOMER: [
{ key: 'LEGAL_NAME', label: 'Name / Firma' },
{ key: 'EMAIL', label: 'E-Mail', type: 'email' },
{ key: 'CONTACT_NAME', label: 'Ansprechpartner' },
{ key: 'ADDRESS_LINE', label: 'Adresse' },
{ key: 'POSTAL_CODE', label: 'PLZ' },
{ key: 'CITY', label: 'Stadt' },
{ key: 'COUNTRY', label: 'Land' },
{ key: 'IS_CONSUMER', label: 'Verbraucher (B2C)', type: 'boolean' },
{ key: 'IS_BUSINESS', label: 'Unternehmer (B2B)', type: 'boolean' },
],
SERVICE: [
{ key: 'NAME', label: 'Dienstname' },
{ key: 'DESCRIPTION', label: 'Beschreibung', type: 'textarea', span: true },
{ key: 'MODEL', label: 'Modell', type: 'select', opts: ['SaaS', 'PaaS', 'IaaS', 'OnPrem', 'Hybrid'] },
{ key: 'TIER', label: 'Plan / Tier' },
{ key: 'DATA_LOCATION', label: 'Datenspeicherort' },
{ key: 'EXPORT_WINDOW_DAYS', label: 'Export-Frist (Tage)', type: 'number' },
{ key: 'MIN_TERM_MONTHS', label: 'Mindestlaufzeit (Monate)', type: 'number' },
{ key: 'TERMINATION_NOTICE_DAYS', label: 'Kündigungsfrist (Tage)', type: 'number' },
],
LEGAL: [
{ key: 'GOVERNING_LAW', label: 'Anwendbares Recht' },
{ key: 'JURISDICTION_CITY', label: 'Gerichtsstand (Stadt)' },
{ key: 'VERSION_DATE', label: 'Versionsstand (JJJJ-MM-TT)' },
{ key: 'EFFECTIVE_DATE', label: 'Gültig ab (JJJJ-MM-TT)' },
],
PRIVACY: [
{ key: 'DPO_NAME', label: 'DSB-Name' },
{ key: 'DPO_EMAIL', label: 'DSB-E-Mail', type: 'email' },
{ key: 'CONTACT_EMAIL', label: 'Datenschutz-Kontakt', type: 'email' },
{ key: 'PRIVACY_POLICY_URL', label: 'Datenschutz-URL' },
{ key: 'COOKIE_POLICY_URL', label: 'Cookie-Policy-URL' },
{ key: 'ANALYTICS_RETENTION_MONTHS', label: 'Analytics-Aufbewahrung (Monate)', type: 'number' },
{ key: 'SUPERVISORY_AUTHORITY_NAME', label: 'Aufsichtsbehörde' },
],
SLA: [
{ key: 'AVAILABILITY_PERCENT', label: 'Verfügbarkeit (%)', type: 'number' },
{ key: 'MAINTENANCE_NOTICE_HOURS', label: 'Wartungsankündigung (h)', type: 'number' },
{ key: 'SUPPORT_EMAIL', label: 'Support-E-Mail', type: 'email' },
{ key: 'SUPPORT_HOURS', label: 'Support-Zeiten' },
{ key: 'RESPONSE_CRITICAL_H', label: 'Reaktion Kritisch (h)', type: 'number' },
{ key: 'RESOLUTION_CRITICAL_H', label: 'Lösung Kritisch (h)', type: 'number' },
{ key: 'RESPONSE_HIGH_H', label: 'Reaktion Hoch (h)', type: 'number' },
{ key: 'RESOLUTION_HIGH_H', label: 'Lösung Hoch (h)', type: 'number' },
{ key: 'RESPONSE_MEDIUM_H', label: 'Reaktion Mittel (h)', type: 'number' },
{ key: 'RESOLUTION_MEDIUM_H', label: 'Lösung Mittel (h)', type: 'number' },
{ key: 'RESPONSE_LOW_H', label: 'Reaktion Niedrig (h)', type: 'number' },
],
PAYMENTS: [
{ key: 'MONTHLY_FEE_EUR', label: 'Monatl. Gebühr (EUR)', type: 'number' },
{ key: 'PAYMENT_DUE_DAY', label: 'Fälligkeitstag', type: 'number' },
{ key: 'PAYMENT_METHOD', label: 'Zahlungsmethode' },
{ key: 'PAYMENT_DAYS', label: 'Zahlungsziel (Tage)', type: 'number' },
],
SECURITY: [
{ key: 'INCIDENT_NOTICE_HOURS', label: 'Meldepflicht Vorfälle (h)', type: 'number' },
{ key: 'LOG_RETENTION_DAYS', label: 'Log-Aufbewahrung (Tage)', type: 'number' },
{ key: 'SECURITY_LOG_RETENTION_DAYS', label: 'Sicherheits-Log (Tage)', type: 'number' },
],
NDA: [
{ key: 'PURPOSE', label: 'Zweck', type: 'textarea', span: true },
{ key: 'DURATION_YEARS', label: 'Laufzeit (Jahre)', type: 'number' },
{ key: 'PENALTY_AMOUNT_EUR', label: 'Vertragsstrafe EUR (leer = keine)', type: 'number', nullable: true },
],
CONSENT: [
{ key: 'WEBSITE_NAME', label: 'Website-Name' },
{ key: 'ANALYTICS_TOOLS', label: 'Analytics-Tools (leer = kein Block)', nullable: true },
{ key: 'MARKETING_PARTNERS', label: 'Marketing-Partner (leer = kein Block)', nullable: true },
],
HOSTING: [
{ key: 'PROVIDER_NAME', label: 'Hosting-Anbieter' },
{ key: 'COUNTRY', label: 'Hosting-Land' },
{ key: 'CONTRACT_TYPE', label: 'Vertragstyp (z. B. AVV nach Art. 28 DSGVO)' },
],
FEATURES: [
// ── DSI / Cookie ─────────────────────────────────────────────────────────
{ key: 'CONSENT_WITHDRAWAL_PATH', label: 'Einwilligungs-Widerrufspfad' },
{ key: 'SECURITY_MEASURES_SUMMARY', label: 'Sicherheitsmaßnahmen (kurz)' },
{ key: 'DATA_SUBJECT_REQUEST_CHANNEL', label: 'Kanal für Betroffenenanfragen' },
{ key: 'HAS_THIRD_COUNTRY', label: 'Drittlandübermittlung möglich', type: 'boolean' },
{ key: 'TRANSFER_GUARDS', label: 'Garantien (z. B. SCC)' },
// ── Cookie/Consent ───────────────────────────────────────────────────────
{ key: 'HAS_FUNCTIONAL_COOKIES', label: 'Funktionale Cookies aktiviert', type: 'boolean' },
{ key: 'CMP_NAME', label: 'Consent-Manager-Name (optional)' },
{ key: 'CMP_LOGS_CONSENTS', label: 'Consent-Protokollierung aktiv', type: 'boolean' },
{ key: 'ANALYTICS_TOOLS_DETAIL', label: 'Analyse-Tools (Detailtext)', type: 'textarea', span: true },
{ key: 'MARKETING_TOOLS_DETAIL', label: 'Marketing-Tools (Detailtext)', type: 'textarea', span: true },
// ── Service-Features ─────────────────────────────────────────────────────
{ key: 'HAS_ACCOUNT', label: 'Nutzerkonten vorhanden', type: 'boolean' },
{ key: 'HAS_PAYMENTS', label: 'Zahlungsabwicklung vorhanden', type: 'boolean' },
{ key: 'PAYMENT_PROVIDER_DETAIL', label: 'Zahlungsanbieter (Detailtext)', type: 'textarea', span: true },
{ key: 'HAS_SUPPORT', label: 'Support-Funktion vorhanden', type: 'boolean' },
{ key: 'SUPPORT_CHANNELS_TEXT', label: 'Support-Kanäle / Zeiten' },
{ key: 'HAS_NEWSLETTER', label: 'Newsletter vorhanden', type: 'boolean' },
{ key: 'NEWSLETTER_PROVIDER_DETAIL', label: 'Newsletter-Anbieter (Detailtext)', type: 'textarea', span: true },
{ key: 'HAS_SOCIAL_MEDIA', label: 'Social-Media-Präsenz', type: 'boolean' },
{ key: 'SOCIAL_MEDIA_DETAIL', label: 'Social-Media-Details', type: 'textarea', span: true },
// ── AGB ──────────────────────────────────────────────────────────────────
{ key: 'HAS_PAID_PLANS', label: 'Kostenpflichtige Pläne', type: 'boolean' },
{ key: 'PRICES_TEXT', label: 'Preise (Text/Link)', type: 'textarea', span: true },
{ key: 'PAYMENT_TERMS_TEXT', label: 'Zahlungsbedingungen', type: 'textarea', span: true },
{ key: 'CONTRACT_TERM_TEXT', label: 'Laufzeit & Kündigung', type: 'textarea', span: true },
{ key: 'HAS_SLA', label: 'SLA vorhanden', type: 'boolean' },
{ key: 'SLA_URL', label: 'SLA-URL' },
{ key: 'HAS_EXPORT_POLICY', label: 'Datenexport/Löschung geregelt', type: 'boolean' },
{ key: 'EXPORT_POLICY_TEXT', label: 'Datenexport-Regelung (Text)', type: 'textarea', span: true },
{ key: 'HAS_WITHDRAWAL', label: 'Widerrufsrecht (B2C digital)', type: 'boolean' },
{ key: 'CONSUMER_WITHDRAWAL_TEXT', label: 'Widerrufsbelehrung (Text)', type: 'textarea', span: true },
{ key: 'LIMITATION_CAP_TEXT', label: 'Haftungsdeckel B2B (Text)' },
// ── Impressum ────────────────────────────────────────────────────────────
{ key: 'HAS_REGULATED_PROFESSION', label: 'Reglementierter Beruf', type: 'boolean' },
{ key: 'REGULATED_PROFESSION_TEXT', label: 'Berufsrecht-Text', type: 'textarea', span: true },
{ key: 'HAS_EDITORIAL_RESPONSIBLE', label: 'V.i.S.d.P. (redaktionell)', type: 'boolean' },
{ key: 'EDITORIAL_RESPONSIBLE_NAME', label: 'V.i.S.d.P. Name' },
{ key: 'EDITORIAL_RESPONSIBLE_ADDRESS', label: 'V.i.S.d.P. Adresse' },
{ key: 'HAS_DISPUTE_RESOLUTION', label: 'Streitbeilegungshinweis', type: 'boolean' },
{ key: 'DISPUTE_RESOLUTION_TEXT', label: 'Streitbeilegungstext', type: 'textarea', span: true },
],
}
// =============================================================================
// SMALL COMPONENTS
// =============================================================================
function LicenseBadge({ licenseId, small = false }: { licenseId: LicenseType | null; small?: boolean }) {
if (!licenseId) return null
const colors: Partial<Record<LicenseType, string>> = {
public_domain: 'bg-green-100 text-green-700 border-green-200',
cc0: 'bg-green-100 text-green-700 border-green-200',
unlicense: 'bg-green-100 text-green-700 border-green-200',
mit: 'bg-blue-100 text-blue-700 border-blue-200',
cc_by_4: 'bg-purple-100 text-purple-700 border-purple-200',
reuse_notice: 'bg-orange-100 text-orange-700 border-orange-200',
}
return (
<span className={`${small ? 'px-1.5 py-0.5 text-[10px]' : 'px-2 py-1 text-xs'} rounded border ${colors[licenseId] || 'bg-gray-100 text-gray-600 border-gray-200'}`}>
{LICENSE_TYPE_LABELS[licenseId] || licenseId}
</span>
)
}
// =============================================================================
// LIBRARY CARD
// =============================================================================
function LibraryCard({
template,
expanded,
onTogglePreview,
onUse,
}: {
template: LegalTemplateResult
expanded: boolean
onTogglePreview: () => void
onUse: () => void
}) {
const typeLabel = template.templateType
? (TEMPLATE_TYPE_LABELS[template.templateType as TemplateType] || template.templateType)
: null
const placeholderCount = template.placeholders?.length ?? 0
return (
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden hover:border-purple-300 transition-colors">
<div className="p-4">
<div className="flex items-start justify-between gap-2 mb-2">
<h3 className="font-medium text-gray-900 text-sm leading-snug">
{template.documentTitle || 'Vorlage'}
</h3>
<span className="text-xs text-gray-400 uppercase shrink-0">{template.language}</span>
</div>
<div className="flex items-center gap-2 flex-wrap mb-3">
{typeLabel && (
<span className="text-xs text-purple-600 bg-purple-50 px-2 py-0.5 rounded">
{typeLabel}
</span>
)}
<LicenseBadge licenseId={template.licenseId as LicenseType} small />
{placeholderCount > 0 && (
<span className="text-xs text-gray-500">{placeholderCount} Platzh.</span>
)}
</div>
<div className="flex gap-2">
<button
onClick={onTogglePreview}
className="flex-1 text-xs px-3 py-1.5 border border-gray-200 rounded-lg hover:bg-gray-50 text-gray-600 transition-colors"
>
{expanded ? 'Vorschau ▲' : 'Vorschau ▼'}
</button>
<button
onClick={onUse}
className="flex-1 text-xs px-3 py-1.5 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
>
Verwenden
</button>
</div>
</div>
{expanded && (
<div className="border-t border-gray-100 bg-gray-50 p-4 max-h-[32rem] overflow-y-auto">
<pre className="text-xs text-gray-600 whitespace-pre-wrap font-mono leading-relaxed">
{template.text}
</pre>
</div>
)}
</div>
)
}
// =============================================================================
// CONTEXT SECTION FORM
// =============================================================================
function ContextSectionForm({
section,
context,
onChange,
}: {
section: keyof TemplateContext
context: TemplateContext
onChange: (section: keyof TemplateContext, key: string, value: unknown) => void
}) {
const fields = SECTION_FIELDS[section]
const sectionData = context[section] as unknown as Record<string, unknown>
return (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{fields.map((field) => {
const rawValue = sectionData[field.key]
const inputCls = 'w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-purple-400'
if (field.type === 'boolean') {
return (
<div key={field.key} className="flex items-center gap-2 py-2">
<input
type="checkbox"
id={`${section}-${field.key}`}
checked={!!rawValue}
onChange={(e) => onChange(section, field.key, e.target.checked)}
className="w-4 h-4 accent-purple-600"
/>
<label htmlFor={`${section}-${field.key}`} className="text-sm text-gray-700">
{field.label}
</label>
</div>
)
}
if (field.type === 'select' && field.opts) {
return (
<div key={field.key} className={field.span ? 'md:col-span-2' : ''}>
<label className="block text-xs text-gray-500 mb-1">{field.label}</label>
<select
value={String(rawValue ?? '')}
onChange={(e) => onChange(section, field.key, e.target.value)}
className={inputCls}
>
{field.opts.map((o) => <option key={o} value={o}>{o}</option>)}
</select>
</div>
)
}
if (field.type === 'textarea') {
return (
<div key={field.key} className={field.span ? 'md:col-span-2' : ''}>
<label className="block text-xs text-gray-500 mb-1">{field.label}</label>
<textarea
value={String(rawValue ?? '')}
onChange={(e) => onChange(section, field.key, field.nullable && e.target.value === '' ? null : e.target.value)}
rows={3}
className={`${inputCls} resize-none`}
/>
</div>
)
}
if (field.type === 'number') {
return (
<div key={field.key} className={field.span ? 'md:col-span-2' : ''}>
<label className="block text-xs text-gray-500 mb-1">{field.label}</label>
<input
type="number"
value={rawValue === null || rawValue === undefined ? '' : String(rawValue)}
onChange={(e) => {
const v = e.target.value
onChange(section, field.key, field.nullable && v === '' ? null : v === '' ? '' : Number(v))
}}
className={inputCls}
/>
</div>
)
}
// default: text / email
return (
<div key={field.key} className={field.span ? 'md:col-span-2' : ''}>
<label className="block text-xs text-gray-500 mb-1">{field.label}</label>
<input
type={field.type === 'email' ? 'email' : 'text'}
value={rawValue === null || rawValue === undefined ? '' : String(rawValue)}
onChange={(e) => onChange(section, field.key, field.nullable && e.target.value === '' ? null : e.target.value)}
className={inputCls}
/>
</div>
)
})}
</div>
)
}
// =============================================================================
// GENERATOR SECTION
// =============================================================================
// Available module definitions (id → display label)
const MODULE_LABELS: Record<string, string> = {
CLOUD_EXPORT_DELETE_DE: 'Datenexport & Löschrecht',
B2C_WITHDRAWAL_DE: 'Widerrufsrecht (B2C)',
}
function GeneratorSection({
template,
context,
onContextChange,
extraPlaceholders,
onExtraChange,
onClose,
enabledModules,
onModuleToggle,
}: {
template: LegalTemplateResult
context: TemplateContext
onContextChange: (section: keyof TemplateContext, key: string, value: unknown) => void
extraPlaceholders: Record<string, string>
onExtraChange: (key: string, value: string) => void
onClose: () => void
enabledModules: string[]
onModuleToggle: (mod: string, checked: boolean) => void
}) {
const [activeTab, setActiveTab] = useState<'placeholders' | 'preview'>('placeholders')
const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set(['PROVIDER', 'LEGAL']))
const placeholders = template.placeholders || []
const relevantSections = useMemo(() => getRelevantSections(placeholders), [placeholders])
const uncovered = useMemo(() => getUncoveredPlaceholders(placeholders, context), [placeholders, context])
const missing = useMemo(() => getMissingRequired(placeholders, context), [placeholders, context])
// Rule engine evaluation
const ruleResult = useMemo((): RuleEngineResult | null => {
if (!template) return null
return runRuleset({
doc_type: getDocType(template.templateType ?? '', template.language ?? 'de'),
render: { lang: template.language ?? 'de', variant: 'standard' },
context,
modules: { enabled: enabledModules },
} satisfies RuleInput)
}, [template, context, enabledModules])
const allPlaceholderValues = useMemo(() => ({
...contextToPlaceholders(ruleResult?.contextAfterDefaults ?? context),
...extraPlaceholders,
}), [context, extraPlaceholders, ruleResult])
// Boolean context for {{#IF}} rendering
const boolCtx = useMemo(
() => ruleResult ? buildBoolContext(ruleResult.contextAfterDefaults, ruleResult.computedFlags) : {},
[ruleResult]
)
const renderedContent = useMemo(() => {
// 1. Remove ruleset-driven blocks ([BLOCK:ID])
let content = applyBlockRemoval(template.text, ruleResult?.removedBlocks ?? [])
// 2. Evaluate {{#IF}} / {{#IF_NOT}} / {{#IF_ANY}} directives
content = applyConditionalBlocks(content, boolCtx)
// 3. Substitute placeholders
for (const [key, value] of Object.entries(allPlaceholderValues)) {
if (value) {
content = content.replace(new RegExp(key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), value)
}
}
return content
}, [template.text, allPlaceholderValues, ruleResult, boolCtx])
// Compute which modules are relevant (mentioned in violations/warnings)
const relevantModules = useMemo(() => {
if (!ruleResult) return []
const mentioned = new Set<string>()
const allIssues = [...ruleResult.violations, ...ruleResult.warnings]
for (const issue of allIssues) {
if (issue.phase === 'module_requirements') {
// Extract module ID from message
for (const modId of Object.keys(MODULE_LABELS)) {
if (issue.message.includes(modId)) mentioned.add(modId)
}
}
}
// Also show modules that are enabled but not mentioned
for (const mod of enabledModules) {
if (mod in MODULE_LABELS) mentioned.add(mod)
}
return [...mentioned]
}, [ruleResult, enabledModules])
const handleCopy = () => navigator.clipboard.writeText(renderedContent)
const handleExportMarkdown = () => {
const blob = new Blob([renderedContent], { type: 'text/markdown' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `${(template.documentTitle || 'dokument').replace(/\s+/g, '-').toLowerCase()}.md`
a.click()
URL.revokeObjectURL(url)
}
const toggleSection = (sec: string) => {
setExpandedSections((prev) => {
const next = new Set(prev)
if (next.has(sec)) next.delete(sec)
else next.add(sec)
return next
})
}
// Auto-expand all relevant sections on first render
useEffect(() => {
if (relevantSections.length > 0) {
setExpandedSections(new Set(relevantSections))
}
}, [template.id]) // eslint-disable-line react-hooks/exhaustive-deps
// Computed flags pills config
const flagPills: { key: string; label: string; color: string }[] = ruleResult ? [
{ key: 'IS_B2C', label: 'B2C', color: 'bg-blue-100 text-blue-700' },
{ key: 'SERVICE_IS_SAAS', label: 'SaaS', color: 'bg-green-100 text-green-700' },
{ key: 'HAS_PENALTY', label: 'Vertragsstrafe', color: 'bg-orange-100 text-orange-700' },
{ key: 'HAS_ANALYTICS', label: 'Analytics', color: 'bg-gray-100 text-gray-600' },
] : []
return (
<div className="bg-white rounded-xl border-2 border-purple-300 overflow-hidden">
{/* Header */}
<div className="bg-purple-50 px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-3 flex-wrap">
<svg className="w-5 h-5 text-purple-600 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
<div>
<div className="text-xs text-purple-500 font-medium uppercase tracking-wide">Generator</div>
<div className="font-semibold text-gray-900 text-sm">{template.documentTitle}</div>
</div>
{/* Computed flags pills */}
{ruleResult && (
<div className="flex gap-1.5 flex-wrap">
{flagPills.map(({ key, label, color }) =>
ruleResult.computedFlags[key] ? (
<span key={key} className={`px-2 py-0.5 text-[10px] font-medium rounded-full ${color}`}>
{label}
</span>
) : null
)}
</div>
)}
</div>
<button onClick={onClose} className="text-gray-400 hover:text-gray-600 transition-colors shrink-0" aria-label="Schließen">
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Tab bar */}
<div className="flex border-b border-gray-200 px-6">
{(['placeholders', 'preview'] as const).map((tab) => (
<button
key={tab}
onClick={() => setActiveTab(tab)}
className={`px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${
activeTab === tab
? 'text-purple-600 border-purple-600'
: 'text-gray-500 border-transparent hover:text-gray-700'
}`}
>
{tab === 'placeholders' ? 'Kontext ausfüllen' : 'Vorschau & Export'}
{tab === 'placeholders' && missing.length > 0 && (
<span className="ml-2 px-1.5 py-0.5 text-[10px] bg-orange-100 text-orange-600 rounded-full">
{missing.length}
</span>
)}
{tab === 'preview' && ruleResult && ruleResult.violations.length > 0 && (
<span className="ml-2 px-1.5 py-0.5 text-[10px] bg-red-100 text-red-600 rounded-full">
{ruleResult.violations.length}
</span>
)}
</button>
))}
</div>
{/* Tab content */}
<div className="p-6">
{activeTab === 'placeholders' && (
<div className="space-y-4">
{placeholders.length === 0 ? (
<div className="text-sm text-gray-500 text-center py-4">
Keine Platzhalter Vorlage kann direkt verwendet werden.
</div>
) : (
<>
{/* Relevant sections */}
{relevantSections.length === 0 ? (
<p className="text-sm text-gray-500">Alle Platzhalter müssen manuell befüllt werden.</p>
) : (
<div className="space-y-3">
{relevantSections.map((section) => (
<div key={section} className="border border-gray-200 rounded-xl overflow-hidden">
<button
onClick={() => toggleSection(section)}
className="w-full flex items-center justify-between px-4 py-3 bg-gray-50 hover:bg-gray-100 transition-colors text-left"
>
<span className="text-sm font-medium text-gray-800">{SECTION_LABELS[section]}</span>
<svg
className={`w-4 h-4 text-gray-400 transition-transform ${expandedSections.has(section) ? 'rotate-180' : ''}`}
fill="none" stroke="currentColor" viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
{expandedSections.has(section) && (
<div className="p-4 border-t border-gray-100">
<ContextSectionForm
section={section}
context={context}
onChange={onContextChange}
/>
</div>
)}
</div>
))}
</div>
)}
{/* Uncovered / manual placeholders */}
{uncovered.length > 0 && (
<div className="border border-dashed border-gray-300 rounded-xl p-4">
<p className="text-xs font-medium text-gray-500 uppercase tracking-wide mb-3">
Weitere Platzhalter (manuell ausfüllen)
</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{uncovered.map((ph) => (
<div key={ph}>
<label className="block text-xs text-gray-500 mb-1 font-mono">{ph}</label>
<input
type="text"
value={extraPlaceholders[ph] || ''}
onChange={(e) => onExtraChange(ph, e.target.value)}
placeholder={`Wert für ${ph}`}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-purple-400"
/>
</div>
))}
</div>
</div>
)}
{/* Module toggles */}
{relevantModules.length > 0 && (
<div className="border border-gray-200 rounded-xl p-4">
<p className="text-xs font-medium text-gray-500 uppercase tracking-wide mb-3">Module</p>
<div className="space-y-2">
{relevantModules.map((modId) => (
<label key={modId} className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={enabledModules.includes(modId)}
onChange={(e) => onModuleToggle(modId, e.target.checked)}
className="w-4 h-4 accent-purple-600"
/>
<span className="text-xs font-mono text-gray-600">{modId}</span>
{MODULE_LABELS[modId] && (
<span className="text-xs text-gray-500">{MODULE_LABELS[modId]}</span>
)}
</label>
))}
</div>
</div>
)}
{/* Validation summary + CTA */}
<div className="flex items-center justify-between pt-2 flex-wrap gap-3">
<div>
{missing.length > 0 ? (
<span className="text-sm text-orange-600">
{missing.length} Pflichtfeld{missing.length > 1 ? 'er' : ''} fehlt{missing.length === 1 ? '' : 'en'}
<span className="ml-1 text-xs text-orange-400">
({missing.map((m) => m.replace(/\{\{|\}\}/g, '')).slice(0, 3).join(', ')}{missing.length > 3 ? ` +${missing.length - 3}` : ''})
</span>
</span>
) : (
<span className="text-sm text-green-600">Alle Pflichtfelder ausgefüllt</span>
)}
</div>
<button
onClick={() => setActiveTab('preview')}
className="px-5 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700 transition-colors"
>
Zur Vorschau
</button>
</div>
</>
)}
</div>
)}
{activeTab === 'preview' && (
<div className="space-y-4">
{/* Rule engine banners */}
{ruleResult && ruleResult.violations.length > 0 && (
<div className="bg-red-50 border border-red-200 rounded-xl p-4">
<p className="text-sm font-semibold text-red-700 mb-2">
🔴 {ruleResult.violations.length} Fehler
</p>
<ul className="space-y-1">
{ruleResult.violations.map((v) => (
<li key={v.id} className="text-xs text-red-600">
<span className="font-mono font-medium">[{v.id}]</span> {v.message}
</li>
))}
</ul>
</div>
)}
{ruleResult && ruleResult.warnings.filter((w) => w.id !== 'WARN_LEGAL_REVIEW').length > 0 && (
<div className="bg-yellow-50 border border-yellow-200 rounded-xl p-4">
<ul className="space-y-1">
{ruleResult.warnings
.filter((w) => w.id !== 'WARN_LEGAL_REVIEW')
.map((w) => (
<li key={w.id} className="text-xs text-yellow-700">
🟡 <span className="font-mono font-medium">[{w.id}]</span> {w.message}
</li>
))}
</ul>
</div>
)}
{ruleResult && (
<div className="bg-blue-50 border border-blue-200 rounded-xl p-3">
<p className="text-xs text-blue-700">
Rechtlicher Hinweis: Diese Vorlage ist MIT-lizenziert. Vor Produktionseinsatz
wird eine rechtliche Überprüfung dringend empfohlen.
</p>
</div>
)}
{ruleResult && ruleResult.appliedDefaults.length > 0 && (
<p className="text-xs text-gray-400">
Defaults angewendet: {ruleResult.appliedDefaults.join(', ')}
</p>
)}
<div className="flex items-center justify-between flex-wrap gap-2">
<span className="text-sm text-gray-600">
{missing.length > 0 && (
<span className="text-orange-600">
{missing.length} Platzhalter noch nicht ausgefüllt
</span>
)}
</span>
<div className="flex gap-2">
<button
onClick={handleCopy}
className="flex items-center gap-1.5 px-3 py-1.5 text-xs border border-gray-200 rounded-lg hover:bg-gray-50 text-gray-600 transition-colors"
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
Kopieren
</button>
<button
onClick={handleExportMarkdown}
className="flex items-center gap-1.5 px-3 py-1.5 text-xs border border-gray-200 rounded-lg hover:bg-gray-50 text-gray-600 transition-colors"
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
Markdown
</button>
<button
onClick={() => window.print()}
className="flex items-center gap-1.5 px-4 py-1.5 text-xs bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
</svg>
PDF drucken
</button>
</div>
</div>
<div className="bg-gray-50 rounded-xl border border-gray-200 p-6 max-h-[600px] overflow-y-auto">
<pre className="text-sm text-gray-800 whitespace-pre-wrap leading-relaxed font-sans">
{renderedContent}
</pre>
</div>
{template.attributionRequired && template.attributionText && (
<div className="text-xs text-orange-600 bg-orange-50 p-3 rounded-lg border border-orange-200">
<strong>Attribution erforderlich:</strong> {template.attributionText}
</div>
)}
</div>
)}
</div>
</div>
)
}
// =============================================================================
// MAIN PAGE
// =============================================================================
function DocumentGeneratorPageInner() { function DocumentGeneratorPageInner() {
const { state } = useSDK() const { state } = useSDK()
@@ -893,7 +96,7 @@ function DocumentGeneratorPageInner() {
// Filtered templates (computed) // Filtered templates (computed)
const filteredTemplates = useMemo(() => { const filteredTemplates = useMemo(() => {
const category = CATEGORIES.find((c) => c.key === activeCategory) const category = CATEGORIES.find((c: { key: string }) => c.key === activeCategory)
return allTemplates.filter((t) => { return allTemplates.filter((t) => {
if (category && category.types !== null) { if (category && category.types !== null) {
if (!category.types.includes(t.templateType || '')) return false if (!category.types.includes(t.templateType || '')) return false

View File

@@ -83,6 +83,19 @@ export default function ObligationDetail({ obligation, onClose, onStatusChange,
</div> </div>
)} )}
{obligation.linked_vendor_ids && obligation.linked_vendor_ids.length > 0 && (
<div>
<span className="text-gray-500">Verknuepfte Auftragsverarbeiter</span>
<div className="flex flex-wrap gap-1 mt-1">
{obligation.linked_vendor_ids.map(id => (
<a key={id} href="/sdk/vendor-compliance" className="px-2 py-0.5 text-xs bg-indigo-50 text-indigo-700 rounded hover:bg-indigo-100 transition-colors">
{id}
</a>
))}
</div>
</div>
)}
{obligation.notes && ( {obligation.notes && (
<div> <div>
<span className="text-gray-500">Notizen</span> <span className="text-gray-500">Notizen</span>

View File

@@ -154,6 +154,18 @@ export default function ObligationModal({
/> />
</div> </div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Verknuepfte Auftragsverarbeiter</label>
<input
type="text"
value={form.linked_vendor_ids}
onChange={e => update('linked_vendor_ids', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500"
placeholder="Kommagetrennt: Vendor-ID-1, Vendor-ID-2"
/>
<p className="text-xs text-gray-400 mt-1">IDs der Auftragsverarbeiter aus dem Vendor Register</p>
</div>
<div> <div>
<label className="block text-sm font-medium text-gray-700 mb-1">Notizen</label> <label className="block text-sm font-medium text-gray-700 mb-1">Notizen</label>
<textarea <textarea

View File

@@ -3,15 +3,22 @@
import React from 'react' import React from 'react'
import type { ObligationStats } from '../_types' import type { ObligationStats } from '../_types'
export default function StatsGrid({ stats }: { stats: ObligationStats | null }) { export default function StatsGrid({
stats,
complianceScore,
}: {
stats: ObligationStats | null
complianceScore: number | string | null
}) {
const items = [ const items = [
{ label: 'Ausstehend', value: stats?.pending ?? 0, color: 'text-gray-600', border: 'border-gray-200' }, { label: 'Ausstehend', value: stats?.pending ?? 0, color: 'text-gray-600', border: 'border-gray-200' },
{ label: 'In Bearbeitung',value: stats?.in_progress ?? 0, color: 'text-blue-600', border: 'border-blue-200' }, { label: 'In Bearbeitung', value: stats?.in_progress ?? 0, color: 'text-blue-600', border: 'border-blue-200' },
{ label: 'Ueberfaellig', value: stats?.overdue ?? 0, color: 'text-red-600', border: 'border-red-200' }, { label: 'Ueberfaellig', value: stats?.overdue ?? 0, color: 'text-red-600', border: 'border-red-200' },
{ label: 'Abgeschlossen', value: stats?.completed ?? 0, color: 'text-green-600', border: 'border-green-200'}, { label: 'Abgeschlossen', value: stats?.completed ?? 0, color: 'text-green-600', border: 'border-green-200' },
{ label: 'Compliance-Score', value: complianceScore ?? '—', color: 'text-purple-600', border: 'border-purple-200' },
] ]
return ( return (
<div className="grid grid-cols-2 md:grid-cols-4 gap-4"> <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
{items.map(s => ( {items.map(s => (
<div key={s.label} className={`bg-white rounded-xl border ${s.border} p-5`}> <div key={s.label} className={`bg-white rounded-xl border ${s.border} p-5`}>
<div className={`text-xs ${s.color}`}>{s.label}</div> <div className={`text-xs ${s.color}`}>{s.label}</div>

View File

@@ -0,0 +1,222 @@
'use client'
import { useState, useEffect, useCallback, useMemo } from 'react'
import { useSDK } from '@/lib/sdk'
import { buildAssessmentPayload } from '@/lib/sdk/scope-to-facts'
import type { ApplicableRegulation } from '@/lib/sdk/compliance-scope-types'
import type { Obligation, ObligationComplianceCheckResult } from '@/lib/sdk/obligations-compliance'
import { runObligationComplianceCheck } from '@/lib/sdk/obligations-compliance'
import {
API, UCCA_API, mapPriority,
type ObligationFormData, type ObligationStats,
} from '../_types'
type Tab = 'uebersicht' | 'editor' | 'profiling' | 'gap-analyse' | 'pflichtenregister'
export function useObligations() {
const { state: sdkState } = useSDK()
const [obligations, setObligations] = useState<Obligation[]>([])
const [stats, setStats] = useState<ObligationStats | null>(null)
const [filter, setFilter] = useState('all')
const [regulationFilter, setRegulationFilter] = useState('all')
const [searchQuery, setSearchQuery] = useState('')
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [showModal, setShowModal] = useState(false)
const [editObligation, setEditObligation] = useState<Obligation | null>(null)
const [detailObligation, setDetailObligation] = useState<Obligation | null>(null)
const [profiling, setProfiling] = useState(false)
const [applicableRegs, setApplicableRegs] = useState<ApplicableRegulation[]>([])
const [activeTab, setActiveTab] = useState<Tab>('uebersicht')
const complianceResult = useMemo<ObligationComplianceCheckResult | null>(() => {
if (obligations.length === 0) return null
return runObligationComplianceCheck(obligations)
}, [obligations])
const loadData = useCallback(async () => {
setLoading(true)
setError(null)
try {
const params = new URLSearchParams({ limit: '200' })
if (filter !== 'all' && ['pending', 'in-progress', 'completed', 'overdue'].includes(filter)) {
params.set('status', filter)
}
if (filter === 'critical' || filter === 'high') {
params.set('priority', filter)
}
if (searchQuery) params.set('search', searchQuery)
const [listRes, statsRes] = await Promise.all([
fetch(`${API}?${params}`),
fetch(`${API}/stats`),
])
if (listRes.ok) {
const data = await listRes.json()
setObligations(data.obligations || [])
}
if (statsRes.ok) {
setStats(await statsRes.json())
}
} catch {
setError('Verbindung zum Backend fehlgeschlagen')
} finally {
setLoading(false)
}
}, [filter, searchQuery])
useEffect(() => {
loadData()
}, [loadData])
const handleCreate = async (form: ObligationFormData) => {
const res = await fetch(API, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: form.title,
description: form.description || null,
source: form.source,
source_article: form.source_article || null,
deadline: form.deadline || null,
status: form.status,
priority: form.priority,
responsible: form.responsible || null,
linked_systems: form.linked_systems ? form.linked_systems.split(',').map(s => s.trim()).filter(Boolean) : [],
linked_vendor_ids: form.linked_vendor_ids ? form.linked_vendor_ids.split(',').map(s => s.trim()).filter(Boolean) : [],
notes: form.notes || null,
}),
})
if (!res.ok) throw new Error('Erstellen fehlgeschlagen')
await loadData()
}
const handleUpdate = async (id: string, form: ObligationFormData) => {
const res = await fetch(`${API}/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: form.title,
description: form.description || null,
source: form.source,
source_article: form.source_article || null,
deadline: form.deadline || null,
status: form.status,
priority: form.priority,
responsible: form.responsible || null,
linked_systems: form.linked_systems ? form.linked_systems.split(',').map(s => s.trim()).filter(Boolean) : [],
linked_vendor_ids: form.linked_vendor_ids ? form.linked_vendor_ids.split(',').map(s => s.trim()).filter(Boolean) : [],
notes: form.notes || null,
}),
})
if (!res.ok) throw new Error('Aktualisierung fehlgeschlagen')
await loadData()
if (detailObligation?.id === id) {
const updated = await fetch(`${API}/${id}`)
if (updated.ok) setDetailObligation(await updated.json())
}
}
const handleStatusChange = async (id: string, newStatus: string) => {
const res = await fetch(`${API}/${id}/status`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: newStatus }),
})
if (!res.ok) return
const updated = await res.json()
setObligations(prev => prev.map(o => o.id === id ? updated : o))
if (detailObligation?.id === id) setDetailObligation(updated)
fetch(`${API}/stats`).then(r => r.json()).then(setStats).catch(() => {})
}
const handleDelete = async (id: string) => {
const res = await fetch(`${API}/${id}`, { method: 'DELETE' })
if (!res.ok && res.status !== 204) throw new Error('Loeschen fehlgeschlagen')
setObligations(prev => prev.filter(o => o.id !== id))
setDetailObligation(null)
fetch(`${API}/stats`).then(r => r.json()).then(setStats).catch(() => {})
}
const handleAutoProfiling = async () => {
setProfiling(true)
setError(null)
try {
const profile = sdkState.companyProfile
const scopeState = sdkState.complianceScope
const scopeAnswers = scopeState?.answers || []
const scopeDecision = scopeState?.decision || null
let payload: Record<string, unknown>
if (profile) {
payload = buildAssessmentPayload(profile, scopeAnswers, scopeDecision) as unknown as Record<string, unknown>
} else {
payload = {
employee_count: 50,
industry: 'technology',
country: 'DE',
processes_personal_data: true,
is_controller: true,
uses_processors: true,
determined_level: scopeDecision?.determinedLevel || 'L2',
}
}
const res = await fetch(`${UCCA_API}/assess-from-scope`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
const regs: ApplicableRegulation[] = data.overview?.applicable_regulations || data.applicable_regulations || []
setApplicableRegs(regs)
const rawObls = data.overview?.obligations || data.obligations || []
if (rawObls.length > 0) {
const autoObls: Obligation[] = rawObls.map((o: Record<string, unknown>) => ({
id: o.id as string,
title: o.title as string,
description: (o.description as string) || '',
source: (o.regulation_id as string || '').toUpperCase(),
source_article: '',
deadline: null,
status: 'pending' as const,
priority: mapPriority(o.priority as string),
responsible: (o.responsible as string) || '',
linked_systems: [],
rule_code: 'auto-profiled',
}))
setObligations(prev => {
const existingIds = new Set(prev.map(p => p.id))
const newOnes = autoObls.filter(a => !existingIds.has(a.id))
return [...prev, ...newOnes]
})
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Auto-Profiling fehlgeschlagen')
} finally {
setProfiling(false)
}
}
const filteredObligations = obligations.filter(o => {
if (regulationFilter !== 'all') {
const src = o.source?.toLowerCase() || ''
const key = regulationFilter.toLowerCase()
if (!src.includes(key)) return false
}
return true
})
return {
sdkState, obligations, stats, filter, regulationFilter, searchQuery,
loading, error, showModal, editObligation, detailObligation,
profiling, applicableRegs, activeTab, complianceResult, filteredObligations,
setFilter, setRegulationFilter, setSearchQuery,
setShowModal, setEditObligation, setDetailObligation, setActiveTab,
loadData, handleCreate, handleUpdate, handleStatusChange, handleDelete, handleAutoProfiling,
}
}

View File

@@ -13,6 +13,7 @@ export interface Obligation {
priority: 'critical' | 'high' | 'medium' | 'low' priority: 'critical' | 'high' | 'medium' | 'low'
responsible: string responsible: string
linked_systems: string[] linked_systems: string[]
linked_vendor_ids?: string[]
assessment_id?: string assessment_id?: string
rule_code?: string rule_code?: string
notes?: string notes?: string
@@ -40,6 +41,7 @@ export interface ObligationFormData {
priority: string priority: string
responsible: string responsible: string
linked_systems: string linked_systems: string
linked_vendor_ids: string
notes: string notes: string
} }
@@ -53,6 +55,7 @@ export const EMPTY_FORM: ObligationFormData = {
priority: 'medium', priority: 'medium',
responsible: '', responsible: '',
linked_systems: '', linked_systems: '',
linked_vendor_ids: '',
notes: '', notes: '',
} }

File diff suppressed because it is too large Load Diff