refactor: Admin-Layout komplett entfernt — SDK als einziges Layout
All checks were successful
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / test-go-ai-compliance (push) Successful in 32s
CI / test-python-backend-compliance (push) Successful in 31s
CI / test-python-document-crawler (push) Successful in 21s
CI / test-python-dsms-gateway (push) Successful in 19s
All checks were successful
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / test-go-ai-compliance (push) Successful in 32s
CI / test-python-backend-compliance (push) Successful in 31s
CI / test-python-document-crawler (push) Successful in 21s
CI / test-python-dsms-gateway (push) Successful in 19s
Kaputtes (admin) Layout geloescht (Role-Selection, 404-Sidebar, localhost-Dashboard). SDK-Flow nach /sdk/sdk-flow verschoben. Route-Gruppe (sdk) aufgeloest. Root-Seite redirected auf /sdk. ~25 ungenutzte Dateien/Verzeichnisse entfernt. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,296 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import {
|
||||
DataPoint,
|
||||
DataPointCategory,
|
||||
CATEGORY_METADATA,
|
||||
RISK_LEVEL_STYLING,
|
||||
RiskLevel,
|
||||
} from '@/lib/sdk/einwilligungen/types'
|
||||
|
||||
interface DataPointsPreviewProps {
|
||||
dataPoints: DataPoint[]
|
||||
onInsertPlaceholder: (placeholder: string) => void
|
||||
language?: 'de' | 'en'
|
||||
}
|
||||
|
||||
/**
|
||||
* Platzhalter-Definitionen mit Beschreibungen
|
||||
*/
|
||||
const PLACEHOLDERS = [
|
||||
{
|
||||
placeholder: '[DATENPUNKTE_TABLE]',
|
||||
label: { de: 'Tabelle', en: 'Table' },
|
||||
description: { de: 'Markdown-Tabelle mit allen Datenpunkten', en: 'Markdown table with all data points' },
|
||||
},
|
||||
{
|
||||
placeholder: '[DATENPUNKTE_LIST]',
|
||||
label: { de: 'Liste', en: 'List' },
|
||||
description: { de: 'Kommaseparierte Liste der Namen', en: 'Comma-separated list of names' },
|
||||
},
|
||||
{
|
||||
placeholder: '[VERARBEITUNGSZWECKE]',
|
||||
label: { de: 'Zwecke', en: 'Purposes' },
|
||||
description: { de: 'Alle Verarbeitungszwecke', en: 'All processing purposes' },
|
||||
},
|
||||
{
|
||||
placeholder: '[RECHTSGRUNDLAGEN]',
|
||||
label: { de: 'Rechtsgrundlagen', en: 'Legal Bases' },
|
||||
description: { de: 'DSGVO-Artikel', en: 'GDPR articles' },
|
||||
},
|
||||
{
|
||||
placeholder: '[SPEICHERFRISTEN]',
|
||||
label: { de: 'Speicherfristen', en: 'Retention' },
|
||||
description: { de: 'Fristen nach Kategorie', en: 'Periods by category' },
|
||||
},
|
||||
{
|
||||
placeholder: '[EMPFAENGER]',
|
||||
label: { de: 'Empfänger', en: 'Recipients' },
|
||||
description: { de: 'Liste aller Drittparteien', en: 'List of third parties' },
|
||||
},
|
||||
{
|
||||
placeholder: '[BESONDERE_KATEGORIEN]',
|
||||
label: { de: 'Art. 9', en: 'Art. 9' },
|
||||
description: { de: 'Abschnitt für sensible Daten', en: 'Section for sensitive data' },
|
||||
},
|
||||
{
|
||||
placeholder: '[DRITTLAND_TRANSFERS]',
|
||||
label: { de: 'Drittländer', en: 'Third Countries' },
|
||||
description: { de: 'Datenübermittlung außerhalb EU', en: 'Data transfers outside EU' },
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* Risiko-Badge Farben
|
||||
*/
|
||||
function getRiskBadgeColor(riskLevel: RiskLevel): string {
|
||||
switch (riskLevel) {
|
||||
case 'HIGH':
|
||||
return 'bg-red-100 text-red-700 border-red-200'
|
||||
case 'MEDIUM':
|
||||
return 'bg-yellow-100 text-yellow-700 border-yellow-200'
|
||||
case 'LOW':
|
||||
default:
|
||||
return 'bg-green-100 text-green-700 border-green-200'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DataPointsPreview Komponente
|
||||
*/
|
||||
export function DataPointsPreview({
|
||||
dataPoints,
|
||||
onInsertPlaceholder,
|
||||
language = 'de',
|
||||
}: DataPointsPreviewProps) {
|
||||
const [expandedCategories, setExpandedCategories] = useState<string[]>([])
|
||||
|
||||
// Gruppiere Datenpunkte nach Kategorie
|
||||
const byCategory = useMemo(() => {
|
||||
return dataPoints.reduce((acc, dp) => {
|
||||
if (!acc[dp.category]) {
|
||||
acc[dp.category] = []
|
||||
}
|
||||
acc[dp.category].push(dp)
|
||||
return acc
|
||||
}, {} as Record<DataPointCategory, DataPoint[]>)
|
||||
}, [dataPoints])
|
||||
|
||||
// Statistiken berechnen
|
||||
const stats = useMemo(() => {
|
||||
const riskCounts: Record<RiskLevel, number> = { LOW: 0, MEDIUM: 0, HIGH: 0 }
|
||||
let specialCategoryCount = 0
|
||||
|
||||
dataPoints.forEach(dp => {
|
||||
riskCounts[dp.riskLevel]++
|
||||
if (dp.isSpecialCategory) specialCategoryCount++
|
||||
})
|
||||
|
||||
return {
|
||||
riskCounts,
|
||||
specialCategoryCount,
|
||||
categoryCount: Object.keys(byCategory).length,
|
||||
}
|
||||
}, [dataPoints, byCategory])
|
||||
|
||||
// Sortierte Kategorien (nach Code)
|
||||
const sortedCategories = useMemo(() => {
|
||||
return Object.entries(byCategory).sort((a, b) => {
|
||||
const codeA = CATEGORY_METADATA[a[0] as DataPointCategory]?.code || 'Z'
|
||||
const codeB = CATEGORY_METADATA[b[0] as DataPointCategory]?.code || 'Z'
|
||||
return codeA.localeCompare(codeB)
|
||||
})
|
||||
}, [byCategory])
|
||||
|
||||
const toggleCategory = (category: string) => {
|
||||
setExpandedCategories(prev =>
|
||||
prev.includes(category)
|
||||
? prev.filter(c => c !== category)
|
||||
: [...prev, category]
|
||||
)
|
||||
}
|
||||
|
||||
if (dataPoints.length === 0) {
|
||||
return (
|
||||
<div className="bg-white rounded-xl border border-gray-200 p-6">
|
||||
<h4 className="font-semibold text-gray-900 flex items-center gap-2 mb-3">
|
||||
<svg className="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4" />
|
||||
</svg>
|
||||
{language === 'de' ? 'Einwilligungen' : 'Consents'}
|
||||
</h4>
|
||||
<p className="text-sm text-gray-500">
|
||||
{language === 'de'
|
||||
? 'Keine Datenpunkte ausgewählt. Wählen Sie Datenpunkte im Einwilligungs-Schritt aus.'
|
||||
: 'No data points selected. Select data points in the consent step.'}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-xl border border-gray-200 p-6 h-full flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="mb-4">
|
||||
<h4 className="font-semibold text-gray-900 flex items-center gap-2">
|
||||
<svg className="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4" />
|
||||
</svg>
|
||||
{language === 'de' ? 'Einwilligungen' : 'Consents'}
|
||||
</h4>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
{dataPoints.length} {language === 'de' ? 'Datenpunkte aus' : 'data points from'}{' '}
|
||||
{stats.categoryCount} {language === 'de' ? 'Kategorien' : 'categories'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Statistik-Badges */}
|
||||
<div className="flex flex-wrap gap-2 mb-4">
|
||||
{stats.riskCounts.HIGH > 0 && (
|
||||
<span className="px-2 py-1 text-xs rounded-full bg-red-100 text-red-700">
|
||||
{stats.riskCounts.HIGH} {language === 'de' ? 'Hoch' : 'High'}
|
||||
</span>
|
||||
)}
|
||||
{stats.riskCounts.MEDIUM > 0 && (
|
||||
<span className="px-2 py-1 text-xs rounded-full bg-yellow-100 text-yellow-700">
|
||||
{stats.riskCounts.MEDIUM} {language === 'de' ? 'Mittel' : 'Medium'}
|
||||
</span>
|
||||
)}
|
||||
{stats.riskCounts.LOW > 0 && (
|
||||
<span className="px-2 py-1 text-xs rounded-full bg-green-100 text-green-700">
|
||||
{stats.riskCounts.LOW} {language === 'de' ? 'Niedrig' : 'Low'}
|
||||
</span>
|
||||
)}
|
||||
{stats.specialCategoryCount > 0 && (
|
||||
<span className="px-2 py-1 text-xs rounded-full bg-orange-100 text-orange-700 flex items-center gap-1">
|
||||
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="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" />
|
||||
</svg>
|
||||
{stats.specialCategoryCount} Art. 9
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-gray-200 my-3"></div>
|
||||
|
||||
{/* Datenpunkte nach Kategorie */}
|
||||
<div className="flex-1 overflow-y-auto space-y-2 max-h-64">
|
||||
{sortedCategories.map(([category, points]) => {
|
||||
const metadata = CATEGORY_METADATA[category as DataPointCategory]
|
||||
if (!metadata) return null
|
||||
const isExpanded = expandedCategories.includes(category)
|
||||
|
||||
return (
|
||||
<div key={category} className="border border-gray-100 rounded-lg">
|
||||
<button
|
||||
onClick={() => toggleCategory(category)}
|
||||
className="w-full flex items-center justify-between p-2 text-sm hover:bg-gray-50 rounded-lg"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs text-gray-400">{metadata.code}</span>
|
||||
<span className="font-medium text-gray-900">
|
||||
{language === 'de' ? metadata.name.de : metadata.name.en}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="px-1.5 py-0.5 text-xs rounded bg-gray-100 text-gray-600">
|
||||
{points.length}
|
||||
</span>
|
||||
<svg
|
||||
className={`w-4 h-4 text-gray-400 transition-transform ${isExpanded ? '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>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{isExpanded && (
|
||||
<ul className="px-2 pb-2 space-y-1">
|
||||
{points.map(dp => (
|
||||
<li
|
||||
key={dp.id}
|
||||
className="flex items-center justify-between text-sm py-1 pl-6"
|
||||
>
|
||||
<span className="truncate max-w-[160px] text-gray-700">
|
||||
{language === 'de' ? dp.name.de : dp.name.en}
|
||||
</span>
|
||||
<div className="flex items-center gap-1">
|
||||
{dp.isSpecialCategory && (
|
||||
<svg className="w-3 h-3 text-orange-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="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" />
|
||||
</svg>
|
||||
)}
|
||||
<span className={`px-1.5 py-0.5 text-[10px] rounded border ${getRiskBadgeColor(dp.riskLevel)}`}>
|
||||
{RISK_LEVEL_STYLING[dp.riskLevel].label[language]}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-gray-200 my-3"></div>
|
||||
|
||||
{/* Schnell-Einfügen Buttons */}
|
||||
<div>
|
||||
<p className="text-xs font-medium text-gray-500 mb-2">
|
||||
{language === 'de' ? 'Platzhalter einfügen:' : 'Insert placeholder:'}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{PLACEHOLDERS.slice(0, 4).map(({ placeholder, label }) => (
|
||||
<button
|
||||
key={placeholder}
|
||||
onClick={() => onInsertPlaceholder(placeholder)}
|
||||
className="px-2 py-1 text-xs bg-purple-50 text-purple-700 rounded hover:bg-purple-100 transition-colors"
|
||||
title={placeholder}
|
||||
>
|
||||
{language === 'de' ? label.de : label.en}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5 mt-1.5">
|
||||
{PLACEHOLDERS.slice(4).map(({ placeholder, label }) => (
|
||||
<button
|
||||
key={placeholder}
|
||||
onClick={() => onInsertPlaceholder(placeholder)}
|
||||
className="px-2 py-1 text-xs bg-purple-50 text-purple-700 rounded hover:bg-purple-100 transition-colors"
|
||||
title={placeholder}
|
||||
>
|
||||
{language === 'de' ? label.de : label.en}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default DataPointsPreview
|
||||
@@ -0,0 +1,211 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { DataPoint } from '@/lib/sdk/einwilligungen/types'
|
||||
import {
|
||||
validateDocument,
|
||||
ValidationWarning,
|
||||
} from '@/lib/sdk/document-generator/datapoint-helpers'
|
||||
|
||||
interface DocumentValidationProps {
|
||||
dataPoints: DataPoint[]
|
||||
documentContent: string
|
||||
language?: 'de' | 'en'
|
||||
onInsertPlaceholder?: (placeholder: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Placeholder-Vorschlag aus der Warnung extrahieren
|
||||
*/
|
||||
function extractPlaceholderSuggestion(warning: ValidationWarning): string | null {
|
||||
const match = warning.suggestion.match(/\[([A-Z_]+)\]/)
|
||||
return match ? match[0] : null
|
||||
}
|
||||
|
||||
/**
|
||||
* DocumentValidation Komponente
|
||||
*/
|
||||
export function DocumentValidation({
|
||||
dataPoints,
|
||||
documentContent,
|
||||
language = 'de',
|
||||
onInsertPlaceholder,
|
||||
}: DocumentValidationProps) {
|
||||
const [expandedWarnings, setExpandedWarnings] = useState<string[]>([])
|
||||
|
||||
// Führe Validierung durch
|
||||
const warnings = useMemo(() => {
|
||||
if (dataPoints.length === 0 || !documentContent) {
|
||||
return []
|
||||
}
|
||||
return validateDocument(dataPoints, documentContent, language)
|
||||
}, [dataPoints, documentContent, language])
|
||||
|
||||
// Gruppiere nach Typ
|
||||
const errorCount = warnings.filter(w => w.type === 'error').length
|
||||
const warningCount = warnings.filter(w => w.type === 'warning').length
|
||||
const infoCount = warnings.filter(w => w.type === 'info').length
|
||||
|
||||
const toggleWarning = (code: string) => {
|
||||
setExpandedWarnings(prev =>
|
||||
prev.includes(code) ? prev.filter(c => c !== code) : [...prev, code]
|
||||
)
|
||||
}
|
||||
|
||||
if (warnings.length === 0) {
|
||||
// Keine Warnungen - zeige Erfolgsmeldung wenn Datenpunkte vorhanden
|
||||
if (dataPoints.length > 0 && documentContent.length > 100) {
|
||||
return (
|
||||
<div className="bg-green-50 border border-green-200 rounded-xl p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<svg className="w-5 h-5 text-green-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<div>
|
||||
<h4 className="font-medium text-green-800">
|
||||
{language === 'de' ? 'Dokument valide' : 'Document valid'}
|
||||
</h4>
|
||||
<p className="text-sm text-green-700 mt-1">
|
||||
{language === 'de'
|
||||
? 'Alle notwendigen Abschnitte für die ausgewählten Datenpunkte sind vorhanden.'
|
||||
: 'All necessary sections for the selected data points are present.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Zusammenfassung */}
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="font-medium text-gray-700">
|
||||
{language === 'de' ? 'Validierung:' : 'Validation:'}
|
||||
</span>
|
||||
{errorCount > 0 && (
|
||||
<span className="px-2 py-0.5 text-xs rounded-full bg-red-100 text-red-700">
|
||||
{errorCount} {language === 'de' ? 'Fehler' : 'Error'}{errorCount > 1 && 's'}
|
||||
</span>
|
||||
)}
|
||||
{warningCount > 0 && (
|
||||
<span className="px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-700">
|
||||
{warningCount} {language === 'de' ? 'Warnung' : 'Warning'}{warningCount > 1 && (language === 'de' ? 'en' : 's')}
|
||||
</span>
|
||||
)}
|
||||
{infoCount > 0 && (
|
||||
<span className="px-2 py-0.5 text-xs rounded-full bg-blue-100 text-blue-700">
|
||||
{infoCount} {language === 'de' ? 'Hinweis' : 'Info'}{infoCount > 1 && (language === 'de' ? 'e' : 's')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Warnungen */}
|
||||
{warnings.map((warning, index) => {
|
||||
const placeholder = extractPlaceholderSuggestion(warning)
|
||||
const isExpanded = expandedWarnings.includes(warning.code)
|
||||
const isError = warning.type === 'error'
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${warning.code}-${index}`}
|
||||
className={`rounded-xl border p-4 ${
|
||||
isError
|
||||
? 'bg-red-50 border-red-200'
|
||||
: 'bg-yellow-50 border-yellow-200'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Icon */}
|
||||
<svg
|
||||
className={`w-5 h-5 mt-0.5 ${isError ? 'text-red-600' : 'text-yellow-600'}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
{isError ? (
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
) : (
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="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" />
|
||||
)}
|
||||
</svg>
|
||||
|
||||
<div className="flex-1">
|
||||
{/* Message */}
|
||||
<p className={`font-medium ${isError ? 'text-red-800' : 'text-yellow-800'}`}>
|
||||
{warning.message}
|
||||
</p>
|
||||
|
||||
{/* Suggestion */}
|
||||
<div className="flex items-start gap-2 mt-2">
|
||||
<svg className="w-4 h-4 mt-0.5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
|
||||
</svg>
|
||||
<span className="text-sm text-gray-600">{warning.suggestion}</span>
|
||||
</div>
|
||||
|
||||
{/* Quick-Fix Button */}
|
||||
{placeholder && onInsertPlaceholder && (
|
||||
<button
|
||||
onClick={() => onInsertPlaceholder(placeholder)}
|
||||
className="mt-3 inline-flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
{language === 'de' ? 'Platzhalter einfügen' : 'Insert placeholder'}
|
||||
<code className="ml-1 text-xs bg-gray-100 px-1.5 py-0.5 rounded">
|
||||
{placeholder}
|
||||
</code>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Betroffene Datenpunkte */}
|
||||
{warning.affectedDataPoints && warning.affectedDataPoints.length > 0 && (
|
||||
<div className="mt-3">
|
||||
<button
|
||||
onClick={() => toggleWarning(warning.code)}
|
||||
className="flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700"
|
||||
>
|
||||
<svg
|
||||
className={`w-3 h-3 transition-transform ${isExpanded ? '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>
|
||||
{warning.affectedDataPoints.length}{' '}
|
||||
{language === 'de' ? 'betroffene Datenpunkte' : 'affected data points'}
|
||||
</button>
|
||||
|
||||
{isExpanded && (
|
||||
<ul className="mt-2 text-xs space-y-0.5 pl-4">
|
||||
{warning.affectedDataPoints.slice(0, 5).map(dp => (
|
||||
<li key={dp.id} className="list-disc text-gray-600">
|
||||
{language === 'de' ? dp.name.de : dp.name.en}
|
||||
</li>
|
||||
))}
|
||||
{warning.affectedDataPoints.length > 5 && (
|
||||
<li className="list-none text-gray-400">
|
||||
... {language === 'de' ? 'und' : 'and'}{' '}
|
||||
{warning.affectedDataPoints.length - 5}{' '}
|
||||
{language === 'de' ? 'weitere' : 'more'}
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default DocumentValidation
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Document Generator Components
|
||||
*
|
||||
* Diese Komponenten integrieren die Einwilligungen-Datenpunkte
|
||||
* in den Dokumentengenerator.
|
||||
*/
|
||||
|
||||
export { DataPointsPreview } from './DataPointsPreview'
|
||||
export { DocumentValidation } from './DocumentValidation'
|
||||
591
admin-compliance/app/sdk/document-generator/page.tsx
Normal file
591
admin-compliance/app/sdk/document-generator/page.tsx
Normal file
@@ -0,0 +1,591 @@
|
||||
'use client'
|
||||
|
||||
import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react'
|
||||
import { useSDK } from '@/lib/sdk'
|
||||
import { useEinwilligungen, EinwilligungenProvider } from '@/lib/sdk/einwilligungen/context'
|
||||
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
|
||||
import {
|
||||
LegalTemplateResult,
|
||||
TemplateType,
|
||||
LicenseType,
|
||||
TEMPLATE_TYPE_LABELS,
|
||||
LICENSE_TYPE_LABELS,
|
||||
} from '@/lib/sdk/types'
|
||||
import { DataPointsPreview } from './components/DataPointsPreview'
|
||||
import { DocumentValidation } from './components/DocumentValidation'
|
||||
import { generateAllPlaceholders } from '@/lib/sdk/document-generator/datapoint-helpers'
|
||||
import { loadAllTemplates, searchTemplates } from './searchTemplates'
|
||||
|
||||
// =============================================================================
|
||||
// CATEGORY CONFIG
|
||||
// =============================================================================
|
||||
|
||||
const CATEGORIES: { key: string; label: string; types: string[] | null }[] = [
|
||||
{ key: 'all', label: 'Alle', types: null },
|
||||
{ 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: 'acceptable_use', label: 'AUP', types: ['acceptable_use'] },
|
||||
{ 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'] },
|
||||
]
|
||||
|
||||
// =============================================================================
|
||||
// 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">
|
||||
{/* Card header */}
|
||||
<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>
|
||||
|
||||
{/* Inline preview */}
|
||||
{expanded && (
|
||||
<div className="border-t border-gray-100 bg-gray-50 p-4 max-h-64 overflow-y-auto">
|
||||
<pre className="text-xs text-gray-600 whitespace-pre-wrap font-mono leading-relaxed">
|
||||
{template.text.slice(0, 1500)}{template.text.length > 1500 ? '\n…' : ''}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// GENERATOR SECTION
|
||||
// =============================================================================
|
||||
|
||||
function GeneratorSection({
|
||||
template,
|
||||
placeholderValues,
|
||||
onPlaceholderChange,
|
||||
onClose,
|
||||
}: {
|
||||
template: LegalTemplateResult
|
||||
placeholderValues: Record<string, string>
|
||||
onPlaceholderChange: (key: string, value: string) => void
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [activeTab, setActiveTab] = useState<'placeholders' | 'preview'>('placeholders')
|
||||
|
||||
const renderedContent = useMemo(() => {
|
||||
let content = template.text
|
||||
for (const [key, value] of Object.entries(placeholderValues)) {
|
||||
if (value) {
|
||||
content = content.replace(new RegExp(key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), value)
|
||||
}
|
||||
}
|
||||
return content
|
||||
}, [template.text, placeholderValues])
|
||||
|
||||
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 handlePrint = () => window.print()
|
||||
|
||||
const placeholders = template.placeholders || []
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-xl border-2 border-purple-300 overflow-hidden">
|
||||
{/* Generator header */}
|
||||
<div className="bg-purple-50 px-6 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<svg className="w-5 h-5 text-purple-600" 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>
|
||||
</div>
|
||||
<button onClick={onClose} className="text-gray-400 hover:text-gray-600 transition-colors" 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' ? 'Platzhalter ausfüllen' : 'Vorschau & Export'}
|
||||
</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>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{placeholders.map((placeholder) => (
|
||||
<div key={placeholder}>
|
||||
<label className="block text-xs text-gray-600 mb-1 font-mono">{placeholder}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={placeholderValues[placeholder] || ''}
|
||||
onChange={(e) => onPlaceholderChange(placeholder, e.target.value)}
|
||||
placeholder={`Wert für ${placeholder}`}
|
||||
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 className="flex justify-end pt-2">
|
||||
<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">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-gray-600">
|
||||
{placeholders.length > 0 && Object.values(placeholderValues).filter(Boolean).length < placeholders.length && (
|
||||
<span className="text-orange-600">
|
||||
⚠ {placeholders.length - Object.values(placeholderValues).filter(Boolean).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={handlePrint}
|
||||
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() {
|
||||
const { state } = useSDK()
|
||||
const { selectedDataPointsData } = useEinwilligungen()
|
||||
|
||||
// Library state
|
||||
const [allTemplates, setAllTemplates] = useState<LegalTemplateResult[]>([])
|
||||
const [isLoadingLibrary, setIsLoadingLibrary] = useState(true)
|
||||
const [activeCategory, setActiveCategory] = useState<string>('all')
|
||||
const [activeLanguage, setActiveLanguage] = useState<'all' | 'de' | 'en'>('all')
|
||||
const [librarySearch, setLibrarySearch] = useState('')
|
||||
const [expandedPreviewId, setExpandedPreviewId] = useState<string | null>(null)
|
||||
|
||||
// Generator state
|
||||
const [activeTemplate, setActiveTemplate] = useState<LegalTemplateResult | null>(null)
|
||||
const [placeholderValues, setPlaceholderValues] = useState<Record<string, string>>({})
|
||||
const generatorRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Status
|
||||
const [totalCount, setTotalCount] = useState<number>(0)
|
||||
|
||||
// Load all templates on mount
|
||||
useEffect(() => {
|
||||
setIsLoadingLibrary(true)
|
||||
loadAllTemplates(200).then((templates) => {
|
||||
setAllTemplates(templates)
|
||||
setTotalCount(templates.length)
|
||||
setIsLoadingLibrary(false)
|
||||
})
|
||||
}, [])
|
||||
|
||||
// Pre-fill placeholders from company profile
|
||||
useEffect(() => {
|
||||
if (state?.companyProfile) {
|
||||
const profile = state.companyProfile
|
||||
setPlaceholderValues((prev) => ({
|
||||
...prev,
|
||||
'{{COMPANY_NAME}}': profile.companyName || '',
|
||||
'{{FIRMENNAME}}': profile.companyName || '',
|
||||
'{{CONTACT_EMAIL}}': profile.dpoEmail || '',
|
||||
'{{DSB_EMAIL}}': profile.dpoEmail || '',
|
||||
'{{DPO_NAME}}': profile.dpoName || '',
|
||||
'{{DSB_NAME}}': profile.dpoName || '',
|
||||
}))
|
||||
}
|
||||
}, [state?.companyProfile])
|
||||
|
||||
// Pre-fill from Einwilligungen data points
|
||||
useEffect(() => {
|
||||
if (selectedDataPointsData && selectedDataPointsData.length > 0) {
|
||||
const generated = generateAllPlaceholders(selectedDataPointsData, 'de')
|
||||
setPlaceholderValues((prev) => ({ ...prev, ...generated }))
|
||||
}
|
||||
}, [selectedDataPointsData])
|
||||
|
||||
// Filtered templates (computed)
|
||||
const filteredTemplates = useMemo(() => {
|
||||
const category = CATEGORIES.find((c) => c.key === activeCategory)
|
||||
return allTemplates.filter((t) => {
|
||||
if (category && category.types !== null) {
|
||||
if (!category.types.includes(t.templateType || '')) return false
|
||||
}
|
||||
if (activeLanguage !== 'all' && t.language !== activeLanguage) return false
|
||||
if (librarySearch.trim()) {
|
||||
const q = librarySearch.toLowerCase()
|
||||
const title = (t.documentTitle || '').toLowerCase()
|
||||
const type = (t.templateType || '').toLowerCase()
|
||||
if (!title.includes(q) && !type.includes(q)) return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
}, [allTemplates, activeCategory, activeLanguage, librarySearch])
|
||||
|
||||
const handleUseTemplate = useCallback((t: LegalTemplateResult) => {
|
||||
setActiveTemplate(t)
|
||||
setExpandedPreviewId(null)
|
||||
// Scroll to generator
|
||||
setTimeout(() => {
|
||||
generatorRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
}, 100)
|
||||
}, [])
|
||||
|
||||
const handleInsertPlaceholder = useCallback((placeholder: string) => {
|
||||
if (!placeholderValues[placeholder]) {
|
||||
const generated = generateAllPlaceholders(selectedDataPointsData || [], 'de')
|
||||
if (generated[placeholder as keyof typeof generated]) {
|
||||
setPlaceholderValues((prev) => ({
|
||||
...prev,
|
||||
[placeholder]: generated[placeholder as keyof typeof generated],
|
||||
}))
|
||||
}
|
||||
}
|
||||
}, [placeholderValues, selectedDataPointsData])
|
||||
|
||||
const stepInfo = STEP_EXPLANATIONS['document-generator'] || {
|
||||
title: 'Dokumentengenerator',
|
||||
description: 'Generieren Sie rechtliche Dokumente aus lizenzkonformen Vorlagen',
|
||||
explanation: 'Der Dokumentengenerator nutzt frei lizenzierte Textbausteine um Datenschutzerklaerungen, AGB und andere rechtliche Dokumente zu erstellen.',
|
||||
tips: ['Wählen Sie eine Vorlage aus der Bibliothek aus', 'Füllen Sie die Platzhalter mit Ihren Unternehmensdaten'],
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* Step Header */}
|
||||
<StepHeader
|
||||
stepId="document-generator"
|
||||
title="Dokumentengenerator"
|
||||
description="Generieren Sie rechtliche Dokumente aus lizenzkonformen Vorlagen"
|
||||
explanation={stepInfo.explanation}
|
||||
tips={stepInfo.tips}
|
||||
/>
|
||||
|
||||
{/* Status bar */}
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="bg-white rounded-xl border border-gray-200 p-5">
|
||||
<div className="text-sm text-gray-500">Vorlagen gesamt</div>
|
||||
<div className="text-3xl font-bold text-gray-900">{totalCount}</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-xl border border-gray-200 p-5">
|
||||
<div className="text-sm text-gray-500">Angezeigt</div>
|
||||
<div className="text-3xl font-bold text-purple-600">{filteredTemplates.length}</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-xl border border-gray-200 p-5">
|
||||
<div className="text-sm text-gray-500">Aktive Vorlage</div>
|
||||
<div className="text-sm font-medium text-gray-900 mt-1 truncate">
|
||||
{activeTemplate ? activeTemplate.documentTitle : '—'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ================================================================= */}
|
||||
{/* SECTION 1: TEMPLATE-BIBLIOTHEK */}
|
||||
{/* ================================================================= */}
|
||||
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
|
||||
{/* Library header */}
|
||||
<div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between flex-wrap gap-3">
|
||||
<h2 className="font-semibold text-gray-900">Template-Bibliothek</h2>
|
||||
{/* Language toggle */}
|
||||
<div className="flex items-center gap-1 bg-gray-100 rounded-lg p-1">
|
||||
{(['all', 'de', 'en'] as const).map((lang) => (
|
||||
<button
|
||||
key={lang}
|
||||
onClick={() => setActiveLanguage(lang)}
|
||||
className={`px-3 py-1.5 text-xs rounded-md font-medium transition-colors ${
|
||||
activeLanguage === lang
|
||||
? 'bg-white text-gray-900 shadow-sm'
|
||||
: 'text-gray-500 hover:text-gray-700'
|
||||
}`}
|
||||
>
|
||||
{lang === 'all' ? 'Alle' : lang.toUpperCase()}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category pills */}
|
||||
<div className="px-6 py-3 border-b border-gray-100 flex gap-2 flex-wrap">
|
||||
{CATEGORIES.map((cat) => {
|
||||
const count = cat.types === null
|
||||
? allTemplates.filter(t => activeLanguage === 'all' || t.language === activeLanguage).length
|
||||
: allTemplates.filter(t =>
|
||||
cat.types!.includes(t.templateType || '') &&
|
||||
(activeLanguage === 'all' || t.language === activeLanguage)
|
||||
).length
|
||||
return (
|
||||
<button
|
||||
key={cat.key}
|
||||
onClick={() => setActiveCategory(cat.key)}
|
||||
className={`px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${
|
||||
activeCategory === cat.key
|
||||
? 'bg-purple-600 text-white'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
{cat.label}
|
||||
{count > 0 && (
|
||||
<span className={`ml-1.5 ${activeCategory === cat.key ? 'text-purple-200' : 'text-gray-400'}`}>
|
||||
{count}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div className="px-6 py-3 border-b border-gray-100">
|
||||
<div className="relative">
|
||||
<svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
|
||||
</svg>
|
||||
<input
|
||||
type="text"
|
||||
value={librarySearch}
|
||||
onChange={(e) => setLibrarySearch(e.target.value)}
|
||||
placeholder="Vorlage suchen... (optional)"
|
||||
className="w-full pl-9 pr-4 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-purple-400"
|
||||
/>
|
||||
{librarySearch && (
|
||||
<button
|
||||
onClick={() => setLibrarySearch('')}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Template grid */}
|
||||
<div className="p-6">
|
||||
{isLoadingLibrary ? (
|
||||
<div className="flex items-center justify-center h-40">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
|
||||
</div>
|
||||
) : filteredTemplates.length === 0 ? (
|
||||
<div className="text-center py-12 text-gray-500">
|
||||
<div className="text-4xl mb-3">📄</div>
|
||||
<p>Keine Vorlagen für diese Auswahl</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{filteredTemplates.map((template) => (
|
||||
<LibraryCard
|
||||
key={template.id}
|
||||
template={template}
|
||||
expanded={expandedPreviewId === template.id}
|
||||
onTogglePreview={() =>
|
||||
setExpandedPreviewId((prev) => (prev === template.id ? null : template.id))
|
||||
}
|
||||
onUse={() => handleUseTemplate(template)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ================================================================= */}
|
||||
{/* SECTION 2: GENERATOR (visible only when activeTemplate is set) */}
|
||||
{/* ================================================================= */}
|
||||
{activeTemplate && (
|
||||
<div ref={generatorRef} className="space-y-6">
|
||||
<GeneratorSection
|
||||
template={activeTemplate}
|
||||
placeholderValues={placeholderValues}
|
||||
onPlaceholderChange={(key, value) =>
|
||||
setPlaceholderValues((prev) => ({ ...prev, [key]: value }))
|
||||
}
|
||||
onClose={() => setActiveTemplate(null)}
|
||||
/>
|
||||
|
||||
{/* Einwilligungen DataPoints sidebar (shown below generator on small screens, side on large) */}
|
||||
{selectedDataPointsData && selectedDataPointsData.length > 0 && (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2">
|
||||
<DocumentValidation
|
||||
dataPoints={selectedDataPointsData}
|
||||
documentContent={activeTemplate.text}
|
||||
language="de"
|
||||
onInsertPlaceholder={handleInsertPlaceholder}
|
||||
/>
|
||||
</div>
|
||||
<div className="lg:col-span-1">
|
||||
<DataPointsPreview
|
||||
dataPoints={selectedDataPointsData}
|
||||
onInsertPlaceholder={handleInsertPlaceholder}
|
||||
language="de"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function DocumentGeneratorPage() {
|
||||
return (
|
||||
<EinwilligungenProvider>
|
||||
<DocumentGeneratorPageInner />
|
||||
</EinwilligungenProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { searchTemplates } from './searchTemplates'
|
||||
|
||||
// jsdom doesn't define window.location.origin — stub it
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: { origin: 'https://localhost' },
|
||||
writable: true,
|
||||
})
|
||||
|
||||
describe('searchTemplates', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('gibt Ergebnisse zurück wenn eigenes Backend verfügbar', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
templates: [{
|
||||
id: 't1',
|
||||
title: 'Datenschutzerklärung (DSGVO-konform)',
|
||||
document_type: 'privacy_policy',
|
||||
content: '# Datenschutzerklärung\n\n{{COMPANY_NAME}}',
|
||||
description: 'Vollständige DSE',
|
||||
language: 'de',
|
||||
jurisdiction: 'DE',
|
||||
license_id: 'mit',
|
||||
license_name: 'MIT License',
|
||||
source_name: 'BreakPilot Compliance',
|
||||
attribution_required: false,
|
||||
is_complete_document: true,
|
||||
placeholders: ['{{COMPANY_NAME}}', '{{CONTACT_EMAIL}}'],
|
||||
}],
|
||||
total: 1,
|
||||
}),
|
||||
}))
|
||||
|
||||
const results = await searchTemplates({ query: 'Datenschutzerklärung' })
|
||||
expect(results).toHaveLength(1)
|
||||
expect(results[0].documentTitle).toBe('Datenschutzerklärung (DSGVO-konform)')
|
||||
expect(results[0].templateType).toBe('privacy_policy')
|
||||
expect(results[0].placeholders).toContain('{{COMPANY_NAME}}')
|
||||
expect((results[0] as any).source).toBe('db')
|
||||
})
|
||||
|
||||
it('fällt auf RAG zurück wenn Backend fehlschlägt', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn()
|
||||
.mockRejectedValueOnce(new Error('Backend down'))
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
results: [{
|
||||
regulation_name: 'DSGVO Art. 13',
|
||||
text: 'Informationspflichten',
|
||||
regulation_code: 'DSGVO-13',
|
||||
score: 0.8,
|
||||
}],
|
||||
}),
|
||||
})
|
||||
)
|
||||
|
||||
const results = await searchTemplates({ query: 'test' })
|
||||
expect(results).toHaveLength(1)
|
||||
expect(results[0].documentTitle).toBe('DSGVO Art. 13')
|
||||
expect((results[0] as any).source).toBe('rag')
|
||||
})
|
||||
|
||||
it('gibt [] zurück wenn beide Services down sind', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('all down')))
|
||||
|
||||
const results = await searchTemplates({ query: 'test' })
|
||||
expect(results).toEqual([])
|
||||
})
|
||||
})
|
||||
171
admin-compliance/app/sdk/document-generator/searchTemplates.ts
Normal file
171
admin-compliance/app/sdk/document-generator/searchTemplates.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* Template search helpers for document-generator.
|
||||
*
|
||||
* Two-tier search:
|
||||
* 1. Primary: own backend (compliance_legal_templates DB) — MIT-licensed, curated
|
||||
* 2. Fallback: RAG proxy (ai-compliance-sdk regulation search — law texts)
|
||||
*/
|
||||
|
||||
import type { LegalTemplateResult } from '@/lib/sdk/types'
|
||||
|
||||
export const TEMPLATES_API = '/api/sdk/v1/compliance/legal-templates'
|
||||
export const RAG_PROXY = '/api/sdk/v1/rag'
|
||||
|
||||
export interface TemplateSearchParams {
|
||||
query: string
|
||||
templateType?: string
|
||||
licenseTypes?: string[]
|
||||
language?: 'de' | 'en'
|
||||
jurisdiction?: string
|
||||
limit?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for legal templates.
|
||||
*
|
||||
* Tries own backend DB first (5 s timeout). Falls back to RAG proxy
|
||||
* (regulation texts — useful as reference, but not ready-made templates).
|
||||
* Returns an empty array if both services are down.
|
||||
*/
|
||||
export async function searchTemplates(
|
||||
params: TemplateSearchParams
|
||||
): Promise<LegalTemplateResult[]> {
|
||||
// 1. Primary: own backend — compliance_legal_templates table
|
||||
try {
|
||||
const url = new URL(TEMPLATES_API, window.location.origin)
|
||||
if (params.query) url.searchParams.set('query', params.query)
|
||||
if (params.templateType) url.searchParams.set('document_type', params.templateType)
|
||||
if (params.language) url.searchParams.set('language', params.language)
|
||||
url.searchParams.set('limit', String(params.limit || 20))
|
||||
url.searchParams.set('status', 'published')
|
||||
|
||||
const res = await fetch(url.toString(), { signal: AbortSignal.timeout(5000) })
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
return (data.templates || []).map(mapTemplateToResult)
|
||||
}
|
||||
} catch {
|
||||
// Backend not reachable — fall through to RAG
|
||||
}
|
||||
|
||||
// 2. Fallback: RAG proxy (Gesetzestexte — Referenz, kein fertiges Template)
|
||||
try {
|
||||
const res = await fetch(`${RAG_PROXY}/search`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ query: params.query || '', limit: params.limit || 10 }),
|
||||
})
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
return (data.results || []).map((r: any, i: number) => ({
|
||||
id: r.regulation_code || `rag-${i}`,
|
||||
score: r.score ?? 0.5,
|
||||
text: r.text || '',
|
||||
documentTitle: r.regulation_name || r.regulation_short || 'Dokument',
|
||||
templateType: 'regulation',
|
||||
clauseCategory: null,
|
||||
language: 'de',
|
||||
jurisdiction: 'eu',
|
||||
licenseId: null,
|
||||
licenseName: null,
|
||||
licenseUrl: null,
|
||||
attributionRequired: false,
|
||||
attributionText: null,
|
||||
sourceName: 'RAG',
|
||||
sourceUrl: null,
|
||||
sourceRepo: null,
|
||||
placeholders: [],
|
||||
isCompleteDocument: false,
|
||||
isModular: true,
|
||||
requiresCustomization: true,
|
||||
outputAllowed: true,
|
||||
modificationAllowed: true,
|
||||
distortionProhibited: false,
|
||||
source: 'rag' as const,
|
||||
}))
|
||||
}
|
||||
} catch {
|
||||
// both services failed
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
function mapTemplateToResult(r: any): LegalTemplateResult {
|
||||
return {
|
||||
id: r.id,
|
||||
score: 1.0,
|
||||
text: r.content || '',
|
||||
documentTitle: r.title,
|
||||
templateType: r.document_type,
|
||||
clauseCategory: null,
|
||||
language: r.language,
|
||||
jurisdiction: r.jurisdiction,
|
||||
licenseId: r.license_id as any,
|
||||
licenseName: r.license_name,
|
||||
licenseUrl: null,
|
||||
attributionRequired: r.attribution_required ?? false,
|
||||
attributionText: null,
|
||||
sourceName: r.source_name,
|
||||
sourceUrl: null,
|
||||
sourceRepo: null,
|
||||
placeholders: r.placeholders || [],
|
||||
isCompleteDocument: r.is_complete_document ?? true,
|
||||
isModular: false,
|
||||
requiresCustomization: (r.placeholders || []).length > 0,
|
||||
outputAllowed: true,
|
||||
modificationAllowed: true,
|
||||
distortionProhibited: false,
|
||||
source: 'db' as const,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all published templates without requiring a search query.
|
||||
* Used for the library-first UX (show all cards on initial load).
|
||||
*/
|
||||
export async function loadAllTemplates(limit = 200): Promise<LegalTemplateResult[]> {
|
||||
try {
|
||||
const url = new URL(TEMPLATES_API, window.location.origin)
|
||||
url.searchParams.set('limit', String(limit))
|
||||
url.searchParams.set('status', 'published')
|
||||
const res = await fetch(url.toString(), { signal: AbortSignal.timeout(5000) })
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
return (data.templates || []).map(mapTemplateToResult)
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
return []
|
||||
}
|
||||
|
||||
export async function getTemplatesStatus(): Promise<any> {
|
||||
try {
|
||||
const res = await fetch(`${TEMPLATES_API}/status`, { signal: AbortSignal.timeout(5000) })
|
||||
if (!res.ok) return null
|
||||
return res.json()
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSources(): Promise<any[]> {
|
||||
try {
|
||||
// Fetch status to get type counts for building source objects
|
||||
const res = await fetch(`${TEMPLATES_API}/status`, { signal: AbortSignal.timeout(5000) })
|
||||
if (!res.ok) return []
|
||||
const data = await res.json()
|
||||
const byType: Record<string, number> = data.by_type || {}
|
||||
const activeTypes = Object.keys(byType).filter(k => byType[k] > 0)
|
||||
return [
|
||||
{
|
||||
name: 'BreakPilot Compliance',
|
||||
enabled: true,
|
||||
license_type: 'mit' as const,
|
||||
description: `${data.total || 0} selbst erstellte Vorlagen (MIT-Lizenz) — DE & EN`,
|
||||
template_types: activeTypes,
|
||||
},
|
||||
]
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user