'use client'
import React, { useState, useEffect, useRef, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { useSDK, ChecklistItem as SDKChecklistItem } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
// =============================================================================
// TYPES
// =============================================================================
type DisplayStatus = 'compliant' | 'non-compliant' | 'partial' | 'not-reviewed'
type DisplayPriority = 'critical' | 'high' | 'medium' | 'low'
interface DisplayChecklistItem {
id: string
requirementId: string
question: string
category: string
status: DisplayStatus
notes: string
evidence: string[]
priority: DisplayPriority
verifiedBy: string | null
verifiedAt: Date | null
}
// =============================================================================
// HELPER FUNCTIONS
// =============================================================================
function mapSDKStatusToDisplay(status: SDKChecklistItem['status']): DisplayStatus {
switch (status) {
case 'PASSED': return 'compliant'
case 'FAILED': return 'non-compliant'
case 'NOT_APPLICABLE': return 'partial'
case 'PENDING':
default: return 'not-reviewed'
}
}
function mapDisplayStatusToSDK(status: DisplayStatus): SDKChecklistItem['status'] {
switch (status) {
case 'compliant': return 'PASSED'
case 'non-compliant': return 'FAILED'
case 'partial': return 'NOT_APPLICABLE'
case 'not-reviewed':
default: return 'PENDING'
}
}
// =============================================================================
// FALLBACK TEMPLATES
// =============================================================================
interface ChecklistTemplate {
id: string
requirementId: string
question: string
category: string
priority: DisplayPriority
}
const checklistTemplates: ChecklistTemplate[] = [
{
id: 'chk-vvt-001',
requirementId: 'req-gdpr-30',
question: 'Ist ein Verzeichnis von Verarbeitungstaetigkeiten (VVT) vorhanden und aktuell?',
category: 'Dokumentation',
priority: 'critical',
},
{
id: 'chk-dse-001',
requirementId: 'req-gdpr-13',
question: 'Sind Datenschutzhinweise fuer alle Verarbeitungen verfuegbar?',
category: 'Transparenz',
priority: 'high',
},
{
id: 'chk-consent-001',
requirementId: 'req-gdpr-6',
question: 'Werden Einwilligungen ordnungsgemaess eingeholt und dokumentiert?',
category: 'Einwilligung',
priority: 'high',
},
{
id: 'chk-dsr-001',
requirementId: 'req-gdpr-15',
question: 'Ist ein Prozess fuer Betroffenenrechte implementiert?',
category: 'Betroffenenrechte',
priority: 'critical',
},
{
id: 'chk-avv-001',
requirementId: 'req-gdpr-28',
question: 'Sind Auftragsverarbeitungsvertraege (AVV) mit allen Dienstleistern abgeschlossen?',
category: 'Auftragsverarbeitung',
priority: 'critical',
},
{
id: 'chk-dsfa-001',
requirementId: 'req-gdpr-35',
question: 'Wird eine DSFA fuer Hochrisiko-Verarbeitungen durchgefuehrt?',
category: 'Risikobewertung',
priority: 'high',
},
{
id: 'chk-tom-001',
requirementId: 'req-gdpr-32',
question: 'Sind technische und organisatorische Massnahmen dokumentiert?',
category: 'TOMs',
priority: 'high',
},
{
id: 'chk-incident-001',
requirementId: 'req-gdpr-33',
question: 'Gibt es einen Incident-Response-Prozess fuer Datenpannen?',
category: 'Incident Response',
priority: 'critical',
},
{
id: 'chk-ai-001',
requirementId: 'req-ai-act-9',
question: 'Ist das KI-System nach EU AI Act klassifiziert?',
category: 'AI Act',
priority: 'high',
},
{
id: 'chk-ai-002',
requirementId: 'req-ai-act-13',
question: 'Sind Transparenzanforderungen fuer KI-Systeme erfuellt?',
category: 'AI Act',
priority: 'high',
},
]
// =============================================================================
// COMPONENTS
// =============================================================================
function ChecklistItemCard({
item,
onStatusChange,
onNotesChange,
onAddEvidence,
}: {
item: DisplayChecklistItem
onStatusChange: (status: DisplayStatus) => void
onNotesChange: (notes: string) => void
onAddEvidence: () => void
}) {
const [showNotes, setShowNotes] = useState(false)
const statusColors = {
compliant: 'bg-green-100 text-green-700 border-green-300',
'non-compliant': 'bg-red-100 text-red-700 border-red-300',
partial: 'bg-yellow-100 text-yellow-700 border-yellow-300',
'not-reviewed': 'bg-gray-100 text-gray-500 border-gray-300',
}
const priorityColors = {
critical: 'bg-red-100 text-red-700',
high: 'bg-orange-100 text-orange-700',
medium: 'bg-yellow-100 text-yellow-700',
low: 'bg-green-100 text-green-700',
}
return (
{item.category}
{item.priority === 'critical' ? 'Kritisch' :
item.priority === 'high' ? 'Hoch' :
item.priority === 'medium' ? 'Mittel' : 'Niedrig'}
{item.requirementId}
{item.question}
{item.notes && (
{item.notes}
)}
{item.evidence.length > 0 && (
Nachweise:
{item.evidence.map(ev => (
{ev}
))}
)}
{item.verifiedBy && item.verifiedAt && (
Geprueft von {item.verifiedBy} am {item.verifiedAt.toLocaleDateString('de-DE')}
)}
{showNotes && (
)}
)
}
function LoadingSkeleton() {
return (
{[1, 2, 3].map(i => (
))}
)
}
// =============================================================================
// MAIN PAGE
// =============================================================================
interface PastSession {
id: string
name: string
status: string
auditor_name: string
created_at: string
completed_at?: string
completion_percentage: number
total_items: number
completed_items: number
}
export default function AuditChecklistPage() {
const { state, dispatch } = useSDK()
const router = useRouter()
const [filter, setFilter] = useState('all')
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [activeSessionId, setActiveSessionId] = useState(null)
const notesTimerRef = useRef>>({})
const [pastSessions, setPastSessions] = useState([])
const [pdfLanguage, setPdfLanguage] = useState<'de' | 'en'>('de')
const [generatingPdf, setGeneratingPdf] = useState(false)
// Fetch checklist from backend on mount
useEffect(() => {
const fetchChecklist = async () => {
try {
setLoading(true)
// First, try to find an active audit session
const sessionsRes = await fetch('/api/sdk/v1/compliance/audit/sessions?status=in_progress')
if (sessionsRes.ok) {
const sessionsData = await sessionsRes.json()
const sessions = sessionsData.sessions || sessionsData
if (Array.isArray(sessions) && sessions.length > 0) {
const session = sessions[0]
setActiveSessionId(session.id)
// Fetch checklist items for this session
const checklistRes = await fetch(`/api/sdk/v1/compliance/audit/checklist/${session.id}`)
if (checklistRes.ok) {
const checklistData = await checklistRes.json()
const items = checklistData.items || checklistData.checklist || checklistData
if (Array.isArray(items) && items.length > 0) {
const mapped: SDKChecklistItem[] = items.map((item: Record) => ({
id: (item.id || item.requirement_id || '') as string,
requirementId: (item.requirement_id || '') as string,
title: (item.title || item.question || '') as string,
description: (item.category || item.description || '') as string,
status: ((item.status || 'PENDING') as string).toUpperCase() as SDKChecklistItem['status'],
notes: (item.notes || item.auditor_notes || '') as string,
verifiedBy: (item.verified_by || item.signed_off_by || null) as string | null,
verifiedAt: item.verified_at || item.signed_off_at ? new Date((item.verified_at || item.signed_off_at) as string) : null,
}))
dispatch({ type: 'SET_STATE', payload: { checklist: mapped } })
setError(null)
return
}
}
}
}
// Fallback: load from templates
loadFromTemplates()
} catch {
loadFromTemplates()
} finally {
setLoading(false)
}
}
const loadFromTemplates = () => {
if (state.checklist.length > 0) return
const templatesToLoad = state.requirements.length > 0
? checklistTemplates.filter(t =>
state.requirements.some(r => r.id === t.requirementId)
)
: checklistTemplates
const items: SDKChecklistItem[] = templatesToLoad.map(template => ({
id: template.id,
requirementId: template.requirementId,
title: template.question,
description: template.category,
status: 'PENDING',
notes: '',
verifiedBy: null,
verifiedAt: null,
}))
if (items.length > 0) {
dispatch({ type: 'SET_STATE', payload: { checklist: items } })
}
}
fetchChecklist()
// Also fetch all sessions for history view
const fetchAllSessions = async () => {
try {
const res = await fetch('/api/sdk/v1/compliance/audit/sessions')
if (res.ok) {
const data = await res.json()
const sessions = data.sessions || []
setPastSessions(sessions)
}
} catch {
// Silently fail
}
}
fetchAllSessions()
}, []) // eslint-disable-line react-hooks/exhaustive-deps
// Convert SDK checklist items to display items
const displayItems: DisplayChecklistItem[] = state.checklist.map(item => {
const template = checklistTemplates.find(t => t.id === item.id)
return {
id: item.id,
requirementId: item.requirementId,
question: item.title,
category: item.description || template?.category || 'Allgemein',
status: mapSDKStatusToDisplay(item.status),
notes: item.notes,
evidence: [],
priority: template?.priority || 'medium',
verifiedBy: item.verifiedBy,
verifiedAt: item.verifiedAt,
}
})
const filteredItems = filter === 'all'
? displayItems
: displayItems.filter(item => item.status === filter || item.category === filter)
const compliantCount = displayItems.filter(i => i.status === 'compliant').length
const nonCompliantCount = displayItems.filter(i => i.status === 'non-compliant').length
const partialCount = displayItems.filter(i => i.status === 'partial').length
const notReviewedCount = displayItems.filter(i => i.status === 'not-reviewed').length
const progress = displayItems.length > 0
? Math.round(((compliantCount + partialCount * 0.5) / displayItems.length) * 100)
: 0
const handleStatusChange = async (itemId: string, status: DisplayStatus) => {
const sdkStatus = mapDisplayStatusToSDK(status)
const updatedChecklist = state.checklist.map(item =>
item.id === itemId
? {
...item,
status: sdkStatus,
verifiedBy: status !== 'not-reviewed' ? 'Aktueller Benutzer' : null,
verifiedAt: status !== 'not-reviewed' ? new Date() : null,
}
: item
)
dispatch({ type: 'SET_STATE', payload: { checklist: updatedChecklist } })
// Persist to backend if we have an active session
if (activeSessionId) {
try {
const item = state.checklist.find(i => i.id === itemId)
await fetch(`/api/sdk/v1/compliance/audit/checklist/${activeSessionId}/items/${item?.requirementId || itemId}/sign-off`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
status: sdkStatus === 'PASSED' ? 'compliant' : sdkStatus === 'FAILED' ? 'non_compliant' : sdkStatus === 'NOT_APPLICABLE' ? 'partially_compliant' : 'not_assessed',
auditor_notes: item?.notes || '',
}),
})
} catch {
// Silently fail
}
}
}
const handleNotesChange = useCallback((itemId: string, notes: string) => {
const updatedChecklist = state.checklist.map(item =>
item.id === itemId ? { ...item, notes } : item
)
dispatch({ type: 'SET_STATE', payload: { checklist: updatedChecklist } })
// Debounced persistence to backend
if (notesTimerRef.current[itemId]) {
clearTimeout(notesTimerRef.current[itemId])
}
notesTimerRef.current[itemId] = setTimeout(async () => {
if (activeSessionId) {
const item = state.checklist.find(i => i.id === itemId)
try {
await fetch(`/api/sdk/v1/compliance/audit/checklist/${activeSessionId}/items/${item?.requirementId || itemId}/sign-off`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ notes }),
})
} catch {
// Silently fail
}
}
}, 1000)
}, [state.checklist, activeSessionId, dispatch])
const handleExport = () => {
const exportData = displayItems.map(item => ({
id: item.id,
requirementId: item.requirementId,
question: item.question,
category: item.category,
status: item.status,
notes: item.notes,
priority: item.priority,
verifiedBy: item.verifiedBy,
verifiedAt: item.verifiedAt?.toISOString() || null,
}))
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `audit-checklist-${new Date().toISOString().split('T')[0]}.json`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
const handlePdfDownload = async () => {
if (!activeSessionId) {
setError('Kein aktives Audit vorhanden. Erstellen Sie zuerst eine Checkliste.')
return
}
setGeneratingPdf(true)
setError(null)
try {
const res = await fetch(`/api/sdk/v1/compliance/audit/sessions/${activeSessionId}/report/pdf?language=${pdfLanguage}`)
if (!res.ok) throw new Error('Fehler bei der PDF-Generierung')
const blob = await res.blob()
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `audit-checklist-${activeSessionId}.pdf`
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
document.body.removeChild(a)
} catch (err) {
setError(err instanceof Error ? err.message : 'PDF-Download fehlgeschlagen')
} finally {
setGeneratingPdf(false)
}
}
const handleNewChecklist = async () => {
try {
setError(null)
const res = await fetch('/api/sdk/v1/compliance/audit/sessions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: `Compliance Audit ${new Date().toLocaleDateString('de-DE')}`,
auditor_name: 'Aktueller Benutzer',
regulation_codes: ['GDPR'],
}),
})
if (res.ok) {
// Reload data
window.location.reload()
} else {
setError('Fehler beim Erstellen der neuen Checkliste')
}
} catch {
setError('Verbindung zum Backend fehlgeschlagen')
}
}
const stepInfo = STEP_EXPLANATIONS['audit-checklist']
return (
{/* Step Header */}
{/* Error Banner */}
{error && (
{error}
)}
{/* Requirements Alert */}
{state.requirements.length === 0 && !loading && (
Keine Anforderungen definiert
Bitte definieren Sie zuerst Anforderungen, um die zugehoerige Checkliste zu generieren.
)}
{/* Checklist Info */}
Compliance Audit {new Date().getFullYear()}
Jaehrliche Ueberpruefung der Compliance-Konformitaet
Frameworks: DSGVO, AI Act
Letzte Aktualisierung: {new Date().toLocaleDateString('de-DE')}
{activeSessionId && (
Session aktiv
)}
{/* Stats */}
Nicht konform
{nonCompliantCount}
Nicht geprueft
{notReviewedCount}
{/* Filter */}
Filter:
{['all', 'not-reviewed', 'non-compliant', 'partial', 'compliant'].map(f => (
))}
{/* Loading State */}
{loading &&
}
{/* Checklist Items */}
{!loading && (
{filteredItems.map(item => (
handleStatusChange(item.id, status)}
onNotesChange={(notes) => handleNotesChange(item.id, notes)}
onAddEvidence={() => router.push('/sdk/evidence')}
/>
))}
)}
{!loading && filteredItems.length === 0 && state.requirements.length > 0 && (
Keine Eintraege gefunden
Passen Sie den Filter an.
)}
{/* Session History */}
{pastSessions.length > 0 && (
Vergangene Audit-Sessions
{pastSessions
.filter(s => s.id !== activeSessionId)
.map(session => {
const statusBadge: Record
= {
draft: 'bg-slate-100 text-slate-700',
in_progress: 'bg-blue-100 text-blue-700',
completed: 'bg-green-100 text-green-700',
archived: 'bg-purple-100 text-purple-700',
}
const statusLabel: Record = {
draft: 'Entwurf',
in_progress: 'In Bearbeitung',
completed: 'Abgeschlossen',
archived: 'Archiviert',
}
return (
router.push(`/sdk/audit-report/${session.id}`)}
>
{statusLabel[session.status] || session.status}
{session.name}
{new Date(session.created_at).toLocaleDateString('de-DE')}
{session.completed_items}/{session.total_items} Punkte
= 80 ? 'text-green-600' :
session.completion_percentage >= 50 ? 'text-yellow-600' : 'text-red-600'
}`}>
{session.completion_percentage}%
)
})}
)}
)
}