'use client' import React, { useState, useEffect, useCallback, useMemo } from 'react' import { useRouter } from 'next/navigation' import { useSDK } from '@/lib/sdk' import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader' import { LoeschfristPolicy, LegalHold, StorageLocation, RETENTION_DRIVER_META, RetentionDriverType, DeletionMethodType, DELETION_METHOD_LABELS, STATUS_LABELS, STATUS_COLORS, TRIGGER_LABELS, TRIGGER_COLORS, REVIEW_INTERVAL_LABELS, STORAGE_LOCATION_LABELS, StorageLocationType, PolicyStatus, ReviewInterval, DeletionTriggerLevel, RetentionUnit, LegalHoldStatus, createEmptyPolicy, createEmptyLegalHold, createEmptyStorageLocation, formatRetentionDuration, isPolicyOverdue, getActiveLegalHolds, getEffectiveDeletionTrigger, LOESCHFRISTEN_STORAGE_KEY, generatePolicyId, } from '@/lib/sdk/loeschfristen-types' import { BASELINE_TEMPLATES, templateToPolicy, getTemplateById, getAllTemplateTags } from '@/lib/sdk/loeschfristen-baseline-catalog' import { PROFILING_STEPS, ProfilingAnswer, ProfilingStep, isStepComplete, getProfilingProgress, generatePoliciesFromProfile, } from '@/lib/sdk/loeschfristen-profiling' import { runComplianceCheck, ComplianceCheckResult, ComplianceIssue, } from '@/lib/sdk/loeschfristen-compliance' import { exportPoliciesAsJSON, exportPoliciesAsCSV, generateComplianceSummary, downloadFile, } from '@/lib/sdk/loeschfristen-export' // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- type Tab = 'uebersicht' | 'editor' | 'generator' | 'export' const STORAGE_KEY = 'bp_loeschfristen' // --------------------------------------------------------------------------- // Helper: TagInput // --------------------------------------------------------------------------- function TagInput({ value, onChange, placeholder, }: { value: string[] onChange: (v: string[]) => void placeholder?: string }) { const [input, setInput] = useState('') const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' || e.key === ',') { e.preventDefault() const trimmed = input.trim().replace(/,+$/, '').trim() if (trimmed && !value.includes(trimmed)) { onChange([...value, trimmed]) } setInput('') } } const remove = (idx: number) => { onChange(value.filter((_, i) => i !== idx)) } return (
{value.map((tag, idx) => ( {tag} ))}
setInput(e.target.value)} onKeyDown={handleKeyDown} placeholder={placeholder ?? 'Eingabe + Enter'} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm" />
) } // --------------------------------------------------------------------------- // Main Page // --------------------------------------------------------------------------- export default function LoeschfristenPage() { const router = useRouter() const sdk = useSDK() // ---- Core state ---- const [tab, setTab] = useState('uebersicht') const [policies, setPolicies] = useState([]) const [loaded, setLoaded] = useState(false) const [editingId, setEditingId] = useState(null) const [filter, setFilter] = useState('all') const [searchQuery, setSearchQuery] = useState('') const [driverFilter, setDriverFilter] = useState('all') // ---- Generator state ---- const [profilingStep, setProfilingStep] = useState(0) const [profilingAnswers, setProfilingAnswers] = useState([]) const [generatedPolicies, setGeneratedPolicies] = useState([]) const [selectedGenerated, setSelectedGenerated] = useState>(new Set()) // ---- Compliance state ---- const [complianceResult, setComplianceResult] = useState(null) // ---- Legal Hold management ---- const [managingLegalHolds, setManagingLegalHolds] = useState(false) // ---- VVT data ---- const [vvtActivities, setVvtActivities] = useState([]) // -------------------------------------------------------------------------- // Persistence // -------------------------------------------------------------------------- useEffect(() => { const stored = localStorage.getItem(STORAGE_KEY) if (stored) { try { const parsed = JSON.parse(stored) as LoeschfristPolicy[] setPolicies(parsed) } catch (e) { console.error('Failed to parse stored policies:', e) } } setLoaded(true) }, []) useEffect(() => { if (loaded && policies.length > 0) { localStorage.setItem(STORAGE_KEY, JSON.stringify(policies)) } else if (loaded && policies.length === 0) { localStorage.removeItem(STORAGE_KEY) } }, [policies, loaded]) // Load VVT activities from localStorage useEffect(() => { try { const raw = localStorage.getItem('bp_vvt') if (raw) { const parsed = JSON.parse(raw) if (Array.isArray(parsed)) setVvtActivities(parsed) } } catch { // ignore } }, [tab, editingId]) // -------------------------------------------------------------------------- // Derived // -------------------------------------------------------------------------- const editingPolicy = useMemo( () => policies.find((p) => p.policyId === editingId) ?? null, [policies, editingId], ) const filteredPolicies = useMemo(() => { let result = [...policies] if (searchQuery.trim()) { const q = searchQuery.toLowerCase() result = result.filter( (p) => p.dataObjectName.toLowerCase().includes(q) || p.policyId.toLowerCase().includes(q) || p.description.toLowerCase().includes(q), ) } if (filter === 'active') result = result.filter((p) => p.status === 'ACTIVE') else if (filter === 'draft') result = result.filter((p) => p.status === 'DRAFT') else if (filter === 'review') result = result.filter((p) => isPolicyOverdue(p)) if (driverFilter !== 'all') result = result.filter((p) => p.retentionDriver === driverFilter) return result }, [policies, searchQuery, filter, driverFilter]) const stats = useMemo(() => { const total = policies.length const active = policies.filter((p) => p.status === 'ACTIVE').length const draft = policies.filter((p) => p.status === 'DRAFT').length const overdue = policies.filter((p) => isPolicyOverdue(p)).length const legalHolds = policies.reduce( (acc, p) => acc + getActiveLegalHolds(p).length, 0, ) return { total, active, draft, overdue, legalHolds } }, [policies]) // -------------------------------------------------------------------------- // Handlers // -------------------------------------------------------------------------- const updatePolicy = useCallback( (id: string, updater: (p: LoeschfristPolicy) => LoeschfristPolicy) => { setPolicies((prev) => prev.map((p) => (p.policyId === id ? updater(p) : p)), ) }, [], ) const createNewPolicy = useCallback(() => { const newP = createEmptyPolicy() setPolicies((prev) => [...prev, newP]) setEditingId(newP.policyId) setTab('editor') }, []) const deletePolicy = useCallback( (id: string) => { setPolicies((prev) => prev.filter((p) => p.policyId !== id)) if (editingId === id) setEditingId(null) }, [editingId], ) const addLegalHold = useCallback( (policyId: string) => { updatePolicy(policyId, (p) => ({ ...p, legalHolds: [...p.legalHolds, createEmptyLegalHold()], })) }, [updatePolicy], ) const removeLegalHold = useCallback( (policyId: string, idx: number) => { updatePolicy(policyId, (p) => ({ ...p, legalHolds: p.legalHolds.filter((_, i) => i !== idx), })) }, [updatePolicy], ) const addStorageLocation = useCallback( (policyId: string) => { updatePolicy(policyId, (p) => ({ ...p, storageLocations: [...p.storageLocations, createEmptyStorageLocation()], })) }, [updatePolicy], ) const removeStorageLocation = useCallback( (policyId: string, idx: number) => { updatePolicy(policyId, (p) => ({ ...p, storageLocations: p.storageLocations.filter((_, i) => i !== idx), })) }, [updatePolicy], ) const handleProfilingAnswer = useCallback( (stepIndex: number, questionId: string, value: any) => { setProfilingAnswers((prev) => { const existing = prev.findIndex( (a) => a.stepIndex === stepIndex && a.questionId === questionId, ) const answer: ProfilingAnswer = { stepIndex, questionId, value } if (existing >= 0) { const copy = [...prev] copy[existing] = answer return copy } return [...prev, answer] }) }, [], ) const handleGenerate = useCallback(() => { const generated = generatePoliciesFromProfile(profilingAnswers) setGeneratedPolicies(generated) setSelectedGenerated(new Set(generated.map((p) => p.policyId))) }, [profilingAnswers]) const adoptGeneratedPolicies = useCallback( (onlySelected: boolean) => { const toAdopt = onlySelected ? generatedPolicies.filter((p) => selectedGenerated.has(p.policyId)) : generatedPolicies setPolicies((prev) => [...prev, ...toAdopt]) setGeneratedPolicies([]) setSelectedGenerated(new Set()) setProfilingStep(0) setProfilingAnswers([]) setTab('uebersicht') }, [generatedPolicies, selectedGenerated], ) const runCompliance = useCallback(() => { const result = runComplianceCheck(policies) setComplianceResult(result) }, [policies]) // -------------------------------------------------------------------------- // Tab definitions // -------------------------------------------------------------------------- const TAB_CONFIG: { key: Tab; label: string }[] = [ { key: 'uebersicht', label: 'Uebersicht' }, { key: 'editor', label: 'Editor' }, { key: 'generator', label: 'Generator' }, { key: 'export', label: 'Export & Compliance' }, ] // -------------------------------------------------------------------------- // Render helpers // -------------------------------------------------------------------------- const renderStatusBadge = (status: PolicyStatus) => { const colors = STATUS_COLORS[status] ?? 'bg-gray-100 text-gray-800' const label = STATUS_LABELS[status] ?? status return ( {label} ) } const renderTriggerBadge = (trigger: DeletionTriggerLevel) => { const colors = TRIGGER_COLORS[trigger] ?? 'bg-gray-100 text-gray-800' const label = TRIGGER_LABELS[trigger] ?? trigger return ( {label} ) } // ========================================================================== // TAB 1: Uebersicht // ========================================================================== const renderUebersicht = () => (
{/* Stats bar */}
{[ { label: 'Gesamt', value: stats.total, color: 'text-gray-900' }, { label: 'Aktiv', value: stats.active, color: 'text-green-600' }, { label: 'Entwurf', value: stats.draft, color: 'text-yellow-600' }, { label: 'Pruefung faellig', value: stats.overdue, color: 'text-red-600', }, { label: 'Legal Holds aktiv', value: stats.legalHolds, color: 'text-orange-600', }, ].map((s) => (
{s.value}
{s.label}
))}
{/* Search & filters */}
setSearchQuery(e.target.value)} placeholder="Suche nach Name, ID oder Beschreibung..." className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500" />
Status: {[ { key: 'all', label: 'Alle' }, { key: 'active', label: 'Aktiv' }, { key: 'draft', label: 'Entwurf' }, { key: 'review', label: 'Pruefung noetig' }, ].map((f) => ( ))} Aufbewahrungstreiber:
{/* Policy cards or empty state */} {filteredPolicies.length === 0 && policies.length === 0 ? (
📋

Noch keine Loeschfristen angelegt

Starten Sie den Generator, um auf Basis Ihres Unternehmensprofils automatisch passende Loeschfristen zu erstellen, oder legen Sie manuell eine neue Loeschfrist an.

) : filteredPolicies.length === 0 ? (

Keine Loeschfristen entsprechen den aktuellen Filtern.

) : (
{filteredPolicies.map((p) => { const trigger = getEffectiveDeletionTrigger(p) const activeHolds = getActiveLegalHolds(p) const overdue = isPolicyOverdue(p) return (
{activeHolds.length > 0 && ( )}
{p.policyId}

{p.dataObjectName || 'Ohne Bezeichnung'}

{renderTriggerBadge(trigger)} {formatRetentionDuration(p)} {renderStatusBadge(p.status)} {overdue && ( Pruefung faellig )}
{p.description && (

{p.description}

)}
) })}
)} {/* Floating action button */} {policies.length > 0 && (
)}
) // ========================================================================== // TAB 2: Editor // ========================================================================== const renderEditorNoSelection = () => (

Loeschfrist zum Bearbeiten waehlen

{policies.length === 0 ? (

Noch keine Loeschfristen vorhanden.{' '}

) : (
{policies.map((p) => ( ))}
)}
) const renderEditorForm = (policy: LoeschfristPolicy) => { const pid = policy.policyId const set = ( key: K, val: LoeschfristPolicy[K], ) => { updatePolicy(pid, (p) => ({ ...p, [key]: val })) } const updateLegalHold = ( idx: number, updater: (h: LegalHold) => LegalHold, ) => { updatePolicy(pid, (p) => ({ ...p, legalHolds: p.legalHolds.map((h, i) => (i === idx ? updater(h) : h)), })) } const updateStorageLocation = ( idx: number, updater: (s: StorageLocation) => StorageLocation, ) => { updatePolicy(pid, (p) => ({ ...p, storageLocations: p.storageLocations.map((s, i) => i === idx ? updater(s) : s, ), })) } return (
{/* Header with back button */}

{policy.dataObjectName || 'Neue Loeschfrist'}

{policy.policyId}
{renderStatusBadge(policy.status)}
{/* Sektion 1: Datenobjekt */}

1. Datenobjekt

set('dataObjectName', e.target.value)} placeholder="z.B. Bewerbungsunterlagen" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500" />