refactor(admin): split audit-checklist, cookie-banner, escalations pages

Each page.tsx was 750-780 LOC. Extracted React components to _components/
and custom hooks to _hooks/ next to each page.tsx. All three pages are now
under 215 LOC (well within the 500 LOC hard cap). Zero behavior changes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Sharang Parnerkar
2026-04-16 13:06:45 +02:00
parent 9f2224efc4
commit 9096aad693
21 changed files with 1892 additions and 1949 deletions

View File

@@ -0,0 +1,119 @@
'use client'
import { useState } from 'react'
import { DisplayChecklistItem, DisplayStatus } from './types'
interface ChecklistItemCardProps {
item: DisplayChecklistItem
onStatusChange: (status: DisplayStatus) => void
onNotesChange: (notes: string) => void
onAddEvidence: () => void
}
export function ChecklistItemCard({
item,
onStatusChange,
onNotesChange,
onAddEvidence,
}: ChecklistItemCardProps) {
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 (
<div className={`bg-white rounded-xl border-2 p-6 ${
item.status === 'non-compliant' ? 'border-red-200' :
item.status === 'partial' ? 'border-yellow-200' :
item.status === 'compliant' ? 'border-green-200' : 'border-gray-200'
}`}>
<div className="flex items-start gap-4">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<span className="text-xs text-gray-500">{item.category}</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${priorityColors[item.priority]}`}>
{item.priority === 'critical' ? 'Kritisch' :
item.priority === 'high' ? 'Hoch' :
item.priority === 'medium' ? 'Mittel' : 'Niedrig'}
</span>
<span className="px-2 py-0.5 text-xs bg-blue-50 text-blue-600 rounded">
{item.requirementId}
</span>
</div>
<p className="text-gray-900 font-medium">{item.question}</p>
</div>
<select
value={item.status}
onChange={(e) => onStatusChange(e.target.value as DisplayStatus)}
className={`px-3 py-2 rounded-lg border text-sm font-medium ${statusColors[item.status]}`}
>
<option value="not-reviewed">Nicht geprueft</option>
<option value="compliant">Konform</option>
<option value="partial">Teilweise</option>
<option value="non-compliant">Nicht konform</option>
</select>
</div>
{item.notes && (
<div className="mt-3 p-3 bg-gray-50 rounded-lg text-sm text-gray-600">
{item.notes}
</div>
)}
{item.evidence.length > 0 && (
<div className="mt-3 flex items-center gap-2">
<span className="text-sm text-gray-500">Nachweise:</span>
{item.evidence.map(ev => (
<span key={ev} className="px-2 py-1 text-xs bg-blue-50 text-blue-600 rounded">
{ev}
</span>
))}
</div>
)}
{item.verifiedBy && item.verifiedAt && (
<div className="mt-3 text-sm text-gray-500">
Geprueft von {item.verifiedBy} am {item.verifiedAt.toLocaleDateString('de-DE')}
</div>
)}
<div className="mt-3 flex items-center gap-2">
<button
onClick={() => setShowNotes(!showNotes)}
className="text-sm text-purple-600 hover:text-purple-700"
>
{showNotes ? 'Notizen ausblenden' : 'Notizen bearbeiten'}
</button>
<button
onClick={onAddEvidence}
className="text-sm text-gray-500 hover:text-gray-700"
>
Nachweis hinzufuegen
</button>
</div>
{showNotes && (
<div className="mt-3">
<textarea
value={item.notes}
onChange={(e) => onNotesChange(e.target.value)}
placeholder="Notizen hinzufuegen..."
rows={2}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent text-sm"
/>
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,17 @@
'use client'
export function LoadingSkeleton() {
return (
<div className="space-y-4">
{[1, 2, 3].map(i => (
<div key={i} className="bg-white rounded-xl border border-gray-200 p-6 animate-pulse">
<div className="flex items-center gap-2 mb-3">
<div className="h-4 w-24 bg-gray-200 rounded" />
<div className="h-4 w-16 bg-gray-200 rounded-full" />
</div>
<div className="h-5 w-full bg-gray-200 rounded" />
</div>
))}
</div>
)
}

View File

@@ -0,0 +1,69 @@
'use client'
import { useRouter } from 'next/navigation'
import { PastSession } from './types'
interface SessionHistoryProps {
pastSessions: PastSession[]
activeSessionId: string | null
}
export function SessionHistory({ pastSessions, activeSessionId }: SessionHistoryProps) {
const router = useRouter()
if (pastSessions.length === 0) return null
const statusBadge: Record<string, string> = {
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<string, string> = {
draft: 'Entwurf',
in_progress: 'In Bearbeitung',
completed: 'Abgeschlossen',
archived: 'Archiviert',
}
return (
<div className="bg-white rounded-xl border border-gray-200 p-6">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Vergangene Audit-Sessions</h3>
<div className="space-y-3">
{pastSessions
.filter(s => s.id !== activeSessionId)
.map(session => (
<div
key={session.id}
className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 cursor-pointer transition-colors"
onClick={() => router.push(`/sdk/audit-report/${session.id}`)}
>
<div className="flex items-center gap-3">
<span className={`px-2 py-0.5 text-xs rounded-full ${statusBadge[session.status] || ''}`}>
{statusLabel[session.status] || session.status}
</span>
<span className="text-sm font-medium text-gray-900">{session.name}</span>
<span className="text-xs text-gray-500">
{new Date(session.created_at).toLocaleDateString('de-DE')}
</span>
</div>
<div className="flex items-center gap-3 text-sm">
<span className="text-gray-500">
{session.completed_items}/{session.total_items} Punkte
</span>
<span className={`font-medium ${
session.completion_percentage >= 80 ? 'text-green-600' :
session.completion_percentage >= 50 ? 'text-yellow-600' : 'text-red-600'
}`}>
{session.completion_percentage}%
</span>
<svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</div>
</div>
))}
</div>
</div>
)
}

View File

@@ -0,0 +1,78 @@
import { ChecklistTemplate } from './types'
// =============================================================================
// FALLBACK TEMPLATES
// =============================================================================
export 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',
},
]

View File

@@ -0,0 +1,26 @@
import { ChecklistItem as SDKChecklistItem } from '@/lib/sdk'
import { DisplayStatus } from './types'
// =============================================================================
// HELPER FUNCTIONS
// =============================================================================
export 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'
}
}
export 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'
}
}

View File

@@ -0,0 +1,39 @@
// =============================================================================
// TYPES
// =============================================================================
export type DisplayStatus = 'compliant' | 'non-compliant' | 'partial' | 'not-reviewed'
export type DisplayPriority = 'critical' | 'high' | 'medium' | 'low'
export interface DisplayChecklistItem {
id: string
requirementId: string
question: string
category: string
status: DisplayStatus
notes: string
evidence: string[]
priority: DisplayPriority
verifiedBy: string | null
verifiedAt: Date | null
}
export 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 interface ChecklistTemplate {
id: string
requirementId: string
question: string
category: string
priority: DisplayPriority
}

View File

@@ -0,0 +1,266 @@
'use client'
import { useState, useEffect, useRef, useCallback } from 'react'
import { useSDK, ChecklistItem as SDKChecklistItem } from '@/lib/sdk'
import { PastSession } from '../_components/types'
import { checklistTemplates } from '../_components/checklistTemplates'
import { mapSDKStatusToDisplay, mapDisplayStatusToSDK } from '../_components/statusHelpers'
import { DisplayStatus, DisplayChecklistItem } from '../_components/types'
export function useAuditChecklist() {
const { state, dispatch } = useSDK()
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [activeSessionId, setActiveSessionId] = useState<string | null>(null)
const notesTimerRef = useRef<Record<string, ReturnType<typeof setTimeout>>>({})
const [pastSessions, setPastSessions] = useState<PastSession[]>([])
const [pdfLanguage, setPdfLanguage] = useState<'de' | 'en'>('de')
const [generatingPdf, setGeneratingPdf] = useState(false)
useEffect(() => {
const fetchChecklist = async () => {
try {
setLoading(true)
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)
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<string, unknown>) => ({
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
}
}
}
}
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()
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
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 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 } })
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 } })
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) {
window.location.reload()
} else {
setError('Fehler beim Erstellen der neuen Checkliste')
}
} catch {
setError('Verbindung zum Backend fehlgeschlagen')
}
}
return {
state,
loading,
error,
setError,
activeSessionId,
pastSessions,
pdfLanguage,
setPdfLanguage,
generatingPdf,
displayItems,
handleStatusChange,
handleNotesChange,
handleExport,
handlePdfDownload,
handleNewChecklist,
}
}

View File

@@ -1,408 +1,33 @@
'use client'
import React, { useState, useEffect, useRef, useCallback } from 'react'
import React, { useState } 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 (
<div className={`bg-white rounded-xl border-2 p-6 ${
item.status === 'non-compliant' ? 'border-red-200' :
item.status === 'partial' ? 'border-yellow-200' :
item.status === 'compliant' ? 'border-green-200' : 'border-gray-200'
}`}>
<div className="flex items-start gap-4">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<span className="text-xs text-gray-500">{item.category}</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${priorityColors[item.priority]}`}>
{item.priority === 'critical' ? 'Kritisch' :
item.priority === 'high' ? 'Hoch' :
item.priority === 'medium' ? 'Mittel' : 'Niedrig'}
</span>
<span className="px-2 py-0.5 text-xs bg-blue-50 text-blue-600 rounded">
{item.requirementId}
</span>
</div>
<p className="text-gray-900 font-medium">{item.question}</p>
</div>
<select
value={item.status}
onChange={(e) => onStatusChange(e.target.value as DisplayStatus)}
className={`px-3 py-2 rounded-lg border text-sm font-medium ${statusColors[item.status]}`}
>
<option value="not-reviewed">Nicht geprueft</option>
<option value="compliant">Konform</option>
<option value="partial">Teilweise</option>
<option value="non-compliant">Nicht konform</option>
</select>
</div>
{item.notes && (
<div className="mt-3 p-3 bg-gray-50 rounded-lg text-sm text-gray-600">
{item.notes}
</div>
)}
{item.evidence.length > 0 && (
<div className="mt-3 flex items-center gap-2">
<span className="text-sm text-gray-500">Nachweise:</span>
{item.evidence.map(ev => (
<span key={ev} className="px-2 py-1 text-xs bg-blue-50 text-blue-600 rounded">
{ev}
</span>
))}
</div>
)}
{item.verifiedBy && item.verifiedAt && (
<div className="mt-3 text-sm text-gray-500">
Geprueft von {item.verifiedBy} am {item.verifiedAt.toLocaleDateString('de-DE')}
</div>
)}
<div className="mt-3 flex items-center gap-2">
<button
onClick={() => setShowNotes(!showNotes)}
className="text-sm text-purple-600 hover:text-purple-700"
>
{showNotes ? 'Notizen ausblenden' : 'Notizen bearbeiten'}
</button>
<button
onClick={onAddEvidence}
className="text-sm text-gray-500 hover:text-gray-700"
>
Nachweis hinzufuegen
</button>
</div>
{showNotes && (
<div className="mt-3">
<textarea
value={item.notes}
onChange={(e) => onNotesChange(e.target.value)}
placeholder="Notizen hinzufuegen..."
rows={2}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent text-sm"
/>
</div>
)}
</div>
)
}
function LoadingSkeleton() {
return (
<div className="space-y-4">
{[1, 2, 3].map(i => (
<div key={i} className="bg-white rounded-xl border border-gray-200 p-6 animate-pulse">
<div className="flex items-center gap-2 mb-3">
<div className="h-4 w-24 bg-gray-200 rounded" />
<div className="h-4 w-16 bg-gray-200 rounded-full" />
</div>
<div className="h-5 w-full bg-gray-200 rounded" />
</div>
))}
</div>
)
}
// =============================================================================
// 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
}
import { useAuditChecklist } from './_hooks/useAuditChecklist'
import { ChecklistItemCard } from './_components/ChecklistItemCard'
import { LoadingSkeleton } from './_components/LoadingSkeleton'
import { SessionHistory } from './_components/SessionHistory'
export default function AuditChecklistPage() {
const { state, dispatch } = useSDK()
const router = useRouter()
const [filter, setFilter] = useState<string>('all')
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [activeSessionId, setActiveSessionId] = useState<string | null>(null)
const notesTimerRef = useRef<Record<string, ReturnType<typeof setTimeout>>>({})
const [pastSessions, setPastSessions] = useState<PastSession[]>([])
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<string, unknown>) => ({
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 {
state,
loading,
error,
setError,
activeSessionId,
pastSessions,
pdfLanguage,
setPdfLanguage,
generatingPdf,
displayItems,
handleStatusChange,
handleNotesChange,
handleExport,
handlePdfDownload,
handleNewChecklist,
} = useAuditChecklist()
const filteredItems = filter === 'all'
? displayItems
@@ -417,141 +42,10 @@ export default function AuditChecklistPage() {
? 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 (
<div className="space-y-6">
{/* Step Header */}
<StepHeader
stepId="audit-checklist"
title={stepInfo.title}
@@ -595,7 +89,6 @@ export default function AuditChecklistPage() {
</div>
</StepHeader>
{/* Error Banner */}
{error && (
<div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-700 flex items-center justify-between">
<span>{error}</span>
@@ -603,7 +96,6 @@ export default function AuditChecklistPage() {
</div>
)}
{/* Requirements Alert */}
{state.requirements.length === 0 && !loading && (
<div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
<div className="flex items-start gap-3">
@@ -620,7 +112,6 @@ export default function AuditChecklistPage() {
</div>
)}
{/* Checklist Info */}
<div className="bg-white rounded-xl border border-gray-200 p-6">
<div className="flex items-center justify-between">
<div>
@@ -649,7 +140,6 @@ export default function AuditChecklistPage() {
</div>
</div>
{/* Stats */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="bg-white rounded-xl border border-green-200 p-4">
<div className="text-sm text-green-600">Konform</div>
@@ -669,7 +159,6 @@ export default function AuditChecklistPage() {
</div>
</div>
{/* Filter */}
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm text-gray-500">Filter:</span>
{['all', 'not-reviewed', 'non-compliant', 'partial', 'compliant'].map(f => (
@@ -690,10 +179,8 @@ export default function AuditChecklistPage() {
))}
</div>
{/* Loading State */}
{loading && <LoadingSkeleton />}
{/* Checklist Items */}
{!loading && (
<div className="space-y-4">
{filteredItems.map(item => (
@@ -720,61 +207,7 @@ export default function AuditChecklistPage() {
</div>
)}
{/* Session History */}
{pastSessions.length > 0 && (
<div className="bg-white rounded-xl border border-gray-200 p-6">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Vergangene Audit-Sessions</h3>
<div className="space-y-3">
{pastSessions
.filter(s => s.id !== activeSessionId)
.map(session => {
const statusBadge: Record<string, string> = {
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<string, string> = {
draft: 'Entwurf',
in_progress: 'In Bearbeitung',
completed: 'Abgeschlossen',
archived: 'Archiviert',
}
return (
<div
key={session.id}
className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 cursor-pointer transition-colors"
onClick={() => router.push(`/sdk/audit-report/${session.id}`)}
>
<div className="flex items-center gap-3">
<span className={`px-2 py-0.5 text-xs rounded-full ${statusBadge[session.status] || ''}`}>
{statusLabel[session.status] || session.status}
</span>
<span className="text-sm font-medium text-gray-900">{session.name}</span>
<span className="text-xs text-gray-500">
{new Date(session.created_at).toLocaleDateString('de-DE')}
</span>
</div>
<div className="flex items-center gap-3 text-sm">
<span className="text-gray-500">
{session.completed_items}/{session.total_items} Punkte
</span>
<span className={`font-medium ${
session.completion_percentage >= 80 ? 'text-green-600' :
session.completion_percentage >= 50 ? 'text-yellow-600' : 'text-red-600'
}`}>
{session.completion_percentage}%
</span>
<svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</div>
</div>
)
})}
</div>
</div>
)}
<SessionHistory pastSessions={pastSessions} activeSessionId={activeSessionId} />
</div>
)
}