fix(admin-v2): Restore complete admin-v2 application

The admin-v2 application was incomplete in the repository. This commit
restores all missing components:

- Admin pages (76 pages): dashboard, ai, compliance, dsgvo, education,
  infrastructure, communication, development, onboarding, rbac
- SDK pages (45 pages): tom, dsfa, vvt, loeschfristen, einwilligungen,
  vendor-compliance, tom-generator, dsr, and more
- Developer portal (25 pages): API docs, SDK guides, frameworks
- All components, lib files, hooks, and types
- Updated package.json with all dependencies

The issue was caused by incomplete initial repository state - the full
admin-v2 codebase existed in backend/admin-v2 and docs-src/admin-v2
but was never fully synced to the main admin-v2 directory.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
BreakPilot Dev
2026-02-08 23:40:15 -08:00
parent f28244753f
commit 660295e218
385 changed files with 138126 additions and 3079 deletions

View File

@@ -0,0 +1,255 @@
/**
* API Route: Datenpunktkatalog
*
* GET - Katalog abrufen (inkl. kundenspezifischer Datenpunkte)
* POST - Katalog speichern/aktualisieren
*/
import { NextRequest, NextResponse } from 'next/server'
import {
DataPointCatalog,
CompanyInfo,
CookieBannerConfig,
DataPoint,
} from '@/lib/sdk/einwilligungen/types'
import { createDefaultCatalog, PREDEFINED_DATA_POINTS } from '@/lib/sdk/einwilligungen/catalog/loader'
// In-Memory Storage (in Produktion: Datenbank)
const catalogStorage = new Map<string, {
catalog: DataPointCatalog
companyInfo: CompanyInfo | null
cookieBannerConfig: CookieBannerConfig | null
}>()
/**
* GET /api/sdk/v1/einwilligungen/catalog
*
* Laedt den Datenpunktkatalog fuer einen Tenant
*/
export async function GET(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
// Hole gespeicherte Daten oder erstelle Default
let stored = catalogStorage.get(tenantId)
if (!stored) {
// Erstelle Default-Katalog
const defaultCatalog = createDefaultCatalog(tenantId)
stored = {
catalog: defaultCatalog,
companyInfo: null,
cookieBannerConfig: null,
}
catalogStorage.set(tenantId, stored)
}
return NextResponse.json({
catalog: stored.catalog,
companyInfo: stored.companyInfo,
cookieBannerConfig: stored.cookieBannerConfig,
})
} catch (error) {
console.error('Error loading catalog:', error)
return NextResponse.json(
{ error: 'Failed to load catalog' },
{ status: 500 }
)
}
}
/**
* POST /api/sdk/v1/einwilligungen/catalog
*
* Speichert den Datenpunktkatalog fuer einen Tenant
*/
export async function POST(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
const body = await request.json()
const { catalog, companyInfo, cookieBannerConfig } = body
if (!catalog) {
return NextResponse.json(
{ error: 'Catalog data required' },
{ status: 400 }
)
}
// Validiere den Katalog
if (!catalog.tenantId || catalog.tenantId !== tenantId) {
return NextResponse.json(
{ error: 'Tenant ID mismatch' },
{ status: 400 }
)
}
// Aktualisiere den Katalog
const updatedCatalog: DataPointCatalog = {
...catalog,
updatedAt: new Date(),
}
// Speichere
catalogStorage.set(tenantId, {
catalog: updatedCatalog,
companyInfo: companyInfo || null,
cookieBannerConfig: cookieBannerConfig || null,
})
return NextResponse.json({
success: true,
catalog: updatedCatalog,
})
} catch (error) {
console.error('Error saving catalog:', error)
return NextResponse.json(
{ error: 'Failed to save catalog' },
{ status: 500 }
)
}
}
/**
* POST /api/sdk/v1/einwilligungen/catalog/customize
*
* Fuegt einen kundenspezifischen Datenpunkt hinzu
*/
export async function PUT(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
const body = await request.json()
const { action, dataPoint, dataPointId } = body
let stored = catalogStorage.get(tenantId)
if (!stored) {
const defaultCatalog = createDefaultCatalog(tenantId)
stored = {
catalog: defaultCatalog,
companyInfo: null,
cookieBannerConfig: null,
}
}
switch (action) {
case 'add': {
if (!dataPoint) {
return NextResponse.json(
{ error: 'Data point required' },
{ status: 400 }
)
}
// Generiere eindeutige ID
const newDataPoint: DataPoint = {
...dataPoint,
id: `custom-${tenantId}-${Date.now()}`,
isCustom: true,
}
stored.catalog.customDataPoints.push(newDataPoint)
stored.catalog.updatedAt = new Date()
catalogStorage.set(tenantId, stored)
return NextResponse.json({
success: true,
dataPoint: newDataPoint,
})
}
case 'update': {
if (!dataPointId || !dataPoint) {
return NextResponse.json(
{ error: 'Data point ID and data required' },
{ status: 400 }
)
}
// Pruefe ob es ein kundenspezifischer Datenpunkt ist
const customIndex = stored.catalog.customDataPoints.findIndex(
(dp) => dp.id === dataPointId
)
if (customIndex !== -1) {
stored.catalog.customDataPoints[customIndex] = {
...stored.catalog.customDataPoints[customIndex],
...dataPoint,
}
} else {
// Vordefinierter Datenpunkt - nur isActive aendern
const predefinedIndex = stored.catalog.dataPoints.findIndex(
(dp) => dp.id === dataPointId
)
if (predefinedIndex !== -1 && 'isActive' in dataPoint) {
stored.catalog.dataPoints[predefinedIndex] = {
...stored.catalog.dataPoints[predefinedIndex],
isActive: dataPoint.isActive,
}
}
}
stored.catalog.updatedAt = new Date()
catalogStorage.set(tenantId, stored)
return NextResponse.json({
success: true,
})
}
case 'delete': {
if (!dataPointId) {
return NextResponse.json(
{ error: 'Data point ID required' },
{ status: 400 }
)
}
stored.catalog.customDataPoints = stored.catalog.customDataPoints.filter(
(dp) => dp.id !== dataPointId
)
stored.catalog.updatedAt = new Date()
catalogStorage.set(tenantId, stored)
return NextResponse.json({
success: true,
})
}
default:
return NextResponse.json(
{ error: 'Invalid action' },
{ status: 400 }
)
}
} catch (error) {
console.error('Error customizing catalog:', error)
return NextResponse.json(
{ error: 'Failed to customize catalog' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,369 @@
/**
* API Route: Consent Management
*
* POST - Consent erfassen
* GET - Consent-Status abrufen
*/
import { NextRequest, NextResponse } from 'next/server'
import {
ConsentEntry,
ConsentStatistics,
DataPointCategory,
LegalBasis,
} from '@/lib/sdk/einwilligungen/types'
import { PREDEFINED_DATA_POINTS } from '@/lib/sdk/einwilligungen/catalog/loader'
// In-Memory Storage fuer Consents
const consentStorage = new Map<string, ConsentEntry[]>() // tenantId -> consents
// Hilfsfunktion: Generiere eindeutige ID
function generateId(): string {
return `consent-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
}
/**
* POST /api/sdk/v1/einwilligungen/consent
*
* Erfasst eine neue Einwilligung
*
* Body:
* - userId: string - Benutzer-ID
* - dataPointId: string - ID des Datenpunkts
* - granted: boolean - Einwilligung erteilt?
* - consentVersion?: string - Version der Einwilligung
*/
export async function POST(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
const body = await request.json()
const { userId, dataPointId, granted, consentVersion = '1.0.0' } = body
if (!userId || !dataPointId || typeof granted !== 'boolean') {
return NextResponse.json(
{ error: 'userId, dataPointId, and granted required' },
{ status: 400 }
)
}
// Hole IP und User-Agent
const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || null
const userAgent = request.headers.get('user-agent') || null
// Erstelle Consent-Eintrag
const consent: ConsentEntry = {
id: generateId(),
userId,
dataPointId,
granted,
grantedAt: new Date(),
revokedAt: undefined,
ipAddress: ipAddress || undefined,
userAgent: userAgent || undefined,
consentVersion,
}
// Hole bestehende Consents
const tenantConsents = consentStorage.get(tenantId) || []
// Pruefe auf bestehende Einwilligung fuer diesen Datenpunkt
const existingIndex = tenantConsents.findIndex(
(c) => c.userId === userId && c.dataPointId === dataPointId && !c.revokedAt
)
if (existingIndex !== -1) {
if (!granted) {
// Widerruf: Setze revokedAt
tenantConsents[existingIndex].revokedAt = new Date()
}
// Bei granted=true: Keine Aenderung noetig, Consent existiert bereits
} else if (granted) {
// Neuer Consent
tenantConsents.push(consent)
}
consentStorage.set(tenantId, tenantConsents)
return NextResponse.json({
success: true,
consent: {
id: consent.id,
dataPointId: consent.dataPointId,
granted: consent.granted,
grantedAt: consent.grantedAt,
},
})
} catch (error) {
console.error('Error recording consent:', error)
return NextResponse.json(
{ error: 'Failed to record consent' },
{ status: 500 }
)
}
}
/**
* GET /api/sdk/v1/einwilligungen/consent
*
* Ruft Consent-Status und Statistiken ab
*
* Query Parameters:
* - userId?: string - Fuer spezifischen Benutzer
* - stats?: boolean - Statistiken inkludieren
*/
export async function GET(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
const { searchParams } = new URL(request.url)
const userId = searchParams.get('userId')
const includeStats = searchParams.get('stats') === 'true'
const tenantConsents = consentStorage.get(tenantId) || []
if (userId) {
// Spezifischer Benutzer
const userConsents = tenantConsents.filter((c) => c.userId === userId)
// Gruppiere nach Datenpunkt
const consentMap: Record<string, { granted: boolean; grantedAt: Date; revokedAt?: Date }> = {}
for (const consent of userConsents) {
consentMap[consent.dataPointId] = {
granted: consent.granted && !consent.revokedAt,
grantedAt: consent.grantedAt,
revokedAt: consent.revokedAt,
}
}
return NextResponse.json({
userId,
consents: consentMap,
totalConsents: Object.keys(consentMap).length,
activeConsents: Object.values(consentMap).filter((c) => c.granted).length,
})
}
// Statistiken fuer alle Consents
if (includeStats) {
const stats = calculateStatistics(tenantConsents)
return NextResponse.json({
statistics: stats,
recentConsents: tenantConsents
.sort((a, b) => new Date(b.grantedAt).getTime() - new Date(a.grantedAt).getTime())
.slice(0, 10)
.map((c) => ({
id: c.id,
userId: c.userId.substring(0, 8) + '...', // Anonymisiert
dataPointId: c.dataPointId,
granted: c.granted,
grantedAt: c.grantedAt,
})),
})
}
// Standard: Alle Consents (anonymisiert)
return NextResponse.json({
totalConsents: tenantConsents.length,
activeConsents: tenantConsents.filter((c) => c.granted && !c.revokedAt).length,
revokedConsents: tenantConsents.filter((c) => c.revokedAt).length,
})
} catch (error) {
console.error('Error fetching consents:', error)
return NextResponse.json(
{ error: 'Failed to fetch consents' },
{ status: 500 }
)
}
}
/**
* PUT /api/sdk/v1/einwilligungen/consent
*
* Batch-Update von Consents (z.B. Cookie-Banner)
*/
export async function PUT(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
const body = await request.json()
const { userId, consents, consentVersion = '1.0.0' } = body
if (!userId || !consents || typeof consents !== 'object') {
return NextResponse.json(
{ error: 'userId and consents object required' },
{ status: 400 }
)
}
const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || null
const userAgent = request.headers.get('user-agent') || null
const tenantConsents = consentStorage.get(tenantId) || []
const now = new Date()
// Verarbeite jeden Consent
for (const [dataPointId, granted] of Object.entries(consents)) {
if (typeof granted !== 'boolean') continue
const existingIndex = tenantConsents.findIndex(
(c) => c.userId === userId && c.dataPointId === dataPointId && !c.revokedAt
)
if (existingIndex !== -1) {
const existing = tenantConsents[existingIndex]
if (existing.granted !== granted) {
if (!granted) {
// Widerruf
tenantConsents[existingIndex].revokedAt = now
} else {
// Neuer Consent nach Widerruf
tenantConsents.push({
id: generateId(),
userId,
dataPointId,
granted: true,
grantedAt: now,
ipAddress: ipAddress || undefined,
userAgent: userAgent || undefined,
consentVersion,
})
}
}
} else if (granted) {
// Neuer Consent
tenantConsents.push({
id: generateId(),
userId,
dataPointId,
granted: true,
grantedAt: now,
ipAddress: ipAddress || undefined,
userAgent: userAgent || undefined,
consentVersion,
})
}
}
consentStorage.set(tenantId, tenantConsents)
// Zaehle aktive Consents fuer diesen User
const activeConsents = tenantConsents.filter(
(c) => c.userId === userId && c.granted && !c.revokedAt
).length
return NextResponse.json({
success: true,
userId,
activeConsents,
updatedAt: now,
})
} catch (error) {
console.error('Error updating consents:', error)
return NextResponse.json(
{ error: 'Failed to update consents' },
{ status: 500 }
)
}
}
/**
* Berechnet Consent-Statistiken
*/
function calculateStatistics(consents: ConsentEntry[]): ConsentStatistics {
const activeConsents = consents.filter((c) => c.granted && !c.revokedAt)
const revokedConsents = consents.filter((c) => c.revokedAt)
// Gruppiere nach Kategorie (18 Kategorien A-R)
const byCategory: Record<DataPointCategory, { total: number; active: number; revoked: number }> = {
MASTER_DATA: { total: 0, active: 0, revoked: 0 },
CONTACT_DATA: { total: 0, active: 0, revoked: 0 },
AUTHENTICATION: { total: 0, active: 0, revoked: 0 },
CONSENT: { total: 0, active: 0, revoked: 0 },
COMMUNICATION: { total: 0, active: 0, revoked: 0 },
PAYMENT: { total: 0, active: 0, revoked: 0 },
USAGE_DATA: { total: 0, active: 0, revoked: 0 },
LOCATION: { total: 0, active: 0, revoked: 0 },
DEVICE_DATA: { total: 0, active: 0, revoked: 0 },
MARKETING: { total: 0, active: 0, revoked: 0 },
ANALYTICS: { total: 0, active: 0, revoked: 0 },
SOCIAL_MEDIA: { total: 0, active: 0, revoked: 0 },
HEALTH_DATA: { total: 0, active: 0, revoked: 0 },
EMPLOYEE_DATA: { total: 0, active: 0, revoked: 0 },
CONTRACT_DATA: { total: 0, active: 0, revoked: 0 },
LOG_DATA: { total: 0, active: 0, revoked: 0 },
AI_DATA: { total: 0, active: 0, revoked: 0 },
SECURITY: { total: 0, active: 0, revoked: 0 },
}
for (const consent of consents) {
const dataPoint = PREDEFINED_DATA_POINTS.find((dp) => dp.id === consent.dataPointId)
if (dataPoint) {
byCategory[dataPoint.category].total++
if (consent.granted && !consent.revokedAt) {
byCategory[dataPoint.category].active++
}
if (consent.revokedAt) {
byCategory[dataPoint.category].revoked++
}
}
}
// Gruppiere nach Rechtsgrundlage (7 Rechtsgrundlagen)
const byLegalBasis: Record<LegalBasis, { total: number; active: number }> = {
CONTRACT: { total: 0, active: 0 },
CONSENT: { total: 0, active: 0 },
EXPLICIT_CONSENT: { total: 0, active: 0 },
LEGITIMATE_INTEREST: { total: 0, active: 0 },
LEGAL_OBLIGATION: { total: 0, active: 0 },
VITAL_INTERESTS: { total: 0, active: 0 },
PUBLIC_INTEREST: { total: 0, active: 0 },
}
for (const consent of consents) {
const dataPoint = PREDEFINED_DATA_POINTS.find((dp) => dp.id === consent.dataPointId)
if (dataPoint) {
byLegalBasis[dataPoint.legalBasis].total++
if (consent.granted && !consent.revokedAt) {
byLegalBasis[dataPoint.legalBasis].active++
}
}
}
// Berechne Conversion Rate (Unique Users mit mindestens einem Consent)
const uniqueUsers = new Set(consents.map((c) => c.userId))
const usersWithActiveConsent = new Set(activeConsents.map((c) => c.userId))
const conversionRate = uniqueUsers.size > 0
? (usersWithActiveConsent.size / uniqueUsers.size) * 100
: 0
return {
totalConsents: consents.length,
activeConsents: activeConsents.length,
revokedConsents: revokedConsents.length,
byCategory,
byLegalBasis,
conversionRate: Math.round(conversionRate * 10) / 10,
}
}

View File

@@ -0,0 +1,215 @@
/**
* API Route: Cookie Banner Configuration
*
* GET - Cookie Banner Konfiguration abrufen
* POST - Cookie Banner Konfiguration speichern
*/
import { NextRequest, NextResponse } from 'next/server'
import {
CookieBannerConfig,
CookieBannerStyling,
CookieBannerTexts,
DataPoint,
} from '@/lib/sdk/einwilligungen/types'
import {
generateCookieBannerConfig,
DEFAULT_COOKIE_BANNER_STYLING,
DEFAULT_COOKIE_BANNER_TEXTS,
} from '@/lib/sdk/einwilligungen/generator/cookie-banner'
import { PREDEFINED_DATA_POINTS } from '@/lib/sdk/einwilligungen/catalog/loader'
// In-Memory Storage fuer Cookie Banner Configs
const configStorage = new Map<string, CookieBannerConfig>()
/**
* GET /api/sdk/v1/einwilligungen/cookie-banner/config
*
* Laedt die Cookie Banner Konfiguration fuer einen Tenant
*/
export async function GET(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
let config = configStorage.get(tenantId)
if (!config) {
// Generiere Default-Konfiguration
config = generateCookieBannerConfig(tenantId, PREDEFINED_DATA_POINTS)
configStorage.set(tenantId, config)
}
return NextResponse.json(config)
} catch (error) {
console.error('Error loading cookie banner config:', error)
return NextResponse.json(
{ error: 'Failed to load cookie banner config' },
{ status: 500 }
)
}
}
/**
* POST /api/sdk/v1/einwilligungen/cookie-banner/config
*
* Speichert oder aktualisiert die Cookie Banner Konfiguration
*
* Body:
* - dataPointIds?: string[] - IDs der Datenpunkte (fuer Neuberechnung)
* - styling?: Partial<CookieBannerStyling> - Styling-Optionen
* - texts?: Partial<CookieBannerTexts> - Text-Optionen
* - customDataPoints?: DataPoint[] - Kundenspezifische Datenpunkte
*/
export async function POST(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
const body = await request.json()
const {
dataPointIds,
styling,
texts,
customDataPoints = [],
} = body
// Hole bestehende Konfiguration oder erstelle neue
let config = configStorage.get(tenantId)
if (dataPointIds && Array.isArray(dataPointIds)) {
// Neu berechnen basierend auf Datenpunkten
const allDataPoints: DataPoint[] = [
...PREDEFINED_DATA_POINTS,
...customDataPoints,
]
const selectedDataPoints = dataPointIds
.map((id: string) => allDataPoints.find((dp) => dp.id === id))
.filter((dp): dp is DataPoint => dp !== undefined)
config = generateCookieBannerConfig(
tenantId,
selectedDataPoints,
texts,
styling
)
} else if (config) {
// Nur Styling/Texts aktualisieren
if (styling) {
config.styling = {
...config.styling,
...styling,
}
}
if (texts) {
config.texts = {
...config.texts,
...texts,
}
}
config.updatedAt = new Date()
} else {
// Erstelle Default
config = generateCookieBannerConfig(
tenantId,
PREDEFINED_DATA_POINTS,
texts,
styling
)
}
configStorage.set(tenantId, config)
return NextResponse.json({
success: true,
config,
})
} catch (error) {
console.error('Error saving cookie banner config:', error)
return NextResponse.json(
{ error: 'Failed to save cookie banner config' },
{ status: 500 }
)
}
}
/**
* PUT /api/sdk/v1/einwilligungen/cookie-banner/config
*
* Aktualisiert einzelne Kategorien
*/
export async function PUT(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
const body = await request.json()
const { categoryId, enabled } = body
if (!categoryId || typeof enabled !== 'boolean') {
return NextResponse.json(
{ error: 'categoryId and enabled required' },
{ status: 400 }
)
}
let config = configStorage.get(tenantId)
if (!config) {
config = generateCookieBannerConfig(tenantId, PREDEFINED_DATA_POINTS)
}
// Finde und aktualisiere die Kategorie
const categoryIndex = config.categories.findIndex((c) => c.id === categoryId)
if (categoryIndex === -1) {
return NextResponse.json(
{ error: 'Category not found' },
{ status: 404 }
)
}
// Essenzielle Cookies koennen nicht deaktiviert werden
if (config.categories[categoryIndex].isRequired && !enabled) {
return NextResponse.json(
{ error: 'Essential cookies cannot be disabled' },
{ status: 400 }
)
}
config.categories[categoryIndex].defaultEnabled = enabled
config.updatedAt = new Date()
configStorage.set(tenantId, config)
return NextResponse.json({
success: true,
category: config.categories[categoryIndex],
})
} catch (error) {
console.error('Error updating cookie category:', error)
return NextResponse.json(
{ error: 'Failed to update cookie category' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,256 @@
/**
* API Route: Cookie Banner Embed Code
*
* GET - Generiert den Embed-Code fuer den Cookie Banner
*/
import { NextRequest, NextResponse } from 'next/server'
import { CookieBannerConfig, CookieBannerEmbedCode } from '@/lib/sdk/einwilligungen/types'
import {
generateCookieBannerConfig,
generateEmbedCode,
} from '@/lib/sdk/einwilligungen/generator/cookie-banner'
import { PREDEFINED_DATA_POINTS } from '@/lib/sdk/einwilligungen/catalog/loader'
// In-Memory Storage (in Produktion mit configStorage aus config/route.ts teilen)
const configStorage = new Map<string, CookieBannerConfig>()
/**
* GET /api/sdk/v1/einwilligungen/cookie-banner/embed-code
*
* Generiert den Embed-Code fuer den Cookie Banner
*
* Query Parameters:
* - privacyPolicyUrl: string - URL zur Datenschutzerklaerung (default: /datenschutz)
* - format: 'combined' | 'separate' - Ausgabeformat (default: combined)
*/
export async function GET(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
const { searchParams } = new URL(request.url)
const privacyPolicyUrl = searchParams.get('privacyPolicyUrl') || '/datenschutz'
const format = searchParams.get('format') || 'combined'
// Hole oder erstelle Konfiguration
let config = configStorage.get(tenantId)
if (!config) {
config = generateCookieBannerConfig(tenantId, PREDEFINED_DATA_POINTS)
configStorage.set(tenantId, config)
}
// Generiere Embed-Code
const embedCode = generateEmbedCode(config, privacyPolicyUrl)
if (format === 'separate') {
// Separate Dateien zurueckgeben
return NextResponse.json({
html: embedCode.html,
css: embedCode.css,
js: embedCode.js,
scriptTag: embedCode.scriptTag,
instructions: {
de: `
Fuegen Sie den folgenden Code in Ihre Website ein:
1. CSS in den <head>-Bereich:
<style>${embedCode.css}</style>
2. HTML vor dem schliessenden </body>-Tag:
${embedCode.html}
3. JavaScript vor dem schliessenden </body>-Tag:
<script>${embedCode.js}</script>
Alternativ koennen Sie die Dateien separat einbinden:
- /cookie-banner.css
- /cookie-banner.js
`,
en: `
Add the following code to your website:
1. CSS in the <head> section:
<style>${embedCode.css}</style>
2. HTML before the closing </body> tag:
${embedCode.html}
3. JavaScript before the closing </body> tag:
<script>${embedCode.js}</script>
Alternatively, you can include the files separately:
- /cookie-banner.css
- /cookie-banner.js
`,
},
})
}
// Combined: Alles in einem HTML-Block
const combinedCode = `
<!-- Cookie Banner - Start -->
<style>
${embedCode.css}
</style>
${embedCode.html}
<script>
${embedCode.js}
</script>
<!-- Cookie Banner - End -->
`.trim()
return NextResponse.json({
embedCode: combinedCode,
scriptTag: embedCode.scriptTag,
config: {
tenantId: config.tenantId,
categories: config.categories.map((c) => ({
id: c.id,
name: c.name,
isRequired: c.isRequired,
defaultEnabled: c.defaultEnabled,
})),
styling: config.styling,
},
instructions: {
de: `Fuegen Sie den folgenden Code vor dem schliessenden </body>-Tag Ihrer Website ein.`,
en: `Add the following code before the closing </body> tag of your website.`,
},
})
} catch (error) {
console.error('Error generating embed code:', error)
return NextResponse.json(
{ error: 'Failed to generate embed code' },
{ status: 500 }
)
}
}
/**
* POST /api/sdk/v1/einwilligungen/cookie-banner/embed-code
*
* Generiert Embed-Code mit benutzerdefinierten Optionen
*/
export async function POST(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
const body = await request.json()
const {
privacyPolicyUrl = '/datenschutz',
styling,
texts,
language = 'de',
} = body
// Hole oder erstelle Konfiguration
let config = configStorage.get(tenantId)
if (!config) {
config = generateCookieBannerConfig(tenantId, PREDEFINED_DATA_POINTS, texts, styling)
} else {
// Wende temporaere Anpassungen an
if (styling) {
config = {
...config,
styling: { ...config.styling, ...styling },
}
}
if (texts) {
config = {
...config,
texts: { ...config.texts, ...texts },
}
}
}
const embedCode = generateEmbedCode(config, privacyPolicyUrl)
// Generiere Preview HTML
const previewHtml = `
<!DOCTYPE html>
<html lang="${language}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Banner Preview</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f1f5f9;
min-height: 100vh;
margin: 0;
padding: 20px;
}
.preview-content {
max-width: 800px;
margin: 0 auto;
padding: 40px;
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
h1 { color: #1e293b; }
p { color: #64748b; line-height: 1.6; }
${embedCode.css}
</style>
</head>
<body>
<div class="preview-content">
<h1>Cookie Banner Preview</h1>
<p>Dies ist eine Vorschau des Cookie Banners. In der produktiven Umgebung wird der Banner auf Ihrer Website angezeigt.</p>
</div>
${embedCode.html}
<script>
${embedCode.js}
// Force show banner for preview
setTimeout(() => {
document.getElementById('cookieBanner')?.classList.add('active');
document.getElementById('cookieBannerOverlay')?.classList.add('active');
}, 100);
</script>
</body>
</html>
`.trim()
return NextResponse.json({
embedCode: {
html: embedCode.html,
css: embedCode.css,
js: embedCode.js,
scriptTag: embedCode.scriptTag,
},
previewHtml,
config: {
tenantId: config.tenantId,
categories: config.categories.length,
styling: config.styling,
},
})
} catch (error) {
console.error('Error generating custom embed code:', error)
return NextResponse.json(
{ error: 'Failed to generate embed code' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,186 @@
/**
* API Route: Privacy Policy Generator
*
* POST - Generiert eine Datenschutzerklaerung aus dem Datenpunktkatalog
*/
import { NextRequest, NextResponse } from 'next/server'
import {
CompanyInfo,
DataPoint,
SupportedLanguage,
ExportFormat,
GeneratedPrivacyPolicy,
} from '@/lib/sdk/einwilligungen/types'
import {
generatePrivacyPolicy,
generatePrivacyPolicySections,
} from '@/lib/sdk/einwilligungen/generator/privacy-policy'
import {
PREDEFINED_DATA_POINTS,
getDataPointById,
} from '@/lib/sdk/einwilligungen/catalog/loader'
// In-Memory Storage fuer generierte Policies
const policyStorage = new Map<string, GeneratedPrivacyPolicy>()
/**
* POST /api/sdk/v1/einwilligungen/privacy-policy/generate
*
* Generiert eine Datenschutzerklaerung
*
* Body:
* - dataPointIds: string[] - IDs der zu inkludierenden Datenpunkte
* - companyInfo: CompanyInfo - Firmeninformationen
* - language: 'de' | 'en' - Sprache
* - format: 'HTML' | 'MARKDOWN' | 'PDF' | 'DOCX' - Ausgabeformat
* - customDataPoints?: DataPoint[] - Kundenspezifische Datenpunkte
*/
export async function POST(request: NextRequest) {
try {
const tenantId = request.headers.get('X-Tenant-ID')
if (!tenantId) {
return NextResponse.json(
{ error: 'Tenant ID required' },
{ status: 400 }
)
}
const body = await request.json()
const {
dataPointIds,
companyInfo,
language = 'de',
format = 'HTML',
customDataPoints = [],
} = body
// Validierung
if (!companyInfo || !companyInfo.name || !companyInfo.address || !companyInfo.email) {
return NextResponse.json(
{ error: 'Company info (name, address, email) required' },
{ status: 400 }
)
}
if (!dataPointIds || !Array.isArray(dataPointIds) || dataPointIds.length === 0) {
return NextResponse.json(
{ error: 'At least one data point ID required' },
{ status: 400 }
)
}
// Validiere Sprache
const validLanguages: SupportedLanguage[] = ['de', 'en']
if (!validLanguages.includes(language)) {
return NextResponse.json(
{ error: 'Invalid language. Must be "de" or "en"' },
{ status: 400 }
)
}
// Validiere Format
const validFormats: ExportFormat[] = ['HTML', 'MARKDOWN', 'PDF', 'DOCX']
if (!validFormats.includes(format)) {
return NextResponse.json(
{ error: 'Invalid format. Must be HTML, MARKDOWN, PDF, or DOCX' },
{ status: 400 }
)
}
// Sammle alle Datenpunkte
const allDataPoints: DataPoint[] = [
...PREDEFINED_DATA_POINTS,
...customDataPoints,
]
// Filtere nach ausgewaehlten IDs
const selectedDataPoints = dataPointIds
.map((id: string) => allDataPoints.find((dp) => dp.id === id))
.filter((dp): dp is DataPoint => dp !== undefined)
if (selectedDataPoints.length === 0) {
return NextResponse.json(
{ error: 'No valid data points found for the provided IDs' },
{ status: 400 }
)
}
// Generiere die Privacy Policy
const policy = generatePrivacyPolicy(
tenantId,
selectedDataPoints,
companyInfo as CompanyInfo,
language as SupportedLanguage,
format as ExportFormat
)
// Speichere fuer spaeteres Abrufen
policyStorage.set(policy.id, policy)
// Fuer PDF/DOCX: Nur Metadaten zurueckgeben, Download separat
if (format === 'PDF' || format === 'DOCX') {
return NextResponse.json({
id: policy.id,
tenantId: policy.tenantId,
language: policy.language,
format: policy.format,
generatedAt: policy.generatedAt,
version: policy.version,
sections: policy.sections.map((s) => ({
id: s.id,
title: s.title,
order: s.order,
})),
downloadUrl: `/api/sdk/v1/einwilligungen/privacy-policy/${policy.id}/download`,
})
}
// Fuer HTML/Markdown: Vollstaendige Policy zurueckgeben
return NextResponse.json(policy)
} catch (error) {
console.error('Error generating privacy policy:', error)
return NextResponse.json(
{ error: 'Failed to generate privacy policy' },
{ status: 500 }
)
}
}
/**
* GET /api/sdk/v1/einwilligungen/privacy-policy/generate
*
* Liefert eine Vorschau der Abschnitte ohne vollstaendige Generierung
*/
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const language = (searchParams.get('language') as SupportedLanguage) || 'de'
// Liefere die Standard-Abschnittsstruktur
const sections = [
{ id: 'controller', order: 1, title: { de: '1. Verantwortlicher', en: '1. Data Controller' } },
{ id: 'data-collection', order: 2, title: { de: '2. Erhobene personenbezogene Daten', en: '2. Personal Data We Collect' } },
{ id: 'purposes', order: 3, title: { de: '3. Zwecke der Datenverarbeitung', en: '3. Purposes of Data Processing' } },
{ id: 'legal-basis', order: 4, title: { de: '4. Rechtsgrundlagen der Verarbeitung', en: '4. Legal Basis for Processing' } },
{ id: 'recipients', order: 5, title: { de: '5. Empfaenger und Datenweitergabe', en: '5. Recipients and Data Sharing' } },
{ id: 'retention', order: 6, title: { de: '6. Speicherdauer', en: '6. Data Retention' } },
{ id: 'rights', order: 7, title: { de: '7. Ihre Rechte als betroffene Person', en: '7. Your Rights as a Data Subject' } },
{ id: 'cookies', order: 8, title: { de: '8. Cookies und aehnliche Technologien', en: '8. Cookies and Similar Technologies' } },
{ id: 'changes', order: 9, title: { de: '9. Aenderungen dieser Datenschutzerklaerung', en: '9. Changes to this Privacy Policy' } },
]
return NextResponse.json({
sections,
availableLanguages: ['de', 'en'],
availableFormats: ['HTML', 'MARKDOWN', 'PDF', 'DOCX'],
})
} catch (error) {
console.error('Error fetching sections:', error)
return NextResponse.json(
{ error: 'Failed to fetch sections' },
{ status: 500 }
)
}
}