'use client'
import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useSDK, Control as SDKControl, ControlType, ImplementationStatus } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
// =============================================================================
// TYPES
// =============================================================================
type DisplayControlType = 'preventive' | 'detective' | 'corrective'
type DisplayCategory = 'technical' | 'organizational' | 'physical'
type DisplayStatus = 'implemented' | 'partial' | 'planned' | 'not-implemented'
interface DisplayControl {
id: string
name: string
description: string
type: ControlType
category: string
implementationStatus: ImplementationStatus
evidence: string[]
owner: string | null
dueDate: Date | null
code: string
displayType: DisplayControlType
displayCategory: DisplayCategory
displayStatus: DisplayStatus
effectivenessPercent: number
linkedRequirements: string[]
linkedEvidence: { id: string; title: string; status: string }[]
lastReview: Date
}
// =============================================================================
// HELPER FUNCTIONS
// =============================================================================
function mapControlTypeToDisplay(type: ControlType): DisplayCategory {
switch (type) {
case 'TECHNICAL': return 'technical'
case 'ORGANIZATIONAL': return 'organizational'
case 'PHYSICAL': return 'physical'
default: return 'technical'
}
}
function mapStatusToDisplay(status: ImplementationStatus): DisplayStatus {
switch (status) {
case 'IMPLEMENTED': return 'implemented'
case 'PARTIAL': return 'partial'
case 'NOT_IMPLEMENTED': return 'not-implemented'
default: return 'not-implemented'
}
}
// =============================================================================
// FALLBACK TEMPLATES
// =============================================================================
interface ControlTemplate {
id: string
code: string
name: string
description: string
type: ControlType
displayType: DisplayControlType
displayCategory: DisplayCategory
category: string
owner: string
linkedRequirements: string[]
}
const controlTemplates: ControlTemplate[] = [
{
id: 'ctrl-tom-001',
code: 'TOM-001',
name: 'Zugriffskontrolle',
description: 'Rollenbasierte Zugriffskontrolle (RBAC) fuer alle Systeme',
type: 'TECHNICAL',
displayType: 'preventive',
displayCategory: 'technical',
category: 'Zutrittskontrolle',
owner: 'IT Security',
linkedRequirements: ['req-gdpr-32'],
},
{
id: 'ctrl-tom-002',
code: 'TOM-002',
name: 'Verschluesselung',
description: 'Verschluesselung von Daten at rest und in transit',
type: 'TECHNICAL',
displayType: 'preventive',
displayCategory: 'technical',
category: 'Weitergabekontrolle',
owner: 'IT Security',
linkedRequirements: ['req-gdpr-32'],
},
{
id: 'ctrl-org-001',
code: 'ORG-001',
name: 'Datenschutzschulung',
description: 'Jaehrliche Datenschutzschulung fuer alle Mitarbeiter',
type: 'ORGANIZATIONAL',
displayType: 'preventive',
displayCategory: 'organizational',
category: 'Schulung',
owner: 'HR',
linkedRequirements: ['req-gdpr-6', 'req-gdpr-32'],
},
{
id: 'ctrl-det-001',
code: 'DET-001',
name: 'Logging und Monitoring',
description: 'Umfassendes Logging aller Datenzugriffe',
type: 'TECHNICAL',
displayType: 'detective',
displayCategory: 'technical',
category: 'Eingabekontrolle',
owner: 'IT Operations',
linkedRequirements: ['req-gdpr-32', 'req-nis2-21'],
},
{
id: 'ctrl-cor-001',
code: 'COR-001',
name: 'Incident Response',
description: 'Prozess zur Behandlung von Datenschutzvorfaellen',
type: 'ORGANIZATIONAL',
displayType: 'corrective',
displayCategory: 'organizational',
category: 'Incident Management',
owner: 'CISO',
linkedRequirements: ['req-gdpr-32', 'req-nis2-21'],
},
{
id: 'ctrl-ai-001',
code: 'AI-001',
name: 'KI-Risikomonitoring',
description: 'Kontinuierliche Ueberwachung von KI-Systemrisiken',
type: 'TECHNICAL',
displayType: 'detective',
displayCategory: 'technical',
category: 'KI-Governance',
owner: 'AI Team',
linkedRequirements: ['req-ai-act-9', 'req-ai-act-13'],
},
]
// =============================================================================
// COMPONENTS
// =============================================================================
function ControlCard({
control,
onStatusChange,
onEffectivenessChange,
onLinkEvidence,
}: {
control: DisplayControl
onStatusChange: (status: ImplementationStatus) => void
onEffectivenessChange: (effectivenessPercent: number) => void
onLinkEvidence: () => void
}) {
const [showEffectivenessSlider, setShowEffectivenessSlider] = useState(false)
const typeColors = {
preventive: 'bg-blue-100 text-blue-700',
detective: 'bg-purple-100 text-purple-700',
corrective: 'bg-orange-100 text-orange-700',
}
const categoryColors = {
technical: 'bg-green-100 text-green-700',
organizational: 'bg-yellow-100 text-yellow-700',
physical: 'bg-gray-100 text-gray-700',
}
const statusColors = {
implemented: 'border-green-200 bg-green-50',
partial: 'border-yellow-200 bg-yellow-50',
planned: 'border-blue-200 bg-blue-50',
'not-implemented': 'border-red-200 bg-red-50',
}
const statusLabels = {
implemented: 'Implementiert',
partial: 'Teilweise',
planned: 'Geplant',
'not-implemented': 'Nicht implementiert',
}
return (
{control.code}
{control.displayType === 'preventive' ? 'Praeventiv' :
control.displayType === 'detective' ? 'Detektiv' : 'Korrektiv'}
{control.displayCategory === 'technical' ? 'Technisch' :
control.displayCategory === 'organizational' ? 'Organisatorisch' : 'Physisch'}
{control.name}
{control.description}
setShowEffectivenessSlider(!showEffectivenessSlider)}
>
Wirksamkeit
{control.effectivenessPercent}%
= 80 ? 'bg-green-500' :
control.effectivenessPercent >= 50 ? 'bg-yellow-500' : 'bg-red-500'
}`}
style={{ width: `${control.effectivenessPercent}%` }}
/>
{showEffectivenessSlider && (
onEffectivenessChange(Number(e.target.value))}
className="w-full"
/>
)}
Verantwortlich:
{control.owner || 'Nicht zugewiesen'}
Letzte Pruefung: {control.lastReview.toLocaleDateString('de-DE')}
{control.linkedRequirements.slice(0, 3).map(req => (
{req}
))}
{control.linkedRequirements.length > 3 && (
+{control.linkedRequirements.length - 3}
)}
{statusLabels[control.displayStatus]}
{/* Linked Evidence */}
{control.linkedEvidence.length > 0 && (
Nachweise:
{control.linkedEvidence.map(ev => (
{ev.title}
))}
)}
)
}
function AddControlForm({
onSubmit,
onCancel,
}: {
onSubmit: (data: { name: string; description: string; type: ControlType; category: string; owner: string }) => void
onCancel: () => void
}) {
const [formData, setFormData] = useState({
name: '',
description: '',
type: 'TECHNICAL' as ControlType,
category: '',
owner: '',
})
return (
Neue Kontrolle
)
}
function LoadingSkeleton() {
return (
{[1, 2, 3].map(i => (
))}
)
}
// =============================================================================
// MAIN PAGE
// =============================================================================
export default function ControlsPage() {
const { state, dispatch } = useSDK()
const router = useRouter()
const [filter, setFilter] = useState
('all')
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [showAddForm, setShowAddForm] = useState(false)
// Track effectiveness locally as it's not in the SDK state type
const [effectivenessMap, setEffectivenessMap] = useState>({})
// Track linked evidence per control
const [evidenceMap, setEvidenceMap] = useState>({})
const fetchEvidenceForControls = async (controlIds: string[]) => {
try {
const res = await fetch('/api/sdk/v1/compliance/evidence')
if (res.ok) {
const data = await res.json()
const allEvidence = data.evidence || data
if (Array.isArray(allEvidence)) {
const map: Record = {}
for (const ev of allEvidence) {
const ctrlId = ev.control_id || ''
if (!map[ctrlId]) map[ctrlId] = []
map[ctrlId].push({
id: ev.id,
title: ev.title || ev.name || 'Nachweis',
status: ev.status || 'pending',
})
}
setEvidenceMap(map)
}
}
} catch {
// Silently fail
}
}
// Fetch controls from backend on mount
useEffect(() => {
const fetchControls = async () => {
try {
setLoading(true)
const res = await fetch('/api/sdk/v1/compliance/controls')
if (res.ok) {
const data = await res.json()
const backendControls = data.controls || data
if (Array.isArray(backendControls) && backendControls.length > 0) {
const mapped: SDKControl[] = backendControls.map((c: Record) => ({
id: (c.control_id || c.id) as string,
name: (c.name || c.title || '') as string,
description: (c.description || '') as string,
type: ((c.type || c.control_type || 'TECHNICAL') as string).toUpperCase() as ControlType,
category: (c.category || '') as string,
implementationStatus: ((c.implementation_status || c.status || 'NOT_IMPLEMENTED') as string).toUpperCase() as ImplementationStatus,
effectiveness: (c.effectiveness || 'LOW') as 'LOW' | 'MEDIUM' | 'HIGH',
evidence: (c.evidence || []) as string[],
owner: (c.owner || null) as string | null,
dueDate: c.due_date ? new Date(c.due_date as string) : null,
}))
dispatch({ type: 'SET_STATE', payload: { controls: mapped } })
setError(null)
// Fetch evidence for all controls
fetchEvidenceForControls(mapped.map(c => c.id))
return
}
}
loadFromTemplates()
} catch {
loadFromTemplates()
} finally {
setLoading(false)
}
}
const loadFromTemplates = () => {
if (state.controls.length > 0) return
if (state.requirements.length === 0) return
const relevantControls = controlTemplates.filter(c =>
c.linkedRequirements.some(reqId => state.requirements.some(r => r.id === reqId))
)
relevantControls.forEach(ctrl => {
const sdkControl: SDKControl = {
id: ctrl.id,
name: ctrl.name,
description: ctrl.description,
type: ctrl.type,
category: ctrl.category,
implementationStatus: 'NOT_IMPLEMENTED',
effectiveness: 'LOW',
evidence: [],
owner: ctrl.owner,
dueDate: null,
}
dispatch({ type: 'ADD_CONTROL', payload: sdkControl })
})
}
fetchControls()
}, []) // eslint-disable-line react-hooks/exhaustive-deps
// Convert SDK controls to display controls
const displayControls: DisplayControl[] = state.controls.map(ctrl => {
const template = controlTemplates.find(t => t.id === ctrl.id)
const effectivenessPercent = effectivenessMap[ctrl.id] ??
(ctrl.implementationStatus === 'IMPLEMENTED' ? 85 :
ctrl.implementationStatus === 'PARTIAL' ? 50 : 0)
return {
id: ctrl.id,
name: ctrl.name,
description: ctrl.description,
type: ctrl.type,
category: ctrl.category,
implementationStatus: ctrl.implementationStatus,
evidence: ctrl.evidence,
owner: ctrl.owner,
dueDate: ctrl.dueDate,
code: template?.code || ctrl.id,
displayType: template?.displayType || 'preventive',
displayCategory: mapControlTypeToDisplay(ctrl.type),
displayStatus: mapStatusToDisplay(ctrl.implementationStatus),
effectivenessPercent,
linkedRequirements: template?.linkedRequirements || [],
linkedEvidence: evidenceMap[ctrl.id] || [],
lastReview: new Date(),
}
})
const filteredControls = filter === 'all'
? displayControls
: displayControls.filter(c =>
c.displayStatus === filter ||
c.displayType === filter ||
c.displayCategory === filter
)
const implementedCount = displayControls.filter(c => c.displayStatus === 'implemented').length
const avgEffectiveness = displayControls.length > 0
? Math.round(displayControls.reduce((sum, c) => sum + c.effectivenessPercent, 0) / displayControls.length)
: 0
const partialCount = displayControls.filter(c => c.displayStatus === 'partial').length
const handleStatusChange = async (controlId: string, status: ImplementationStatus) => {
dispatch({
type: 'UPDATE_CONTROL',
payload: { id: controlId, data: { implementationStatus: status } },
})
try {
await fetch(`/api/sdk/v1/compliance/controls/${controlId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ implementation_status: status }),
})
} catch {
// Silently fail — SDK state is already updated
}
}
const handleEffectivenessChange = async (controlId: string, effectiveness: number) => {
setEffectivenessMap(prev => ({ ...prev, [controlId]: effectiveness }))
// Persist to backend
try {
await fetch(`/api/sdk/v1/compliance/controls/${controlId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ effectiveness_score: effectiveness }),
})
} catch {
// Silently fail — local state is already updated
}
}
const handleAddControl = (data: { name: string; description: string; type: ControlType; category: string; owner: string }) => {
const newControl: SDKControl = {
id: `ctrl-${Date.now()}`,
name: data.name,
description: data.description,
type: data.type,
category: data.category,
implementationStatus: 'NOT_IMPLEMENTED',
effectiveness: 'LOW',
evidence: [],
owner: data.owner || null,
dueDate: null,
}
dispatch({ type: 'ADD_CONTROL', payload: newControl })
setShowAddForm(false)
}
const stepInfo = STEP_EXPLANATIONS['controls']
return (
{/* Step Header */}
{/* Add Form */}
{showAddForm && (
setShowAddForm(false)}
/>
)}
{/* Error Banner */}
{error && (
{error}
)}
{/* Requirements Alert */}
{state.requirements.length === 0 && !loading && (
Keine Anforderungen definiert
Bitte definieren Sie zuerst Anforderungen, um die zugehoerigen Kontrollen zu laden.
)}
{/* Stats */}
Gesamt
{displayControls.length}
Implementiert
{implementedCount}
Durchschn. Wirksamkeit
{avgEffectiveness}%
{/* Filter */}
Filter:
{['all', 'implemented', 'partial', 'not-implemented', 'technical', 'organizational', 'preventive', 'detective'].map(f => (
))}
{/* Loading State */}
{loading && }
{/* Controls List */}
{!loading && (
{filteredControls.map(control => (
handleStatusChange(control.id, status)}
onEffectivenessChange={(effectiveness) => handleEffectivenessChange(control.id, effectiveness)}
onLinkEvidence={() => router.push(`/sdk/evidence?control_id=${control.id}`)}
/>
))}
)}
{!loading && filteredControls.length === 0 && state.requirements.length > 0 && (
Keine Kontrollen gefunden
Passen Sie den Filter an oder fuegen Sie neue Kontrollen hinzu.
)}
)
}