feat(sdk): Audit-Dashboard + RBAC-Admin Frontends, UCCA/Go Cleanup
Some checks failed
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) Failing after 33s
CI / test-python-backend-compliance (push) Successful in 32s
CI / test-python-document-crawler (push) Successful in 18s
CI / test-python-dsms-gateway (push) Successful in 16s

- Remove 5 unused UCCA routes (wizard, stats, dsb-pool) from Go main.go
- Delete 64 deprecated Go handlers (DSGVO, Vendors, Incidents, Drafting)
- Delete legacy proxy routes (dsgvo, vendors)
- Add LLM Audit Dashboard (3 tabs: Log, Nutzung, Compliance) with export
- Add RBAC Admin UI (5 tabs: Mandanten, Namespaces, Rollen, Benutzer, LLM-Policies)
- Add proxy routes for audit-llm and rbac to Go backend
- Add Workshop, Portfolio, Roadmap proxy routes and frontends
- Add LLM Audit + RBAC Admin to SDKSidebar

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Benjamin Admin
2026-03-07 09:45:56 +01:00
parent 3467bce222
commit 37166c966f
23 changed files with 4323 additions and 6295 deletions

View File

@@ -0,0 +1,108 @@
/**
* LLM Audit API Proxy - Catch-all route
* Proxies all /api/sdk/v1/audit-llm/* requests to ai-compliance-sdk /sdk/v1/audit/*
*/
import { NextRequest, NextResponse } from 'next/server'
const SDK_BACKEND_URL = process.env.SDK_API_URL || 'http://ai-compliance-sdk:8090'
async function proxyRequest(
request: NextRequest,
pathSegments: string[] | undefined,
method: string
) {
const pathStr = pathSegments?.join('/') || ''
const searchParams = request.nextUrl.searchParams.toString()
const basePath = `${SDK_BACKEND_URL}/sdk/v1/audit`
const url = pathStr
? `${basePath}/${pathStr}${searchParams ? `?${searchParams}` : ''}`
: `${basePath}${searchParams ? `?${searchParams}` : ''}`
try {
const headers: HeadersInit = {
'Content-Type': 'application/json',
}
const headerNames = ['authorization', 'x-namespace-id', 'x-tenant-slug']
for (const name of headerNames) {
const value = request.headers.get(name)
if (value) {
headers[name] = value
}
}
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const clientUserId = request.headers.get('x-user-id')
const clientTenantId = request.headers.get('x-tenant-id')
headers['X-User-ID'] = (clientUserId && uuidRegex.test(clientUserId)) ? clientUserId : '00000000-0000-0000-0000-000000000001'
headers['X-Tenant-ID'] = (clientTenantId && uuidRegex.test(clientTenantId)) ? clientTenantId : (process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e')
const fetchOptions: RequestInit = {
method,
headers,
signal: AbortSignal.timeout(60000),
}
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
const body = await request.text()
if (body) {
fetchOptions.body = body
}
}
const response = await fetch(url, fetchOptions)
// Handle export endpoints that may return CSV
const contentType = response.headers.get('content-type') || ''
if (contentType.includes('text/csv') || contentType.includes('application/octet-stream')) {
const blob = await response.arrayBuffer()
return new NextResponse(blob, {
status: response.status,
headers: {
'Content-Type': contentType,
'Content-Disposition': response.headers.get('content-disposition') || 'attachment',
},
})
}
if (!response.ok) {
const errorText = await response.text()
let errorJson
try {
errorJson = JSON.parse(errorText)
} catch {
errorJson = { error: errorText }
}
return NextResponse.json(
{ error: `Backend Error: ${response.status}`, ...errorJson },
{ status: response.status }
)
}
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
console.error('LLM Audit API proxy error:', error)
return NextResponse.json(
{ error: 'Verbindung zum SDK Backend fehlgeschlagen' },
{ status: 503 }
)
}
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'GET')
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'POST')
}

View File

@@ -1,6 +1,6 @@
/**
* DSGVO API Proxy - Catch-all route
* Proxies all /api/sdk/v1/dsgvo/* requests to ai-compliance-sdk backend
* Portfolio API Proxy - Catch-all route
* Proxies all /api/sdk/v1/portfolio/* requests to ai-compliance-sdk backend
*/
import { NextRequest, NextResponse } from 'next/server'
@@ -9,61 +9,50 @@ const SDK_BACKEND_URL = process.env.SDK_API_URL || 'http://ai-compliance-sdk:809
async function proxyRequest(
request: NextRequest,
pathSegments: string[],
pathSegments: string[] | undefined,
method: string
) {
const pathStr = pathSegments.join('/')
const pathStr = pathSegments?.join('/') || ''
const searchParams = request.nextUrl.searchParams.toString()
const url = `${SDK_BACKEND_URL}/sdk/v1/dsgvo/${pathStr}${searchParams ? `?${searchParams}` : ''}`
const basePath = `${SDK_BACKEND_URL}/sdk/v1/portfolios`
const url = pathStr
? `${basePath}/${pathStr}${searchParams ? `?${searchParams}` : ''}`
: `${basePath}${searchParams ? `?${searchParams}` : ''}`
try {
const headers: HeadersInit = {
'Content-Type': 'application/json',
}
// Forward auth headers if present
const authHeader = request.headers.get('authorization')
if (authHeader) {
headers['Authorization'] = authHeader
const headerNames = ['authorization', 'x-namespace-id', 'x-tenant-slug']
for (const name of headerNames) {
const value = request.headers.get(name)
if (value) {
headers[name] = value
}
}
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const clientUserId = request.headers.get('x-user-id')
const clientTenantId = request.headers.get('x-tenant-id')
headers['X-User-ID'] = (clientUserId && uuidRegex.test(clientUserId)) ? clientUserId : '00000000-0000-0000-0000-000000000001'
headers['X-Tenant-ID'] = (clientTenantId && uuidRegex.test(clientTenantId)) ? clientTenantId : (process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e')
const fetchOptions: RequestInit = {
method,
headers,
signal: AbortSignal.timeout(30000),
signal: AbortSignal.timeout(60000),
}
// Add body for POST/PUT/PATCH methods
if (['POST', 'PUT', 'PATCH'].includes(method)) {
const contentType = request.headers.get('content-type')
if (contentType?.includes('application/json')) {
try {
const text = await request.text()
if (text && text.trim()) {
fetchOptions.body = text
}
} catch {
// Empty or invalid body - continue without
}
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
const body = await request.text()
if (body) {
fetchOptions.body = body
}
}
const response = await fetch(url, fetchOptions)
// Handle non-JSON responses (e.g., PDF export)
const responseContentType = response.headers.get('content-type')
if (responseContentType?.includes('application/pdf') ||
responseContentType?.includes('application/octet-stream')) {
const blob = await response.blob()
return new NextResponse(blob, {
status: response.status,
headers: {
'Content-Type': responseContentType,
'Content-Disposition': response.headers.get('content-disposition') || '',
},
})
}
if (!response.ok) {
const errorText = await response.text()
let errorJson
@@ -81,7 +70,7 @@ async function proxyRequest(
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
console.error('DSGVO API proxy error:', error)
console.error('Portfolio API proxy error:', error)
return NextResponse.json(
{ error: 'Verbindung zum SDK Backend fehlgeschlagen' },
{ status: 503 }
@@ -91,7 +80,7 @@ async function proxyRequest(
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'GET')
@@ -99,7 +88,7 @@ export async function GET(
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'POST')
@@ -107,7 +96,7 @@ export async function POST(
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'PUT')
@@ -115,7 +104,7 @@ export async function PUT(
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'PATCH')
@@ -123,7 +112,7 @@ export async function PATCH(
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'DELETE')

View File

@@ -0,0 +1,125 @@
/**
* RBAC Admin API Proxy - Catch-all route
* Proxies /api/sdk/v1/rbac/<resource>/... to ai-compliance-sdk /sdk/v1/<resource>/...
*
* Mapping: /rbac/tenants/... → /sdk/v1/tenants/...
* /rbac/namespaces/... → /sdk/v1/namespaces/...
* /rbac/roles/... → /sdk/v1/roles/...
* /rbac/user-roles/... → /sdk/v1/user-roles/...
* /rbac/permissions/... → /sdk/v1/permissions/...
* /rbac/llm/policies/... → /sdk/v1/llm/policies/...
*/
import { NextRequest, NextResponse } from 'next/server'
const SDK_BACKEND_URL = process.env.SDK_API_URL || 'http://ai-compliance-sdk:8090'
async function proxyRequest(
request: NextRequest,
pathSegments: string[] | undefined,
method: string
) {
// Path segments come as the full sub-path after /rbac/
// e.g. /rbac/tenants/123 → pathSegments = ['tenants', '123']
const pathStr = pathSegments?.join('/') || ''
const searchParams = request.nextUrl.searchParams.toString()
const url = `${SDK_BACKEND_URL}/sdk/v1/${pathStr}${searchParams ? `?${searchParams}` : ''}`
try {
const headers: HeadersInit = {
'Content-Type': 'application/json',
}
const headerNames = ['authorization', 'x-namespace-id', 'x-tenant-slug']
for (const name of headerNames) {
const value = request.headers.get(name)
if (value) {
headers[name] = value
}
}
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const clientUserId = request.headers.get('x-user-id')
const clientTenantId = request.headers.get('x-tenant-id')
headers['X-User-ID'] = (clientUserId && uuidRegex.test(clientUserId)) ? clientUserId : '00000000-0000-0000-0000-000000000001'
headers['X-Tenant-ID'] = (clientTenantId && uuidRegex.test(clientTenantId)) ? clientTenantId : (process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e')
const fetchOptions: RequestInit = {
method,
headers,
signal: AbortSignal.timeout(60000),
}
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
const body = await request.text()
if (body) {
fetchOptions.body = body
}
}
const response = await fetch(url, fetchOptions)
if (!response.ok) {
const errorText = await response.text()
let errorJson
try {
errorJson = JSON.parse(errorText)
} catch {
errorJson = { error: errorText }
}
return NextResponse.json(
{ error: `Backend Error: ${response.status}`, ...errorJson },
{ status: response.status }
)
}
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
console.error('RBAC API proxy error:', error)
return NextResponse.json(
{ error: 'Verbindung zum SDK Backend fehlgeschlagen' },
{ status: 503 }
)
}
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'GET')
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'POST')
}
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'PUT')
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'PATCH')
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'DELETE')
}

View File

@@ -0,0 +1,111 @@
/**
* Roadmap Items API Proxy - Catch-all route
* Proxies /api/sdk/v1/roadmap-items/* to ai-compliance-sdk /sdk/v1/roadmap-items/*
*/
import { NextRequest, NextResponse } from 'next/server'
const SDK_BACKEND_URL = process.env.SDK_API_URL || 'http://ai-compliance-sdk:8090'
async function proxyRequest(
request: NextRequest,
pathSegments: string[] | undefined,
method: string
) {
const pathStr = pathSegments?.join('/') || ''
const searchParams = request.nextUrl.searchParams.toString()
const basePath = `${SDK_BACKEND_URL}/sdk/v1/roadmap-items`
const url = pathStr
? `${basePath}/${pathStr}${searchParams ? `?${searchParams}` : ''}`
: `${basePath}${searchParams ? `?${searchParams}` : ''}`
try {
const headers: HeadersInit = {
'Content-Type': 'application/json',
}
const headerNames = ['authorization', 'x-namespace-id', 'x-tenant-slug']
for (const name of headerNames) {
const value = request.headers.get(name)
if (value) {
headers[name] = value
}
}
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const clientUserId = request.headers.get('x-user-id')
const clientTenantId = request.headers.get('x-tenant-id')
headers['X-User-ID'] = (clientUserId && uuidRegex.test(clientUserId)) ? clientUserId : '00000000-0000-0000-0000-000000000001'
headers['X-Tenant-ID'] = (clientTenantId && uuidRegex.test(clientTenantId)) ? clientTenantId : (process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e')
const fetchOptions: RequestInit = {
method,
headers,
signal: AbortSignal.timeout(60000),
}
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
const body = await request.text()
if (body) {
fetchOptions.body = body
}
}
const response = await fetch(url, fetchOptions)
if (!response.ok) {
const errorText = await response.text()
let errorJson
try {
errorJson = JSON.parse(errorText)
} catch {
errorJson = { error: errorText }
}
return NextResponse.json(
{ error: `Backend Error: ${response.status}`, ...errorJson },
{ status: response.status }
)
}
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
console.error('Roadmap Items API proxy error:', error)
return NextResponse.json(
{ error: 'Verbindung zum SDK Backend fehlgeschlagen' },
{ status: 503 }
)
}
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'GET')
}
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'PUT')
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'PATCH')
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'DELETE')
}

View File

@@ -1,6 +1,6 @@
/**
* Vendor Compliance API Proxy - Catch-all route
* Proxies all /api/sdk/v1/vendors/* requests to ai-compliance-sdk backend
* Roadmap API Proxy - Catch-all route
* Proxies all /api/sdk/v1/roadmap/* requests to ai-compliance-sdk backend
*/
import { NextRequest, NextResponse } from 'next/server'
@@ -14,7 +14,7 @@ async function proxyRequest(
) {
const pathStr = pathSegments?.join('/') || ''
const searchParams = request.nextUrl.searchParams.toString()
const basePath = `${SDK_BACKEND_URL}/sdk/v1/vendors`
const basePath = `${SDK_BACKEND_URL}/sdk/v1/roadmaps`
const url = pathStr
? `${basePath}/${pathStr}${searchParams ? `?${searchParams}` : ''}`
: `${basePath}${searchParams ? `?${searchParams}` : ''}`
@@ -24,8 +24,7 @@ async function proxyRequest(
'Content-Type': 'application/json',
}
// Forward all relevant headers
const headerNames = ['authorization', 'x-tenant-id', 'x-user-id', 'x-namespace-id', 'x-tenant-slug']
const headerNames = ['authorization', 'x-namespace-id', 'x-tenant-slug']
for (const name of headerNames) {
const value = request.headers.get(name)
if (value) {
@@ -33,42 +32,27 @@ async function proxyRequest(
}
}
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const clientUserId = request.headers.get('x-user-id')
const clientTenantId = request.headers.get('x-tenant-id')
headers['X-User-ID'] = (clientUserId && uuidRegex.test(clientUserId)) ? clientUserId : '00000000-0000-0000-0000-000000000001'
headers['X-Tenant-ID'] = (clientTenantId && uuidRegex.test(clientTenantId)) ? clientTenantId : (process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e')
const fetchOptions: RequestInit = {
method,
headers,
signal: AbortSignal.timeout(30000),
signal: AbortSignal.timeout(60000),
}
if (['POST', 'PUT', 'PATCH'].includes(method)) {
const contentType = request.headers.get('content-type')
if (contentType?.includes('application/json')) {
try {
const text = await request.text()
if (text && text.trim()) {
fetchOptions.body = text
}
} catch {
// Empty or invalid body - continue without
}
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
const body = await request.text()
if (body) {
fetchOptions.body = body
}
}
const response = await fetch(url, fetchOptions)
// Handle non-JSON responses (e.g., PDF exports)
const responseContentType = response.headers.get('content-type')
if (responseContentType?.includes('application/pdf') ||
responseContentType?.includes('application/octet-stream')) {
const blob = await response.blob()
return new NextResponse(blob, {
status: response.status,
headers: {
'Content-Type': responseContentType,
'Content-Disposition': response.headers.get('content-disposition') || '',
},
})
}
if (!response.ok) {
const errorText = await response.text()
let errorJson
@@ -83,10 +67,22 @@ async function proxyRequest(
)
}
const contentType = response.headers.get('content-type') || ''
if (contentType.includes('application/octet-stream') || contentType.includes('text/csv')) {
const blob = await response.blob()
return new NextResponse(blob, {
status: response.status,
headers: {
'Content-Type': contentType,
'Content-Disposition': response.headers.get('content-disposition') || '',
},
})
}
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
console.error('Vendor Compliance API proxy error:', error)
console.error('Roadmap API proxy error:', error)
return NextResponse.json(
{ error: 'Verbindung zum SDK Backend fehlgeschlagen' },
{ status: 503 }

View File

@@ -0,0 +1,119 @@
/**
* Workshop API Proxy - Catch-all route
* Proxies all /api/sdk/v1/workshops/* requests to ai-compliance-sdk backend
*/
import { NextRequest, NextResponse } from 'next/server'
const SDK_BACKEND_URL = process.env.SDK_API_URL || 'http://ai-compliance-sdk:8090'
async function proxyRequest(
request: NextRequest,
pathSegments: string[] | undefined,
method: string
) {
const pathStr = pathSegments?.join('/') || ''
const searchParams = request.nextUrl.searchParams.toString()
const basePath = `${SDK_BACKEND_URL}/sdk/v1/workshops`
const url = pathStr
? `${basePath}/${pathStr}${searchParams ? `?${searchParams}` : ''}`
: `${basePath}${searchParams ? `?${searchParams}` : ''}`
try {
const headers: HeadersInit = {
'Content-Type': 'application/json',
}
const headerNames = ['authorization', 'x-namespace-id', 'x-tenant-slug']
for (const name of headerNames) {
const value = request.headers.get(name)
if (value) {
headers[name] = value
}
}
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const clientUserId = request.headers.get('x-user-id')
const clientTenantId = request.headers.get('x-tenant-id')
headers['X-User-ID'] = (clientUserId && uuidRegex.test(clientUserId)) ? clientUserId : '00000000-0000-0000-0000-000000000001'
headers['X-Tenant-ID'] = (clientTenantId && uuidRegex.test(clientTenantId)) ? clientTenantId : (process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e')
const fetchOptions: RequestInit = {
method,
headers,
signal: AbortSignal.timeout(60000),
}
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
const body = await request.text()
if (body) {
fetchOptions.body = body
}
}
const response = await fetch(url, fetchOptions)
if (!response.ok) {
const errorText = await response.text()
let errorJson
try {
errorJson = JSON.parse(errorText)
} catch {
errorJson = { error: errorText }
}
return NextResponse.json(
{ error: `Backend Error: ${response.status}`, ...errorJson },
{ status: response.status }
)
}
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
console.error('Workshop API proxy error:', error)
return NextResponse.json(
{ error: 'Verbindung zum SDK Backend fehlgeschlagen' },
{ status: 503 }
)
}
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'GET')
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'POST')
}
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'PUT')
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'PATCH')
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const { path } = await params
return proxyRequest(request, path, 'DELETE')
}

View File

@@ -0,0 +1,561 @@
'use client'
import React, { useState, useEffect, useCallback } from 'react'
import { useSDK } from '@/lib/sdk'
// =============================================================================
// TYPES
// =============================================================================
interface LLMLogEntry {
id: string
user_id: string
namespace: string
model: string
provider: string
prompt_tokens: number
completion_tokens: number
total_tokens: number
pii_detected: boolean
pii_categories: string[]
redacted: boolean
duration_ms: number
status: string
created_at: string
}
interface UsageStats {
total_requests: number
total_tokens: number
total_prompt_tokens: number
total_completion_tokens: number
models_used: Record<string, number>
providers_used: Record<string, number>
avg_duration_ms: number
pii_detection_rate: number
period_start: string
period_end: string
}
interface ComplianceReport {
total_requests: number
pii_incidents: number
pii_rate: number
redaction_rate: number
policy_violations: number
top_pii_categories: Record<string, number>
namespace_breakdown: Record<string, { requests: number; pii_incidents: number }>
user_breakdown: Record<string, { requests: number; pii_incidents: number }>
period_start: string
period_end: string
}
type TabId = 'llm-log' | 'usage' | 'compliance'
// =============================================================================
// HELPERS
// =============================================================================
const API_BASE = '/api/sdk/v1/audit-llm'
function formatDate(iso: string): string {
return new Date(iso).toLocaleString('de-DE', {
day: '2-digit', month: '2-digit', year: 'numeric',
hour: '2-digit', minute: '2-digit',
})
}
function formatNumber(n: number): string {
return n.toLocaleString('de-DE')
}
function formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`
return `${(ms / 1000).toFixed(1)}s`
}
function getDateRange(period: string): { from: string; to: string } {
const now = new Date()
const to = now.toISOString().slice(0, 10)
const from = new Date(now)
switch (period) {
case '7d': from.setDate(from.getDate() - 7); break
case '30d': from.setDate(from.getDate() - 30); break
case '90d': from.setDate(from.getDate() - 90); break
default: from.setDate(from.getDate() - 7)
}
return { from: from.toISOString().slice(0, 10), to }
}
// =============================================================================
// MAIN PAGE
// =============================================================================
export default function AuditLLMPage() {
const { state } = useSDK()
const [activeTab, setActiveTab] = useState<TabId>('llm-log')
const [period, setPeriod] = useState('7d')
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
// LLM Log state
const [logEntries, setLogEntries] = useState<LLMLogEntry[]>([])
const [logFilter, setLogFilter] = useState({ model: '', pii: '' })
// Usage state
const [usageStats, setUsageStats] = useState<UsageStats | null>(null)
// Compliance state
const [complianceReport, setComplianceReport] = useState<ComplianceReport | null>(null)
// ─── Load Data ───────────────────────────────────────────────────────
const loadLLMLog = useCallback(async () => {
setLoading(true)
setError(null)
try {
const { from, to } = getDateRange(period)
const params = new URLSearchParams({ from, to, limit: '100' })
if (logFilter.model) params.set('model', logFilter.model)
if (logFilter.pii === 'true') params.set('pii_detected', 'true')
if (logFilter.pii === 'false') params.set('pii_detected', 'false')
const res = await fetch(`${API_BASE}/llm?${params}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
setLogEntries(Array.isArray(data) ? data : data.entries || data.logs || [])
} catch (e) {
setError(e instanceof Error ? e.message : 'Fehler beim Laden')
} finally {
setLoading(false)
}
}, [period, logFilter])
const loadUsage = useCallback(async () => {
setLoading(true)
setError(null)
try {
const { from, to } = getDateRange(period)
const res = await fetch(`${API_BASE}/usage?from=${from}&to=${to}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
setUsageStats(data)
} catch (e) {
setError(e instanceof Error ? e.message : 'Fehler beim Laden')
} finally {
setLoading(false)
}
}, [period])
const loadCompliance = useCallback(async () => {
setLoading(true)
setError(null)
try {
const { from, to } = getDateRange(period)
const res = await fetch(`${API_BASE}/compliance-report?from=${from}&to=${to}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
setComplianceReport(data)
} catch (e) {
setError(e instanceof Error ? e.message : 'Fehler beim Laden')
} finally {
setLoading(false)
}
}, [period])
useEffect(() => {
if (activeTab === 'llm-log') loadLLMLog()
else if (activeTab === 'usage') loadUsage()
else if (activeTab === 'compliance') loadCompliance()
}, [activeTab, loadLLMLog, loadUsage, loadCompliance])
// ─── Export ──────────────────────────────────────────────────────────
const handleExport = async (type: 'llm' | 'general' | 'compliance', format: 'json' | 'csv') => {
try {
const { from, to } = getDateRange(period)
const res = await fetch(`${API_BASE}/export/${type}?from=${from}&to=${to}&format=${format}`)
if (!res.ok) throw new Error(`Export fehlgeschlagen: ${res.status}`)
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `audit-${type}-${from}-${to}.${format}`
a.click()
URL.revokeObjectURL(url)
} catch (e) {
setError(e instanceof Error ? e.message : 'Export fehlgeschlagen')
}
}
// ─── Tabs ────────────────────────────────────────────────────────────
const tabs: { id: TabId; label: string }[] = [
{ id: 'llm-log', label: 'LLM-Log' },
{ id: 'usage', label: 'Nutzung' },
{ id: 'compliance', label: 'Compliance' },
]
return (
<div className="p-6 max-w-7xl mx-auto">
{/* Header */}
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900">LLM Audit Dashboard</h1>
<p className="text-gray-500 mt-1">Monitoring und Compliance-Analyse der LLM-Operationen</p>
</div>
{/* Period + Tabs */}
<div className="flex items-center justify-between mb-6">
<div className="flex gap-1 bg-gray-100 rounded-lg p-1">
{tabs.map(tab => (
<button
key={tab.id}
onClick={() => setActiveTab(tab.id)}
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
activeTab === tab.id
? 'bg-white text-purple-700 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
{tab.label}
</button>
))}
</div>
<div className="flex items-center gap-3">
<select
value={period}
onChange={e => setPeriod(e.target.value)}
className="border border-gray-300 rounded-lg px-3 py-2 text-sm"
>
<option value="7d">Letzte 7 Tage</option>
<option value="30d">Letzte 30 Tage</option>
<option value="90d">Letzte 90 Tage</option>
</select>
<button
onClick={() => {
if (activeTab === 'llm-log') handleExport('llm', 'csv')
else if (activeTab === 'compliance') handleExport('compliance', 'json')
else handleExport('general', 'csv')
}}
className="px-4 py-2 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
>
Export
</button>
</div>
</div>
{error && (
<div className="mb-4 p-3 bg-red-50 text-red-700 rounded-lg text-sm">{error}</div>
)}
{loading && (
<div className="flex items-center justify-center py-12">
<div className="w-8 h-8 border-4 border-purple-200 border-t-purple-600 rounded-full animate-spin" />
</div>
)}
{/* ── LLM-Log Tab ── */}
{!loading && activeTab === 'llm-log' && (
<div>
{/* Filters */}
<div className="flex gap-3 mb-4">
<input
type="text"
placeholder="Model filtern..."
value={logFilter.model}
onChange={e => setLogFilter(f => ({ ...f, model: e.target.value }))}
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-48"
/>
<select
value={logFilter.pii}
onChange={e => setLogFilter(f => ({ ...f, pii: e.target.value }))}
className="border border-gray-300 rounded-lg px-3 py-2 text-sm"
>
<option value="">Alle PII-Status</option>
<option value="true">PII erkannt</option>
<option value="false">Kein PII</option>
</select>
</div>
{/* Table */}
<div className="overflow-x-auto bg-white rounded-xl border border-gray-200">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-gray-200 bg-gray-50">
<th className="text-left px-4 py-3 font-medium text-gray-600">Zeitpunkt</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">User</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Model</th>
<th className="text-right px-4 py-3 font-medium text-gray-600">Tokens</th>
<th className="text-center px-4 py-3 font-medium text-gray-600">PII</th>
<th className="text-right px-4 py-3 font-medium text-gray-600">Dauer</th>
<th className="text-center px-4 py-3 font-medium text-gray-600">Status</th>
</tr>
</thead>
<tbody>
{logEntries.length === 0 ? (
<tr>
<td colSpan={7} className="text-center py-8 text-gray-400">
Keine Log-Eintraege im gewaehlten Zeitraum
</td>
</tr>
) : logEntries.map(entry => (
<tr key={entry.id} className="border-b border-gray-100 hover:bg-gray-50">
<td className="px-4 py-3 text-gray-500">{formatDate(entry.created_at)}</td>
<td className="px-4 py-3 font-mono text-xs">{entry.user_id?.slice(0, 8)}...</td>
<td className="px-4 py-3">
<span className="px-2 py-0.5 bg-blue-50 text-blue-700 rounded text-xs font-medium">
{entry.model}
</span>
</td>
<td className="px-4 py-3 text-right font-mono">{formatNumber(entry.total_tokens)}</td>
<td className="px-4 py-3 text-center">
{entry.pii_detected ? (
<span className="px-2 py-0.5 bg-red-50 text-red-700 rounded text-xs font-medium">
{entry.redacted ? 'Redacted' : 'Erkannt'}
</span>
) : (
<span className="text-gray-400 text-xs">-</span>
)}
</td>
<td className="px-4 py-3 text-right text-gray-500">{formatDuration(entry.duration_ms)}</td>
<td className="px-4 py-3 text-center">
<span className={`px-2 py-0.5 rounded text-xs font-medium ${
entry.status === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
}`}>
{entry.status}
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="mt-2 text-xs text-gray-400">{logEntries.length} Eintraege</div>
</div>
)}
{/* ── Nutzung Tab ── */}
{!loading && activeTab === 'usage' && usageStats && (
<div>
{/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
<StatCard label="Requests gesamt" value={formatNumber(usageStats.total_requests)} />
<StatCard label="Tokens gesamt" value={formatNumber(usageStats.total_tokens)} />
<StatCard label="Avg. Dauer" value={formatDuration(usageStats.avg_duration_ms)} />
<StatCard
label="PII-Rate"
value={`${(usageStats.pii_detection_rate * 100).toFixed(1)}%`}
highlight={usageStats.pii_detection_rate > 0.1}
/>
</div>
{/* Token Breakdown */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="bg-white rounded-xl border border-gray-200 p-5">
<h3 className="font-semibold text-gray-900 mb-4">Model-Nutzung</h3>
{Object.entries(usageStats.models_used || {}).length === 0 ? (
<p className="text-gray-400 text-sm">Keine Daten</p>
) : (
<div className="space-y-3">
{Object.entries(usageStats.models_used).sort((a, b) => b[1] - a[1]).map(([model, count]) => (
<div key={model} className="flex items-center justify-between">
<span className="text-sm text-gray-700">{model}</span>
<div className="flex items-center gap-3">
<div className="w-32 h-2 bg-gray-100 rounded-full overflow-hidden">
<div
className="h-full bg-purple-500 rounded-full"
style={{ width: `${(count / usageStats.total_requests) * 100}%` }}
/>
</div>
<span className="text-sm font-mono text-gray-500 w-16 text-right">{formatNumber(count)}</span>
</div>
</div>
))}
</div>
)}
</div>
<div className="bg-white rounded-xl border border-gray-200 p-5">
<h3 className="font-semibold text-gray-900 mb-4">Provider-Verteilung</h3>
{Object.entries(usageStats.providers_used || {}).length === 0 ? (
<p className="text-gray-400 text-sm">Keine Daten</p>
) : (
<div className="space-y-3">
{Object.entries(usageStats.providers_used).sort((a, b) => b[1] - a[1]).map(([provider, count]) => (
<div key={provider} className="flex items-center justify-between">
<span className="text-sm text-gray-700 capitalize">{provider}</span>
<span className="text-sm font-mono text-gray-500">{formatNumber(count)}</span>
</div>
))}
</div>
)}
</div>
</div>
{/* Token Details */}
<div className="mt-6 bg-white rounded-xl border border-gray-200 p-5">
<h3 className="font-semibold text-gray-900 mb-4">Token-Aufschluesselung</h3>
<div className="grid grid-cols-3 gap-4">
<div className="text-center">
<div className="text-2xl font-bold text-gray-900">{formatNumber(usageStats.total_prompt_tokens)}</div>
<div className="text-sm text-gray-500">Prompt Tokens</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-gray-900">{formatNumber(usageStats.total_completion_tokens)}</div>
<div className="text-sm text-gray-500">Completion Tokens</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-purple-600">{formatNumber(usageStats.total_tokens)}</div>
<div className="text-sm text-gray-500">Gesamt</div>
</div>
</div>
</div>
</div>
)}
{/* ── Compliance Tab ── */}
{!loading && activeTab === 'compliance' && complianceReport && (
<div>
{/* Summary Cards */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
<StatCard label="Requests" value={formatNumber(complianceReport.total_requests)} />
<StatCard
label="PII-Vorfaelle"
value={formatNumber(complianceReport.pii_incidents)}
highlight={complianceReport.pii_incidents > 0}
/>
<StatCard
label="PII-Rate"
value={`${(complianceReport.pii_rate * 100).toFixed(1)}%`}
highlight={complianceReport.pii_rate > 0.05}
/>
<StatCard label="Redaction-Rate" value={`${(complianceReport.redaction_rate * 100).toFixed(1)}%`} />
</div>
{complianceReport.policy_violations > 0 && (
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-xl">
<div className="flex items-center gap-2 text-red-700 font-semibold">
<svg className="w-5 h-5" 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>
{complianceReport.policy_violations} Policy-Verletzungen im Zeitraum
</div>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* PII Categories */}
<div className="bg-white rounded-xl border border-gray-200 p-5">
<h3 className="font-semibold text-gray-900 mb-4">PII-Kategorien</h3>
{Object.entries(complianceReport.top_pii_categories || {}).length === 0 ? (
<p className="text-gray-400 text-sm">Keine PII erkannt</p>
) : (
<div className="space-y-2">
{Object.entries(complianceReport.top_pii_categories).sort((a, b) => b[1] - a[1]).map(([cat, count]) => (
<div key={cat} className="flex items-center justify-between py-1">
<span className="text-sm text-gray-700">{cat}</span>
<span className="px-2 py-0.5 bg-red-50 text-red-700 rounded text-xs font-mono">{count}</span>
</div>
))}
</div>
)}
</div>
{/* Namespace Breakdown */}
<div className="bg-white rounded-xl border border-gray-200 p-5">
<h3 className="font-semibold text-gray-900 mb-4">Namespace-Analyse</h3>
{Object.entries(complianceReport.namespace_breakdown || {}).length === 0 ? (
<p className="text-gray-400 text-sm">Keine Namespace-Daten</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-gray-100">
<th className="text-left py-2 text-gray-500 font-medium">Namespace</th>
<th className="text-right py-2 text-gray-500 font-medium">Requests</th>
<th className="text-right py-2 text-gray-500 font-medium">PII</th>
</tr>
</thead>
<tbody>
{Object.entries(complianceReport.namespace_breakdown).map(([ns, data]) => (
<tr key={ns} className="border-b border-gray-50">
<td className="py-2 font-mono text-xs">{ns}</td>
<td className="py-2 text-right">{formatNumber(data.requests)}</td>
<td className="py-2 text-right">
{data.pii_incidents > 0 ? (
<span className="text-red-600 font-medium">{data.pii_incidents}</span>
) : (
<span className="text-gray-400">0</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
{/* User Breakdown */}
{Object.entries(complianceReport.user_breakdown || {}).length > 0 && (
<div className="mt-6 bg-white rounded-xl border border-gray-200 p-5">
<h3 className="font-semibold text-gray-900 mb-4">Top-Nutzer</h3>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-gray-100">
<th className="text-left py-2 text-gray-500 font-medium">User-ID</th>
<th className="text-right py-2 text-gray-500 font-medium">Requests</th>
<th className="text-right py-2 text-gray-500 font-medium">PII-Vorfaelle</th>
</tr>
</thead>
<tbody>
{Object.entries(complianceReport.user_breakdown)
.sort((a, b) => b[1].requests - a[1].requests)
.slice(0, 10)
.map(([userId, data]) => (
<tr key={userId} className="border-b border-gray-50">
<td className="py-2 font-mono text-xs">{userId}</td>
<td className="py-2 text-right">{formatNumber(data.requests)}</td>
<td className="py-2 text-right">
{data.pii_incidents > 0 ? (
<span className="text-red-600 font-medium">{data.pii_incidents}</span>
) : (
<span className="text-gray-400">0</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
)}
{/* Empty state for usage/compliance when no data */}
{!loading && activeTab === 'usage' && !usageStats && !error && (
<div className="text-center py-12 text-gray-400">Keine Nutzungsdaten verfuegbar</div>
)}
{!loading && activeTab === 'compliance' && !complianceReport && !error && (
<div className="text-center py-12 text-gray-400">Kein Compliance-Report verfuegbar</div>
)}
</div>
)
}
// =============================================================================
// STAT CARD
// =============================================================================
function StatCard({ label, value, highlight }: { label: string; value: string; highlight?: boolean }) {
return (
<div className={`rounded-xl border p-4 ${highlight ? 'border-red-200 bg-red-50' : 'border-gray-200 bg-white'}`}>
<div className="text-sm text-gray-500">{label}</div>
<div className={`text-2xl font-bold mt-1 ${highlight ? 'text-red-700' : 'text-gray-900'}`}>{value}</div>
</div>
)
}

View File

@@ -0,0 +1,658 @@
'use client'
import React, { useState, useEffect, useCallback } from 'react'
import { useSDK } from '@/lib/sdk'
// =============================================================================
// TYPES
// =============================================================================
interface Portfolio {
id: string
name: string
description: string
status: 'DRAFT' | 'ACTIVE' | 'REVIEW' | 'APPROVED' | 'ARCHIVED'
department: string
business_unit: string
owner: string
owner_email: string
total_assessments: number
total_roadmaps: number
total_workshops: number
avg_risk_score: number
high_risk_count: number
compliance_score: number
auto_update_metrics: boolean
require_approval: boolean
created_at: string
updated_at: string
approved_at: string | null
approved_by: string | null
}
interface PortfolioItem {
id: string
portfolio_id: string
item_type: 'ASSESSMENT' | 'ROADMAP' | 'WORKSHOP' | 'DOCUMENT'
item_id: string
title: string
status: string
risk_level: string
risk_score: number
feasibility: string
sort_order: number
tags: string[]
notes: string
created_at: string
}
interface PortfolioStats {
total_items: number
items_by_type: Record<string, number>
risk_distribution: Record<string, number>
avg_risk_score: number
compliance_score: number
}
interface ActivityEntry {
timestamp: string
action: string
item_type: string
item_id: string
item_title: string
user_id: string
}
interface CompareResult {
portfolios: Portfolio[]
risk_scores: Record<string, number>
compliance_scores: Record<string, number>
item_counts: Record<string, number>
common_items: string[]
unique_items: Record<string, string[]>
}
// =============================================================================
// API
// =============================================================================
const API_BASE = '/api/sdk/v1/portfolio'
async function api<T>(path: string, options?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
headers: { 'Content-Type': 'application/json' },
...options,
})
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(err.error || err.message || `HTTP ${res.status}`)
}
return res.json()
}
// =============================================================================
// COMPONENTS
// =============================================================================
const statusColors: Record<string, string> = {
DRAFT: 'bg-gray-100 text-gray-700',
ACTIVE: 'bg-green-100 text-green-700',
REVIEW: 'bg-yellow-100 text-yellow-700',
APPROVED: 'bg-purple-100 text-purple-700',
ARCHIVED: 'bg-red-100 text-red-700',
}
const statusLabels: Record<string, string> = {
DRAFT: 'Entwurf',
ACTIVE: 'Aktiv',
REVIEW: 'In Pruefung',
APPROVED: 'Genehmigt',
ARCHIVED: 'Archiviert',
}
function PortfolioCard({ portfolio, onSelect, onDelete }: {
portfolio: Portfolio
onSelect: (p: Portfolio) => void
onDelete: (id: string) => void
}) {
const totalItems = portfolio.total_assessments + portfolio.total_roadmaps + portfolio.total_workshops
return (
<div className="bg-white rounded-xl border-2 border-gray-200 p-6 hover:border-purple-300 transition-colors cursor-pointer"
onClick={() => onSelect(portfolio)}>
<div className="flex items-start justify-between mb-3">
<div className="flex-1 min-w-0">
<h4 className="font-semibold text-gray-900 truncate">{portfolio.name}</h4>
{portfolio.department && <span className="text-xs text-gray-500">{portfolio.department}</span>}
</div>
<span className={`px-2 py-1 text-xs rounded-full ml-2 ${statusColors[portfolio.status] || 'bg-gray-100 text-gray-700'}`}>
{statusLabels[portfolio.status] || portfolio.status}
</span>
</div>
{portfolio.description && (
<p className="text-sm text-gray-600 mb-3 line-clamp-2">{portfolio.description}</p>
)}
<div className="grid grid-cols-3 gap-2 mb-4">
<div className="bg-gray-50 rounded-lg p-2 text-center">
<div className="text-lg font-bold text-purple-600">{portfolio.compliance_score}%</div>
<div className="text-xs text-gray-500">Compliance</div>
</div>
<div className="bg-gray-50 rounded-lg p-2 text-center">
<div className="text-lg font-bold text-gray-900">{portfolio.avg_risk_score.toFixed(1)}</div>
<div className="text-xs text-gray-500">Risiko</div>
</div>
<div className="bg-gray-50 rounded-lg p-2 text-center">
<div className="text-lg font-bold text-gray-900">{totalItems}</div>
<div className="text-xs text-gray-500">Items</div>
</div>
</div>
{portfolio.high_risk_count > 0 && (
<div className="flex items-center gap-1 text-xs text-red-600 mb-3">
<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="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
</svg>
{portfolio.high_risk_count} Hoch-Risiko
</div>
)}
<div className="flex justify-between items-center">
<span className="text-xs text-gray-400">{portfolio.owner || 'Kein Owner'}</span>
<button onClick={(e) => { e.stopPropagation(); onDelete(portfolio.id) }}
className="text-xs text-red-500 hover:text-red-700 hover:bg-red-50 px-2 py-1 rounded">
Loeschen
</button>
</div>
</div>
)
}
function CreatePortfolioModal({ onClose, onCreated }: {
onClose: () => void
onCreated: () => void
}) {
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [department, setDepartment] = useState('')
const [owner, setOwner] = useState('')
const [saving, setSaving] = useState(false)
const handleCreate = async () => {
if (!name.trim()) return
setSaving(true)
try {
await api('', {
method: 'POST',
body: JSON.stringify({
name: name.trim(),
description: description.trim(),
department: department.trim(),
owner: owner.trim(),
}),
})
onCreated()
} catch (err) {
console.error('Create portfolio error:', err)
} finally {
setSaving(false)
}
}
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-white rounded-2xl p-6 w-full max-w-lg" onClick={e => e.stopPropagation()}>
<h3 className="text-lg font-bold text-gray-900 mb-4">Neues Portfolio</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Name *</label>
<input type="text" value={name} onChange={e => setName(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
placeholder="z.B. KI-Portfolio Q1 2026" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
<textarea value={description} onChange={e => setDescription(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
rows={3} />
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Abteilung</label>
<input type="text" value={department} onChange={e => setDepartment(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Verantwortlicher</label>
<input type="text" value={owner} onChange={e => setOwner(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" />
</div>
</div>
</div>
<div className="flex justify-end gap-3 mt-6">
<button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
<button onClick={handleCreate} disabled={!name.trim() || saving}
className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
{saving ? 'Erstelle...' : 'Erstellen'}
</button>
</div>
</div>
</div>
)
}
function PortfolioDetailView({ portfolio, onBack, onRefresh }: {
portfolio: Portfolio
onBack: () => void
onRefresh: () => void
}) {
const [items, setItems] = useState<PortfolioItem[]>([])
const [activity, setActivity] = useState<ActivityEntry[]>([])
const [stats, setStats] = useState<PortfolioStats | null>(null)
const [activeTab, setActiveTab] = useState<'items' | 'activity' | 'compare'>('items')
const [loading, setLoading] = useState(true)
const [compareIds, setCompareIds] = useState('')
const [compareResult, setCompareResult] = useState<CompareResult | null>(null)
const loadDetails = useCallback(async () => {
setLoading(true)
try {
const [i, a, s] = await Promise.all([
api<PortfolioItem[]>(`/${portfolio.id}/items`).catch(() => []),
api<ActivityEntry[]>(`/${portfolio.id}/activity`).catch(() => []),
api<PortfolioStats>(`/${portfolio.id}/stats`).catch(() => null),
])
setItems(Array.isArray(i) ? i : [])
setActivity(Array.isArray(a) ? a : [])
setStats(s)
} finally {
setLoading(false)
}
}, [portfolio.id])
useEffect(() => { loadDetails() }, [loadDetails])
const handleSubmitReview = async () => {
try {
await api(`/${portfolio.id}/submit-review`, { method: 'POST' })
onRefresh()
} catch (err) {
console.error('Submit review error:', err)
}
}
const handleApprove = async () => {
try {
await api(`/${portfolio.id}/approve`, { method: 'POST' })
onRefresh()
} catch (err) {
console.error('Approve error:', err)
}
}
const handleRecalculate = async () => {
try {
await api(`/${portfolio.id}/recalculate`, { method: 'POST' })
loadDetails()
onRefresh()
} catch (err) {
console.error('Recalculate error:', err)
}
}
const handleCompare = async () => {
const ids = compareIds.split(',').map(s => s.trim()).filter(Boolean)
if (ids.length < 1) return
try {
const result = await api<CompareResult>('/compare', {
method: 'POST',
body: JSON.stringify({ portfolio_ids: [portfolio.id, ...ids] }),
})
setCompareResult(result)
} catch (err) {
console.error('Compare error:', err)
}
}
const handleRemoveItem = async (itemId: string) => {
try {
await api(`/${portfolio.id}/items/${itemId}`, { method: 'DELETE' })
setItems(prev => prev.filter(i => i.id !== itemId))
} catch (err) {
console.error('Remove item error:', err)
}
}
const typeLabels: Record<string, string> = {
ASSESSMENT: 'Assessment', ROADMAP: 'Roadmap', WORKSHOP: 'Workshop', DOCUMENT: 'Dokument',
}
const typeColors: Record<string, string> = {
ASSESSMENT: 'bg-blue-100 text-blue-700', ROADMAP: 'bg-green-100 text-green-700',
WORKSHOP: 'bg-purple-100 text-purple-700', DOCUMENT: 'bg-orange-100 text-orange-700',
}
return (
<div>
<button onClick={onBack} className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-4">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
Zurueck zur Uebersicht
</button>
<div className="bg-white rounded-xl border-2 border-gray-200 p-6 mb-6">
<div className="flex items-start justify-between mb-4">
<div>
<h2 className="text-xl font-bold text-gray-900">{portfolio.name}</h2>
<p className="text-sm text-gray-500 mt-1">{portfolio.description}</p>
</div>
<span className={`px-3 py-1 text-sm rounded-full ${statusColors[portfolio.status]}`}>
{statusLabels[portfolio.status]}
</span>
</div>
{stats && (
<div className="grid grid-cols-4 gap-4 mb-4">
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-purple-600">{stats.compliance_score}%</div>
<div className="text-xs text-gray-500">Compliance</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-gray-900">{stats.avg_risk_score.toFixed(1)}</div>
<div className="text-xs text-gray-500">Risiko-Score</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-gray-900">{stats.total_items}</div>
<div className="text-xs text-gray-500">Items</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-red-600">{portfolio.high_risk_count}</div>
<div className="text-xs text-gray-500">Hoch-Risiko</div>
</div>
</div>
)}
<div className="flex gap-2">
{portfolio.status === 'ACTIVE' && (
<button onClick={handleSubmitReview} className="px-3 py-1.5 text-sm bg-yellow-600 text-white rounded-lg hover:bg-yellow-700">
Zur Pruefung einreichen
</button>
)}
{portfolio.status === 'REVIEW' && (
<button onClick={handleApprove} className="px-3 py-1.5 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700">
Genehmigen
</button>
)}
<button onClick={handleRecalculate} className="px-3 py-1.5 text-sm border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
Metriken neu berechnen
</button>
</div>
</div>
{/* Tabs */}
<div className="flex gap-1 mb-4 bg-gray-100 p-1 rounded-lg">
{(['items', 'activity', 'compare'] as const).map(tab => (
<button key={tab} onClick={() => setActiveTab(tab)}
className={`flex-1 px-4 py-2 text-sm rounded-md transition-colors ${activeTab === tab ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'}`}>
{tab === 'items' ? `Items (${items.length})` : tab === 'activity' ? 'Aktivitaet' : 'Vergleich'}
</button>
))}
</div>
{loading ? (
<div className="text-center py-8 text-gray-500">Laden...</div>
) : (
<>
{activeTab === 'items' && (
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
<table className="w-full">
<thead className="bg-gray-50">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Titel</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Typ</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Risiko</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aktion</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{items.map(item => (
<tr key={item.id} className="hover:bg-gray-50">
<td className="px-4 py-3">
<div className="font-medium text-gray-900">{item.title}</div>
{item.notes && <div className="text-xs text-gray-500 truncate max-w-xs">{item.notes}</div>}
</td>
<td className="px-4 py-3">
<span className={`px-2 py-0.5 text-xs rounded-full ${typeColors[item.item_type] || 'bg-gray-100 text-gray-700'}`}>
{typeLabels[item.item_type] || item.item_type}
</span>
</td>
<td className="px-4 py-3 text-sm text-gray-600">{item.status}</td>
<td className="px-4 py-3">
<span className={`text-sm font-medium ${
item.risk_score >= 7 ? 'text-red-600' : item.risk_score >= 4 ? 'text-yellow-600' : 'text-green-600'
}`}>{item.risk_score.toFixed(1)}</span>
</td>
<td className="px-4 py-3">
<button onClick={() => handleRemoveItem(item.id)}
className="text-xs text-red-500 hover:text-red-700">Entfernen</button>
</td>
</tr>
))}
{items.length === 0 && (
<tr><td colSpan={5} className="px-4 py-8 text-center text-gray-500">Keine Items</td></tr>
)}
</tbody>
</table>
</div>
)}
{activeTab === 'activity' && (
<div className="space-y-3">
{activity.map((a, i) => (
<div key={i} className="bg-white rounded-lg border border-gray-200 p-4 flex items-center gap-4">
<div className={`w-8 h-8 rounded-full flex items-center justify-center text-white text-xs ${
a.action === 'added' ? 'bg-green-500' : a.action === 'removed' ? 'bg-red-500' : 'bg-blue-500'
}`}>
{a.action === 'added' ? '+' : a.action === 'removed' ? '-' : '~'}
</div>
<div className="flex-1">
<div className="text-sm text-gray-900">
<span className="font-medium">{a.item_title || a.item_id}</span> {a.action}
</div>
<div className="text-xs text-gray-500">{a.item_type}</div>
</div>
<div className="text-xs text-gray-400">{new Date(a.timestamp).toLocaleString('de-DE')}</div>
</div>
))}
{activity.length === 0 && (
<div className="text-center py-8 text-gray-500">Keine Aktivitaet</div>
)}
</div>
)}
{activeTab === 'compare' && (
<div className="bg-white rounded-xl border border-gray-200 p-6">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Portfolio-Vergleich</h3>
<div className="flex gap-3 mb-4">
<input
type="text" value={compareIds} onChange={e => setCompareIds(e.target.value)}
className="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500"
placeholder="Portfolio-IDs (kommagetrennt)"
/>
<button onClick={handleCompare}
className="px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700">
Vergleichen
</button>
</div>
{compareResult && (
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-50">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500">Portfolio</th>
<th className="px-4 py-3 text-center text-xs font-medium text-gray-500">Risiko-Score</th>
<th className="px-4 py-3 text-center text-xs font-medium text-gray-500">Compliance</th>
<th className="px-4 py-3 text-center text-xs font-medium text-gray-500">Items</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{compareResult.portfolios?.map(p => (
<tr key={p.id}>
<td className="px-4 py-3 font-medium text-gray-900">{p.name}</td>
<td className="px-4 py-3 text-center">{compareResult.risk_scores?.[p.id]?.toFixed(1) ?? '-'}</td>
<td className="px-4 py-3 text-center">{compareResult.compliance_scores?.[p.id] ?? '-'}%</td>
<td className="px-4 py-3 text-center">{compareResult.item_counts?.[p.id] ?? '-'}</td>
</tr>
))}
</tbody>
</table>
{compareResult.common_items?.length > 0 && (
<div className="mt-4 p-3 bg-gray-50 rounded-lg">
<div className="text-xs font-medium text-gray-500 mb-1">Gemeinsame Items: {compareResult.common_items.length}</div>
</div>
)}
</div>
)}
</div>
)}
</>
)}
</div>
)
}
// =============================================================================
// MAIN PAGE
// =============================================================================
export default function PortfolioPage() {
const { setCurrentModule } = useSDK()
const [portfolios, setPortfolios] = useState<Portfolio[]>([])
const [loading, setLoading] = useState(true)
const [showCreate, setShowCreate] = useState(false)
const [selectedPortfolio, setSelectedPortfolio] = useState<Portfolio | null>(null)
const [filter, setFilter] = useState<string>('all')
useEffect(() => {
setCurrentModule('portfolio')
}, [setCurrentModule])
const loadPortfolios = useCallback(async () => {
setLoading(true)
try {
const data = await api<Portfolio[] | { portfolios: Portfolio[] }>('')
const list = Array.isArray(data) ? data : (data.portfolios || [])
setPortfolios(list)
} catch (err) {
console.error('Load portfolios error:', err)
} finally {
setLoading(false)
}
}, [])
useEffect(() => { loadPortfolios() }, [loadPortfolios])
const handleDelete = async (id: string) => {
if (!confirm('Portfolio wirklich loeschen?')) return
try {
await api(`/${id}`, { method: 'DELETE' })
setPortfolios(prev => prev.filter(p => p.id !== id))
} catch (err) {
console.error('Delete error:', err)
}
}
const filteredPortfolios = filter === 'all'
? portfolios
: portfolios.filter(p => p.status === filter)
if (selectedPortfolio) {
return (
<div className="p-6 max-w-6xl mx-auto">
<PortfolioDetailView
portfolio={selectedPortfolio}
onBack={() => { setSelectedPortfolio(null); loadPortfolios() }}
onRefresh={() => {
loadPortfolios().then(() => {
const updated = portfolios.find(p => p.id === selectedPortfolio.id)
if (updated) setSelectedPortfolio(updated)
})
}}
/>
</div>
)
}
return (
<div className="p-6 max-w-6xl mx-auto">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-gray-900">KI-Portfolios</h1>
<p className="text-sm text-gray-500 mt-1">
Verwaltung und Vergleich von Compliance-Portfolios
</p>
</div>
<button onClick={() => setShowCreate(true)}
className="px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700 flex items-center gap-2">
<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>
Neues Portfolio
</button>
</div>
{/* Stats */}
<div className="grid grid-cols-4 gap-4 mb-6">
{[
{ label: 'Gesamt', value: portfolios.length, color: 'text-gray-900' },
{ label: 'Aktiv', value: portfolios.filter(p => p.status === 'ACTIVE').length, color: 'text-green-600' },
{ label: 'In Pruefung', value: portfolios.filter(p => p.status === 'REVIEW').length, color: 'text-yellow-600' },
{ label: 'Genehmigt', value: portfolios.filter(p => p.status === 'APPROVED').length, color: 'text-purple-600' },
].map(stat => (
<div key={stat.label} className="bg-white rounded-xl border border-gray-200 p-4 text-center">
<div className={`text-2xl font-bold ${stat.color}`}>{stat.value}</div>
<div className="text-xs text-gray-500">{stat.label}</div>
</div>
))}
</div>
{/* Filter */}
<div className="flex gap-2 mb-6">
{['all', 'DRAFT', 'ACTIVE', 'REVIEW', 'APPROVED'].map(f => (
<button key={f} onClick={() => setFilter(f)}
className={`px-3 py-1.5 text-sm rounded-lg ${filter === f ? 'bg-purple-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>
{f === 'all' ? 'Alle' : statusLabels[f] || f}
</button>
))}
</div>
{loading ? (
<div className="text-center py-12 text-gray-500">Portfolios werden geladen...</div>
) : filteredPortfolios.length === 0 ? (
<div className="text-center py-12">
<div className="text-gray-400 mb-2">
<svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
</div>
<p className="text-gray-500">Keine Portfolios gefunden</p>
<button onClick={() => setShowCreate(true)} className="mt-3 text-sm text-purple-600 hover:text-purple-700">
Erstes Portfolio erstellen
</button>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filteredPortfolios.map(p => (
<PortfolioCard key={p.id} portfolio={p} onSelect={setSelectedPortfolio} onDelete={handleDelete} />
))}
</div>
)}
{showCreate && (
<CreatePortfolioModal onClose={() => setShowCreate(false)} onCreated={() => { setShowCreate(false); loadPortfolios() }} />
)}
</div>
)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,882 @@
'use client'
import React, { useState, useEffect, useCallback, useRef } from 'react'
import { useSDK } from '@/lib/sdk'
// =============================================================================
// TYPES
// =============================================================================
interface Roadmap {
id: string
title: string
description: string
version: number
status: 'draft' | 'active' | 'completed' | 'archived'
assessment_id: string | null
portfolio_id: string | null
total_items: number
completed_items: number
progress: number
start_date: string | null
target_date: string | null
created_at: string
updated_at: string
}
interface RoadmapItem {
id: string
roadmap_id: string
title: string
description: string
category: 'TECHNICAL' | 'ORGANIZATIONAL' | 'PROCESSUAL' | 'DOCUMENTATION' | 'TRAINING'
priority: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW'
status: 'PLANNED' | 'IN_PROGRESS' | 'BLOCKED' | 'COMPLETED' | 'DEFERRED'
control_id: string | null
regulation_ref: string | null
effort_days: number
effort_hours: number
estimated_cost: number
assignee_name: string
department: string
planned_start: string | null
planned_end: string | null
actual_start: string | null
actual_end: string | null
evidence_required: boolean
evidence_provided: boolean
sort_order: number
created_at: string
updated_at: string
}
interface RoadmapStats {
by_status: Record<string, number>
by_priority: Record<string, number>
by_category: Record<string, number>
by_department: Record<string, number>
overdue_items: number
upcoming_items: number
total_effort_days: number
progress: number
}
interface ImportJob {
id: string
status: 'pending' | 'parsing' | 'validating' | 'completed' | 'failed'
filename: string
total_rows: number
valid_rows: number
invalid_rows: number
items: ParsedItem[]
}
interface ParsedItem {
row: number
title: string
description: string
category: string
priority: string
is_valid: boolean
errors: string[]
warnings: string[]
matched_control: string | null
match_confidence: number
}
// =============================================================================
// API
// =============================================================================
const API_BASE = '/api/sdk/v1/roadmap'
async function api<T>(path: string, options?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
headers: { 'Content-Type': 'application/json' },
...options,
})
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(err.error || err.message || `HTTP ${res.status}`)
}
return res.json()
}
// =============================================================================
// COMPONENTS
// =============================================================================
const statusColors: Record<string, string> = {
draft: 'bg-gray-100 text-gray-700',
active: 'bg-green-100 text-green-700',
completed: 'bg-purple-100 text-purple-700',
archived: 'bg-red-100 text-red-700',
}
const statusLabels: Record<string, string> = {
draft: 'Entwurf',
active: 'Aktiv',
completed: 'Abgeschlossen',
archived: 'Archiviert',
}
const itemStatusColors: Record<string, string> = {
PLANNED: 'bg-gray-100 text-gray-700',
IN_PROGRESS: 'bg-blue-100 text-blue-700',
BLOCKED: 'bg-red-100 text-red-700',
COMPLETED: 'bg-green-100 text-green-700',
DEFERRED: 'bg-yellow-100 text-yellow-700',
}
const itemStatusLabels: Record<string, string> = {
PLANNED: 'Geplant',
IN_PROGRESS: 'In Arbeit',
BLOCKED: 'Blockiert',
COMPLETED: 'Erledigt',
DEFERRED: 'Verschoben',
}
const priorityColors: Record<string, string> = {
CRITICAL: 'bg-red-100 text-red-700',
HIGH: 'bg-orange-100 text-orange-700',
MEDIUM: 'bg-yellow-100 text-yellow-700',
LOW: 'bg-green-100 text-green-700',
}
const categoryLabels: Record<string, string> = {
TECHNICAL: 'Technisch',
ORGANIZATIONAL: 'Organisatorisch',
PROCESSUAL: 'Prozessual',
DOCUMENTATION: 'Dokumentation',
TRAINING: 'Schulung',
}
function RoadmapCard({ roadmap, onSelect, onDelete }: {
roadmap: Roadmap
onSelect: (r: Roadmap) => void
onDelete: (id: string) => void
}) {
return (
<div className="bg-white rounded-xl border-2 border-gray-200 p-6 hover:border-purple-300 transition-colors cursor-pointer"
onClick={() => onSelect(roadmap)}>
<div className="flex items-start justify-between mb-3">
<h4 className="font-semibold text-gray-900 truncate flex-1">{roadmap.title}</h4>
<span className={`px-2 py-1 text-xs rounded-full ml-2 ${statusColors[roadmap.status] || 'bg-gray-100 text-gray-700'}`}>
{statusLabels[roadmap.status] || roadmap.status}
</span>
</div>
{roadmap.description && (
<p className="text-sm text-gray-600 mb-3 line-clamp-2">{roadmap.description}</p>
)}
<div className="mb-3">
<div className="flex justify-between text-xs text-gray-500 mb-1">
<span>{roadmap.completed_items}/{roadmap.total_items} Items</span>
<span>{roadmap.progress}%</span>
</div>
<div className="w-full h-2 bg-gray-100 rounded-full overflow-hidden">
<div className="h-full bg-purple-500 rounded-full transition-all" style={{ width: `${roadmap.progress}%` }} />
</div>
</div>
{(roadmap.start_date || roadmap.target_date) && (
<div className="flex items-center gap-2 text-xs text-gray-500 mb-3">
{roadmap.start_date && <span>Start: {new Date(roadmap.start_date).toLocaleDateString('de-DE')}</span>}
{roadmap.target_date && <span>Ziel: {new Date(roadmap.target_date).toLocaleDateString('de-DE')}</span>}
</div>
)}
<div className="flex justify-between items-center">
<span className="text-xs text-gray-400">v{roadmap.version}</span>
<button onClick={(e) => { e.stopPropagation(); onDelete(roadmap.id) }}
className="text-xs text-red-500 hover:text-red-700 hover:bg-red-50 px-2 py-1 rounded">
Loeschen
</button>
</div>
</div>
)
}
function CreateRoadmapModal({ onClose, onCreated }: {
onClose: () => void
onCreated: () => void
}) {
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [startDate, setStartDate] = useState('')
const [targetDate, setTargetDate] = useState('')
const [saving, setSaving] = useState(false)
const handleCreate = async () => {
if (!title.trim()) return
setSaving(true)
try {
await api('', {
method: 'POST',
body: JSON.stringify({
title: title.trim(),
description: description.trim(),
start_date: startDate || null,
target_date: targetDate || null,
}),
})
onCreated()
} catch (err) {
console.error('Create roadmap error:', err)
} finally {
setSaving(false)
}
}
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-white rounded-2xl p-6 w-full max-w-lg" onClick={e => e.stopPropagation()}>
<h3 className="text-lg font-bold text-gray-900 mb-4">Neue Roadmap</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Titel *</label>
<input type="text" value={title} onChange={e => setTitle(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
placeholder="z.B. AI Act Compliance Roadmap" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
<textarea value={description} onChange={e => setDescription(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
rows={3} />
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Startdatum</label>
<input type="date" value={startDate} onChange={e => setStartDate(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Zieldatum</label>
<input type="date" value={targetDate} onChange={e => setTargetDate(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" />
</div>
</div>
</div>
<div className="flex justify-end gap-3 mt-6">
<button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
<button onClick={handleCreate} disabled={!title.trim() || saving}
className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
{saving ? 'Erstelle...' : 'Erstellen'}
</button>
</div>
</div>
</div>
)
}
function CreateItemModal({ roadmapId, onClose, onCreated }: {
roadmapId: string
onClose: () => void
onCreated: () => void
}) {
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [category, setCategory] = useState<string>('TECHNICAL')
const [priority, setPriority] = useState<string>('MEDIUM')
const [assigneeName, setAssigneeName] = useState('')
const [department, setDepartment] = useState('')
const [effortDays, setEffortDays] = useState(1)
const [saving, setSaving] = useState(false)
const handleCreate = async () => {
if (!title.trim()) return
setSaving(true)
try {
await api(`/${roadmapId}/items`, {
method: 'POST',
body: JSON.stringify({
title: title.trim(),
description: description.trim(),
category,
priority,
assignee_name: assigneeName.trim(),
department: department.trim(),
effort_days: effortDays,
}),
})
onCreated()
} catch (err) {
console.error('Create item error:', err)
} finally {
setSaving(false)
}
}
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-white rounded-2xl p-6 w-full max-w-lg max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
<h3 className="text-lg font-bold text-gray-900 mb-4">Neues Item</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Titel *</label>
<input type="text" value={title} onChange={e => setTitle(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
<textarea value={description} onChange={e => setDescription(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" rows={2} />
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Kategorie</label>
<select value={category} onChange={e => setCategory(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
{Object.entries(categoryLabels).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Prioritaet</label>
<select value={priority} onChange={e => setPriority(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
<option value="CRITICAL">Kritisch</option>
<option value="HIGH">Hoch</option>
<option value="MEDIUM">Mittel</option>
<option value="LOW">Niedrig</option>
</select>
</div>
</div>
<div className="grid grid-cols-3 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Zustaendig</label>
<input type="text" value={assigneeName} onChange={e => setAssigneeName(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Abteilung</label>
<input type="text" value={department} onChange={e => setDepartment(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Aufwand (Tage)</label>
<input type="number" value={effortDays} onChange={e => setEffortDays(Number(e.target.value))}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" min={0} />
</div>
</div>
</div>
<div className="flex justify-end gap-3 mt-6">
<button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
<button onClick={handleCreate} disabled={!title.trim() || saving}
className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
{saving ? 'Erstelle...' : 'Erstellen'}
</button>
</div>
</div>
</div>
)
}
function ImportWizard({ onClose, onImported }: {
onClose: () => void
onImported: () => void
}) {
const [step, setStep] = useState<'upload' | 'preview' | 'confirm'>('upload')
const [importJob, setImportJob] = useState<ImportJob | null>(null)
const [uploading, setUploading] = useState(false)
const [confirming, setConfirming] = useState(false)
const [roadmapTitle, setRoadmapTitle] = useState('')
const fileRef = useRef<HTMLInputElement>(null)
const handleUpload = async () => {
const file = fileRef.current?.files?.[0]
if (!file) return
setUploading(true)
try {
const formData = new FormData()
formData.append('file', file)
const res = await fetch(`${API_BASE}/import/upload`, {
method: 'POST',
body: formData,
})
if (!res.ok) throw new Error(`Upload failed: ${res.status}`)
const data = await res.json()
// Fetch parsed job
const job = await api<ImportJob>(`/import/${data.job_id || data.id}`)
setImportJob(job)
setStep('preview')
} catch (err) {
console.error('Upload error:', err)
} finally {
setUploading(false)
}
}
const handleConfirm = async () => {
if (!importJob) return
setConfirming(true)
try {
await api(`/import/${importJob.id}/confirm`, {
method: 'POST',
body: JSON.stringify({
job_id: importJob.id,
roadmap_title: roadmapTitle || `Import ${new Date().toLocaleDateString('de-DE')}`,
selected_rows: importJob.items.filter(i => i.is_valid).map(i => i.row),
apply_mappings: true,
}),
})
onImported()
} catch (err) {
console.error('Confirm error:', err)
} finally {
setConfirming(false)
}
}
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-white rounded-2xl p-6 w-full max-w-2xl max-h-[80vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
<h3 className="text-lg font-bold text-gray-900 mb-4">Roadmap importieren</h3>
{step === 'upload' && (
<div className="space-y-4">
<div className="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center">
<input ref={fileRef} type="file" accept=".xlsx,.xls,.csv" className="hidden" onChange={() => {}} />
<svg className="w-12 h-12 mx-auto text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
</svg>
<button onClick={() => fileRef.current?.click()}
className="px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700">
Datei auswaehlen
</button>
<p className="text-xs text-gray-500 mt-2">Excel (.xlsx, .xls) oder CSV</p>
</div>
<div className="flex justify-end gap-3">
<button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
<button onClick={handleUpload} disabled={uploading || !fileRef.current?.files?.length}
className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
{uploading ? 'Lade hoch...' : 'Hochladen'}
</button>
</div>
</div>
)}
{step === 'preview' && importJob && (
<div className="space-y-4">
<div className="grid grid-cols-3 gap-3">
<div className="bg-green-50 rounded-lg p-3 text-center">
<div className="text-xl font-bold text-green-600">{importJob.valid_rows}</div>
<div className="text-xs text-gray-500">Gueltig</div>
</div>
<div className="bg-red-50 rounded-lg p-3 text-center">
<div className="text-xl font-bold text-red-600">{importJob.invalid_rows}</div>
<div className="text-xs text-gray-500">Ungueltig</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-xl font-bold text-gray-900">{importJob.total_rows}</div>
<div className="text-xs text-gray-500">Gesamt</div>
</div>
</div>
<div className="max-h-64 overflow-y-auto border rounded-lg">
<table className="w-full text-sm">
<thead className="bg-gray-50 sticky top-0">
<tr>
<th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Zeile</th>
<th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Titel</th>
<th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Kategorie</th>
<th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Status</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{importJob.items?.map(item => (
<tr key={item.row} className={item.is_valid ? '' : 'bg-red-50'}>
<td className="px-3 py-2 text-gray-500">{item.row}</td>
<td className="px-3 py-2 text-gray-900">{item.title}</td>
<td className="px-3 py-2 text-gray-600">{item.category}</td>
<td className="px-3 py-2">
{item.is_valid ? (
<span className="text-green-600 text-xs">OK</span>
) : (
<span className="text-red-600 text-xs">{item.errors?.join(', ')}</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Roadmap-Titel</label>
<input type="text" value={roadmapTitle} onChange={e => setRoadmapTitle(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500"
placeholder="Name fuer die importierte Roadmap" />
</div>
<div className="flex justify-end gap-3">
<button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
<button onClick={handleConfirm} disabled={confirming || importJob.valid_rows === 0}
className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
{confirming ? 'Importiere...' : `${importJob.valid_rows} Items importieren`}
</button>
</div>
</div>
)}
</div>
</div>
)
}
function RoadmapDetailView({ roadmap, onBack, onRefresh }: {
roadmap: Roadmap
onBack: () => void
onRefresh: () => void
}) {
const [items, setItems] = useState<RoadmapItem[]>([])
const [stats, setStats] = useState<RoadmapStats | null>(null)
const [loading, setLoading] = useState(true)
const [showCreateItem, setShowCreateItem] = useState(false)
const [filterStatus, setFilterStatus] = useState<string>('all')
const [filterPriority, setFilterPriority] = useState<string>('all')
const loadDetails = useCallback(async () => {
setLoading(true)
try {
const [i, s] = await Promise.all([
api<RoadmapItem[] | { items: RoadmapItem[] }>(`/${roadmap.id}/items`).catch(() => []),
api<RoadmapStats>(`/${roadmap.id}/stats`).catch(() => null),
])
const itemList = Array.isArray(i) ? i : ((i as { items: RoadmapItem[] }).items || [])
setItems(itemList)
setStats(s)
} finally {
setLoading(false)
}
}, [roadmap.id])
useEffect(() => { loadDetails() }, [loadDetails])
const handleStatusChange = async (itemId: string, newStatus: string) => {
try {
// roadmap-items is a separate route group in Go backend
const res = await fetch(`/api/sdk/v1/roadmap-items/${itemId}/status`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: newStatus }),
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
loadDetails()
} catch (err) {
console.error('Status change error:', err)
}
}
const handleDeleteItem = async (itemId: string) => {
try {
const res = await fetch(`/api/sdk/v1/roadmap-items/${itemId}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
setItems(prev => prev.filter(i => i.id !== itemId))
} catch (err) {
console.error('Delete item error:', err)
}
}
const filteredItems = items.filter(i => {
if (filterStatus !== 'all' && i.status !== filterStatus) return false
if (filterPriority !== 'all' && i.priority !== filterPriority) return false
return true
})
return (
<div>
<button onClick={onBack} className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-4">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
Zurueck zur Uebersicht
</button>
<div className="bg-white rounded-xl border-2 border-gray-200 p-6 mb-6">
<div className="flex items-start justify-between mb-4">
<div>
<h2 className="text-xl font-bold text-gray-900">{roadmap.title}</h2>
<p className="text-sm text-gray-500 mt-1">{roadmap.description}</p>
</div>
<span className={`px-3 py-1 text-sm rounded-full ${statusColors[roadmap.status]}`}>
{statusLabels[roadmap.status]}
</span>
</div>
<div className="mb-4">
<div className="flex justify-between text-sm text-gray-500 mb-1">
<span>{roadmap.completed_items}/{roadmap.total_items} Items abgeschlossen</span>
<span>{roadmap.progress}%</span>
</div>
<div className="w-full h-3 bg-gray-100 rounded-full overflow-hidden">
<div className="h-full bg-purple-500 rounded-full transition-all" style={{ width: `${roadmap.progress}%` }} />
</div>
</div>
{stats && (
<div className="grid grid-cols-4 gap-4 mb-4">
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-red-600">{stats.overdue_items}</div>
<div className="text-xs text-gray-500">Ueberfaellig</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-yellow-600">{stats.upcoming_items}</div>
<div className="text-xs text-gray-500">Anstehend</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-gray-900">{stats.total_effort_days}</div>
<div className="text-xs text-gray-500">Aufwand (Tage)</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-purple-600">{stats.progress}%</div>
<div className="text-xs text-gray-500">Fortschritt</div>
</div>
</div>
)}
<button onClick={() => setShowCreateItem(true)}
className="px-3 py-1.5 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700">
Neues Item
</button>
</div>
{/* Filters */}
<div className="flex gap-4 mb-4">
<div className="flex items-center gap-2">
<span className="text-sm text-gray-500">Status:</span>
<select value={filterStatus} onChange={e => setFilterStatus(e.target.value)}
className="px-2 py-1 text-sm border rounded-lg">
<option value="all">Alle</option>
{Object.entries(itemStatusLabels).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
</select>
</div>
<div className="flex items-center gap-2">
<span className="text-sm text-gray-500">Prioritaet:</span>
<select value={filterPriority} onChange={e => setFilterPriority(e.target.value)}
className="px-2 py-1 text-sm border rounded-lg">
<option value="all">Alle</option>
<option value="CRITICAL">Kritisch</option>
<option value="HIGH">Hoch</option>
<option value="MEDIUM">Mittel</option>
<option value="LOW">Niedrig</option>
</select>
</div>
</div>
{loading ? (
<div className="text-center py-8 text-gray-500">Laden...</div>
) : (
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
<table className="w-full">
<thead className="bg-gray-50">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Titel</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Kategorie</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Prioritaet</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Zustaendig</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aufwand</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aktion</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{filteredItems.map(item => (
<tr key={item.id} className="hover:bg-gray-50">
<td className="px-4 py-3">
<div className="font-medium text-gray-900">{item.title}</div>
{item.regulation_ref && <div className="text-xs text-gray-500">{item.regulation_ref}</div>}
</td>
<td className="px-4 py-3 text-sm text-gray-600">
{categoryLabels[item.category] || item.category}
</td>
<td className="px-4 py-3">
<span className={`px-2 py-0.5 text-xs rounded-full ${priorityColors[item.priority] || 'bg-gray-100 text-gray-700'}`}>
{item.priority}
</span>
</td>
<td className="px-4 py-3">
<select
value={item.status}
onChange={e => handleStatusChange(item.id, e.target.value)}
className={`px-2 py-0.5 text-xs rounded-full border-0 ${itemStatusColors[item.status] || 'bg-gray-100 text-gray-700'}`}
>
{Object.entries(itemStatusLabels).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
</select>
</td>
<td className="px-4 py-3 text-sm text-gray-600">
{item.assignee_name || '-'}
{item.department && <div className="text-xs text-gray-400">{item.department}</div>}
</td>
<td className="px-4 py-3 text-sm text-gray-600">{item.effort_days}d</td>
<td className="px-4 py-3">
<button onClick={() => handleDeleteItem(item.id)}
className="text-xs text-red-500 hover:text-red-700">Loeschen</button>
</td>
</tr>
))}
{filteredItems.length === 0 && (
<tr><td colSpan={7} className="px-4 py-8 text-center text-gray-500">Keine Items</td></tr>
)}
</tbody>
</table>
</div>
)}
{showCreateItem && (
<CreateItemModal roadmapId={roadmap.id} onClose={() => setShowCreateItem(false)}
onCreated={() => { setShowCreateItem(false); loadDetails(); onRefresh() }} />
)}
</div>
)
}
// =============================================================================
// MAIN PAGE
// =============================================================================
export default function RoadmapPage() {
const { setCurrentModule } = useSDK()
const [roadmaps, setRoadmaps] = useState<Roadmap[]>([])
const [loading, setLoading] = useState(true)
const [showCreate, setShowCreate] = useState(false)
const [showImport, setShowImport] = useState(false)
const [selectedRoadmap, setSelectedRoadmap] = useState<Roadmap | null>(null)
const [filter, setFilter] = useState<string>('all')
useEffect(() => {
setCurrentModule('roadmap')
}, [setCurrentModule])
const loadRoadmaps = useCallback(async () => {
setLoading(true)
try {
const data = await api<Roadmap[] | { roadmaps: Roadmap[] }>('')
const list = Array.isArray(data) ? data : (data.roadmaps || [])
setRoadmaps(list)
} catch (err) {
console.error('Load roadmaps error:', err)
} finally {
setLoading(false)
}
}, [])
useEffect(() => { loadRoadmaps() }, [loadRoadmaps])
const handleDelete = async (id: string) => {
if (!confirm('Roadmap wirklich loeschen?')) return
try {
await api(`/${id}`, { method: 'DELETE' })
setRoadmaps(prev => prev.filter(r => r.id !== id))
} catch (err) {
console.error('Delete error:', err)
}
}
const filteredRoadmaps = filter === 'all'
? roadmaps
: roadmaps.filter(r => r.status === filter)
if (selectedRoadmap) {
return (
<div className="p-6 max-w-6xl mx-auto">
<RoadmapDetailView
roadmap={selectedRoadmap}
onBack={() => { setSelectedRoadmap(null); loadRoadmaps() }}
onRefresh={() => {
loadRoadmaps().then(() => {
const updated = roadmaps.find(r => r.id === selectedRoadmap.id)
if (updated) setSelectedRoadmap(updated)
})
}}
/>
</div>
)
}
return (
<div className="p-6 max-w-6xl mx-auto">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-gray-900">Compliance Roadmaps</h1>
<p className="text-sm text-gray-500 mt-1">
Umsetzungsplaene fuer Compliance-Massnahmen
</p>
</div>
<div className="flex gap-2">
<button onClick={() => setShowImport(true)}
className="px-4 py-2 border border-gray-300 text-gray-700 text-sm rounded-lg hover:bg-gray-50 flex items-center gap-2">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
</svg>
Importieren
</button>
<button onClick={() => setShowCreate(true)}
className="px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700 flex items-center gap-2">
<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>
Neue Roadmap
</button>
</div>
</div>
{/* Stats */}
<div className="grid grid-cols-4 gap-4 mb-6">
{[
{ label: 'Gesamt', value: roadmaps.length, color: 'text-gray-900' },
{ label: 'Aktiv', value: roadmaps.filter(r => r.status === 'active').length, color: 'text-green-600' },
{ label: 'Entwurf', value: roadmaps.filter(r => r.status === 'draft').length, color: 'text-gray-600' },
{ label: 'Abgeschlossen', value: roadmaps.filter(r => r.status === 'completed').length, color: 'text-purple-600' },
].map(stat => (
<div key={stat.label} className="bg-white rounded-xl border border-gray-200 p-4 text-center">
<div className={`text-2xl font-bold ${stat.color}`}>{stat.value}</div>
<div className="text-xs text-gray-500">{stat.label}</div>
</div>
))}
</div>
{/* Filter */}
<div className="flex gap-2 mb-6">
{['all', 'draft', 'active', 'completed'].map(f => (
<button key={f} onClick={() => setFilter(f)}
className={`px-3 py-1.5 text-sm rounded-lg ${filter === f ? 'bg-purple-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>
{f === 'all' ? 'Alle' : statusLabels[f] || f}
</button>
))}
</div>
{loading ? (
<div className="text-center py-12 text-gray-500">Roadmaps werden geladen...</div>
) : filteredRoadmaps.length === 0 ? (
<div className="text-center py-12">
<div className="text-gray-400 mb-2">
<svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2" />
</svg>
</div>
<p className="text-gray-500">Keine Roadmaps gefunden</p>
<button onClick={() => setShowCreate(true)} className="mt-3 text-sm text-purple-600 hover:text-purple-700">
Erste Roadmap erstellen
</button>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filteredRoadmaps.map(r => (
<RoadmapCard key={r.id} roadmap={r} onSelect={setSelectedRoadmap} onDelete={handleDelete} />
))}
</div>
)}
{showCreate && (
<CreateRoadmapModal onClose={() => setShowCreate(false)} onCreated={() => { setShowCreate(false); loadRoadmaps() }} />
)}
{showImport && (
<ImportWizard onClose={() => setShowImport(false)} onImported={() => { setShowImport(false); loadRoadmaps() }} />
)}
</div>
)
}

View File

@@ -0,0 +1,616 @@
'use client'
import React, { useState, useEffect, useCallback } from 'react'
import { useSDK } from '@/lib/sdk'
// =============================================================================
// TYPES
// =============================================================================
interface WorkshopSession {
id: string
title: string
description: string
session_type: 'ucca' | 'dsfa' | 'custom'
status: 'DRAFT' | 'SCHEDULED' | 'ACTIVE' | 'PAUSED' | 'COMPLETED' | 'CANCELLED'
current_step: number
total_steps: number
join_code: string
require_auth: boolean
allow_anonymous: boolean
scheduled_start: string | null
scheduled_end: string | null
actual_start: string | null
actual_end: string | null
assessment_id: string | null
roadmap_id: string | null
portfolio_id: string | null
created_at: string
updated_at: string
}
interface Participant {
id: string
session_id: string
user_id: string | null
name: string
email: string
role: 'FACILITATOR' | 'EXPERT' | 'STAKEHOLDER' | 'OBSERVER'
department: string
is_active: boolean
last_active_at: string | null
joined_at: string
can_edit: boolean
can_comment: boolean
can_approve: boolean
}
interface WorkshopResponse {
id: string
session_id: string
participant_id: string
step_number: number
field_id: string
value: unknown
value_type: string
response_status: 'PENDING' | 'DRAFT' | 'SUBMITTED' | 'REVIEWED'
created_at: string
}
interface WorkshopComment {
id: string
session_id: string
participant_id: string
step_number: number | null
field_id: string | null
text: string
is_resolved: boolean
created_at: string
}
interface SessionStats {
total_participants: number
active_participants: number
total_responses: number
completed_steps: number
total_steps: number
progress: number
}
// =============================================================================
// API
// =============================================================================
const API_BASE = '/api/sdk/v1/workshops'
async function api<T>(path: string, options?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
headers: { 'Content-Type': 'application/json' },
...options,
})
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(err.error || err.message || `HTTP ${res.status}`)
}
return res.json()
}
// =============================================================================
// COMPONENTS
// =============================================================================
const statusColors: Record<string, string> = {
DRAFT: 'bg-gray-100 text-gray-700',
SCHEDULED: 'bg-blue-100 text-blue-700',
ACTIVE: 'bg-green-100 text-green-700',
PAUSED: 'bg-yellow-100 text-yellow-700',
COMPLETED: 'bg-purple-100 text-purple-700',
CANCELLED: 'bg-red-100 text-red-700',
}
const statusLabels: Record<string, string> = {
DRAFT: 'Entwurf',
SCHEDULED: 'Geplant',
ACTIVE: 'Aktiv',
PAUSED: 'Pausiert',
COMPLETED: 'Abgeschlossen',
CANCELLED: 'Abgebrochen',
}
const typeLabels: Record<string, string> = {
ucca: 'UCCA Assessment',
dsfa: 'DSFA Workshop',
custom: 'Benutzerdefiniert',
}
function SessionCard({ session, onSelect, onDelete }: {
session: WorkshopSession
onSelect: (s: WorkshopSession) => void
onDelete: (id: string) => void
}) {
const progress = session.total_steps > 0
? Math.round((session.current_step / session.total_steps) * 100)
: 0
return (
<div className="bg-white rounded-xl border-2 border-gray-200 p-6 hover:border-purple-300 transition-colors cursor-pointer"
onClick={() => onSelect(session)}>
<div className="flex items-start justify-between mb-3">
<div>
<h4 className="font-semibold text-gray-900">{session.title}</h4>
<span className="text-xs text-gray-500">{typeLabels[session.session_type] || session.session_type}</span>
</div>
<span className={`px-2 py-1 text-xs rounded-full ${statusColors[session.status] || 'bg-gray-100 text-gray-700'}`}>
{statusLabels[session.status] || session.status}
</span>
</div>
{session.description && (
<p className="text-sm text-gray-600 mb-3 line-clamp-2">{session.description}</p>
)}
<div className="flex items-center gap-4 text-xs text-gray-500 mb-3">
<span>Code: <code className="bg-gray-100 px-1 rounded">{session.join_code}</code></span>
<span>Schritt {session.current_step}/{session.total_steps}</span>
</div>
<div className="w-full h-2 bg-gray-100 rounded-full overflow-hidden mb-3">
<div className="h-full bg-purple-500 rounded-full transition-all" style={{ width: `${progress}%` }} />
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-gray-400">
{new Date(session.created_at).toLocaleDateString('de-DE')}
</span>
<button
onClick={(e) => { e.stopPropagation(); onDelete(session.id) }}
className="text-xs text-red-500 hover:text-red-700 hover:bg-red-50 px-2 py-1 rounded"
>
Loeschen
</button>
</div>
</div>
)
}
function CreateSessionModal({ onClose, onCreated }: {
onClose: () => void
onCreated: () => void
}) {
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [sessionType, setSessionType] = useState<'ucca' | 'dsfa' | 'custom'>('custom')
const [totalSteps, setTotalSteps] = useState(5)
const [saving, setSaving] = useState(false)
const handleCreate = async () => {
if (!title.trim()) return
setSaving(true)
try {
await api('', {
method: 'POST',
body: JSON.stringify({
title: title.trim(),
description: description.trim(),
session_type: sessionType,
total_steps: totalSteps,
}),
})
onCreated()
} catch (err) {
console.error('Create session error:', err)
} finally {
setSaving(false)
}
}
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-white rounded-2xl p-6 w-full max-w-lg" onClick={e => e.stopPropagation()}>
<h3 className="text-lg font-bold text-gray-900 mb-4">Neuer Workshop</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Titel *</label>
<input
type="text" value={title} onChange={e => setTitle(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
placeholder="z.B. DSFA Workshop Q1"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
<textarea
value={description} onChange={e => setDescription(e.target.value)}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
rows={3} placeholder="Beschreibung des Workshops..."
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Typ</label>
<select value={sessionType} onChange={e => setSessionType(e.target.value as 'ucca' | 'dsfa' | 'custom')}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
<option value="custom">Benutzerdefiniert</option>
<option value="ucca">UCCA Assessment</option>
<option value="dsfa">DSFA Workshop</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Schritte</label>
<input type="number" value={totalSteps} onChange={e => setTotalSteps(Number(e.target.value))}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500" min={1} max={50}
/>
</div>
</div>
</div>
<div className="flex justify-end gap-3 mt-6">
<button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
<button onClick={handleCreate} disabled={!title.trim() || saving}
className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
{saving ? 'Erstelle...' : 'Erstellen'}
</button>
</div>
</div>
</div>
)
}
function SessionDetailView({ session, onBack, onRefresh }: {
session: WorkshopSession
onBack: () => void
onRefresh: () => void
}) {
const [participants, setParticipants] = useState<Participant[]>([])
const [responses, setResponses] = useState<WorkshopResponse[]>([])
const [comments, setComments] = useState<WorkshopComment[]>([])
const [stats, setStats] = useState<SessionStats | null>(null)
const [activeTab, setActiveTab] = useState<'participants' | 'responses' | 'comments'>('participants')
const [loading, setLoading] = useState(true)
const loadDetails = useCallback(async () => {
setLoading(true)
try {
const [p, r, c, s] = await Promise.all([
api<Participant[]>(`/${session.id}/participants`).catch(() => []),
api<WorkshopResponse[]>(`/${session.id}/responses`).catch(() => []),
api<WorkshopComment[]>(`/${session.id}/comments`).catch(() => []),
api<SessionStats>(`/${session.id}/stats`).catch(() => null),
])
setParticipants(Array.isArray(p) ? p : [])
setResponses(Array.isArray(r) ? r : [])
setComments(Array.isArray(c) ? c : [])
setStats(s)
} finally {
setLoading(false)
}
}, [session.id])
useEffect(() => { loadDetails() }, [loadDetails])
const handleLifecycle = async (action: 'start' | 'pause' | 'complete') => {
try {
await api(`/${session.id}/${action}`, { method: 'POST' })
onRefresh()
} catch (err) {
console.error(`${action} error:`, err)
}
}
const handleExport = async () => {
try {
const data = await api(`/${session.id}/export`)
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url; a.download = `workshop-${session.id}.json`; a.click()
URL.revokeObjectURL(url)
} catch (err) {
console.error('Export error:', err)
}
}
const roleColors: Record<string, string> = {
FACILITATOR: 'bg-purple-100 text-purple-700',
EXPERT: 'bg-blue-100 text-blue-700',
STAKEHOLDER: 'bg-green-100 text-green-700',
OBSERVER: 'bg-gray-100 text-gray-700',
}
return (
<div>
<button onClick={onBack} className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-4">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
Zurueck zur Uebersicht
</button>
<div className="bg-white rounded-xl border-2 border-gray-200 p-6 mb-6">
<div className="flex items-start justify-between mb-4">
<div>
<h2 className="text-xl font-bold text-gray-900">{session.title}</h2>
<p className="text-sm text-gray-500 mt-1">{session.description}</p>
</div>
<span className={`px-3 py-1 text-sm rounded-full ${statusColors[session.status]}`}>
{statusLabels[session.status]}
</span>
</div>
{stats && (
<div className="grid grid-cols-4 gap-4 mb-4">
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-gray-900">{stats.total_participants}</div>
<div className="text-xs text-gray-500">Teilnehmer</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-gray-900">{stats.active_participants}</div>
<div className="text-xs text-gray-500">Aktiv</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-gray-900">{stats.total_responses}</div>
<div className="text-xs text-gray-500">Antworten</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 text-center">
<div className="text-2xl font-bold text-purple-600">{stats.progress}%</div>
<div className="text-xs text-gray-500">Fortschritt</div>
</div>
</div>
)}
<div className="flex items-center gap-3 mb-4">
<span className="text-sm text-gray-500">Join-Code: <code className="bg-gray-100 px-2 py-0.5 rounded font-mono">{session.join_code}</code></span>
<span className="text-sm text-gray-500">Typ: {typeLabels[session.session_type]}</span>
<span className="text-sm text-gray-500">Schritt {session.current_step}/{session.total_steps}</span>
</div>
<div className="flex gap-2">
{session.status === 'DRAFT' && (
<button onClick={() => handleLifecycle('start')} className="px-3 py-1.5 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700">Starten</button>
)}
{session.status === 'ACTIVE' && (
<button onClick={() => handleLifecycle('pause')} className="px-3 py-1.5 text-sm bg-yellow-600 text-white rounded-lg hover:bg-yellow-700">Pausieren</button>
)}
{(session.status === 'ACTIVE' || session.status === 'PAUSED') && (
<button onClick={() => handleLifecycle('complete')} className="px-3 py-1.5 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700">Abschliessen</button>
)}
<button onClick={handleExport} className="px-3 py-1.5 text-sm border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">Exportieren</button>
</div>
</div>
{/* Tabs */}
<div className="flex gap-1 mb-4 bg-gray-100 p-1 rounded-lg">
{(['participants', 'responses', 'comments'] as const).map(tab => (
<button key={tab} onClick={() => setActiveTab(tab)}
className={`flex-1 px-4 py-2 text-sm rounded-md transition-colors ${activeTab === tab ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'}`}>
{tab === 'participants' ? `Teilnehmer (${participants.length})` :
tab === 'responses' ? `Antworten (${responses.length})` :
`Kommentare (${comments.length})`}
</button>
))}
</div>
{loading ? (
<div className="text-center py-8 text-gray-500">Laden...</div>
) : (
<>
{activeTab === 'participants' && (
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
<table className="w-full">
<thead className="bg-gray-50">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Name</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Rolle</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Abteilung</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Beigetreten</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{participants.map(p => (
<tr key={p.id} className="hover:bg-gray-50">
<td className="px-4 py-3">
<div className="font-medium text-gray-900">{p.name}</div>
<div className="text-xs text-gray-500">{p.email}</div>
</td>
<td className="px-4 py-3">
<span className={`px-2 py-0.5 text-xs rounded-full ${roleColors[p.role] || 'bg-gray-100 text-gray-700'}`}>
{p.role}
</span>
</td>
<td className="px-4 py-3 text-sm text-gray-600">{p.department || '-'}</td>
<td className="px-4 py-3">
<span className={`inline-block w-2 h-2 rounded-full ${p.is_active ? 'bg-green-500' : 'bg-gray-300'}`} />
</td>
<td className="px-4 py-3 text-sm text-gray-500">
{new Date(p.joined_at).toLocaleDateString('de-DE')}
</td>
</tr>
))}
{participants.length === 0 && (
<tr><td colSpan={5} className="px-4 py-8 text-center text-gray-500">Keine Teilnehmer</td></tr>
)}
</tbody>
</table>
</div>
)}
{activeTab === 'responses' && (
<div className="space-y-3">
{responses.map(r => (
<div key={r.id} className="bg-white rounded-lg border border-gray-200 p-4">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium text-gray-900">Schritt {r.step_number} / {r.field_id}</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${
r.response_status === 'SUBMITTED' ? 'bg-green-100 text-green-700' :
r.response_status === 'REVIEWED' ? 'bg-purple-100 text-purple-700' :
'bg-gray-100 text-gray-700'
}`}>{r.response_status}</span>
</div>
<pre className="text-sm text-gray-600 bg-gray-50 p-2 rounded overflow-auto max-h-32">
{typeof r.value === 'string' ? r.value : JSON.stringify(r.value, null, 2)}
</pre>
<div className="text-xs text-gray-400 mt-2">
{new Date(r.created_at).toLocaleString('de-DE')}
</div>
</div>
))}
{responses.length === 0 && (
<div className="text-center py-8 text-gray-500">Keine Antworten</div>
)}
</div>
)}
{activeTab === 'comments' && (
<div className="space-y-3">
{comments.map(c => (
<div key={c.id} className={`bg-white rounded-lg border p-4 ${c.is_resolved ? 'border-green-200' : 'border-gray-200'}`}>
<div className="flex items-center justify-between mb-2">
{c.step_number != null && <span className="text-xs text-gray-500">Schritt {c.step_number}</span>}
{c.is_resolved && <span className="text-xs text-green-600">Geloest</span>}
</div>
<p className="text-sm text-gray-700">{c.text}</p>
<div className="text-xs text-gray-400 mt-2">
{new Date(c.created_at).toLocaleString('de-DE')}
</div>
</div>
))}
{comments.length === 0 && (
<div className="text-center py-8 text-gray-500">Keine Kommentare</div>
)}
</div>
)}
</>
)}
</div>
)
}
// =============================================================================
// MAIN PAGE
// =============================================================================
export default function WorkshopPage() {
const { setCurrentModule } = useSDK()
const [sessions, setSessions] = useState<WorkshopSession[]>([])
const [loading, setLoading] = useState(true)
const [showCreate, setShowCreate] = useState(false)
const [selectedSession, setSelectedSession] = useState<WorkshopSession | null>(null)
const [filter, setFilter] = useState<string>('all')
useEffect(() => {
setCurrentModule('workshop')
}, [setCurrentModule])
const loadSessions = useCallback(async () => {
setLoading(true)
try {
const data = await api<WorkshopSession[] | { sessions: WorkshopSession[] }>('')
const list = Array.isArray(data) ? data : (data.sessions || [])
setSessions(list)
} catch (err) {
console.error('Load sessions error:', err)
} finally {
setLoading(false)
}
}, [])
useEffect(() => { loadSessions() }, [loadSessions])
const handleDelete = async (id: string) => {
if (!confirm('Workshop wirklich loeschen?')) return
try {
await api(`/${id}`, { method: 'DELETE' })
setSessions(prev => prev.filter(s => s.id !== id))
} catch (err) {
console.error('Delete error:', err)
}
}
const filteredSessions = filter === 'all'
? sessions
: sessions.filter(s => s.status === filter)
if (selectedSession) {
return (
<div className="p-6 max-w-6xl mx-auto">
<SessionDetailView
session={selectedSession}
onBack={() => { setSelectedSession(null); loadSessions() }}
onRefresh={() => {
loadSessions().then(() => {
const updated = sessions.find(s => s.id === selectedSession.id)
if (updated) setSelectedSession(updated)
})
}}
/>
</div>
)
}
return (
<div className="p-6 max-w-6xl mx-auto">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-gray-900">Compliance Workshops</h1>
<p className="text-sm text-gray-500 mt-1">
Kollaborative Workshops fuer DSFA, UCCA und andere Compliance-Prozesse
</p>
</div>
<button onClick={() => setShowCreate(true)}
className="px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700 flex items-center gap-2">
<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>
Neuer Workshop
</button>
</div>
{/* Stats */}
<div className="grid grid-cols-4 gap-4 mb-6">
{[
{ label: 'Gesamt', value: sessions.length, color: 'text-gray-900' },
{ label: 'Aktiv', value: sessions.filter(s => s.status === 'ACTIVE').length, color: 'text-green-600' },
{ label: 'Entwurf', value: sessions.filter(s => s.status === 'DRAFT').length, color: 'text-gray-600' },
{ label: 'Abgeschlossen', value: sessions.filter(s => s.status === 'COMPLETED').length, color: 'text-purple-600' },
].map(stat => (
<div key={stat.label} className="bg-white rounded-xl border border-gray-200 p-4 text-center">
<div className={`text-2xl font-bold ${stat.color}`}>{stat.value}</div>
<div className="text-xs text-gray-500">{stat.label}</div>
</div>
))}
</div>
{/* Filter */}
<div className="flex gap-2 mb-6">
{['all', 'DRAFT', 'ACTIVE', 'PAUSED', 'COMPLETED'].map(f => (
<button key={f} onClick={() => setFilter(f)}
className={`px-3 py-1.5 text-sm rounded-lg ${filter === f ? 'bg-purple-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>
{f === 'all' ? 'Alle' : statusLabels[f] || f}
</button>
))}
</div>
{loading ? (
<div className="text-center py-12 text-gray-500">Workshops werden geladen...</div>
) : filteredSessions.length === 0 ? (
<div className="text-center py-12">
<div className="text-gray-400 mb-2">
<svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
</div>
<p className="text-gray-500">Keine Workshops gefunden</p>
<button onClick={() => setShowCreate(true)} className="mt-3 text-sm text-purple-600 hover:text-purple-700">
Ersten Workshop erstellen
</button>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filteredSessions.map(s => (
<SessionCard key={s.id} session={s} onSelect={setSelectedSession} onDelete={handleDelete} />
))}
</div>
)}
{showCreate && (
<CreateSessionModal onClose={() => setShowCreate(false)} onCreated={() => { setShowCreate(false); loadSessions() }} />
)}
</div>
)
}

View File

@@ -623,6 +623,66 @@ export function SDKSidebar({ collapsed = false, onCollapsedChange }: SDKSidebarP
isActive={pathname?.startsWith('/sdk/agents') ?? false}
collapsed={collapsed}
/>
<AdditionalModuleItem
href="/sdk/workshop"
icon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
}
label="Workshop"
isActive={pathname === '/sdk/workshop'}
collapsed={collapsed}
/>
<AdditionalModuleItem
href="/sdk/portfolio"
icon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
}
label="Portfolio"
isActive={pathname === '/sdk/portfolio'}
collapsed={collapsed}
/>
<AdditionalModuleItem
href="/sdk/roadmap"
icon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2" />
</svg>
}
label="Roadmap"
isActive={pathname === '/sdk/roadmap'}
collapsed={collapsed}
/>
<AdditionalModuleItem
href="/sdk/audit-llm"
icon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
}
label="LLM Audit"
isActive={pathname === '/sdk/audit-llm'}
collapsed={collapsed}
/>
<AdditionalModuleItem
href="/sdk/rbac"
icon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
</svg>
}
label="RBAC Admin"
isActive={pathname === '/sdk/rbac'}
collapsed={collapsed}
/>
<AdditionalModuleItem
href="/sdk/catalog-manager"
icon={