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
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:
108
admin-compliance/app/api/sdk/v1/audit-llm/[[...path]]/route.ts
Normal file
108
admin-compliance/app/api/sdk/v1/audit-llm/[[...path]]/route.ts
Normal 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')
|
||||
}
|
||||
@@ -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')
|
||||
125
admin-compliance/app/api/sdk/v1/rbac/[[...path]]/route.ts
Normal file
125
admin-compliance/app/api/sdk/v1/rbac/[[...path]]/route.ts
Normal 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')
|
||||
}
|
||||
@@ -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')
|
||||
}
|
||||
@@ -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 }
|
||||
119
admin-compliance/app/api/sdk/v1/workshops/[[...path]]/route.ts
Normal file
119
admin-compliance/app/api/sdk/v1/workshops/[[...path]]/route.ts
Normal 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')
|
||||
}
|
||||
561
admin-compliance/app/sdk/audit-llm/page.tsx
Normal file
561
admin-compliance/app/sdk/audit-llm/page.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
658
admin-compliance/app/sdk/portfolio/page.tsx
Normal file
658
admin-compliance/app/sdk/portfolio/page.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
1023
admin-compliance/app/sdk/rbac/page.tsx
Normal file
1023
admin-compliance/app/sdk/rbac/page.tsx
Normal file
File diff suppressed because it is too large
Load Diff
882
admin-compliance/app/sdk/roadmap/page.tsx
Normal file
882
admin-compliance/app/sdk/roadmap/page.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
616
admin-compliance/app/sdk/workshop/page.tsx
Normal file
616
admin-compliance/app/sdk/workshop/page.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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={
|
||||
|
||||
@@ -12,17 +12,14 @@ import (
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/api/handlers"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/audit"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/config"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/dsgvo"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/llm"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/academy"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/incidents"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/roadmap"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/training"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/ucca"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/whistleblower"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/iace"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/vendor"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/workshop"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/portfolio"
|
||||
"github.com/gin-contrib/cors"
|
||||
@@ -59,7 +56,6 @@ func main() {
|
||||
// Initialize stores
|
||||
rbacStore := rbac.NewStore(pool)
|
||||
auditStore := audit.NewStore(pool)
|
||||
dsgvoStore := dsgvo.NewStore(pool)
|
||||
uccaStore := ucca.NewStore(pool)
|
||||
escalationStore := ucca.NewEscalationStore(pool)
|
||||
corpusVersionStore := ucca.NewCorpusVersionStore(pool)
|
||||
@@ -68,8 +64,6 @@ func main() {
|
||||
portfolioStore := portfolio.NewStore(pool)
|
||||
academyStore := academy.NewStore(pool)
|
||||
whistleblowerStore := whistleblower.NewStore(pool)
|
||||
incidentStore := incidents.NewStore(pool)
|
||||
vendorStore := vendor.NewStore(pool)
|
||||
iaceStore := iace.NewStore(pool)
|
||||
trainingStore := training.NewStore(pool)
|
||||
|
||||
@@ -108,17 +102,13 @@ func main() {
|
||||
rbacHandlers := handlers.NewRBACHandlers(rbacStore, rbacService, policyEngine)
|
||||
llmHandlers := handlers.NewLLMHandlers(accessGate, providerRegistry, piiDetector, auditStore, trailBuilder)
|
||||
auditHandlers := handlers.NewAuditHandlers(auditStore, exporter)
|
||||
dsgvoHandlers := handlers.NewDSGVOHandlers(dsgvoStore)
|
||||
uccaHandlers := handlers.NewUCCAHandlers(uccaStore, escalationStore, providerRegistry)
|
||||
escalationHandlers := handlers.NewEscalationHandlers(escalationStore, uccaStore)
|
||||
roadmapHandlers := handlers.NewRoadmapHandlers(roadmapStore)
|
||||
workshopHandlers := handlers.NewWorkshopHandlers(workshopStore)
|
||||
portfolioHandlers := handlers.NewPortfolioHandlers(portfolioStore)
|
||||
draftingHandlers := handlers.NewDraftingHandlers(accessGate, providerRegistry, piiDetector, auditStore, trailBuilder)
|
||||
academyHandlers := handlers.NewAcademyHandlers(academyStore, trainingStore)
|
||||
whistleblowerHandlers := handlers.NewWhistleblowerHandlers(whistleblowerStore)
|
||||
incidentHandlers := handlers.NewIncidentHandlers(incidentStore)
|
||||
vendorHandlers := handlers.NewVendorHandlers(vendorStore)
|
||||
iaceHandler := handlers.NewIACEHandler(iaceStore)
|
||||
trainingHandlers := handlers.NewTrainingHandlers(trainingStore, contentGenerator)
|
||||
ragHandlers := handlers.NewRAGHandlers(corpusVersionStore)
|
||||
@@ -245,74 +235,6 @@ func main() {
|
||||
auditRoutes.GET("/export/compliance", auditHandlers.ExportComplianceReport)
|
||||
}
|
||||
|
||||
// DSGVO routes (Art. 30, 32, 35, 15-22 DSGVO)
|
||||
dsgvoRoutes := v1.Group("/dsgvo")
|
||||
{
|
||||
// Statistics
|
||||
dsgvoRoutes.GET("/stats", dsgvoHandlers.GetStats)
|
||||
|
||||
// DEPRECATED: VVT routes - frontend uses backend-compliance proxy instead
|
||||
// VVT - Verarbeitungsverzeichnis (Art. 30)
|
||||
vvt := dsgvoRoutes.Group("/processing-activities")
|
||||
{
|
||||
vvt.GET("", dsgvoHandlers.ListProcessingActivities)
|
||||
vvt.GET("/:id", dsgvoHandlers.GetProcessingActivity)
|
||||
vvt.POST("", dsgvoHandlers.CreateProcessingActivity)
|
||||
vvt.PUT("/:id", dsgvoHandlers.UpdateProcessingActivity)
|
||||
vvt.DELETE("/:id", dsgvoHandlers.DeleteProcessingActivity)
|
||||
}
|
||||
|
||||
// TOM - Technische und Organisatorische Maßnahmen (Art. 32)
|
||||
// DEPRECATED: TOM is now managed by backend-compliance (Python).
|
||||
// Use: GET/POST /api/compliance/tom/state, /tom/measures, /tom/stats, /tom/export
|
||||
tom := dsgvoRoutes.Group("/tom")
|
||||
{
|
||||
tom.GET("", dsgvoHandlers.ListTOMs)
|
||||
tom.GET("/:id", dsgvoHandlers.GetTOM)
|
||||
tom.POST("", dsgvoHandlers.CreateTOM)
|
||||
}
|
||||
|
||||
// DSR - Data Subject Requests / Betroffenenrechte (Art. 15-22)
|
||||
// DEPRECATED: DSR is now managed by backend-compliance (Python).
|
||||
// Use: GET/POST/PUT /api/compliance/dsr/* on backend-compliance:8002
|
||||
dsr := dsgvoRoutes.Group("/dsr")
|
||||
{
|
||||
dsr.GET("", dsgvoHandlers.ListDSRs)
|
||||
dsr.GET("/:id", dsgvoHandlers.GetDSR)
|
||||
dsr.POST("", dsgvoHandlers.CreateDSR)
|
||||
dsr.PUT("/:id", dsgvoHandlers.UpdateDSR)
|
||||
}
|
||||
|
||||
// Retention Policies - Löschfristen (Art. 17)
|
||||
retention := dsgvoRoutes.Group("/retention-policies")
|
||||
{
|
||||
retention.GET("", dsgvoHandlers.ListRetentionPolicies)
|
||||
retention.POST("", dsgvoHandlers.CreateRetentionPolicy)
|
||||
}
|
||||
|
||||
// DSFA - Datenschutz-Folgenabschätzung (Art. 35)
|
||||
// DEPRECATED: DSFA migrated to backend-compliance (Python/FastAPI).
|
||||
// Use backend-compliance /api/compliance/dsfa/* instead.
|
||||
dsfa := dsgvoRoutes.Group("/dsfa")
|
||||
{
|
||||
dsfa.GET("", dsgvoHandlers.ListDSFAs)
|
||||
dsfa.GET("/:id", dsgvoHandlers.GetDSFA)
|
||||
dsfa.POST("", dsgvoHandlers.CreateDSFA)
|
||||
dsfa.PUT("/:id", dsgvoHandlers.UpdateDSFA)
|
||||
dsfa.DELETE("/:id", dsgvoHandlers.DeleteDSFA)
|
||||
dsfa.GET("/:id/export", dsgvoHandlers.ExportDSFA)
|
||||
}
|
||||
|
||||
// Export routes
|
||||
exports := dsgvoRoutes.Group("/export")
|
||||
{
|
||||
exports.GET("/vvt", dsgvoHandlers.ExportVVT) // DEPRECATED: use backend-compliance /vvt/export?format=csv
|
||||
exports.GET("/tom", dsgvoHandlers.ExportTOM) // DEPRECATED: use backend-compliance /tom/export?format=csv
|
||||
exports.GET("/dsr", dsgvoHandlers.ExportDSR) // DEPRECATED: use backend-compliance /dsr/export?format=csv
|
||||
exports.GET("/retention", dsgvoHandlers.ExportRetentionPolicies)
|
||||
}
|
||||
}
|
||||
|
||||
// UCCA routes - Use-Case Compliance & Feasibility Advisor
|
||||
uccaRoutes := v1.Group("/ucca")
|
||||
{
|
||||
@@ -338,16 +260,7 @@ func main() {
|
||||
// Export
|
||||
uccaRoutes.GET("/export/:id", uccaHandlers.Export)
|
||||
|
||||
// Statistics
|
||||
uccaRoutes.GET("/stats", uccaHandlers.GetStats)
|
||||
|
||||
// Wizard routes - Legal Assistant integrated
|
||||
uccaRoutes.GET("/wizard/schema", uccaHandlers.GetWizardSchema)
|
||||
uccaRoutes.POST("/wizard/ask", uccaHandlers.AskWizardQuestion)
|
||||
|
||||
// DEPRECATED: UCCA Escalation management (E0-E3 workflow)
|
||||
// Frontend uses Python backend-compliance escalation_routes.py (/api/compliance/escalations).
|
||||
// These UCCA-specific routes remain for assessment-review workflows only.
|
||||
// Escalation management (assessment-review workflows)
|
||||
uccaRoutes.GET("/escalations", escalationHandlers.ListEscalations)
|
||||
uccaRoutes.GET("/escalations/stats", escalationHandlers.GetEscalationStats)
|
||||
uccaRoutes.GET("/escalations/:id", escalationHandlers.GetEscalation)
|
||||
@@ -356,10 +269,6 @@ func main() {
|
||||
uccaRoutes.POST("/escalations/:id/review", escalationHandlers.StartReview)
|
||||
uccaRoutes.POST("/escalations/:id/decide", escalationHandlers.DecideEscalation)
|
||||
|
||||
// DEPRECATED: DSB Pool management — see note above
|
||||
uccaRoutes.GET("/dsb-pool", escalationHandlers.ListDSBPool)
|
||||
uccaRoutes.POST("/dsb-pool", escalationHandlers.AddDSBPoolMember)
|
||||
|
||||
// Obligations framework (v2 with TOM mapping)
|
||||
obligationsHandlers.RegisterRoutes(uccaRoutes)
|
||||
}
|
||||
@@ -477,15 +386,6 @@ func main() {
|
||||
portfolioRoutes.POST("/compare", portfolioHandlers.ComparePortfolios)
|
||||
}
|
||||
|
||||
// Drafting Engine routes - Compliance Document Drafting & Validation
|
||||
draftingRoutes := v1.Group("/drafting")
|
||||
draftingRoutes.Use(rbacMiddleware.RequireLLMAccess())
|
||||
{
|
||||
draftingRoutes.POST("/draft", draftingHandlers.DraftDocument)
|
||||
draftingRoutes.POST("/validate", draftingHandlers.ValidateDocument)
|
||||
draftingRoutes.GET("/history", draftingHandlers.GetDraftHistory)
|
||||
}
|
||||
|
||||
// Academy routes - E-Learning / Compliance Training
|
||||
academyRoutes := v1.Group("/academy")
|
||||
{
|
||||
@@ -616,82 +516,6 @@ func main() {
|
||||
whistleblowerRoutes.GET("/stats", whistleblowerHandlers.GetStatistics)
|
||||
}
|
||||
|
||||
// DEPRECATED: Incidents routes — Python backend is now Source of Truth.
|
||||
// Frontend proxies to backend-compliance:8002/api/compliance/incidents/*
|
||||
// These Go routes remain registered but should not be extended.
|
||||
incidentRoutes := v1.Group("/incidents")
|
||||
{
|
||||
// Incident CRUD
|
||||
incidentRoutes.POST("", incidentHandlers.CreateIncident)
|
||||
incidentRoutes.GET("", incidentHandlers.ListIncidents)
|
||||
incidentRoutes.GET("/:id", incidentHandlers.GetIncident)
|
||||
incidentRoutes.PUT("/:id", incidentHandlers.UpdateIncident)
|
||||
incidentRoutes.DELETE("/:id", incidentHandlers.DeleteIncident)
|
||||
|
||||
// Risk Assessment
|
||||
incidentRoutes.POST("/:id/assess-risk", incidentHandlers.AssessRisk)
|
||||
|
||||
// Authority Notification (Art. 33)
|
||||
incidentRoutes.POST("/:id/notify-authority", incidentHandlers.SubmitAuthorityNotification)
|
||||
|
||||
// Data Subject Notification (Art. 34)
|
||||
incidentRoutes.POST("/:id/notify-subjects", incidentHandlers.NotifyDataSubjects)
|
||||
|
||||
// Measures
|
||||
incidentRoutes.POST("/:id/measures", incidentHandlers.AddMeasure)
|
||||
incidentRoutes.PUT("/:id/measures/:measureId", incidentHandlers.UpdateMeasure)
|
||||
incidentRoutes.POST("/:id/measures/:measureId/complete", incidentHandlers.CompleteMeasure)
|
||||
|
||||
// Timeline
|
||||
incidentRoutes.POST("/:id/timeline", incidentHandlers.AddTimelineEntry)
|
||||
|
||||
// Lifecycle
|
||||
incidentRoutes.POST("/:id/close", incidentHandlers.CloseIncident)
|
||||
|
||||
// Statistics
|
||||
incidentRoutes.GET("/stats", incidentHandlers.GetStatistics)
|
||||
}
|
||||
|
||||
// DEPRECATED: Vendor Compliance routes — Python backend is now Source of Truth.
|
||||
// Frontend proxies to backend-compliance:8002/api/compliance/vendor-compliance/*
|
||||
// These Go routes remain registered but should not be extended.
|
||||
vendorRoutes := v1.Group("/vendors")
|
||||
{
|
||||
// Vendor CRUD
|
||||
vendorRoutes.POST("", vendorHandlers.CreateVendor)
|
||||
vendorRoutes.GET("", vendorHandlers.ListVendors)
|
||||
vendorRoutes.GET("/:id", vendorHandlers.GetVendor)
|
||||
vendorRoutes.PUT("/:id", vendorHandlers.UpdateVendor)
|
||||
vendorRoutes.DELETE("/:id", vendorHandlers.DeleteVendor)
|
||||
|
||||
// Contracts (AVV/DPA)
|
||||
vendorRoutes.POST("/contracts", vendorHandlers.CreateContract)
|
||||
vendorRoutes.GET("/contracts", vendorHandlers.ListContracts)
|
||||
vendorRoutes.GET("/contracts/:id", vendorHandlers.GetContract)
|
||||
vendorRoutes.PUT("/contracts/:id", vendorHandlers.UpdateContract)
|
||||
vendorRoutes.DELETE("/contracts/:id", vendorHandlers.DeleteContract)
|
||||
|
||||
// Findings
|
||||
vendorRoutes.POST("/findings", vendorHandlers.CreateFinding)
|
||||
vendorRoutes.GET("/findings", vendorHandlers.ListFindings)
|
||||
vendorRoutes.GET("/findings/:id", vendorHandlers.GetFinding)
|
||||
vendorRoutes.PUT("/findings/:id", vendorHandlers.UpdateFinding)
|
||||
vendorRoutes.POST("/findings/:id/resolve", vendorHandlers.ResolveFinding)
|
||||
|
||||
// Control Instances
|
||||
vendorRoutes.POST("/controls", vendorHandlers.UpsertControlInstance)
|
||||
vendorRoutes.GET("/controls", vendorHandlers.ListControlInstances)
|
||||
|
||||
// Templates
|
||||
vendorRoutes.GET("/templates", vendorHandlers.ListTemplates)
|
||||
vendorRoutes.GET("/templates/:templateId", vendorHandlers.GetTemplate)
|
||||
vendorRoutes.POST("/templates", vendorHandlers.CreateTemplate)
|
||||
vendorRoutes.POST("/templates/:templateId/apply", vendorHandlers.ApplyTemplate)
|
||||
|
||||
// Statistics
|
||||
vendorRoutes.GET("/stats", vendorHandlers.GetStatistics)
|
||||
}
|
||||
|
||||
// IACE routes - Industrial AI Compliance Engine (CE-Risikobeurteilung SW/FW/KI)
|
||||
iaceRoutes := v1.Group("/iace")
|
||||
{
|
||||
|
||||
@@ -1,336 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/audit"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/llm"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// DraftingHandlers handles Drafting Engine API endpoints
|
||||
type DraftingHandlers struct {
|
||||
accessGate *llm.AccessGate
|
||||
registry *llm.ProviderRegistry
|
||||
piiDetector *llm.PIIDetector
|
||||
auditStore *audit.Store
|
||||
trailBuilder *audit.TrailBuilder
|
||||
}
|
||||
|
||||
// NewDraftingHandlers creates new Drafting Engine handlers
|
||||
func NewDraftingHandlers(
|
||||
accessGate *llm.AccessGate,
|
||||
registry *llm.ProviderRegistry,
|
||||
piiDetector *llm.PIIDetector,
|
||||
auditStore *audit.Store,
|
||||
trailBuilder *audit.TrailBuilder,
|
||||
) *DraftingHandlers {
|
||||
return &DraftingHandlers{
|
||||
accessGate: accessGate,
|
||||
registry: registry,
|
||||
piiDetector: piiDetector,
|
||||
auditStore: auditStore,
|
||||
trailBuilder: trailBuilder,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Request/Response Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// DraftDocumentRequest represents a request to generate a compliance document draft
|
||||
type DraftDocumentRequest struct {
|
||||
DocumentType string `json:"document_type" binding:"required"`
|
||||
ScopeLevel string `json:"scope_level" binding:"required"`
|
||||
Context map[string]interface{} `json:"context"`
|
||||
Instructions string `json:"instructions"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
|
||||
// ValidateDocumentRequest represents a request to validate document consistency
|
||||
type ValidateDocumentRequest struct {
|
||||
DocumentType string `json:"document_type" binding:"required"`
|
||||
DraftContent string `json:"draft_content"`
|
||||
ValidationContext map[string]interface{} `json:"validation_context"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
|
||||
// DraftHistoryEntry represents a single audit trail entry for drafts
|
||||
type DraftHistoryEntry struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
TenantID string `json:"tenant_id"`
|
||||
DocumentType string `json:"document_type"`
|
||||
ScopeLevel string `json:"scope_level"`
|
||||
Operation string `json:"operation"`
|
||||
ConstraintsRespected bool `json:"constraints_respected"`
|
||||
TokensUsed int `json:"tokens_used"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// DraftDocument handles document draft generation via LLM with constraint validation
|
||||
func (h *DraftingHandlers) DraftDocument(c *gin.Context) {
|
||||
var req DraftDocumentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
namespaceID := rbac.GetNamespaceID(c)
|
||||
|
||||
if userID == uuid.Nil || tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "authentication required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate scope level
|
||||
validLevels := map[string]bool{"L1": true, "L2": true, "L3": true, "L4": true}
|
||||
if !validLevels[req.ScopeLevel] {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid scope_level, must be L1-L4"})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate document type
|
||||
validTypes := map[string]bool{
|
||||
"vvt": true, "tom": true, "dsfa": true, "dsi": true, "lf": true,
|
||||
"av_vertrag": true, "betroffenenrechte": true, "einwilligung": true,
|
||||
"daten_transfer": true, "datenpannen": true, "vertragsmanagement": true,
|
||||
"schulung": true, "audit_log": true, "risikoanalyse": true,
|
||||
"notfallplan": true, "zertifizierung": true, "datenschutzmanagement": true,
|
||||
"iace_ce_assessment": true,
|
||||
}
|
||||
if !validTypes[req.DocumentType] {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid document_type"})
|
||||
return
|
||||
}
|
||||
|
||||
// Build system prompt for drafting
|
||||
systemPrompt := fmt.Sprintf(
|
||||
`Du bist ein DSGVO-Compliance-Experte. Erstelle einen strukturierten Entwurf fuer Dokument "%s" auf Level %s.
|
||||
Antworte NUR im JSON-Format mit einem "sections" Array.
|
||||
Jede Section hat: id, title, content, schemaField.
|
||||
Halte die Tiefe strikt am vorgegebenen Level.
|
||||
Markiere fehlende Informationen mit [PLATZHALTER: Beschreibung].
|
||||
Sprache: Deutsch.`,
|
||||
req.DocumentType, req.ScopeLevel,
|
||||
)
|
||||
|
||||
userPrompt := "Erstelle den Dokumententwurf."
|
||||
if req.Instructions != "" {
|
||||
userPrompt = req.Instructions
|
||||
}
|
||||
|
||||
// Detect PII in context
|
||||
contextStr := fmt.Sprintf("%v", req.Context)
|
||||
dataCategories := h.piiDetector.DetectDataCategories(contextStr)
|
||||
|
||||
// Process through access gate
|
||||
chatReq := &llm.ChatRequest{
|
||||
Model: req.Model,
|
||||
Messages: []llm.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: userPrompt},
|
||||
},
|
||||
MaxTokens: 16384,
|
||||
Temperature: 0.15,
|
||||
}
|
||||
|
||||
gatedReq, err := h.accessGate.ProcessChatRequest(
|
||||
c.Request.Context(),
|
||||
userID, tenantID, namespaceID,
|
||||
chatReq, dataCategories,
|
||||
)
|
||||
if err != nil {
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, req.ScopeLevel, "draft", false, 0, err.Error())
|
||||
c.JSON(http.StatusForbidden, gin.H{
|
||||
"error": "access_denied",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Execute the request
|
||||
resp, err := h.accessGate.ExecuteChat(c.Request.Context(), gatedReq)
|
||||
if err != nil {
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, req.ScopeLevel, "draft", false, 0, err.Error())
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "llm_error",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
tokensUsed := 0
|
||||
if resp.Usage.TotalTokens > 0 {
|
||||
tokensUsed = resp.Usage.TotalTokens
|
||||
}
|
||||
|
||||
// Log successful draft
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, req.ScopeLevel, "draft", true, tokensUsed, "")
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"document_type": req.DocumentType,
|
||||
"scope_level": req.ScopeLevel,
|
||||
"content": resp.Message.Content,
|
||||
"model": resp.Model,
|
||||
"provider": resp.Provider,
|
||||
"tokens_used": tokensUsed,
|
||||
"pii_detected": gatedReq.PIIDetected,
|
||||
})
|
||||
}
|
||||
|
||||
// ValidateDocument handles document cross-consistency validation
|
||||
func (h *DraftingHandlers) ValidateDocument(c *gin.Context) {
|
||||
var req ValidateDocumentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
namespaceID := rbac.GetNamespaceID(c)
|
||||
|
||||
if userID == uuid.Nil || tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "authentication required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Build validation prompt
|
||||
systemPrompt := `Du bist ein DSGVO-Compliance-Validator. Pruefe die Konsistenz und Vollstaendigkeit.
|
||||
Antworte NUR im JSON-Format:
|
||||
{
|
||||
"passed": boolean,
|
||||
"errors": [{"id": string, "severity": "error", "title": string, "description": string, "documentType": string, "legalReference": string}],
|
||||
"warnings": [{"id": string, "severity": "warning", "title": string, "description": string}],
|
||||
"suggestions": [{"id": string, "severity": "suggestion", "title": string, "description": string, "suggestion": string}]
|
||||
}`
|
||||
|
||||
validationPrompt := fmt.Sprintf("Validiere Dokument '%s'.\nInhalt:\n%s\nKontext:\n%v",
|
||||
req.DocumentType, req.DraftContent, req.ValidationContext)
|
||||
|
||||
// Detect PII
|
||||
dataCategories := h.piiDetector.DetectDataCategories(req.DraftContent)
|
||||
|
||||
chatReq := &llm.ChatRequest{
|
||||
Model: req.Model,
|
||||
Messages: []llm.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: validationPrompt},
|
||||
},
|
||||
MaxTokens: 8192,
|
||||
Temperature: 0.1,
|
||||
}
|
||||
|
||||
gatedReq, err := h.accessGate.ProcessChatRequest(
|
||||
c.Request.Context(),
|
||||
userID, tenantID, namespaceID,
|
||||
chatReq, dataCategories,
|
||||
)
|
||||
if err != nil {
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, "", "validate", false, 0, err.Error())
|
||||
c.JSON(http.StatusForbidden, gin.H{
|
||||
"error": "access_denied",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.accessGate.ExecuteChat(c.Request.Context(), gatedReq)
|
||||
if err != nil {
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, "", "validate", false, 0, err.Error())
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "llm_error",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
tokensUsed := 0
|
||||
if resp.Usage.TotalTokens > 0 {
|
||||
tokensUsed = resp.Usage.TotalTokens
|
||||
}
|
||||
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, "", "validate", true, tokensUsed, "")
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"document_type": req.DocumentType,
|
||||
"validation": resp.Message.Content,
|
||||
"model": resp.Model,
|
||||
"provider": resp.Provider,
|
||||
"tokens_used": tokensUsed,
|
||||
"pii_detected": gatedReq.PIIDetected,
|
||||
})
|
||||
}
|
||||
|
||||
// GetDraftHistory returns the audit trail of all drafting operations for a tenant
|
||||
func (h *DraftingHandlers) GetDraftHistory(c *gin.Context) {
|
||||
userID := rbac.GetUserID(c)
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
if userID == uuid.Nil || tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "authentication required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Query audit store for drafting operations
|
||||
entries, _, err := h.auditStore.QueryGeneralAuditEntries(c.Request.Context(), &audit.GeneralAuditFilter{
|
||||
TenantID: tenantID,
|
||||
ResourceType: "compliance_document",
|
||||
Limit: 50,
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to query draft history"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"history": entries,
|
||||
"total": len(entries),
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Audit Logging
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func (h *DraftingHandlers) logDraftAudit(
|
||||
c *gin.Context,
|
||||
userID, tenantID uuid.UUID,
|
||||
documentType, scopeLevel, operation string,
|
||||
constraintsRespected bool,
|
||||
tokensUsed int,
|
||||
errorMsg string,
|
||||
) {
|
||||
newValues := map[string]any{
|
||||
"document_type": documentType,
|
||||
"scope_level": scopeLevel,
|
||||
"constraints_respected": constraintsRespected,
|
||||
"tokens_used": tokensUsed,
|
||||
}
|
||||
if errorMsg != "" {
|
||||
newValues["error"] = errorMsg
|
||||
}
|
||||
|
||||
entry := h.trailBuilder.NewGeneralEntry().
|
||||
WithTenant(tenantID).
|
||||
WithUser(userID).
|
||||
WithAction("drafting_engine." + operation).
|
||||
WithResource("compliance_document", nil).
|
||||
WithNewValues(newValues).
|
||||
WithClient(c.ClientIP(), c.GetHeader("User-Agent"))
|
||||
|
||||
go func() {
|
||||
entry.Save(c.Request.Context())
|
||||
}()
|
||||
}
|
||||
@@ -1,802 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/dsgvo"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// DSGVOHandlers handles DSGVO-related API endpoints
|
||||
type DSGVOHandlers struct {
|
||||
store *dsgvo.Store
|
||||
}
|
||||
|
||||
// NewDSGVOHandlers creates new DSGVO handlers
|
||||
func NewDSGVOHandlers(store *dsgvo.Store) *DSGVOHandlers {
|
||||
return &DSGVOHandlers{store: store}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// VVT - Verarbeitungsverzeichnis (Processing Activities)
|
||||
// DEPRECATED: VVT is now managed by backend-compliance (Python).
|
||||
// These handlers will be removed once all DSGVO sub-modules are consolidated.
|
||||
// ============================================================================
|
||||
|
||||
// ListProcessingActivities returns all processing activities for a tenant
|
||||
func (h *DSGVOHandlers) ListProcessingActivities(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var namespaceID *uuid.UUID
|
||||
if nsID := c.Query("namespace_id"); nsID != "" {
|
||||
if id, err := uuid.Parse(nsID); err == nil {
|
||||
namespaceID = &id
|
||||
}
|
||||
}
|
||||
|
||||
activities, err := h.store.ListProcessingActivities(c.Request.Context(), tenantID, namespaceID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"processing_activities": activities})
|
||||
}
|
||||
|
||||
// GetProcessingActivity returns a processing activity by ID
|
||||
func (h *DSGVOHandlers) GetProcessingActivity(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
activity, err := h.store.GetProcessingActivity(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if activity == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, activity)
|
||||
}
|
||||
|
||||
// CreateProcessingActivity creates a new processing activity
|
||||
func (h *DSGVOHandlers) CreateProcessingActivity(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var activity dsgvo.ProcessingActivity
|
||||
if err := c.ShouldBindJSON(&activity); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
activity.TenantID = tenantID
|
||||
activity.CreatedBy = userID
|
||||
if activity.Status == "" {
|
||||
activity.Status = "draft"
|
||||
}
|
||||
|
||||
if err := h.store.CreateProcessingActivity(c.Request.Context(), &activity); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, activity)
|
||||
}
|
||||
|
||||
// UpdateProcessingActivity updates a processing activity
|
||||
func (h *DSGVOHandlers) UpdateProcessingActivity(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var activity dsgvo.ProcessingActivity
|
||||
if err := c.ShouldBindJSON(&activity); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
activity.ID = id
|
||||
if err := h.store.UpdateProcessingActivity(c.Request.Context(), &activity); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, activity)
|
||||
}
|
||||
|
||||
// DeleteProcessingActivity deletes a processing activity
|
||||
func (h *DSGVOHandlers) DeleteProcessingActivity(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.DeleteProcessingActivity(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "deleted"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// TOM - Technische und Organisatorische Maßnahmen
|
||||
// ============================================================================
|
||||
// DEPRECATED: TOM is now managed by backend-compliance (Python).
|
||||
// These handlers remain for backwards compatibility but should not be used.
|
||||
// Use backend-compliance endpoints: GET/POST /api/compliance/tom/...
|
||||
|
||||
// ListTOMs returns all TOMs for a tenant
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/tom/measures
|
||||
func (h *DSGVOHandlers) ListTOMs(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
category := c.Query("category")
|
||||
|
||||
toms, err := h.store.ListTOMs(c.Request.Context(), tenantID, category)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"toms": toms, "categories": dsgvo.TOMCategories})
|
||||
}
|
||||
|
||||
// GetTOM returns a TOM by ID
|
||||
func (h *DSGVOHandlers) GetTOM(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
tom, err := h.store.GetTOM(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if tom == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, tom)
|
||||
}
|
||||
|
||||
// CreateTOM creates a new TOM
|
||||
func (h *DSGVOHandlers) CreateTOM(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var tom dsgvo.TOM
|
||||
if err := c.ShouldBindJSON(&tom); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tom.TenantID = tenantID
|
||||
tom.CreatedBy = userID
|
||||
if tom.ImplementationStatus == "" {
|
||||
tom.ImplementationStatus = "planned"
|
||||
}
|
||||
|
||||
if err := h.store.CreateTOM(c.Request.Context(), &tom); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, tom)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSR - Data Subject Requests
|
||||
// DEPRECATED: DSR is now managed by backend-compliance (Python/FastAPI).
|
||||
// Use: /api/compliance/dsr/* endpoints on backend-compliance:8002
|
||||
// ============================================================================
|
||||
|
||||
// ListDSRs returns all DSRs for a tenant
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsr
|
||||
func (h *DSGVOHandlers) ListDSRs(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
status := c.Query("status")
|
||||
requestType := c.Query("type")
|
||||
|
||||
dsrs, err := h.store.ListDSRs(c.Request.Context(), tenantID, status, requestType)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"dsrs": dsrs, "types": dsgvo.DSRTypes})
|
||||
}
|
||||
|
||||
// GetDSR returns a DSR by ID
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsr/{id}
|
||||
func (h *DSGVOHandlers) GetDSR(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
dsr, err := h.store.GetDSR(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if dsr == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dsr)
|
||||
}
|
||||
|
||||
// CreateDSR creates a new DSR
|
||||
// DEPRECATED: Use backend-compliance POST /api/compliance/dsr
|
||||
func (h *DSGVOHandlers) CreateDSR(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var dsr dsgvo.DSR
|
||||
if err := c.ShouldBindJSON(&dsr); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
dsr.TenantID = tenantID
|
||||
dsr.CreatedBy = userID
|
||||
if dsr.Status == "" {
|
||||
dsr.Status = "received"
|
||||
}
|
||||
|
||||
if err := h.store.CreateDSR(c.Request.Context(), &dsr); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dsr)
|
||||
}
|
||||
|
||||
// UpdateDSR updates a DSR
|
||||
// DEPRECATED: Use backend-compliance PUT /api/compliance/dsr/{id}
|
||||
func (h *DSGVOHandlers) UpdateDSR(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var dsr dsgvo.DSR
|
||||
if err := c.ShouldBindJSON(&dsr); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
dsr.ID = id
|
||||
if err := h.store.UpdateDSR(c.Request.Context(), &dsr); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dsr)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Retention Policies
|
||||
// ============================================================================
|
||||
|
||||
// ListRetentionPolicies returns all retention policies for a tenant
|
||||
func (h *DSGVOHandlers) ListRetentionPolicies(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
policies, err := h.store.ListRetentionPolicies(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"policies": policies,
|
||||
"common_periods": dsgvo.CommonRetentionPeriods,
|
||||
})
|
||||
}
|
||||
|
||||
// CreateRetentionPolicy creates a new retention policy
|
||||
func (h *DSGVOHandlers) CreateRetentionPolicy(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var policy dsgvo.RetentionPolicy
|
||||
if err := c.ShouldBindJSON(&policy); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
policy.TenantID = tenantID
|
||||
policy.CreatedBy = userID
|
||||
if policy.Status == "" {
|
||||
policy.Status = "draft"
|
||||
}
|
||||
|
||||
if err := h.store.CreateRetentionPolicy(c.Request.Context(), &policy); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, policy)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// GetStats returns DSGVO statistics for a tenant
|
||||
func (h *DSGVOHandlers) GetStats(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
stats, err := h.store.GetStats(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, stats)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSFA - Datenschutz-Folgenabschätzung
|
||||
// DEPRECATED: DSFA endpoints migrated to backend-compliance (Python/FastAPI).
|
||||
// These in-memory Go handlers are kept for backwards compatibility only.
|
||||
// Use backend-compliance /api/compliance/dsfa/* instead.
|
||||
// ============================================================================
|
||||
|
||||
// ListDSFAs returns all DSFAs for a tenant
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsfa
|
||||
func (h *DSGVOHandlers) ListDSFAs(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
status := c.Query("status")
|
||||
|
||||
dsfas, err := h.store.ListDSFAs(c.Request.Context(), tenantID, status)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"dsfas": dsfas})
|
||||
}
|
||||
|
||||
// GetDSFA returns a DSFA by ID
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsfa/{id}
|
||||
func (h *DSGVOHandlers) GetDSFA(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
dsfa, err := h.store.GetDSFA(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if dsfa == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dsfa)
|
||||
}
|
||||
|
||||
// CreateDSFA creates a new DSFA
|
||||
// DEPRECATED: Use backend-compliance POST /api/compliance/dsfa
|
||||
func (h *DSGVOHandlers) CreateDSFA(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var dsfa dsgvo.DSFA
|
||||
if err := c.ShouldBindJSON(&dsfa); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
dsfa.TenantID = tenantID
|
||||
dsfa.CreatedBy = userID
|
||||
if dsfa.Status == "" {
|
||||
dsfa.Status = "draft"
|
||||
}
|
||||
|
||||
if err := h.store.CreateDSFA(c.Request.Context(), &dsfa); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dsfa)
|
||||
}
|
||||
|
||||
// UpdateDSFA updates a DSFA
|
||||
// DEPRECATED: Use backend-compliance PUT /api/compliance/dsfa/{id}
|
||||
func (h *DSGVOHandlers) UpdateDSFA(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var dsfa dsgvo.DSFA
|
||||
if err := c.ShouldBindJSON(&dsfa); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
dsfa.ID = id
|
||||
if err := h.store.UpdateDSFA(c.Request.Context(), &dsfa); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dsfa)
|
||||
}
|
||||
|
||||
// DeleteDSFA deletes a DSFA
|
||||
// DEPRECATED: Use backend-compliance DELETE /api/compliance/dsfa/{id}
|
||||
func (h *DSGVOHandlers) DeleteDSFA(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.DeleteDSFA(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "deleted"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PDF Export
|
||||
// ============================================================================
|
||||
|
||||
// ExportVVT exports the Verarbeitungsverzeichnis as CSV/JSON
|
||||
func (h *DSGVOHandlers) ExportVVT(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
format := c.DefaultQuery("format", "csv")
|
||||
|
||||
activities, err := h.store.ListProcessingActivities(c.Request.Context(), tenantID, nil)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if format == "json" {
|
||||
c.Header("Content-Disposition", "attachment; filename=vvt_export.json")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"exported_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"processing_activities": activities,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// CSV Export
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("ID;Name;Zweck;Rechtsgrundlage;Datenkategorien;Betroffene;Empfänger;Drittland;Aufbewahrung;Verantwortlich;Status;Erstellt\n")
|
||||
|
||||
for _, pa := range activities {
|
||||
buf.WriteString(fmt.Sprintf("%s;%s;%s;%s;%s;%s;%s;%t;%s;%s;%s;%s\n",
|
||||
pa.ID.String(),
|
||||
escapeCSV(pa.Name),
|
||||
escapeCSV(pa.Purpose),
|
||||
pa.LegalBasis,
|
||||
joinStrings(pa.DataCategories),
|
||||
joinStrings(pa.DataSubjectCategories),
|
||||
joinStrings(pa.Recipients),
|
||||
pa.ThirdCountryTransfer,
|
||||
pa.RetentionPeriod,
|
||||
escapeCSV(pa.ResponsiblePerson),
|
||||
pa.Status,
|
||||
pa.CreatedAt.Format("2006-01-02"),
|
||||
))
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition", "attachment; filename=vvt_export.csv")
|
||||
c.Data(http.StatusOK, "text/csv; charset=utf-8", buf.Bytes())
|
||||
}
|
||||
|
||||
// ExportTOM exports the TOM catalog as CSV/JSON
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/tom/export
|
||||
func (h *DSGVOHandlers) ExportTOM(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
format := c.DefaultQuery("format", "csv")
|
||||
|
||||
toms, err := h.store.ListTOMs(c.Request.Context(), tenantID, "")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if format == "json" {
|
||||
c.Header("Content-Disposition", "attachment; filename=tom_export.json")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"exported_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"toms": toms,
|
||||
"categories": dsgvo.TOMCategories,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// CSV Export
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("ID;Kategorie;Name;Beschreibung;Typ;Status;Implementiert am;Verantwortlich;Wirksamkeit;Erstellt\n")
|
||||
|
||||
for _, tom := range toms {
|
||||
implementedAt := ""
|
||||
if tom.ImplementedAt != nil {
|
||||
implementedAt = tom.ImplementedAt.Format("2006-01-02")
|
||||
}
|
||||
buf.WriteString(fmt.Sprintf("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n",
|
||||
tom.ID.String(),
|
||||
tom.Category,
|
||||
escapeCSV(tom.Name),
|
||||
escapeCSV(tom.Description),
|
||||
tom.Type,
|
||||
tom.ImplementationStatus,
|
||||
implementedAt,
|
||||
escapeCSV(tom.ResponsiblePerson),
|
||||
tom.EffectivenessRating,
|
||||
tom.CreatedAt.Format("2006-01-02"),
|
||||
))
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition", "attachment; filename=tom_export.csv")
|
||||
c.Data(http.StatusOK, "text/csv; charset=utf-8", buf.Bytes())
|
||||
}
|
||||
|
||||
// ExportDSR exports DSR overview as CSV/JSON
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsr/export?format=csv|json
|
||||
func (h *DSGVOHandlers) ExportDSR(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
format := c.DefaultQuery("format", "csv")
|
||||
|
||||
dsrs, err := h.store.ListDSRs(c.Request.Context(), tenantID, "", "")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if format == "json" {
|
||||
c.Header("Content-Disposition", "attachment; filename=dsr_export.json")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"exported_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"dsrs": dsrs,
|
||||
"types": dsgvo.DSRTypes,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// CSV Export
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("ID;Typ;Name;E-Mail;Status;Eingegangen;Frist;Abgeschlossen;Kanal;Zugewiesen\n")
|
||||
|
||||
for _, dsr := range dsrs {
|
||||
completedAt := ""
|
||||
if dsr.CompletedAt != nil {
|
||||
completedAt = dsr.CompletedAt.Format("2006-01-02")
|
||||
}
|
||||
assignedTo := ""
|
||||
if dsr.AssignedTo != nil {
|
||||
assignedTo = dsr.AssignedTo.String()
|
||||
}
|
||||
buf.WriteString(fmt.Sprintf("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n",
|
||||
dsr.ID.String(),
|
||||
dsr.RequestType,
|
||||
escapeCSV(dsr.SubjectName),
|
||||
dsr.SubjectEmail,
|
||||
dsr.Status,
|
||||
dsr.ReceivedAt.Format("2006-01-02"),
|
||||
dsr.DeadlineAt.Format("2006-01-02"),
|
||||
completedAt,
|
||||
dsr.RequestChannel,
|
||||
assignedTo,
|
||||
))
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition", "attachment; filename=dsr_export.csv")
|
||||
c.Data(http.StatusOK, "text/csv; charset=utf-8", buf.Bytes())
|
||||
}
|
||||
|
||||
// ExportDSFA exports a DSFA as JSON
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsfa/{id}/export?format=json
|
||||
func (h *DSGVOHandlers) ExportDSFA(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
dsfa, err := h.store.GetDSFA(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if dsfa == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=dsfa_%s.json", id.String()[:8]))
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"exported_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"dsfa": dsfa,
|
||||
})
|
||||
}
|
||||
|
||||
// ExportRetentionPolicies exports retention policies as CSV/JSON
|
||||
func (h *DSGVOHandlers) ExportRetentionPolicies(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
format := c.DefaultQuery("format", "csv")
|
||||
|
||||
policies, err := h.store.ListRetentionPolicies(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if format == "json" {
|
||||
c.Header("Content-Disposition", "attachment; filename=retention_policies_export.json")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"exported_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"policies": policies,
|
||||
"common_periods": dsgvo.CommonRetentionPeriods,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// CSV Export
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("ID;Name;Datenkategorie;Aufbewahrungsdauer (Tage);Dauer (Text);Rechtsgrundlage;Referenz;Löschmethode;Status\n")
|
||||
|
||||
for _, rp := range policies {
|
||||
buf.WriteString(fmt.Sprintf("%s;%s;%s;%d;%s;%s;%s;%s;%s\n",
|
||||
rp.ID.String(),
|
||||
escapeCSV(rp.Name),
|
||||
rp.DataCategory,
|
||||
rp.RetentionPeriodDays,
|
||||
escapeCSV(rp.RetentionPeriodText),
|
||||
escapeCSV(rp.LegalBasis),
|
||||
escapeCSV(rp.LegalReference),
|
||||
rp.DeletionMethod,
|
||||
rp.Status,
|
||||
))
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition", "attachment; filename=retention_policies_export.csv")
|
||||
c.Data(http.StatusOK, "text/csv; charset=utf-8", buf.Bytes())
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
func escapeCSV(s string) string {
|
||||
// Simple CSV escaping - wrap in quotes if contains semicolon, quote, or newline
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
needsQuotes := false
|
||||
for _, c := range s {
|
||||
if c == ';' || c == '"' || c == '\n' || c == '\r' {
|
||||
needsQuotes = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if needsQuotes {
|
||||
// Double any quotes and wrap in quotes
|
||||
escaped := ""
|
||||
for _, c := range s {
|
||||
if c == '"' {
|
||||
escaped += "\"\""
|
||||
} else if c == '\n' || c == '\r' {
|
||||
escaped += " "
|
||||
} else {
|
||||
escaped += string(c)
|
||||
}
|
||||
}
|
||||
return "\"" + escaped + "\""
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func joinStrings(strs []string) string {
|
||||
if len(strs) == 0 {
|
||||
return ""
|
||||
}
|
||||
result := strs[0]
|
||||
for i := 1; i < len(strs); i++ {
|
||||
result += ", " + strs[i]
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,672 +0,0 @@
|
||||
// DEPRECATED: Python backend (backend-compliance) is now Source of Truth for Incidents.
|
||||
// Frontend proxies to backend-compliance:8002/api/compliance/incidents/*
|
||||
// These Go handlers remain for backward compatibility but should not be extended.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/incidents"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// IncidentHandlers handles incident/breach management HTTP requests
|
||||
// DEPRECATED: Use Python backend-compliance incident_routes.py instead.
|
||||
type IncidentHandlers struct {
|
||||
store *incidents.Store
|
||||
}
|
||||
|
||||
// NewIncidentHandlers creates new incident handlers
|
||||
func NewIncidentHandlers(store *incidents.Store) *IncidentHandlers {
|
||||
return &IncidentHandlers{store: store}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Incident CRUD
|
||||
// ============================================================================
|
||||
|
||||
// CreateIncident creates a new incident
|
||||
// POST /sdk/v1/incidents
|
||||
func (h *IncidentHandlers) CreateIncident(c *gin.Context) {
|
||||
var req incidents.CreateIncidentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
detectedAt := time.Now().UTC()
|
||||
if req.DetectedAt != nil {
|
||||
detectedAt = *req.DetectedAt
|
||||
}
|
||||
|
||||
// Auto-calculate 72h deadline per DSGVO Art. 33
|
||||
deadline := incidents.Calculate72hDeadline(detectedAt)
|
||||
|
||||
incident := &incidents.Incident{
|
||||
TenantID: tenantID,
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
Category: req.Category,
|
||||
Status: incidents.IncidentStatusDetected,
|
||||
Severity: req.Severity,
|
||||
DetectedAt: detectedAt,
|
||||
ReportedBy: userID,
|
||||
AffectedDataCategories: req.AffectedDataCategories,
|
||||
AffectedDataSubjectCount: req.AffectedDataSubjectCount,
|
||||
AffectedSystems: req.AffectedSystems,
|
||||
AuthorityNotification: &incidents.AuthorityNotification{
|
||||
Status: incidents.NotificationStatusPending,
|
||||
Deadline: deadline,
|
||||
},
|
||||
DataSubjectNotification: &incidents.DataSubjectNotification{
|
||||
Required: false,
|
||||
Status: incidents.NotificationStatusNotRequired,
|
||||
},
|
||||
Timeline: []incidents.TimelineEntry{
|
||||
{
|
||||
Timestamp: time.Now().UTC(),
|
||||
Action: "incident_created",
|
||||
UserID: userID,
|
||||
Details: "Incident detected and reported",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if err := h.store.CreateIncident(c.Request.Context(), incident); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"incident": incident,
|
||||
"authority_deadline": deadline,
|
||||
"hours_until_deadline": time.Until(deadline).Hours(),
|
||||
})
|
||||
}
|
||||
|
||||
// GetIncident retrieves an incident by ID
|
||||
// GET /sdk/v1/incidents/:id
|
||||
func (h *IncidentHandlers) GetIncident(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// Get measures
|
||||
measures, _ := h.store.ListMeasures(c.Request.Context(), id)
|
||||
|
||||
// Calculate deadline info if authority notification exists
|
||||
var deadlineInfo gin.H
|
||||
if incident.AuthorityNotification != nil {
|
||||
hoursRemaining := time.Until(incident.AuthorityNotification.Deadline).Hours()
|
||||
deadlineInfo = gin.H{
|
||||
"deadline": incident.AuthorityNotification.Deadline,
|
||||
"hours_remaining": hoursRemaining,
|
||||
"overdue": hoursRemaining < 0,
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"incident": incident,
|
||||
"measures": measures,
|
||||
"deadline_info": deadlineInfo,
|
||||
})
|
||||
}
|
||||
|
||||
// ListIncidents lists incidents for a tenant
|
||||
// GET /sdk/v1/incidents
|
||||
func (h *IncidentHandlers) ListIncidents(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
filters := &incidents.IncidentFilters{
|
||||
Limit: 50,
|
||||
}
|
||||
|
||||
if status := c.Query("status"); status != "" {
|
||||
filters.Status = incidents.IncidentStatus(status)
|
||||
}
|
||||
if severity := c.Query("severity"); severity != "" {
|
||||
filters.Severity = incidents.IncidentSeverity(severity)
|
||||
}
|
||||
if category := c.Query("category"); category != "" {
|
||||
filters.Category = incidents.IncidentCategory(category)
|
||||
}
|
||||
|
||||
incidentList, total, err := h.store.ListIncidents(c.Request.Context(), tenantID, filters)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, incidents.IncidentListResponse{
|
||||
Incidents: incidentList,
|
||||
Total: total,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateIncident updates an incident
|
||||
// PUT /sdk/v1/incidents/:id
|
||||
func (h *IncidentHandlers) UpdateIncident(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.UpdateIncidentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if req.Title != "" {
|
||||
incident.Title = req.Title
|
||||
}
|
||||
if req.Description != "" {
|
||||
incident.Description = req.Description
|
||||
}
|
||||
if req.Category != "" {
|
||||
incident.Category = req.Category
|
||||
}
|
||||
if req.Status != "" {
|
||||
incident.Status = req.Status
|
||||
}
|
||||
if req.Severity != "" {
|
||||
incident.Severity = req.Severity
|
||||
}
|
||||
if req.AffectedDataCategories != nil {
|
||||
incident.AffectedDataCategories = req.AffectedDataCategories
|
||||
}
|
||||
if req.AffectedDataSubjectCount != nil {
|
||||
incident.AffectedDataSubjectCount = *req.AffectedDataSubjectCount
|
||||
}
|
||||
if req.AffectedSystems != nil {
|
||||
incident.AffectedSystems = req.AffectedSystems
|
||||
}
|
||||
|
||||
if err := h.store.UpdateIncident(c.Request.Context(), incident); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"incident": incident})
|
||||
}
|
||||
|
||||
// DeleteIncident deletes an incident
|
||||
// DELETE /sdk/v1/incidents/:id
|
||||
func (h *IncidentHandlers) DeleteIncident(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.DeleteIncident(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "incident deleted"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Risk Assessment
|
||||
// ============================================================================
|
||||
|
||||
// AssessRisk performs a risk assessment for an incident
|
||||
// POST /sdk/v1/incidents/:id/risk-assessment
|
||||
func (h *IncidentHandlers) AssessRisk(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.RiskAssessmentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
// Auto-calculate risk level
|
||||
riskLevel := incidents.CalculateRiskLevel(req.Likelihood, req.Impact)
|
||||
notificationRequired := incidents.IsNotificationRequired(riskLevel)
|
||||
|
||||
assessment := &incidents.RiskAssessment{
|
||||
Likelihood: req.Likelihood,
|
||||
Impact: req.Impact,
|
||||
RiskLevel: riskLevel,
|
||||
AssessedAt: time.Now().UTC(),
|
||||
AssessedBy: userID,
|
||||
Notes: req.Notes,
|
||||
}
|
||||
|
||||
if err := h.store.UpdateRiskAssessment(c.Request.Context(), id, assessment); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Update status to assessment
|
||||
incident.Status = incidents.IncidentStatusAssessment
|
||||
h.store.UpdateIncident(c.Request.Context(), incident)
|
||||
|
||||
// Add timeline entry
|
||||
h.store.AddTimelineEntry(c.Request.Context(), id, incidents.TimelineEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
Action: "risk_assessed",
|
||||
UserID: userID,
|
||||
Details: fmt.Sprintf("Risk level: %s (likelihood=%d, impact=%d)", riskLevel, req.Likelihood, req.Impact),
|
||||
})
|
||||
|
||||
// If notification is required, update authority notification status
|
||||
if notificationRequired && incident.AuthorityNotification != nil {
|
||||
incident.AuthorityNotification.Status = incidents.NotificationStatusPending
|
||||
h.store.UpdateAuthorityNotification(c.Request.Context(), id, incident.AuthorityNotification)
|
||||
|
||||
// Update status to notification_required
|
||||
incident.Status = incidents.IncidentStatusNotificationRequired
|
||||
h.store.UpdateIncident(c.Request.Context(), incident)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"risk_assessment": assessment,
|
||||
"notification_required": notificationRequired,
|
||||
"incident_status": incident.Status,
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Authority Notification (Art. 33)
|
||||
// ============================================================================
|
||||
|
||||
// SubmitAuthorityNotification submits the supervisory authority notification
|
||||
// POST /sdk/v1/incidents/:id/authority-notification
|
||||
func (h *IncidentHandlers) SubmitAuthorityNotification(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.SubmitAuthorityNotificationRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
now := time.Now().UTC()
|
||||
|
||||
// Preserve existing deadline
|
||||
deadline := incidents.Calculate72hDeadline(incident.DetectedAt)
|
||||
if incident.AuthorityNotification != nil {
|
||||
deadline = incident.AuthorityNotification.Deadline
|
||||
}
|
||||
|
||||
notification := &incidents.AuthorityNotification{
|
||||
Status: incidents.NotificationStatusSent,
|
||||
Deadline: deadline,
|
||||
SubmittedAt: &now,
|
||||
AuthorityName: req.AuthorityName,
|
||||
ReferenceNumber: req.ReferenceNumber,
|
||||
ContactPerson: req.ContactPerson,
|
||||
Notes: req.Notes,
|
||||
}
|
||||
|
||||
if err := h.store.UpdateAuthorityNotification(c.Request.Context(), id, notification); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Update incident status
|
||||
incident.Status = incidents.IncidentStatusNotificationSent
|
||||
h.store.UpdateIncident(c.Request.Context(), incident)
|
||||
|
||||
// Add timeline entry
|
||||
h.store.AddTimelineEntry(c.Request.Context(), id, incidents.TimelineEntry{
|
||||
Timestamp: now,
|
||||
Action: "authority_notified",
|
||||
UserID: userID,
|
||||
Details: "Authority notification submitted to " + req.AuthorityName,
|
||||
})
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"authority_notification": notification,
|
||||
"submitted_within_72h": now.Before(deadline),
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Data Subject Notification (Art. 34)
|
||||
// ============================================================================
|
||||
|
||||
// NotifyDataSubjects submits the data subject notification
|
||||
// POST /sdk/v1/incidents/:id/data-subject-notification
|
||||
func (h *IncidentHandlers) NotifyDataSubjects(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.NotifyDataSubjectsRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
now := time.Now().UTC()
|
||||
|
||||
affectedCount := req.AffectedCount
|
||||
if affectedCount == 0 {
|
||||
affectedCount = incident.AffectedDataSubjectCount
|
||||
}
|
||||
|
||||
notification := &incidents.DataSubjectNotification{
|
||||
Required: true,
|
||||
Status: incidents.NotificationStatusSent,
|
||||
SentAt: &now,
|
||||
AffectedCount: affectedCount,
|
||||
NotificationText: req.NotificationText,
|
||||
Channel: req.Channel,
|
||||
}
|
||||
|
||||
if err := h.store.UpdateDataSubjectNotification(c.Request.Context(), id, notification); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Add timeline entry
|
||||
h.store.AddTimelineEntry(c.Request.Context(), id, incidents.TimelineEntry{
|
||||
Timestamp: now,
|
||||
Action: "data_subjects_notified",
|
||||
UserID: userID,
|
||||
Details: "Data subjects notified via " + req.Channel + " (" + fmt.Sprintf("%d", affectedCount) + " affected)",
|
||||
})
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data_subject_notification": notification,
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Measures
|
||||
// ============================================================================
|
||||
|
||||
// AddMeasure adds a corrective measure to an incident
|
||||
// POST /sdk/v1/incidents/:id/measures
|
||||
func (h *IncidentHandlers) AddMeasure(c *gin.Context) {
|
||||
incidentID, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
// Verify incident exists
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), incidentID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.AddMeasureRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
measure := &incidents.IncidentMeasure{
|
||||
IncidentID: incidentID,
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
MeasureType: req.MeasureType,
|
||||
Status: incidents.MeasureStatusPlanned,
|
||||
Responsible: req.Responsible,
|
||||
DueDate: req.DueDate,
|
||||
}
|
||||
|
||||
if err := h.store.AddMeasure(c.Request.Context(), measure); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Add timeline entry
|
||||
h.store.AddTimelineEntry(c.Request.Context(), incidentID, incidents.TimelineEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
Action: "measure_added",
|
||||
UserID: userID,
|
||||
Details: "Measure added: " + req.Title + " (" + string(req.MeasureType) + ")",
|
||||
})
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"measure": measure})
|
||||
}
|
||||
|
||||
// UpdateMeasure updates a measure
|
||||
// PUT /sdk/v1/incidents/measures/:measureId
|
||||
func (h *IncidentHandlers) UpdateMeasure(c *gin.Context) {
|
||||
measureID, err := uuid.Parse(c.Param("measureId"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid measure ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
MeasureType incidents.MeasureType `json:"measure_type,omitempty"`
|
||||
Status incidents.MeasureStatus `json:"status,omitempty"`
|
||||
Responsible string `json:"responsible,omitempty"`
|
||||
DueDate *time.Time `json:"due_date,omitempty"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
measure := &incidents.IncidentMeasure{
|
||||
ID: measureID,
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
MeasureType: req.MeasureType,
|
||||
Status: req.Status,
|
||||
Responsible: req.Responsible,
|
||||
DueDate: req.DueDate,
|
||||
}
|
||||
|
||||
if err := h.store.UpdateMeasure(c.Request.Context(), measure); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"measure": measure})
|
||||
}
|
||||
|
||||
// CompleteMeasure marks a measure as completed
|
||||
// POST /sdk/v1/incidents/measures/:measureId/complete
|
||||
func (h *IncidentHandlers) CompleteMeasure(c *gin.Context) {
|
||||
measureID, err := uuid.Parse(c.Param("measureId"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid measure ID"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.CompleteMeasure(c.Request.Context(), measureID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "measure completed"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Timeline
|
||||
// ============================================================================
|
||||
|
||||
// AddTimelineEntry adds a timeline entry to an incident
|
||||
// POST /sdk/v1/incidents/:id/timeline
|
||||
func (h *IncidentHandlers) AddTimelineEntry(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.AddTimelineEntryRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
entry := incidents.TimelineEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
Action: req.Action,
|
||||
UserID: userID,
|
||||
Details: req.Details,
|
||||
}
|
||||
|
||||
if err := h.store.AddTimelineEntry(c.Request.Context(), id, entry); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"timeline_entry": entry})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Close Incident
|
||||
// ============================================================================
|
||||
|
||||
// CloseIncident closes an incident with root cause analysis
|
||||
// POST /sdk/v1/incidents/:id/close
|
||||
func (h *IncidentHandlers) CloseIncident(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.CloseIncidentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
if err := h.store.CloseIncident(c.Request.Context(), id, req.RootCause, req.LessonsLearned); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Add timeline entry
|
||||
h.store.AddTimelineEntry(c.Request.Context(), id, incidents.TimelineEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
Action: "incident_closed",
|
||||
UserID: userID,
|
||||
Details: "Incident closed. Root cause: " + req.RootCause,
|
||||
})
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "incident closed",
|
||||
"root_cause": req.RootCause,
|
||||
"lessons_learned": req.LessonsLearned,
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// GetStatistics returns aggregated incident statistics
|
||||
// GET /sdk/v1/incidents/statistics
|
||||
func (h *IncidentHandlers) GetStatistics(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
stats, err := h.store.GetStatistics(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, stats)
|
||||
}
|
||||
|
||||
@@ -1,855 +0,0 @@
|
||||
// DEPRECATED: Vendor Compliance handlers are superseded by the Python backend
|
||||
// (backend-compliance/compliance/api/vendor_compliance_routes.py).
|
||||
// Frontend now routes through /api/sdk/v1/vendor-compliance → backend-compliance:8002.
|
||||
// These Go handlers remain for backward compatibility but should not be extended.
|
||||
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/vendor"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// VendorHandlers handles vendor-compliance HTTP requests
|
||||
type VendorHandlers struct {
|
||||
store *vendor.Store
|
||||
}
|
||||
|
||||
// NewVendorHandlers creates new vendor handlers
|
||||
func NewVendorHandlers(store *vendor.Store) *VendorHandlers {
|
||||
return &VendorHandlers{store: store}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Vendor CRUD
|
||||
// ============================================================================
|
||||
|
||||
// CreateVendor creates a new vendor
|
||||
// POST /sdk/v1/vendors
|
||||
func (h *VendorHandlers) CreateVendor(c *gin.Context) {
|
||||
var req vendor.CreateVendorRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
v := &vendor.Vendor{
|
||||
TenantID: tenantID,
|
||||
Name: req.Name,
|
||||
LegalForm: req.LegalForm,
|
||||
Country: req.Country,
|
||||
Address: req.Address,
|
||||
Website: req.Website,
|
||||
ContactName: req.ContactName,
|
||||
ContactEmail: req.ContactEmail,
|
||||
ContactPhone: req.ContactPhone,
|
||||
ContactDepartment: req.ContactDepartment,
|
||||
Role: req.Role,
|
||||
ServiceCategory: req.ServiceCategory,
|
||||
ServiceDescription: req.ServiceDescription,
|
||||
DataAccessLevel: req.DataAccessLevel,
|
||||
ProcessingLocations: req.ProcessingLocations,
|
||||
Certifications: req.Certifications,
|
||||
ReviewFrequency: req.ReviewFrequency,
|
||||
ProcessingActivityIDs: req.ProcessingActivityIDs,
|
||||
TemplateID: req.TemplateID,
|
||||
Status: vendor.VendorStatusActive,
|
||||
CreatedBy: userID.String(),
|
||||
}
|
||||
|
||||
if err := h.store.CreateVendor(c.Request.Context(), v); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"vendor": v})
|
||||
}
|
||||
|
||||
// ListVendors lists all vendors for a tenant
|
||||
// GET /sdk/v1/vendors
|
||||
func (h *VendorHandlers) ListVendors(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
vendors, err := h.store.ListVendors(c.Request.Context(), tenantID.String())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"vendors": vendors,
|
||||
"total": len(vendors),
|
||||
})
|
||||
}
|
||||
|
||||
// GetVendor retrieves a vendor by ID with contracts and findings
|
||||
// GET /sdk/v1/vendors/:id
|
||||
func (h *VendorHandlers) GetVendor(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
v, err := h.store.GetVendor(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if v == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "vendor not found"})
|
||||
return
|
||||
}
|
||||
|
||||
contracts, _ := h.store.ListContracts(c.Request.Context(), tenantID.String(), &id)
|
||||
findings, _ := h.store.ListFindings(c.Request.Context(), tenantID.String(), &id, nil)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"vendor": v,
|
||||
"contracts": contracts,
|
||||
"findings": findings,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateVendor updates a vendor
|
||||
// PUT /sdk/v1/vendors/:id
|
||||
func (h *VendorHandlers) UpdateVendor(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
v, err := h.store.GetVendor(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if v == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "vendor not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req vendor.UpdateVendorRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Apply non-nil fields
|
||||
if req.Name != nil {
|
||||
v.Name = *req.Name
|
||||
}
|
||||
if req.LegalForm != nil {
|
||||
v.LegalForm = *req.LegalForm
|
||||
}
|
||||
if req.Country != nil {
|
||||
v.Country = *req.Country
|
||||
}
|
||||
if req.Address != nil {
|
||||
v.Address = req.Address
|
||||
}
|
||||
if req.Website != nil {
|
||||
v.Website = *req.Website
|
||||
}
|
||||
if req.ContactName != nil {
|
||||
v.ContactName = *req.ContactName
|
||||
}
|
||||
if req.ContactEmail != nil {
|
||||
v.ContactEmail = *req.ContactEmail
|
||||
}
|
||||
if req.ContactPhone != nil {
|
||||
v.ContactPhone = *req.ContactPhone
|
||||
}
|
||||
if req.ContactDepartment != nil {
|
||||
v.ContactDepartment = *req.ContactDepartment
|
||||
}
|
||||
if req.Role != nil {
|
||||
v.Role = *req.Role
|
||||
}
|
||||
if req.ServiceCategory != nil {
|
||||
v.ServiceCategory = *req.ServiceCategory
|
||||
}
|
||||
if req.ServiceDescription != nil {
|
||||
v.ServiceDescription = *req.ServiceDescription
|
||||
}
|
||||
if req.DataAccessLevel != nil {
|
||||
v.DataAccessLevel = *req.DataAccessLevel
|
||||
}
|
||||
if req.ProcessingLocations != nil {
|
||||
v.ProcessingLocations = req.ProcessingLocations
|
||||
}
|
||||
if req.Certifications != nil {
|
||||
v.Certifications = req.Certifications
|
||||
}
|
||||
if req.InherentRiskScore != nil {
|
||||
v.InherentRiskScore = req.InherentRiskScore
|
||||
}
|
||||
if req.ResidualRiskScore != nil {
|
||||
v.ResidualRiskScore = req.ResidualRiskScore
|
||||
}
|
||||
if req.ManualRiskAdjustment != nil {
|
||||
v.ManualRiskAdjustment = req.ManualRiskAdjustment
|
||||
}
|
||||
if req.ReviewFrequency != nil {
|
||||
v.ReviewFrequency = *req.ReviewFrequency
|
||||
}
|
||||
if req.LastReviewDate != nil {
|
||||
v.LastReviewDate = req.LastReviewDate
|
||||
}
|
||||
if req.NextReviewDate != nil {
|
||||
v.NextReviewDate = req.NextReviewDate
|
||||
}
|
||||
if req.ProcessingActivityIDs != nil {
|
||||
v.ProcessingActivityIDs = req.ProcessingActivityIDs
|
||||
}
|
||||
if req.Status != nil {
|
||||
v.Status = *req.Status
|
||||
}
|
||||
if req.TemplateID != nil {
|
||||
v.TemplateID = req.TemplateID
|
||||
}
|
||||
|
||||
if err := h.store.UpdateVendor(c.Request.Context(), v); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"vendor": v})
|
||||
}
|
||||
|
||||
// DeleteVendor deletes a vendor
|
||||
// DELETE /sdk/v1/vendors/:id
|
||||
func (h *VendorHandlers) DeleteVendor(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
if err := h.store.DeleteVendor(c.Request.Context(), tenantID.String(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "vendor deleted"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Contract CRUD
|
||||
// ============================================================================
|
||||
|
||||
// CreateContract creates a new contract for a vendor
|
||||
// POST /sdk/v1/vendors/contracts
|
||||
func (h *VendorHandlers) CreateContract(c *gin.Context) {
|
||||
var req vendor.CreateContractRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
contract := &vendor.Contract{
|
||||
TenantID: tenantID,
|
||||
VendorID: req.VendorID,
|
||||
FileName: req.FileName,
|
||||
OriginalName: req.OriginalName,
|
||||
MimeType: req.MimeType,
|
||||
FileSize: req.FileSize,
|
||||
StoragePath: req.StoragePath,
|
||||
DocumentType: req.DocumentType,
|
||||
Parties: req.Parties,
|
||||
EffectiveDate: req.EffectiveDate,
|
||||
ExpirationDate: req.ExpirationDate,
|
||||
AutoRenewal: req.AutoRenewal,
|
||||
RenewalNoticePeriod: req.RenewalNoticePeriod,
|
||||
Version: req.Version,
|
||||
PreviousVersionID: req.PreviousVersionID,
|
||||
ReviewStatus: "PENDING",
|
||||
CreatedBy: userID.String(),
|
||||
}
|
||||
|
||||
if contract.Version == "" {
|
||||
contract.Version = "1.0"
|
||||
}
|
||||
|
||||
if err := h.store.CreateContract(c.Request.Context(), contract); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"contract": contract})
|
||||
}
|
||||
|
||||
// ListContracts lists contracts for a tenant
|
||||
// GET /sdk/v1/vendors/contracts
|
||||
func (h *VendorHandlers) ListContracts(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
var vendorID *string
|
||||
if vid := c.Query("vendor_id"); vid != "" {
|
||||
vendorID = &vid
|
||||
}
|
||||
|
||||
contracts, err := h.store.ListContracts(c.Request.Context(), tenantID.String(), vendorID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"contracts": contracts,
|
||||
"total": len(contracts),
|
||||
})
|
||||
}
|
||||
|
||||
// GetContract retrieves a contract by ID
|
||||
// GET /sdk/v1/vendors/contracts/:id
|
||||
func (h *VendorHandlers) GetContract(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
contract, err := h.store.GetContract(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if contract == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "contract not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"contract": contract})
|
||||
}
|
||||
|
||||
// UpdateContract updates a contract
|
||||
// PUT /sdk/v1/vendors/contracts/:id
|
||||
func (h *VendorHandlers) UpdateContract(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
contract, err := h.store.GetContract(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if contract == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "contract not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req vendor.UpdateContractRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if req.DocumentType != nil {
|
||||
contract.DocumentType = *req.DocumentType
|
||||
}
|
||||
if req.Parties != nil {
|
||||
contract.Parties = req.Parties
|
||||
}
|
||||
if req.EffectiveDate != nil {
|
||||
contract.EffectiveDate = req.EffectiveDate
|
||||
}
|
||||
if req.ExpirationDate != nil {
|
||||
contract.ExpirationDate = req.ExpirationDate
|
||||
}
|
||||
if req.AutoRenewal != nil {
|
||||
contract.AutoRenewal = *req.AutoRenewal
|
||||
}
|
||||
if req.RenewalNoticePeriod != nil {
|
||||
contract.RenewalNoticePeriod = *req.RenewalNoticePeriod
|
||||
}
|
||||
if req.ReviewStatus != nil {
|
||||
contract.ReviewStatus = *req.ReviewStatus
|
||||
}
|
||||
if req.ReviewCompletedAt != nil {
|
||||
contract.ReviewCompletedAt = req.ReviewCompletedAt
|
||||
}
|
||||
if req.ComplianceScore != nil {
|
||||
contract.ComplianceScore = req.ComplianceScore
|
||||
}
|
||||
if req.Version != nil {
|
||||
contract.Version = *req.Version
|
||||
}
|
||||
if req.ExtractedText != nil {
|
||||
contract.ExtractedText = *req.ExtractedText
|
||||
}
|
||||
if req.PageCount != nil {
|
||||
contract.PageCount = req.PageCount
|
||||
}
|
||||
|
||||
if err := h.store.UpdateContract(c.Request.Context(), contract); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"contract": contract})
|
||||
}
|
||||
|
||||
// DeleteContract deletes a contract
|
||||
// DELETE /sdk/v1/vendors/contracts/:id
|
||||
func (h *VendorHandlers) DeleteContract(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
if err := h.store.DeleteContract(c.Request.Context(), tenantID.String(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "contract deleted"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Finding CRUD
|
||||
// ============================================================================
|
||||
|
||||
// CreateFinding creates a new compliance finding
|
||||
// POST /sdk/v1/vendors/findings
|
||||
func (h *VendorHandlers) CreateFinding(c *gin.Context) {
|
||||
var req vendor.CreateFindingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
finding := &vendor.Finding{
|
||||
TenantID: tenantID,
|
||||
VendorID: req.VendorID,
|
||||
ContractID: req.ContractID,
|
||||
FindingType: req.FindingType,
|
||||
Category: req.Category,
|
||||
Severity: req.Severity,
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
Recommendation: req.Recommendation,
|
||||
Citations: req.Citations,
|
||||
Status: vendor.FindingStatusOpen,
|
||||
Assignee: req.Assignee,
|
||||
DueDate: req.DueDate,
|
||||
}
|
||||
|
||||
if err := h.store.CreateFinding(c.Request.Context(), finding); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"finding": finding})
|
||||
}
|
||||
|
||||
// ListFindings lists findings for a tenant
|
||||
// GET /sdk/v1/vendors/findings
|
||||
func (h *VendorHandlers) ListFindings(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
var vendorID, contractID *string
|
||||
if vid := c.Query("vendor_id"); vid != "" {
|
||||
vendorID = &vid
|
||||
}
|
||||
if cid := c.Query("contract_id"); cid != "" {
|
||||
contractID = &cid
|
||||
}
|
||||
|
||||
findings, err := h.store.ListFindings(c.Request.Context(), tenantID.String(), vendorID, contractID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"findings": findings,
|
||||
"total": len(findings),
|
||||
})
|
||||
}
|
||||
|
||||
// GetFinding retrieves a finding by ID
|
||||
// GET /sdk/v1/vendors/findings/:id
|
||||
func (h *VendorHandlers) GetFinding(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
finding, err := h.store.GetFinding(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if finding == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "finding not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"finding": finding})
|
||||
}
|
||||
|
||||
// UpdateFinding updates a finding
|
||||
// PUT /sdk/v1/vendors/findings/:id
|
||||
func (h *VendorHandlers) UpdateFinding(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
finding, err := h.store.GetFinding(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if finding == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "finding not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req vendor.UpdateFindingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if req.FindingType != nil {
|
||||
finding.FindingType = *req.FindingType
|
||||
}
|
||||
if req.Category != nil {
|
||||
finding.Category = *req.Category
|
||||
}
|
||||
if req.Severity != nil {
|
||||
finding.Severity = *req.Severity
|
||||
}
|
||||
if req.Title != nil {
|
||||
finding.Title = *req.Title
|
||||
}
|
||||
if req.Description != nil {
|
||||
finding.Description = *req.Description
|
||||
}
|
||||
if req.Recommendation != nil {
|
||||
finding.Recommendation = *req.Recommendation
|
||||
}
|
||||
if req.Citations != nil {
|
||||
finding.Citations = req.Citations
|
||||
}
|
||||
if req.Status != nil {
|
||||
finding.Status = *req.Status
|
||||
}
|
||||
if req.Assignee != nil {
|
||||
finding.Assignee = *req.Assignee
|
||||
}
|
||||
if req.DueDate != nil {
|
||||
finding.DueDate = req.DueDate
|
||||
}
|
||||
if req.Resolution != nil {
|
||||
finding.Resolution = *req.Resolution
|
||||
}
|
||||
|
||||
if err := h.store.UpdateFinding(c.Request.Context(), finding); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"finding": finding})
|
||||
}
|
||||
|
||||
// ResolveFinding resolves a finding with a resolution description
|
||||
// POST /sdk/v1/vendors/findings/:id/resolve
|
||||
func (h *VendorHandlers) ResolveFinding(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
var req vendor.ResolveFindingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.ResolveFinding(c.Request.Context(), tenantID.String(), id, req.Resolution, userID.String()); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "finding resolved"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Control Instance Operations
|
||||
// ============================================================================
|
||||
|
||||
// UpsertControlInstance creates or updates a control instance
|
||||
// POST /sdk/v1/vendors/controls
|
||||
func (h *VendorHandlers) UpsertControlInstance(c *gin.Context) {
|
||||
var req struct {
|
||||
VendorID string `json:"vendor_id" binding:"required"`
|
||||
ControlID string `json:"control_id" binding:"required"`
|
||||
ControlDomain string `json:"control_domain"`
|
||||
Status vendor.ControlStatus `json:"status" binding:"required"`
|
||||
EvidenceIDs json.RawMessage `json:"evidence_ids,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
NextAssessmentDate *time.Time `json:"next_assessment_date,omitempty"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
now := time.Now().UTC()
|
||||
userIDStr := userID.String()
|
||||
|
||||
ci := &vendor.ControlInstance{
|
||||
TenantID: tenantID,
|
||||
ControlID: req.ControlID,
|
||||
ControlDomain: req.ControlDomain,
|
||||
Status: req.Status,
|
||||
EvidenceIDs: req.EvidenceIDs,
|
||||
Notes: req.Notes,
|
||||
LastAssessedAt: &now,
|
||||
LastAssessedBy: &userIDStr,
|
||||
NextAssessmentDate: req.NextAssessmentDate,
|
||||
}
|
||||
|
||||
// Parse VendorID
|
||||
vendorUUID, err := parseUUID(req.VendorID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid vendor_id"})
|
||||
return
|
||||
}
|
||||
ci.VendorID = vendorUUID
|
||||
|
||||
if err := h.store.UpsertControlInstance(c.Request.Context(), ci); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"control_instance": ci})
|
||||
}
|
||||
|
||||
// ListControlInstances lists control instances for a vendor
|
||||
// GET /sdk/v1/vendors/controls
|
||||
func (h *VendorHandlers) ListControlInstances(c *gin.Context) {
|
||||
vendorID := c.Query("vendor_id")
|
||||
if vendorID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "vendor_id query parameter is required"})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
instances, err := h.store.ListControlInstances(c.Request.Context(), tenantID.String(), vendorID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"control_instances": instances,
|
||||
"total": len(instances),
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Template Operations
|
||||
// ============================================================================
|
||||
|
||||
// ListTemplates lists available templates
|
||||
// GET /sdk/v1/vendors/templates
|
||||
func (h *VendorHandlers) ListTemplates(c *gin.Context) {
|
||||
templateType := c.DefaultQuery("type", "VENDOR")
|
||||
|
||||
var category, industry *string
|
||||
if cat := c.Query("category"); cat != "" {
|
||||
category = &cat
|
||||
}
|
||||
if ind := c.Query("industry"); ind != "" {
|
||||
industry = &ind
|
||||
}
|
||||
|
||||
templates, err := h.store.ListTemplates(c.Request.Context(), templateType, category, industry)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"templates": templates,
|
||||
"total": len(templates),
|
||||
})
|
||||
}
|
||||
|
||||
// GetTemplate retrieves a template by its template_id string
|
||||
// GET /sdk/v1/vendors/templates/:templateId
|
||||
func (h *VendorHandlers) GetTemplate(c *gin.Context) {
|
||||
templateID := c.Param("templateId")
|
||||
if templateID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "template ID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
tmpl, err := h.store.GetTemplate(c.Request.Context(), templateID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if tmpl == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "template not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"template": tmpl})
|
||||
}
|
||||
|
||||
// CreateTemplate creates a custom template
|
||||
// POST /sdk/v1/vendors/templates
|
||||
func (h *VendorHandlers) CreateTemplate(c *gin.Context) {
|
||||
var req vendor.CreateTemplateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tmpl := &vendor.Template{
|
||||
TemplateType: req.TemplateType,
|
||||
TemplateID: req.TemplateID,
|
||||
Category: req.Category,
|
||||
NameDE: req.NameDE,
|
||||
NameEN: req.NameEN,
|
||||
DescriptionDE: req.DescriptionDE,
|
||||
DescriptionEN: req.DescriptionEN,
|
||||
TemplateData: req.TemplateData,
|
||||
Industry: req.Industry,
|
||||
Tags: req.Tags,
|
||||
IsSystem: req.IsSystem,
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
// Set tenant for custom (non-system) templates
|
||||
if !req.IsSystem {
|
||||
tid := rbac.GetTenantID(c).String()
|
||||
tmpl.TenantID = &tid
|
||||
}
|
||||
|
||||
if err := h.store.CreateTemplate(c.Request.Context(), tmpl); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"template": tmpl})
|
||||
}
|
||||
|
||||
// ApplyTemplate creates a vendor from a template
|
||||
// POST /sdk/v1/vendors/templates/:templateId/apply
|
||||
func (h *VendorHandlers) ApplyTemplate(c *gin.Context) {
|
||||
templateID := c.Param("templateId")
|
||||
if templateID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "template ID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
tmpl, err := h.store.GetTemplate(c.Request.Context(), templateID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if tmpl == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "template not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// Parse template_data to extract suggested vendor fields
|
||||
var templateData struct {
|
||||
ServiceCategory string `json:"service_category"`
|
||||
SuggestedRole string `json:"suggested_role"`
|
||||
DataAccessLevel string `json:"data_access_level"`
|
||||
ReviewFrequency string `json:"review_frequency"`
|
||||
Certifications json.RawMessage `json:"certifications"`
|
||||
ProcessingLocations json.RawMessage `json:"processing_locations"`
|
||||
}
|
||||
if err := json.Unmarshal(tmpl.TemplateData, &templateData); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to parse template data"})
|
||||
return
|
||||
}
|
||||
|
||||
// Optional overrides from request body
|
||||
var overrides struct {
|
||||
Name string `json:"name"`
|
||||
Country string `json:"country"`
|
||||
Website string `json:"website"`
|
||||
ContactName string `json:"contact_name"`
|
||||
ContactEmail string `json:"contact_email"`
|
||||
}
|
||||
c.ShouldBindJSON(&overrides)
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
v := &vendor.Vendor{
|
||||
TenantID: tenantID,
|
||||
Name: overrides.Name,
|
||||
Country: overrides.Country,
|
||||
Website: overrides.Website,
|
||||
ContactName: overrides.ContactName,
|
||||
ContactEmail: overrides.ContactEmail,
|
||||
Role: vendor.VendorRole(templateData.SuggestedRole),
|
||||
ServiceCategory: templateData.ServiceCategory,
|
||||
DataAccessLevel: templateData.DataAccessLevel,
|
||||
ReviewFrequency: templateData.ReviewFrequency,
|
||||
Certifications: templateData.Certifications,
|
||||
ProcessingLocations: templateData.ProcessingLocations,
|
||||
Status: vendor.VendorStatusActive,
|
||||
TemplateID: &templateID,
|
||||
CreatedBy: userID.String(),
|
||||
}
|
||||
|
||||
if v.Name == "" {
|
||||
v.Name = tmpl.NameDE
|
||||
}
|
||||
if v.Country == "" {
|
||||
v.Country = "DE"
|
||||
}
|
||||
if v.Role == "" {
|
||||
v.Role = vendor.VendorRoleProcessor
|
||||
}
|
||||
|
||||
if err := h.store.CreateVendor(c.Request.Context(), v); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Increment template usage
|
||||
_ = h.store.IncrementTemplateUsage(c.Request.Context(), templateID)
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"vendor": v,
|
||||
"template_id": templateID,
|
||||
"message": "vendor created from template",
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// GetStatistics returns aggregated vendor statistics
|
||||
// GET /sdk/v1/vendors/stats
|
||||
func (h *VendorHandlers) GetStatistics(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
stats, err := h.store.GetVendorStats(c.Request.Context(), tenantID.String())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, stats)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Helpers
|
||||
// ============================================================================
|
||||
|
||||
func parseUUID(s string) (uuid.UUID, error) {
|
||||
return uuid.Parse(s)
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
package dsgvo
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// VVT - Verarbeitungsverzeichnis (Art. 30 DSGVO)
|
||||
// ============================================================================
|
||||
|
||||
// ProcessingActivity represents an entry in the Records of Processing Activities
|
||||
type ProcessingActivity struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Purpose string `json:"purpose"`
|
||||
LegalBasis string `json:"legal_basis"` // consent, contract, legal_obligation, vital_interests, public_interest, legitimate_interests
|
||||
LegalBasisDetails string `json:"legal_basis_details,omitempty"`
|
||||
DataCategories []string `json:"data_categories"` // personal, sensitive, health, financial, etc.
|
||||
DataSubjectCategories []string `json:"data_subject_categories"` // customers, employees, suppliers, etc.
|
||||
Recipients []string `json:"recipients"` // Internal departments, external processors
|
||||
ThirdCountryTransfer bool `json:"third_country_transfer"`
|
||||
TransferSafeguards string `json:"transfer_safeguards,omitempty"` // SCCs, adequacy decision, BCRs
|
||||
RetentionPeriod string `json:"retention_period"`
|
||||
RetentionPolicyID *uuid.UUID `json:"retention_policy_id,omitempty"`
|
||||
TOMReference []uuid.UUID `json:"tom_reference,omitempty"` // Links to TOM entries
|
||||
DSFARequired bool `json:"dsfa_required"`
|
||||
DSFAID *uuid.UUID `json:"dsfa_id,omitempty"`
|
||||
ResponsiblePerson string `json:"responsible_person"`
|
||||
ResponsibleDepartment string `json:"responsible_department"`
|
||||
Systems []string `json:"systems"` // IT systems involved
|
||||
Status string `json:"status"` // draft, active, under_review, archived
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
LastReviewedAt *time.Time `json:"last_reviewed_at,omitempty"`
|
||||
NextReviewAt *time.Time `json:"next_review_at,omitempty"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSFA - Datenschutz-Folgenabschätzung (Art. 35 DSGVO)
|
||||
// ============================================================================
|
||||
|
||||
// DSFA represents a Data Protection Impact Assessment
|
||||
type DSFA struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`
|
||||
ProcessingActivityID *uuid.UUID `json:"processing_activity_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
ProcessingDescription string `json:"processing_description"`
|
||||
NecessityAssessment string `json:"necessity_assessment"`
|
||||
ProportionalityAssment string `json:"proportionality_assessment"`
|
||||
Risks []DSFARisk `json:"risks"`
|
||||
Mitigations []DSFAMitigation `json:"mitigations"`
|
||||
DPOConsulted bool `json:"dpo_consulted"`
|
||||
DPOOpinion string `json:"dpo_opinion,omitempty"`
|
||||
AuthorityConsulted bool `json:"authority_consulted"`
|
||||
AuthorityReference string `json:"authority_reference,omitempty"`
|
||||
Status string `json:"status"` // draft, in_progress, completed, approved, rejected
|
||||
OverallRiskLevel string `json:"overall_risk_level"` // low, medium, high, very_high
|
||||
Conclusion string `json:"conclusion"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
ApprovedBy *uuid.UUID `json:"approved_by,omitempty"`
|
||||
ApprovedAt *time.Time `json:"approved_at,omitempty"`
|
||||
}
|
||||
|
||||
// DSFARisk represents a risk identified in the DSFA
|
||||
type DSFARisk struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Category string `json:"category"` // confidentiality, integrity, availability, rights_freedoms
|
||||
Description string `json:"description"`
|
||||
Likelihood string `json:"likelihood"` // low, medium, high
|
||||
Impact string `json:"impact"` // low, medium, high
|
||||
RiskLevel string `json:"risk_level"` // calculated: low, medium, high, very_high
|
||||
AffectedData []string `json:"affected_data"`
|
||||
}
|
||||
|
||||
// DSFAMitigation represents a mitigation measure for a DSFA risk
|
||||
type DSFAMitigation struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
RiskID uuid.UUID `json:"risk_id"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type"` // technical, organizational, legal
|
||||
Status string `json:"status"` // planned, in_progress, implemented, verified
|
||||
ImplementedAt *time.Time `json:"implemented_at,omitempty"`
|
||||
VerifiedAt *time.Time `json:"verified_at,omitempty"`
|
||||
ResidualRisk string `json:"residual_risk"` // low, medium, high
|
||||
TOMReference *uuid.UUID `json:"tom_reference,omitempty"`
|
||||
ResponsibleParty string `json:"responsible_party"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// TOM - Technische und Organisatorische Maßnahmen (Art. 32 DSGVO)
|
||||
// ============================================================================
|
||||
|
||||
// TOM represents a Technical or Organizational Measure
|
||||
type TOM struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`
|
||||
Category string `json:"category"` // access_control, encryption, pseudonymization, availability, resilience, monitoring, incident_response
|
||||
Subcategory string `json:"subcategory,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type"` // technical, organizational
|
||||
ImplementationStatus string `json:"implementation_status"` // planned, in_progress, implemented, verified, not_applicable
|
||||
ImplementedAt *time.Time `json:"implemented_at,omitempty"`
|
||||
VerifiedAt *time.Time `json:"verified_at,omitempty"`
|
||||
VerifiedBy *uuid.UUID `json:"verified_by,omitempty"`
|
||||
EffectivenessRating string `json:"effectiveness_rating,omitempty"` // low, medium, high
|
||||
Documentation string `json:"documentation,omitempty"`
|
||||
ResponsiblePerson string `json:"responsible_person"`
|
||||
ResponsibleDepartment string `json:"responsible_department"`
|
||||
ReviewFrequency string `json:"review_frequency"` // monthly, quarterly, annually
|
||||
LastReviewAt *time.Time `json:"last_review_at,omitempty"`
|
||||
NextReviewAt *time.Time `json:"next_review_at,omitempty"`
|
||||
RelatedControls []string `json:"related_controls,omitempty"` // ISO 27001 controls, SOC2, etc.
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
}
|
||||
|
||||
// TOMCategory represents predefined TOM categories per Art. 32 DSGVO
|
||||
var TOMCategories = []string{
|
||||
"access_control", // Zutrittskontrolle
|
||||
"admission_control", // Zugangskontrolle
|
||||
"access_management", // Zugriffskontrolle
|
||||
"transfer_control", // Weitergabekontrolle
|
||||
"input_control", // Eingabekontrolle
|
||||
"availability_control", // Verfügbarkeitskontrolle
|
||||
"separation_control", // Trennungskontrolle
|
||||
"encryption", // Verschlüsselung
|
||||
"pseudonymization", // Pseudonymisierung
|
||||
"resilience", // Belastbarkeit
|
||||
"recovery", // Wiederherstellung
|
||||
"testing", // Regelmäßige Überprüfung
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSR - Data Subject Requests / Betroffenenrechte (Art. 15-22 DSGVO)
|
||||
// ============================================================================
|
||||
|
||||
// DSR represents a Data Subject Request
|
||||
type DSR struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`
|
||||
RequestType string `json:"request_type"` // access, rectification, erasure, restriction, portability, objection
|
||||
Status string `json:"status"` // received, verified, in_progress, completed, rejected, extended
|
||||
SubjectName string `json:"subject_name"`
|
||||
SubjectEmail string `json:"subject_email"`
|
||||
SubjectIdentifier string `json:"subject_identifier,omitempty"` // Customer ID, User ID, etc.
|
||||
RequestDescription string `json:"request_description"`
|
||||
RequestChannel string `json:"request_channel"` // email, form, phone, letter
|
||||
ReceivedAt time.Time `json:"received_at"`
|
||||
VerifiedAt *time.Time `json:"verified_at,omitempty"`
|
||||
VerificationMethod string `json:"verification_method,omitempty"`
|
||||
DeadlineAt time.Time `json:"deadline_at"` // Art. 12(3): 1 month, extendable by 2 months
|
||||
ExtendedDeadlineAt *time.Time `json:"extended_deadline_at,omitempty"`
|
||||
ExtensionReason string `json:"extension_reason,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
ResponseSent bool `json:"response_sent"`
|
||||
ResponseSentAt *time.Time `json:"response_sent_at,omitempty"`
|
||||
ResponseMethod string `json:"response_method,omitempty"`
|
||||
RejectionReason string `json:"rejection_reason,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
AffectedSystems []string `json:"affected_systems,omitempty"`
|
||||
AssignedTo *uuid.UUID `json:"assigned_to,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
}
|
||||
|
||||
// DSRType represents the types of data subject requests
|
||||
var DSRTypes = map[string]string{
|
||||
"access": "Art. 15 - Auskunftsrecht",
|
||||
"rectification": "Art. 16 - Recht auf Berichtigung",
|
||||
"erasure": "Art. 17 - Recht auf Löschung",
|
||||
"restriction": "Art. 18 - Recht auf Einschränkung",
|
||||
"portability": "Art. 20 - Recht auf Datenübertragbarkeit",
|
||||
"objection": "Art. 21 - Widerspruchsrecht",
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Retention - Löschfristen (Art. 17 DSGVO)
|
||||
// ============================================================================
|
||||
|
||||
// RetentionPolicy represents a data retention policy
|
||||
type RetentionPolicy struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
DataCategory string `json:"data_category"`
|
||||
RetentionPeriodDays int `json:"retention_period_days"`
|
||||
RetentionPeriodText string `json:"retention_period_text"` // Human readable: "3 Jahre", "10 Jahre nach Vertragsende"
|
||||
LegalBasis string `json:"legal_basis"` // Legal requirement, consent, legitimate interest
|
||||
LegalReference string `json:"legal_reference,omitempty"` // § 147 AO, § 257 HGB, etc.
|
||||
DeletionMethod string `json:"deletion_method"` // automatic, manual, anonymization
|
||||
DeletionProcedure string `json:"deletion_procedure,omitempty"`
|
||||
ExceptionCriteria string `json:"exception_criteria,omitempty"`
|
||||
ApplicableSystems []string `json:"applicable_systems,omitempty"`
|
||||
ResponsiblePerson string `json:"responsible_person"`
|
||||
ResponsibleDepartment string `json:"responsible_department"`
|
||||
Status string `json:"status"` // draft, active, archived
|
||||
LastReviewAt *time.Time `json:"last_review_at,omitempty"`
|
||||
NextReviewAt *time.Time `json:"next_review_at,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
}
|
||||
|
||||
// CommonRetentionPeriods defines common retention periods in German law
|
||||
var CommonRetentionPeriods = map[string]int{
|
||||
"steuerlich_10_jahre": 3650, // § 147 AO - Buchungsbelege
|
||||
"handelsrechtlich_6_jahre": 2190, // § 257 HGB - Handelsbriefe
|
||||
"arbeitsrechtlich_3_jahre": 1095, // Lohnunterlagen nach Ausscheiden
|
||||
"bewerbungen_6_monate": 180, // AGG-Frist
|
||||
"consent_widerruf_3_jahre": 1095, // Nachweis der Einwilligung
|
||||
"vertragsunterlagen_3_jahre": 1095, // Verjährungsfrist
|
||||
}
|
||||
@@ -1,664 +0,0 @@
|
||||
package dsgvo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Store handles DSGVO data persistence
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewStore creates a new DSGVO store
|
||||
func NewStore(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// VVT - Verarbeitungsverzeichnis
|
||||
// ============================================================================
|
||||
|
||||
// CreateProcessingActivity creates a new processing activity
|
||||
func (s *Store) CreateProcessingActivity(ctx context.Context, pa *ProcessingActivity) error {
|
||||
pa.ID = uuid.New()
|
||||
pa.CreatedAt = time.Now().UTC()
|
||||
pa.UpdatedAt = pa.CreatedAt
|
||||
|
||||
metadata, _ := json.Marshal(pa.Metadata)
|
||||
dataCategories, _ := json.Marshal(pa.DataCategories)
|
||||
dataSubjectCategories, _ := json.Marshal(pa.DataSubjectCategories)
|
||||
recipients, _ := json.Marshal(pa.Recipients)
|
||||
tomReference, _ := json.Marshal(pa.TOMReference)
|
||||
systems, _ := json.Marshal(pa.Systems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO dsgvo_processing_activities (
|
||||
id, tenant_id, namespace_id, name, description, purpose, legal_basis, legal_basis_details,
|
||||
data_categories, data_subject_categories, recipients, third_country_transfer, transfer_safeguards,
|
||||
retention_period, retention_policy_id, tom_reference, dsfa_required, dsfa_id,
|
||||
responsible_person, responsible_department, systems, status, metadata,
|
||||
created_at, updated_at, created_by, last_reviewed_at, next_review_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)
|
||||
`, pa.ID, pa.TenantID, pa.NamespaceID, pa.Name, pa.Description, pa.Purpose, pa.LegalBasis, pa.LegalBasisDetails,
|
||||
dataCategories, dataSubjectCategories, recipients, pa.ThirdCountryTransfer, pa.TransferSafeguards,
|
||||
pa.RetentionPeriod, pa.RetentionPolicyID, tomReference, pa.DSFARequired, pa.DSFAID,
|
||||
pa.ResponsiblePerson, pa.ResponsibleDepartment, systems, pa.Status, metadata,
|
||||
pa.CreatedAt, pa.UpdatedAt, pa.CreatedBy, pa.LastReviewedAt, pa.NextReviewAt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetProcessingActivity retrieves a processing activity by ID
|
||||
func (s *Store) GetProcessingActivity(ctx context.Context, id uuid.UUID) (*ProcessingActivity, error) {
|
||||
var pa ProcessingActivity
|
||||
var metadata, dataCategories, dataSubjectCategories, recipients, tomReference, systems []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, tenant_id, namespace_id, name, description, purpose, legal_basis, legal_basis_details,
|
||||
data_categories, data_subject_categories, recipients, third_country_transfer, transfer_safeguards,
|
||||
retention_period, retention_policy_id, tom_reference, dsfa_required, dsfa_id,
|
||||
responsible_person, responsible_department, systems, status, metadata,
|
||||
created_at, updated_at, created_by, last_reviewed_at, next_review_at
|
||||
FROM dsgvo_processing_activities WHERE id = $1
|
||||
`, id).Scan(&pa.ID, &pa.TenantID, &pa.NamespaceID, &pa.Name, &pa.Description, &pa.Purpose, &pa.LegalBasis, &pa.LegalBasisDetails,
|
||||
&dataCategories, &dataSubjectCategories, &recipients, &pa.ThirdCountryTransfer, &pa.TransferSafeguards,
|
||||
&pa.RetentionPeriod, &pa.RetentionPolicyID, &tomReference, &pa.DSFARequired, &pa.DSFAID,
|
||||
&pa.ResponsiblePerson, &pa.ResponsibleDepartment, &systems, &pa.Status, &metadata,
|
||||
&pa.CreatedAt, &pa.UpdatedAt, &pa.CreatedBy, &pa.LastReviewedAt, &pa.NextReviewAt)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &pa.Metadata)
|
||||
json.Unmarshal(dataCategories, &pa.DataCategories)
|
||||
json.Unmarshal(dataSubjectCategories, &pa.DataSubjectCategories)
|
||||
json.Unmarshal(recipients, &pa.Recipients)
|
||||
json.Unmarshal(tomReference, &pa.TOMReference)
|
||||
json.Unmarshal(systems, &pa.Systems)
|
||||
|
||||
return &pa, nil
|
||||
}
|
||||
|
||||
// ListProcessingActivities lists processing activities for a tenant
|
||||
func (s *Store) ListProcessingActivities(ctx context.Context, tenantID uuid.UUID, namespaceID *uuid.UUID) ([]ProcessingActivity, error) {
|
||||
query := `
|
||||
SELECT id, tenant_id, namespace_id, name, description, purpose, legal_basis, legal_basis_details,
|
||||
data_categories, data_subject_categories, recipients, third_country_transfer, transfer_safeguards,
|
||||
retention_period, retention_policy_id, tom_reference, dsfa_required, dsfa_id,
|
||||
responsible_person, responsible_department, systems, status, metadata,
|
||||
created_at, updated_at, created_by, last_reviewed_at, next_review_at
|
||||
FROM dsgvo_processing_activities WHERE tenant_id = $1`
|
||||
|
||||
args := []interface{}{tenantID}
|
||||
if namespaceID != nil {
|
||||
query += " AND namespace_id = $2"
|
||||
args = append(args, *namespaceID)
|
||||
}
|
||||
query += " ORDER BY name"
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var activities []ProcessingActivity
|
||||
for rows.Next() {
|
||||
var pa ProcessingActivity
|
||||
var metadata, dataCategories, dataSubjectCategories, recipients, tomReference, systems []byte
|
||||
|
||||
err := rows.Scan(&pa.ID, &pa.TenantID, &pa.NamespaceID, &pa.Name, &pa.Description, &pa.Purpose, &pa.LegalBasis, &pa.LegalBasisDetails,
|
||||
&dataCategories, &dataSubjectCategories, &recipients, &pa.ThirdCountryTransfer, &pa.TransferSafeguards,
|
||||
&pa.RetentionPeriod, &pa.RetentionPolicyID, &tomReference, &pa.DSFARequired, &pa.DSFAID,
|
||||
&pa.ResponsiblePerson, &pa.ResponsibleDepartment, &systems, &pa.Status, &metadata,
|
||||
&pa.CreatedAt, &pa.UpdatedAt, &pa.CreatedBy, &pa.LastReviewedAt, &pa.NextReviewAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &pa.Metadata)
|
||||
json.Unmarshal(dataCategories, &pa.DataCategories)
|
||||
json.Unmarshal(dataSubjectCategories, &pa.DataSubjectCategories)
|
||||
json.Unmarshal(recipients, &pa.Recipients)
|
||||
json.Unmarshal(tomReference, &pa.TOMReference)
|
||||
json.Unmarshal(systems, &pa.Systems)
|
||||
|
||||
activities = append(activities, pa)
|
||||
}
|
||||
|
||||
return activities, nil
|
||||
}
|
||||
|
||||
// UpdateProcessingActivity updates a processing activity
|
||||
func (s *Store) UpdateProcessingActivity(ctx context.Context, pa *ProcessingActivity) error {
|
||||
pa.UpdatedAt = time.Now().UTC()
|
||||
|
||||
metadata, _ := json.Marshal(pa.Metadata)
|
||||
dataCategories, _ := json.Marshal(pa.DataCategories)
|
||||
dataSubjectCategories, _ := json.Marshal(pa.DataSubjectCategories)
|
||||
recipients, _ := json.Marshal(pa.Recipients)
|
||||
tomReference, _ := json.Marshal(pa.TOMReference)
|
||||
systems, _ := json.Marshal(pa.Systems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE dsgvo_processing_activities SET
|
||||
name = $2, description = $3, purpose = $4, legal_basis = $5, legal_basis_details = $6,
|
||||
data_categories = $7, data_subject_categories = $8, recipients = $9, third_country_transfer = $10,
|
||||
transfer_safeguards = $11, retention_period = $12, retention_policy_id = $13, tom_reference = $14,
|
||||
dsfa_required = $15, dsfa_id = $16, responsible_person = $17, responsible_department = $18,
|
||||
systems = $19, status = $20, metadata = $21, updated_at = $22, last_reviewed_at = $23, next_review_at = $24
|
||||
WHERE id = $1
|
||||
`, pa.ID, pa.Name, pa.Description, pa.Purpose, pa.LegalBasis, pa.LegalBasisDetails,
|
||||
dataCategories, dataSubjectCategories, recipients, pa.ThirdCountryTransfer,
|
||||
pa.TransferSafeguards, pa.RetentionPeriod, pa.RetentionPolicyID, tomReference,
|
||||
pa.DSFARequired, pa.DSFAID, pa.ResponsiblePerson, pa.ResponsibleDepartment,
|
||||
systems, pa.Status, metadata, pa.UpdatedAt, pa.LastReviewedAt, pa.NextReviewAt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteProcessingActivity deletes a processing activity
|
||||
func (s *Store) DeleteProcessingActivity(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := s.pool.Exec(ctx, "DELETE FROM dsgvo_processing_activities WHERE id = $1", id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// TOM - Technische und Organisatorische Maßnahmen
|
||||
// ============================================================================
|
||||
|
||||
// CreateTOM creates a new TOM entry
|
||||
func (s *Store) CreateTOM(ctx context.Context, tom *TOM) error {
|
||||
tom.ID = uuid.New()
|
||||
tom.CreatedAt = time.Now().UTC()
|
||||
tom.UpdatedAt = tom.CreatedAt
|
||||
|
||||
metadata, _ := json.Marshal(tom.Metadata)
|
||||
relatedControls, _ := json.Marshal(tom.RelatedControls)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO dsgvo_tom (
|
||||
id, tenant_id, namespace_id, category, subcategory, name, description, type,
|
||||
implementation_status, implemented_at, verified_at, verified_by, effectiveness_rating,
|
||||
documentation, responsible_person, responsible_department, review_frequency,
|
||||
last_review_at, next_review_at, related_controls, metadata, created_at, updated_at, created_by
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24)
|
||||
`, tom.ID, tom.TenantID, tom.NamespaceID, tom.Category, tom.Subcategory, tom.Name, tom.Description, tom.Type,
|
||||
tom.ImplementationStatus, tom.ImplementedAt, tom.VerifiedAt, tom.VerifiedBy, tom.EffectivenessRating,
|
||||
tom.Documentation, tom.ResponsiblePerson, tom.ResponsibleDepartment, tom.ReviewFrequency,
|
||||
tom.LastReviewAt, tom.NextReviewAt, relatedControls, metadata, tom.CreatedAt, tom.UpdatedAt, tom.CreatedBy)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetTOM retrieves a TOM by ID
|
||||
func (s *Store) GetTOM(ctx context.Context, id uuid.UUID) (*TOM, error) {
|
||||
var tom TOM
|
||||
var metadata, relatedControls []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, tenant_id, namespace_id, category, subcategory, name, description, type,
|
||||
implementation_status, implemented_at, verified_at, verified_by, effectiveness_rating,
|
||||
documentation, responsible_person, responsible_department, review_frequency,
|
||||
last_review_at, next_review_at, related_controls, metadata, created_at, updated_at, created_by
|
||||
FROM dsgvo_tom WHERE id = $1
|
||||
`, id).Scan(&tom.ID, &tom.TenantID, &tom.NamespaceID, &tom.Category, &tom.Subcategory, &tom.Name, &tom.Description, &tom.Type,
|
||||
&tom.ImplementationStatus, &tom.ImplementedAt, &tom.VerifiedAt, &tom.VerifiedBy, &tom.EffectivenessRating,
|
||||
&tom.Documentation, &tom.ResponsiblePerson, &tom.ResponsibleDepartment, &tom.ReviewFrequency,
|
||||
&tom.LastReviewAt, &tom.NextReviewAt, &relatedControls, &metadata, &tom.CreatedAt, &tom.UpdatedAt, &tom.CreatedBy)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &tom.Metadata)
|
||||
json.Unmarshal(relatedControls, &tom.RelatedControls)
|
||||
|
||||
return &tom, nil
|
||||
}
|
||||
|
||||
// ListTOMs lists TOMs for a tenant
|
||||
func (s *Store) ListTOMs(ctx context.Context, tenantID uuid.UUID, category string) ([]TOM, error) {
|
||||
query := `
|
||||
SELECT id, tenant_id, namespace_id, category, subcategory, name, description, type,
|
||||
implementation_status, implemented_at, verified_at, verified_by, effectiveness_rating,
|
||||
documentation, responsible_person, responsible_department, review_frequency,
|
||||
last_review_at, next_review_at, related_controls, metadata, created_at, updated_at, created_by
|
||||
FROM dsgvo_tom WHERE tenant_id = $1`
|
||||
|
||||
args := []interface{}{tenantID}
|
||||
if category != "" {
|
||||
query += " AND category = $2"
|
||||
args = append(args, category)
|
||||
}
|
||||
query += " ORDER BY category, name"
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var toms []TOM
|
||||
for rows.Next() {
|
||||
var tom TOM
|
||||
var metadata, relatedControls []byte
|
||||
|
||||
err := rows.Scan(&tom.ID, &tom.TenantID, &tom.NamespaceID, &tom.Category, &tom.Subcategory, &tom.Name, &tom.Description, &tom.Type,
|
||||
&tom.ImplementationStatus, &tom.ImplementedAt, &tom.VerifiedAt, &tom.VerifiedBy, &tom.EffectivenessRating,
|
||||
&tom.Documentation, &tom.ResponsiblePerson, &tom.ResponsibleDepartment, &tom.ReviewFrequency,
|
||||
&tom.LastReviewAt, &tom.NextReviewAt, &relatedControls, &metadata, &tom.CreatedAt, &tom.UpdatedAt, &tom.CreatedBy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &tom.Metadata)
|
||||
json.Unmarshal(relatedControls, &tom.RelatedControls)
|
||||
|
||||
toms = append(toms, tom)
|
||||
}
|
||||
|
||||
return toms, nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSR - Data Subject Requests
|
||||
// ============================================================================
|
||||
|
||||
// CreateDSR creates a new DSR
|
||||
func (s *Store) CreateDSR(ctx context.Context, dsr *DSR) error {
|
||||
dsr.ID = uuid.New()
|
||||
dsr.CreatedAt = time.Now().UTC()
|
||||
dsr.UpdatedAt = dsr.CreatedAt
|
||||
|
||||
// Default deadline: 1 month from receipt
|
||||
if dsr.DeadlineAt.IsZero() {
|
||||
dsr.DeadlineAt = dsr.ReceivedAt.AddDate(0, 1, 0)
|
||||
}
|
||||
|
||||
metadata, _ := json.Marshal(dsr.Metadata)
|
||||
affectedSystems, _ := json.Marshal(dsr.AffectedSystems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO dsgvo_dsr (
|
||||
id, tenant_id, namespace_id, request_type, status, subject_name, subject_email,
|
||||
subject_identifier, request_description, request_channel, received_at, verified_at,
|
||||
verification_method, deadline_at, extended_deadline_at, extension_reason,
|
||||
completed_at, response_sent, response_sent_at, response_method, rejection_reason,
|
||||
notes, affected_systems, assigned_to, metadata, created_at, updated_at, created_by
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)
|
||||
`, dsr.ID, dsr.TenantID, dsr.NamespaceID, dsr.RequestType, dsr.Status, dsr.SubjectName, dsr.SubjectEmail,
|
||||
dsr.SubjectIdentifier, dsr.RequestDescription, dsr.RequestChannel, dsr.ReceivedAt, dsr.VerifiedAt,
|
||||
dsr.VerificationMethod, dsr.DeadlineAt, dsr.ExtendedDeadlineAt, dsr.ExtensionReason,
|
||||
dsr.CompletedAt, dsr.ResponseSent, dsr.ResponseSentAt, dsr.ResponseMethod, dsr.RejectionReason,
|
||||
dsr.Notes, affectedSystems, dsr.AssignedTo, metadata, dsr.CreatedAt, dsr.UpdatedAt, dsr.CreatedBy)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetDSR retrieves a DSR by ID
|
||||
func (s *Store) GetDSR(ctx context.Context, id uuid.UUID) (*DSR, error) {
|
||||
var dsr DSR
|
||||
var metadata, affectedSystems []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, tenant_id, namespace_id, request_type, status, subject_name, subject_email,
|
||||
subject_identifier, request_description, request_channel, received_at, verified_at,
|
||||
verification_method, deadline_at, extended_deadline_at, extension_reason,
|
||||
completed_at, response_sent, response_sent_at, response_method, rejection_reason,
|
||||
notes, affected_systems, assigned_to, metadata, created_at, updated_at, created_by
|
||||
FROM dsgvo_dsr WHERE id = $1
|
||||
`, id).Scan(&dsr.ID, &dsr.TenantID, &dsr.NamespaceID, &dsr.RequestType, &dsr.Status, &dsr.SubjectName, &dsr.SubjectEmail,
|
||||
&dsr.SubjectIdentifier, &dsr.RequestDescription, &dsr.RequestChannel, &dsr.ReceivedAt, &dsr.VerifiedAt,
|
||||
&dsr.VerificationMethod, &dsr.DeadlineAt, &dsr.ExtendedDeadlineAt, &dsr.ExtensionReason,
|
||||
&dsr.CompletedAt, &dsr.ResponseSent, &dsr.ResponseSentAt, &dsr.ResponseMethod, &dsr.RejectionReason,
|
||||
&dsr.Notes, &affectedSystems, &dsr.AssignedTo, &metadata, &dsr.CreatedAt, &dsr.UpdatedAt, &dsr.CreatedBy)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &dsr.Metadata)
|
||||
json.Unmarshal(affectedSystems, &dsr.AffectedSystems)
|
||||
|
||||
return &dsr, nil
|
||||
}
|
||||
|
||||
// ListDSRs lists DSRs for a tenant with optional filters
|
||||
func (s *Store) ListDSRs(ctx context.Context, tenantID uuid.UUID, status string, requestType string) ([]DSR, error) {
|
||||
query := `
|
||||
SELECT id, tenant_id, namespace_id, request_type, status, subject_name, subject_email,
|
||||
subject_identifier, request_description, request_channel, received_at, verified_at,
|
||||
verification_method, deadline_at, extended_deadline_at, extension_reason,
|
||||
completed_at, response_sent, response_sent_at, response_method, rejection_reason,
|
||||
notes, affected_systems, assigned_to, metadata, created_at, updated_at, created_by
|
||||
FROM dsgvo_dsr WHERE tenant_id = $1`
|
||||
|
||||
args := []interface{}{tenantID}
|
||||
argIdx := 2
|
||||
|
||||
if status != "" {
|
||||
query += " AND status = $" + string(rune('0'+argIdx))
|
||||
args = append(args, status)
|
||||
argIdx++
|
||||
}
|
||||
if requestType != "" {
|
||||
query += " AND request_type = $" + string(rune('0'+argIdx))
|
||||
args = append(args, requestType)
|
||||
}
|
||||
query += " ORDER BY deadline_at ASC"
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var dsrs []DSR
|
||||
for rows.Next() {
|
||||
var dsr DSR
|
||||
var metadata, affectedSystems []byte
|
||||
|
||||
err := rows.Scan(&dsr.ID, &dsr.TenantID, &dsr.NamespaceID, &dsr.RequestType, &dsr.Status, &dsr.SubjectName, &dsr.SubjectEmail,
|
||||
&dsr.SubjectIdentifier, &dsr.RequestDescription, &dsr.RequestChannel, &dsr.ReceivedAt, &dsr.VerifiedAt,
|
||||
&dsr.VerificationMethod, &dsr.DeadlineAt, &dsr.ExtendedDeadlineAt, &dsr.ExtensionReason,
|
||||
&dsr.CompletedAt, &dsr.ResponseSent, &dsr.ResponseSentAt, &dsr.ResponseMethod, &dsr.RejectionReason,
|
||||
&dsr.Notes, &affectedSystems, &dsr.AssignedTo, &metadata, &dsr.CreatedAt, &dsr.UpdatedAt, &dsr.CreatedBy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &dsr.Metadata)
|
||||
json.Unmarshal(affectedSystems, &dsr.AffectedSystems)
|
||||
|
||||
dsrs = append(dsrs, dsr)
|
||||
}
|
||||
|
||||
return dsrs, nil
|
||||
}
|
||||
|
||||
// UpdateDSR updates a DSR
|
||||
func (s *Store) UpdateDSR(ctx context.Context, dsr *DSR) error {
|
||||
dsr.UpdatedAt = time.Now().UTC()
|
||||
|
||||
metadata, _ := json.Marshal(dsr.Metadata)
|
||||
affectedSystems, _ := json.Marshal(dsr.AffectedSystems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE dsgvo_dsr SET
|
||||
status = $2, verified_at = $3, verification_method = $4, extended_deadline_at = $5,
|
||||
extension_reason = $6, completed_at = $7, response_sent = $8, response_sent_at = $9,
|
||||
response_method = $10, rejection_reason = $11, notes = $12, affected_systems = $13,
|
||||
assigned_to = $14, metadata = $15, updated_at = $16
|
||||
WHERE id = $1
|
||||
`, dsr.ID, dsr.Status, dsr.VerifiedAt, dsr.VerificationMethod, dsr.ExtendedDeadlineAt,
|
||||
dsr.ExtensionReason, dsr.CompletedAt, dsr.ResponseSent, dsr.ResponseSentAt,
|
||||
dsr.ResponseMethod, dsr.RejectionReason, dsr.Notes, affectedSystems,
|
||||
dsr.AssignedTo, metadata, dsr.UpdatedAt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Retention Policies
|
||||
// ============================================================================
|
||||
|
||||
// CreateRetentionPolicy creates a new retention policy
|
||||
func (s *Store) CreateRetentionPolicy(ctx context.Context, rp *RetentionPolicy) error {
|
||||
rp.ID = uuid.New()
|
||||
rp.CreatedAt = time.Now().UTC()
|
||||
rp.UpdatedAt = rp.CreatedAt
|
||||
|
||||
metadata, _ := json.Marshal(rp.Metadata)
|
||||
applicableSystems, _ := json.Marshal(rp.ApplicableSystems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO dsgvo_retention_policies (
|
||||
id, tenant_id, namespace_id, name, description, data_category, retention_period_days,
|
||||
retention_period_text, legal_basis, legal_reference, deletion_method, deletion_procedure,
|
||||
exception_criteria, applicable_systems, responsible_person, responsible_department,
|
||||
status, last_review_at, next_review_at, metadata, created_at, updated_at, created_by
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23)
|
||||
`, rp.ID, rp.TenantID, rp.NamespaceID, rp.Name, rp.Description, rp.DataCategory, rp.RetentionPeriodDays,
|
||||
rp.RetentionPeriodText, rp.LegalBasis, rp.LegalReference, rp.DeletionMethod, rp.DeletionProcedure,
|
||||
rp.ExceptionCriteria, applicableSystems, rp.ResponsiblePerson, rp.ResponsibleDepartment,
|
||||
rp.Status, rp.LastReviewAt, rp.NextReviewAt, metadata, rp.CreatedAt, rp.UpdatedAt, rp.CreatedBy)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ListRetentionPolicies lists retention policies for a tenant
|
||||
func (s *Store) ListRetentionPolicies(ctx context.Context, tenantID uuid.UUID) ([]RetentionPolicy, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, tenant_id, namespace_id, name, description, data_category, retention_period_days,
|
||||
retention_period_text, legal_basis, legal_reference, deletion_method, deletion_procedure,
|
||||
exception_criteria, applicable_systems, responsible_person, responsible_department,
|
||||
status, last_review_at, next_review_at, metadata, created_at, updated_at, created_by
|
||||
FROM dsgvo_retention_policies WHERE tenant_id = $1 ORDER BY name
|
||||
`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var policies []RetentionPolicy
|
||||
for rows.Next() {
|
||||
var rp RetentionPolicy
|
||||
var metadata, applicableSystems []byte
|
||||
|
||||
err := rows.Scan(&rp.ID, &rp.TenantID, &rp.NamespaceID, &rp.Name, &rp.Description, &rp.DataCategory, &rp.RetentionPeriodDays,
|
||||
&rp.RetentionPeriodText, &rp.LegalBasis, &rp.LegalReference, &rp.DeletionMethod, &rp.DeletionProcedure,
|
||||
&rp.ExceptionCriteria, &applicableSystems, &rp.ResponsiblePerson, &rp.ResponsibleDepartment,
|
||||
&rp.Status, &rp.LastReviewAt, &rp.NextReviewAt, &metadata, &rp.CreatedAt, &rp.UpdatedAt, &rp.CreatedBy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &rp.Metadata)
|
||||
json.Unmarshal(applicableSystems, &rp.ApplicableSystems)
|
||||
|
||||
policies = append(policies, rp)
|
||||
}
|
||||
|
||||
return policies, nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSFA - Datenschutz-Folgenabschätzung
|
||||
// ============================================================================
|
||||
|
||||
// CreateDSFA creates a new DSFA
|
||||
func (s *Store) CreateDSFA(ctx context.Context, dsfa *DSFA) error {
|
||||
dsfa.ID = uuid.New()
|
||||
dsfa.CreatedAt = time.Now().UTC()
|
||||
dsfa.UpdatedAt = dsfa.CreatedAt
|
||||
|
||||
metadata, _ := json.Marshal(dsfa.Metadata)
|
||||
risks, _ := json.Marshal(dsfa.Risks)
|
||||
mitigations, _ := json.Marshal(dsfa.Mitigations)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO dsgvo_dsfa (
|
||||
id, tenant_id, namespace_id, processing_activity_id, name, description,
|
||||
processing_description, necessity_assessment, proportionality_assessment,
|
||||
risks, mitigations, dpo_consulted, dpo_opinion, authority_consulted, authority_reference,
|
||||
status, overall_risk_level, conclusion, metadata, created_at, updated_at, created_by,
|
||||
approved_by, approved_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24)
|
||||
`, dsfa.ID, dsfa.TenantID, dsfa.NamespaceID, dsfa.ProcessingActivityID, dsfa.Name, dsfa.Description,
|
||||
dsfa.ProcessingDescription, dsfa.NecessityAssessment, dsfa.ProportionalityAssment,
|
||||
risks, mitigations, dsfa.DPOConsulted, dsfa.DPOOpinion, dsfa.AuthorityConsulted, dsfa.AuthorityReference,
|
||||
dsfa.Status, dsfa.OverallRiskLevel, dsfa.Conclusion, metadata, dsfa.CreatedAt, dsfa.UpdatedAt, dsfa.CreatedBy,
|
||||
dsfa.ApprovedBy, dsfa.ApprovedAt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetDSFA retrieves a DSFA by ID
|
||||
func (s *Store) GetDSFA(ctx context.Context, id uuid.UUID) (*DSFA, error) {
|
||||
var dsfa DSFA
|
||||
var metadata, risks, mitigations []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, tenant_id, namespace_id, processing_activity_id, name, description,
|
||||
processing_description, necessity_assessment, proportionality_assessment,
|
||||
risks, mitigations, dpo_consulted, dpo_opinion, authority_consulted, authority_reference,
|
||||
status, overall_risk_level, conclusion, metadata, created_at, updated_at, created_by,
|
||||
approved_by, approved_at
|
||||
FROM dsgvo_dsfa WHERE id = $1
|
||||
`, id).Scan(&dsfa.ID, &dsfa.TenantID, &dsfa.NamespaceID, &dsfa.ProcessingActivityID, &dsfa.Name, &dsfa.Description,
|
||||
&dsfa.ProcessingDescription, &dsfa.NecessityAssessment, &dsfa.ProportionalityAssment,
|
||||
&risks, &mitigations, &dsfa.DPOConsulted, &dsfa.DPOOpinion, &dsfa.AuthorityConsulted, &dsfa.AuthorityReference,
|
||||
&dsfa.Status, &dsfa.OverallRiskLevel, &dsfa.Conclusion, &metadata, &dsfa.CreatedAt, &dsfa.UpdatedAt, &dsfa.CreatedBy,
|
||||
&dsfa.ApprovedBy, &dsfa.ApprovedAt)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &dsfa.Metadata)
|
||||
json.Unmarshal(risks, &dsfa.Risks)
|
||||
json.Unmarshal(mitigations, &dsfa.Mitigations)
|
||||
|
||||
return &dsfa, nil
|
||||
}
|
||||
|
||||
// ListDSFAs lists DSFAs for a tenant
|
||||
func (s *Store) ListDSFAs(ctx context.Context, tenantID uuid.UUID, status string) ([]DSFA, error) {
|
||||
query := `
|
||||
SELECT id, tenant_id, namespace_id, processing_activity_id, name, description,
|
||||
processing_description, necessity_assessment, proportionality_assessment,
|
||||
risks, mitigations, dpo_consulted, dpo_opinion, authority_consulted, authority_reference,
|
||||
status, overall_risk_level, conclusion, metadata, created_at, updated_at, created_by,
|
||||
approved_by, approved_at
|
||||
FROM dsgvo_dsfa WHERE tenant_id = $1`
|
||||
|
||||
args := []interface{}{tenantID}
|
||||
if status != "" {
|
||||
query += " AND status = $2"
|
||||
args = append(args, status)
|
||||
}
|
||||
query += " ORDER BY created_at DESC"
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var dsfas []DSFA
|
||||
for rows.Next() {
|
||||
var dsfa DSFA
|
||||
var metadata, risks, mitigations []byte
|
||||
|
||||
err := rows.Scan(&dsfa.ID, &dsfa.TenantID, &dsfa.NamespaceID, &dsfa.ProcessingActivityID, &dsfa.Name, &dsfa.Description,
|
||||
&dsfa.ProcessingDescription, &dsfa.NecessityAssessment, &dsfa.ProportionalityAssment,
|
||||
&risks, &mitigations, &dsfa.DPOConsulted, &dsfa.DPOOpinion, &dsfa.AuthorityConsulted, &dsfa.AuthorityReference,
|
||||
&dsfa.Status, &dsfa.OverallRiskLevel, &dsfa.Conclusion, &metadata, &dsfa.CreatedAt, &dsfa.UpdatedAt, &dsfa.CreatedBy,
|
||||
&dsfa.ApprovedBy, &dsfa.ApprovedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &dsfa.Metadata)
|
||||
json.Unmarshal(risks, &dsfa.Risks)
|
||||
json.Unmarshal(mitigations, &dsfa.Mitigations)
|
||||
|
||||
dsfas = append(dsfas, dsfa)
|
||||
}
|
||||
|
||||
return dsfas, nil
|
||||
}
|
||||
|
||||
// UpdateDSFA updates a DSFA
|
||||
func (s *Store) UpdateDSFA(ctx context.Context, dsfa *DSFA) error {
|
||||
dsfa.UpdatedAt = time.Now().UTC()
|
||||
|
||||
metadata, _ := json.Marshal(dsfa.Metadata)
|
||||
risks, _ := json.Marshal(dsfa.Risks)
|
||||
mitigations, _ := json.Marshal(dsfa.Mitigations)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE dsgvo_dsfa SET
|
||||
name = $2, description = $3, processing_description = $4,
|
||||
necessity_assessment = $5, proportionality_assessment = $6,
|
||||
risks = $7, mitigations = $8, dpo_consulted = $9, dpo_opinion = $10,
|
||||
authority_consulted = $11, authority_reference = $12, status = $13,
|
||||
overall_risk_level = $14, conclusion = $15, metadata = $16, updated_at = $17,
|
||||
approved_by = $18, approved_at = $19
|
||||
WHERE id = $1
|
||||
`, dsfa.ID, dsfa.Name, dsfa.Description, dsfa.ProcessingDescription,
|
||||
dsfa.NecessityAssessment, dsfa.ProportionalityAssment,
|
||||
risks, mitigations, dsfa.DPOConsulted, dsfa.DPOOpinion,
|
||||
dsfa.AuthorityConsulted, dsfa.AuthorityReference, dsfa.Status,
|
||||
dsfa.OverallRiskLevel, dsfa.Conclusion, metadata, dsfa.UpdatedAt,
|
||||
dsfa.ApprovedBy, dsfa.ApprovedAt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteDSFA deletes a DSFA
|
||||
func (s *Store) DeleteDSFA(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := s.pool.Exec(ctx, "DELETE FROM dsgvo_dsfa WHERE id = $1", id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// DSGVOStats contains DSGVO module statistics
|
||||
type DSGVOStats struct {
|
||||
ProcessingActivities int `json:"processing_activities"`
|
||||
ActiveProcessings int `json:"active_processings"`
|
||||
TOMsImplemented int `json:"toms_implemented"`
|
||||
TOMsPlanned int `json:"toms_planned"`
|
||||
OpenDSRs int `json:"open_dsrs"`
|
||||
OverdueDSRs int `json:"overdue_dsrs"`
|
||||
RetentionPolicies int `json:"retention_policies"`
|
||||
DSFAsCompleted int `json:"dsfas_completed"`
|
||||
}
|
||||
|
||||
// GetStats returns DSGVO statistics for a tenant
|
||||
func (s *Store) GetStats(ctx context.Context, tenantID uuid.UUID) (*DSGVOStats, error) {
|
||||
stats := &DSGVOStats{}
|
||||
|
||||
// Processing Activities
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_processing_activities WHERE tenant_id = $1", tenantID).Scan(&stats.ProcessingActivities)
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_processing_activities WHERE tenant_id = $1 AND status = 'active'", tenantID).Scan(&stats.ActiveProcessings)
|
||||
|
||||
// TOMs
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_tom WHERE tenant_id = $1 AND implementation_status = 'implemented'", tenantID).Scan(&stats.TOMsImplemented)
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_tom WHERE tenant_id = $1 AND implementation_status IN ('planned', 'in_progress')", tenantID).Scan(&stats.TOMsPlanned)
|
||||
|
||||
// DSRs
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_dsr WHERE tenant_id = $1 AND status NOT IN ('completed', 'rejected')", tenantID).Scan(&stats.OpenDSRs)
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_dsr WHERE tenant_id = $1 AND status NOT IN ('completed', 'rejected') AND deadline_at < NOW()", tenantID).Scan(&stats.OverdueDSRs)
|
||||
|
||||
// Retention Policies
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_retention_policies WHERE tenant_id = $1 AND status = 'active'", tenantID).Scan(&stats.RetentionPolicies)
|
||||
|
||||
// DSFAs
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_dsfa WHERE tenant_id = $1 AND status = 'approved'", tenantID).Scan(&stats.DSFAsCompleted)
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
@@ -1,305 +0,0 @@
|
||||
package incidents
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Constants / Enums
|
||||
// ============================================================================
|
||||
|
||||
// IncidentCategory represents the category of a security/data breach incident
|
||||
type IncidentCategory string
|
||||
|
||||
const (
|
||||
IncidentCategoryDataBreach IncidentCategory = "data_breach"
|
||||
IncidentCategoryUnauthorizedAccess IncidentCategory = "unauthorized_access"
|
||||
IncidentCategoryDataLoss IncidentCategory = "data_loss"
|
||||
IncidentCategorySystemCompromise IncidentCategory = "system_compromise"
|
||||
IncidentCategoryPhishing IncidentCategory = "phishing"
|
||||
IncidentCategoryRansomware IncidentCategory = "ransomware"
|
||||
IncidentCategoryInsiderThreat IncidentCategory = "insider_threat"
|
||||
IncidentCategoryPhysicalBreach IncidentCategory = "physical_breach"
|
||||
IncidentCategoryOther IncidentCategory = "other"
|
||||
)
|
||||
|
||||
// IncidentStatus represents the status of an incident through its lifecycle
|
||||
type IncidentStatus string
|
||||
|
||||
const (
|
||||
IncidentStatusDetected IncidentStatus = "detected"
|
||||
IncidentStatusAssessment IncidentStatus = "assessment"
|
||||
IncidentStatusContainment IncidentStatus = "containment"
|
||||
IncidentStatusNotificationRequired IncidentStatus = "notification_required"
|
||||
IncidentStatusNotificationSent IncidentStatus = "notification_sent"
|
||||
IncidentStatusRemediation IncidentStatus = "remediation"
|
||||
IncidentStatusClosed IncidentStatus = "closed"
|
||||
)
|
||||
|
||||
// IncidentSeverity represents the severity level of an incident
|
||||
type IncidentSeverity string
|
||||
|
||||
const (
|
||||
IncidentSeverityCritical IncidentSeverity = "critical"
|
||||
IncidentSeverityHigh IncidentSeverity = "high"
|
||||
IncidentSeverityMedium IncidentSeverity = "medium"
|
||||
IncidentSeverityLow IncidentSeverity = "low"
|
||||
)
|
||||
|
||||
// MeasureType represents the type of corrective measure
|
||||
type MeasureType string
|
||||
|
||||
const (
|
||||
MeasureTypeImmediate MeasureType = "immediate"
|
||||
MeasureTypeLongTerm MeasureType = "long_term"
|
||||
)
|
||||
|
||||
// MeasureStatus represents the status of a corrective measure
|
||||
type MeasureStatus string
|
||||
|
||||
const (
|
||||
MeasureStatusPlanned MeasureStatus = "planned"
|
||||
MeasureStatusInProgress MeasureStatus = "in_progress"
|
||||
MeasureStatusCompleted MeasureStatus = "completed"
|
||||
)
|
||||
|
||||
// NotificationStatus represents the status of a notification (authority or data subject)
|
||||
type NotificationStatus string
|
||||
|
||||
const (
|
||||
NotificationStatusNotRequired NotificationStatus = "not_required"
|
||||
NotificationStatusPending NotificationStatus = "pending"
|
||||
NotificationStatusSent NotificationStatus = "sent"
|
||||
NotificationStatusConfirmed NotificationStatus = "confirmed"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Main Entities
|
||||
// ============================================================================
|
||||
|
||||
// Incident represents a security or data breach incident per DSGVO Art. 33/34
|
||||
type Incident struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
|
||||
// Incident info
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Category IncidentCategory `json:"category"`
|
||||
Status IncidentStatus `json:"status"`
|
||||
Severity IncidentSeverity `json:"severity"`
|
||||
|
||||
// Detection & reporting
|
||||
DetectedAt time.Time `json:"detected_at"`
|
||||
ReportedBy uuid.UUID `json:"reported_by"`
|
||||
|
||||
// Affected scope
|
||||
AffectedDataCategories []string `json:"affected_data_categories"` // JSONB
|
||||
AffectedDataSubjectCount int `json:"affected_data_subject_count"`
|
||||
AffectedSystems []string `json:"affected_systems"` // JSONB
|
||||
|
||||
// Assessments & notifications (JSONB embedded objects)
|
||||
RiskAssessment *RiskAssessment `json:"risk_assessment,omitempty"`
|
||||
AuthorityNotification *AuthorityNotification `json:"authority_notification,omitempty"`
|
||||
DataSubjectNotification *DataSubjectNotification `json:"data_subject_notification,omitempty"`
|
||||
|
||||
// Resolution
|
||||
RootCause string `json:"root_cause,omitempty"`
|
||||
LessonsLearned string `json:"lessons_learned,omitempty"`
|
||||
|
||||
// Timeline (JSONB array)
|
||||
Timeline []TimelineEntry `json:"timeline"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ClosedAt *time.Time `json:"closed_at,omitempty"`
|
||||
}
|
||||
|
||||
// RiskAssessment contains the risk assessment for an incident
|
||||
type RiskAssessment struct {
|
||||
Likelihood int `json:"likelihood"` // 1-5
|
||||
Impact int `json:"impact"` // 1-5
|
||||
RiskLevel string `json:"risk_level"` // critical, high, medium, low (auto-calculated)
|
||||
AssessedAt time.Time `json:"assessed_at"`
|
||||
AssessedBy uuid.UUID `json:"assessed_by"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// AuthorityNotification tracks the supervisory authority notification per DSGVO Art. 33
|
||||
type AuthorityNotification struct {
|
||||
Status NotificationStatus `json:"status"`
|
||||
Deadline time.Time `json:"deadline"` // 72h from detected_at per Art. 33
|
||||
SubmittedAt *time.Time `json:"submitted_at,omitempty"`
|
||||
AuthorityName string `json:"authority_name,omitempty"`
|
||||
ReferenceNumber string `json:"reference_number,omitempty"`
|
||||
ContactPerson string `json:"contact_person,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// DataSubjectNotification tracks the data subject notification per DSGVO Art. 34
|
||||
type DataSubjectNotification struct {
|
||||
Required bool `json:"required"`
|
||||
Status NotificationStatus `json:"status"`
|
||||
SentAt *time.Time `json:"sent_at,omitempty"`
|
||||
AffectedCount int `json:"affected_count"`
|
||||
NotificationText string `json:"notification_text,omitempty"`
|
||||
Channel string `json:"channel,omitempty"` // email, letter, website
|
||||
}
|
||||
|
||||
// TimelineEntry represents a single event in the incident timeline
|
||||
type TimelineEntry struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Action string `json:"action"`
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
Details string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// IncidentMeasure represents a corrective or preventive measure for an incident
|
||||
type IncidentMeasure struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
IncidentID uuid.UUID `json:"incident_id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description,omitempty"`
|
||||
MeasureType MeasureType `json:"measure_type"`
|
||||
Status MeasureStatus `json:"status"`
|
||||
Responsible string `json:"responsible,omitempty"`
|
||||
DueDate *time.Time `json:"due_date,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// IncidentStatistics contains aggregated incident statistics for a tenant
|
||||
type IncidentStatistics struct {
|
||||
TotalIncidents int `json:"total_incidents"`
|
||||
OpenIncidents int `json:"open_incidents"`
|
||||
ByStatus map[string]int `json:"by_status"`
|
||||
BySeverity map[string]int `json:"by_severity"`
|
||||
ByCategory map[string]int `json:"by_category"`
|
||||
NotificationsPending int `json:"notifications_pending"`
|
||||
AvgResolutionHours float64 `json:"avg_resolution_hours"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API Request/Response Types
|
||||
// ============================================================================
|
||||
|
||||
// CreateIncidentRequest is the API request for creating an incident
|
||||
type CreateIncidentRequest struct {
|
||||
Title string `json:"title" binding:"required"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Category IncidentCategory `json:"category" binding:"required"`
|
||||
Severity IncidentSeverity `json:"severity" binding:"required"`
|
||||
DetectedAt *time.Time `json:"detected_at,omitempty"` // defaults to now
|
||||
AffectedDataCategories []string `json:"affected_data_categories,omitempty"`
|
||||
AffectedDataSubjectCount int `json:"affected_data_subject_count,omitempty"`
|
||||
AffectedSystems []string `json:"affected_systems,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateIncidentRequest is the API request for updating an incident
|
||||
type UpdateIncidentRequest struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Category IncidentCategory `json:"category,omitempty"`
|
||||
Status IncidentStatus `json:"status,omitempty"`
|
||||
Severity IncidentSeverity `json:"severity,omitempty"`
|
||||
AffectedDataCategories []string `json:"affected_data_categories,omitempty"`
|
||||
AffectedDataSubjectCount *int `json:"affected_data_subject_count,omitempty"`
|
||||
AffectedSystems []string `json:"affected_systems,omitempty"`
|
||||
}
|
||||
|
||||
// RiskAssessmentRequest is the API request for assessing risk
|
||||
type RiskAssessmentRequest struct {
|
||||
Likelihood int `json:"likelihood" binding:"required,min=1,max=5"`
|
||||
Impact int `json:"impact" binding:"required,min=1,max=5"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// SubmitAuthorityNotificationRequest is the API request for submitting authority notification
|
||||
type SubmitAuthorityNotificationRequest struct {
|
||||
AuthorityName string `json:"authority_name" binding:"required"`
|
||||
ContactPerson string `json:"contact_person,omitempty"`
|
||||
ReferenceNumber string `json:"reference_number,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// NotifyDataSubjectsRequest is the API request for notifying data subjects
|
||||
type NotifyDataSubjectsRequest struct {
|
||||
NotificationText string `json:"notification_text" binding:"required"`
|
||||
Channel string `json:"channel" binding:"required"` // email, letter, website
|
||||
AffectedCount int `json:"affected_count,omitempty"`
|
||||
}
|
||||
|
||||
// AddMeasureRequest is the API request for adding a corrective measure
|
||||
type AddMeasureRequest struct {
|
||||
Title string `json:"title" binding:"required"`
|
||||
Description string `json:"description,omitempty"`
|
||||
MeasureType MeasureType `json:"measure_type" binding:"required"`
|
||||
Responsible string `json:"responsible,omitempty"`
|
||||
DueDate *time.Time `json:"due_date,omitempty"`
|
||||
}
|
||||
|
||||
// CloseIncidentRequest is the API request for closing an incident
|
||||
type CloseIncidentRequest struct {
|
||||
RootCause string `json:"root_cause" binding:"required"`
|
||||
LessonsLearned string `json:"lessons_learned,omitempty"`
|
||||
}
|
||||
|
||||
// AddTimelineEntryRequest is the API request for adding a timeline entry
|
||||
type AddTimelineEntryRequest struct {
|
||||
Action string `json:"action" binding:"required"`
|
||||
Details string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// IncidentListResponse is the API response for listing incidents
|
||||
type IncidentListResponse struct {
|
||||
Incidents []Incident `json:"incidents"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// IncidentFilters defines filters for listing incidents
|
||||
type IncidentFilters struct {
|
||||
Status IncidentStatus
|
||||
Severity IncidentSeverity
|
||||
Category IncidentCategory
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Helper Functions
|
||||
// ============================================================================
|
||||
|
||||
// CalculateRiskLevel calculates the risk level from likelihood and impact scores.
|
||||
// Risk score = likelihood * impact. Thresholds:
|
||||
// - critical: score >= 20
|
||||
// - high: score >= 12
|
||||
// - medium: score >= 6
|
||||
// - low: score < 6
|
||||
func CalculateRiskLevel(likelihood, impact int) string {
|
||||
score := likelihood * impact
|
||||
switch {
|
||||
case score >= 20:
|
||||
return "critical"
|
||||
case score >= 12:
|
||||
return "high"
|
||||
case score >= 6:
|
||||
return "medium"
|
||||
default:
|
||||
return "low"
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate72hDeadline calculates the 72-hour notification deadline per DSGVO Art. 33.
|
||||
// The supervisory authority must be notified within 72 hours of becoming aware of a breach.
|
||||
func Calculate72hDeadline(detectedAt time.Time) time.Time {
|
||||
return detectedAt.Add(72 * time.Hour)
|
||||
}
|
||||
|
||||
// IsNotificationRequired determines whether authority notification is required
|
||||
// based on the assessed risk level. Notification is required for critical and high risk.
|
||||
func IsNotificationRequired(riskLevel string) bool {
|
||||
return riskLevel == "critical" || riskLevel == "high"
|
||||
}
|
||||
@@ -1,571 +0,0 @@
|
||||
package incidents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Store handles incident data persistence
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewStore creates a new incident store
|
||||
func NewStore(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Incident CRUD Operations
|
||||
// ============================================================================
|
||||
|
||||
// CreateIncident creates a new incident
|
||||
func (s *Store) CreateIncident(ctx context.Context, incident *Incident) error {
|
||||
incident.ID = uuid.New()
|
||||
incident.CreatedAt = time.Now().UTC()
|
||||
incident.UpdatedAt = incident.CreatedAt
|
||||
if incident.Status == "" {
|
||||
incident.Status = IncidentStatusDetected
|
||||
}
|
||||
if incident.AffectedDataCategories == nil {
|
||||
incident.AffectedDataCategories = []string{}
|
||||
}
|
||||
if incident.AffectedSystems == nil {
|
||||
incident.AffectedSystems = []string{}
|
||||
}
|
||||
if incident.Timeline == nil {
|
||||
incident.Timeline = []TimelineEntry{}
|
||||
}
|
||||
|
||||
affectedDataCategories, _ := json.Marshal(incident.AffectedDataCategories)
|
||||
affectedSystems, _ := json.Marshal(incident.AffectedSystems)
|
||||
riskAssessment, _ := json.Marshal(incident.RiskAssessment)
|
||||
authorityNotification, _ := json.Marshal(incident.AuthorityNotification)
|
||||
dataSubjectNotification, _ := json.Marshal(incident.DataSubjectNotification)
|
||||
timeline, _ := json.Marshal(incident.Timeline)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO incident_incidents (
|
||||
id, tenant_id, title, description, category, status, severity,
|
||||
detected_at, reported_by,
|
||||
affected_data_categories, affected_data_subject_count, affected_systems,
|
||||
risk_assessment, authority_notification, data_subject_notification,
|
||||
root_cause, lessons_learned, timeline,
|
||||
created_at, updated_at, closed_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7,
|
||||
$8, $9,
|
||||
$10, $11, $12,
|
||||
$13, $14, $15,
|
||||
$16, $17, $18,
|
||||
$19, $20, $21
|
||||
)
|
||||
`,
|
||||
incident.ID, incident.TenantID, incident.Title, incident.Description,
|
||||
string(incident.Category), string(incident.Status), string(incident.Severity),
|
||||
incident.DetectedAt, incident.ReportedBy,
|
||||
affectedDataCategories, incident.AffectedDataSubjectCount, affectedSystems,
|
||||
riskAssessment, authorityNotification, dataSubjectNotification,
|
||||
incident.RootCause, incident.LessonsLearned, timeline,
|
||||
incident.CreatedAt, incident.UpdatedAt, incident.ClosedAt,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetIncident retrieves an incident by ID
|
||||
func (s *Store) GetIncident(ctx context.Context, id uuid.UUID) (*Incident, error) {
|
||||
var incident Incident
|
||||
var category, status, severity string
|
||||
var affectedDataCategories, affectedSystems []byte
|
||||
var riskAssessment, authorityNotification, dataSubjectNotification []byte
|
||||
var timeline []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
id, tenant_id, title, description, category, status, severity,
|
||||
detected_at, reported_by,
|
||||
affected_data_categories, affected_data_subject_count, affected_systems,
|
||||
risk_assessment, authority_notification, data_subject_notification,
|
||||
root_cause, lessons_learned, timeline,
|
||||
created_at, updated_at, closed_at
|
||||
FROM incident_incidents WHERE id = $1
|
||||
`, id).Scan(
|
||||
&incident.ID, &incident.TenantID, &incident.Title, &incident.Description,
|
||||
&category, &status, &severity,
|
||||
&incident.DetectedAt, &incident.ReportedBy,
|
||||
&affectedDataCategories, &incident.AffectedDataSubjectCount, &affectedSystems,
|
||||
&riskAssessment, &authorityNotification, &dataSubjectNotification,
|
||||
&incident.RootCause, &incident.LessonsLearned, &timeline,
|
||||
&incident.CreatedAt, &incident.UpdatedAt, &incident.ClosedAt,
|
||||
)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
incident.Category = IncidentCategory(category)
|
||||
incident.Status = IncidentStatus(status)
|
||||
incident.Severity = IncidentSeverity(severity)
|
||||
|
||||
json.Unmarshal(affectedDataCategories, &incident.AffectedDataCategories)
|
||||
json.Unmarshal(affectedSystems, &incident.AffectedSystems)
|
||||
json.Unmarshal(riskAssessment, &incident.RiskAssessment)
|
||||
json.Unmarshal(authorityNotification, &incident.AuthorityNotification)
|
||||
json.Unmarshal(dataSubjectNotification, &incident.DataSubjectNotification)
|
||||
json.Unmarshal(timeline, &incident.Timeline)
|
||||
|
||||
if incident.AffectedDataCategories == nil {
|
||||
incident.AffectedDataCategories = []string{}
|
||||
}
|
||||
if incident.AffectedSystems == nil {
|
||||
incident.AffectedSystems = []string{}
|
||||
}
|
||||
if incident.Timeline == nil {
|
||||
incident.Timeline = []TimelineEntry{}
|
||||
}
|
||||
|
||||
return &incident, nil
|
||||
}
|
||||
|
||||
// ListIncidents lists incidents for a tenant with optional filters
|
||||
func (s *Store) ListIncidents(ctx context.Context, tenantID uuid.UUID, filters *IncidentFilters) ([]Incident, int, error) {
|
||||
// Count query
|
||||
countQuery := "SELECT COUNT(*) FROM incident_incidents WHERE tenant_id = $1"
|
||||
countArgs := []interface{}{tenantID}
|
||||
countArgIdx := 2
|
||||
|
||||
if filters != nil {
|
||||
if filters.Status != "" {
|
||||
countQuery += fmt.Sprintf(" AND status = $%d", countArgIdx)
|
||||
countArgs = append(countArgs, string(filters.Status))
|
||||
countArgIdx++
|
||||
}
|
||||
if filters.Severity != "" {
|
||||
countQuery += fmt.Sprintf(" AND severity = $%d", countArgIdx)
|
||||
countArgs = append(countArgs, string(filters.Severity))
|
||||
countArgIdx++
|
||||
}
|
||||
if filters.Category != "" {
|
||||
countQuery += fmt.Sprintf(" AND category = $%d", countArgIdx)
|
||||
countArgs = append(countArgs, string(filters.Category))
|
||||
countArgIdx++
|
||||
}
|
||||
}
|
||||
|
||||
var total int
|
||||
err := s.pool.QueryRow(ctx, countQuery, countArgs...).Scan(&total)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Data query
|
||||
query := `
|
||||
SELECT
|
||||
id, tenant_id, title, description, category, status, severity,
|
||||
detected_at, reported_by,
|
||||
affected_data_categories, affected_data_subject_count, affected_systems,
|
||||
risk_assessment, authority_notification, data_subject_notification,
|
||||
root_cause, lessons_learned, timeline,
|
||||
created_at, updated_at, closed_at
|
||||
FROM incident_incidents WHERE tenant_id = $1`
|
||||
|
||||
args := []interface{}{tenantID}
|
||||
argIdx := 2
|
||||
|
||||
if filters != nil {
|
||||
if filters.Status != "" {
|
||||
query += fmt.Sprintf(" AND status = $%d", argIdx)
|
||||
args = append(args, string(filters.Status))
|
||||
argIdx++
|
||||
}
|
||||
if filters.Severity != "" {
|
||||
query += fmt.Sprintf(" AND severity = $%d", argIdx)
|
||||
args = append(args, string(filters.Severity))
|
||||
argIdx++
|
||||
}
|
||||
if filters.Category != "" {
|
||||
query += fmt.Sprintf(" AND category = $%d", argIdx)
|
||||
args = append(args, string(filters.Category))
|
||||
argIdx++
|
||||
}
|
||||
}
|
||||
|
||||
query += " ORDER BY detected_at DESC"
|
||||
|
||||
if filters != nil && filters.Limit > 0 {
|
||||
query += fmt.Sprintf(" LIMIT $%d", argIdx)
|
||||
args = append(args, filters.Limit)
|
||||
argIdx++
|
||||
|
||||
if filters.Offset > 0 {
|
||||
query += fmt.Sprintf(" OFFSET $%d", argIdx)
|
||||
args = append(args, filters.Offset)
|
||||
argIdx++
|
||||
}
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var incidents []Incident
|
||||
for rows.Next() {
|
||||
var incident Incident
|
||||
var category, status, severity string
|
||||
var affectedDataCategories, affectedSystems []byte
|
||||
var riskAssessment, authorityNotification, dataSubjectNotification []byte
|
||||
var timeline []byte
|
||||
|
||||
err := rows.Scan(
|
||||
&incident.ID, &incident.TenantID, &incident.Title, &incident.Description,
|
||||
&category, &status, &severity,
|
||||
&incident.DetectedAt, &incident.ReportedBy,
|
||||
&affectedDataCategories, &incident.AffectedDataSubjectCount, &affectedSystems,
|
||||
&riskAssessment, &authorityNotification, &dataSubjectNotification,
|
||||
&incident.RootCause, &incident.LessonsLearned, &timeline,
|
||||
&incident.CreatedAt, &incident.UpdatedAt, &incident.ClosedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
incident.Category = IncidentCategory(category)
|
||||
incident.Status = IncidentStatus(status)
|
||||
incident.Severity = IncidentSeverity(severity)
|
||||
|
||||
json.Unmarshal(affectedDataCategories, &incident.AffectedDataCategories)
|
||||
json.Unmarshal(affectedSystems, &incident.AffectedSystems)
|
||||
json.Unmarshal(riskAssessment, &incident.RiskAssessment)
|
||||
json.Unmarshal(authorityNotification, &incident.AuthorityNotification)
|
||||
json.Unmarshal(dataSubjectNotification, &incident.DataSubjectNotification)
|
||||
json.Unmarshal(timeline, &incident.Timeline)
|
||||
|
||||
if incident.AffectedDataCategories == nil {
|
||||
incident.AffectedDataCategories = []string{}
|
||||
}
|
||||
if incident.AffectedSystems == nil {
|
||||
incident.AffectedSystems = []string{}
|
||||
}
|
||||
if incident.Timeline == nil {
|
||||
incident.Timeline = []TimelineEntry{}
|
||||
}
|
||||
|
||||
incidents = append(incidents, incident)
|
||||
}
|
||||
|
||||
return incidents, total, nil
|
||||
}
|
||||
|
||||
// UpdateIncident updates an incident
|
||||
func (s *Store) UpdateIncident(ctx context.Context, incident *Incident) error {
|
||||
incident.UpdatedAt = time.Now().UTC()
|
||||
|
||||
affectedDataCategories, _ := json.Marshal(incident.AffectedDataCategories)
|
||||
affectedSystems, _ := json.Marshal(incident.AffectedSystems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
title = $2, description = $3, category = $4, status = $5, severity = $6,
|
||||
affected_data_categories = $7, affected_data_subject_count = $8, affected_systems = $9,
|
||||
root_cause = $10, lessons_learned = $11,
|
||||
updated_at = $12
|
||||
WHERE id = $1
|
||||
`,
|
||||
incident.ID, incident.Title, incident.Description,
|
||||
string(incident.Category), string(incident.Status), string(incident.Severity),
|
||||
affectedDataCategories, incident.AffectedDataSubjectCount, affectedSystems,
|
||||
incident.RootCause, incident.LessonsLearned,
|
||||
incident.UpdatedAt,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteIncident deletes an incident and its related measures (cascade handled by FK)
|
||||
func (s *Store) DeleteIncident(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := s.pool.Exec(ctx, "DELETE FROM incident_incidents WHERE id = $1", id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Risk Assessment Operations
|
||||
// ============================================================================
|
||||
|
||||
// UpdateRiskAssessment updates the risk assessment for an incident
|
||||
func (s *Store) UpdateRiskAssessment(ctx context.Context, incidentID uuid.UUID, assessment *RiskAssessment) error {
|
||||
assessmentJSON, _ := json.Marshal(assessment)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
risk_assessment = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, incidentID, assessmentJSON)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Notification Operations
|
||||
// ============================================================================
|
||||
|
||||
// UpdateAuthorityNotification updates the authority notification for an incident
|
||||
func (s *Store) UpdateAuthorityNotification(ctx context.Context, incidentID uuid.UUID, notification *AuthorityNotification) error {
|
||||
notificationJSON, _ := json.Marshal(notification)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
authority_notification = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, incidentID, notificationJSON)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// UpdateDataSubjectNotification updates the data subject notification for an incident
|
||||
func (s *Store) UpdateDataSubjectNotification(ctx context.Context, incidentID uuid.UUID, notification *DataSubjectNotification) error {
|
||||
notificationJSON, _ := json.Marshal(notification)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
data_subject_notification = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, incidentID, notificationJSON)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Measure Operations
|
||||
// ============================================================================
|
||||
|
||||
// AddMeasure adds a corrective measure to an incident
|
||||
func (s *Store) AddMeasure(ctx context.Context, measure *IncidentMeasure) error {
|
||||
measure.ID = uuid.New()
|
||||
measure.CreatedAt = time.Now().UTC()
|
||||
if measure.Status == "" {
|
||||
measure.Status = MeasureStatusPlanned
|
||||
}
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO incident_measures (
|
||||
id, incident_id, title, description, measure_type, status,
|
||||
responsible, due_date, completed_at, created_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6,
|
||||
$7, $8, $9, $10
|
||||
)
|
||||
`,
|
||||
measure.ID, measure.IncidentID, measure.Title, measure.Description,
|
||||
string(measure.MeasureType), string(measure.Status),
|
||||
measure.Responsible, measure.DueDate, measure.CompletedAt, measure.CreatedAt,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ListMeasures lists all measures for an incident
|
||||
func (s *Store) ListMeasures(ctx context.Context, incidentID uuid.UUID) ([]IncidentMeasure, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT
|
||||
id, incident_id, title, description, measure_type, status,
|
||||
responsible, due_date, completed_at, created_at
|
||||
FROM incident_measures WHERE incident_id = $1
|
||||
ORDER BY created_at ASC
|
||||
`, incidentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var measures []IncidentMeasure
|
||||
for rows.Next() {
|
||||
var m IncidentMeasure
|
||||
var measureType, status string
|
||||
|
||||
err := rows.Scan(
|
||||
&m.ID, &m.IncidentID, &m.Title, &m.Description,
|
||||
&measureType, &status,
|
||||
&m.Responsible, &m.DueDate, &m.CompletedAt, &m.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
m.MeasureType = MeasureType(measureType)
|
||||
m.Status = MeasureStatus(status)
|
||||
|
||||
measures = append(measures, m)
|
||||
}
|
||||
|
||||
return measures, nil
|
||||
}
|
||||
|
||||
// UpdateMeasure updates an existing measure
|
||||
func (s *Store) UpdateMeasure(ctx context.Context, measure *IncidentMeasure) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_measures SET
|
||||
title = $2, description = $3, measure_type = $4, status = $5,
|
||||
responsible = $6, due_date = $7, completed_at = $8
|
||||
WHERE id = $1
|
||||
`,
|
||||
measure.ID, measure.Title, measure.Description,
|
||||
string(measure.MeasureType), string(measure.Status),
|
||||
measure.Responsible, measure.DueDate, measure.CompletedAt,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// CompleteMeasure marks a measure as completed
|
||||
func (s *Store) CompleteMeasure(ctx context.Context, id uuid.UUID) error {
|
||||
now := time.Now().UTC()
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_measures SET
|
||||
status = $2,
|
||||
completed_at = $3
|
||||
WHERE id = $1
|
||||
`, id, string(MeasureStatusCompleted), now)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Timeline Operations
|
||||
// ============================================================================
|
||||
|
||||
// AddTimelineEntry appends a timeline entry to the incident's JSONB timeline array
|
||||
func (s *Store) AddTimelineEntry(ctx context.Context, incidentID uuid.UUID, entry TimelineEntry) error {
|
||||
entryJSON, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Use the || operator to append to the JSONB array
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
timeline = COALESCE(timeline, '[]'::jsonb) || $2::jsonb,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, incidentID, string(entryJSON))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Close Incident
|
||||
// ============================================================================
|
||||
|
||||
// CloseIncident closes an incident with root cause and lessons learned
|
||||
func (s *Store) CloseIncident(ctx context.Context, id uuid.UUID, rootCause, lessonsLearned string) error {
|
||||
now := time.Now().UTC()
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
status = $2,
|
||||
root_cause = $3,
|
||||
lessons_learned = $4,
|
||||
closed_at = $5,
|
||||
updated_at = $5
|
||||
WHERE id = $1
|
||||
`, id, string(IncidentStatusClosed), rootCause, lessonsLearned, now)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// GetStatistics returns aggregated incident statistics for a tenant
|
||||
func (s *Store) GetStatistics(ctx context.Context, tenantID uuid.UUID) (*IncidentStatistics, error) {
|
||||
stats := &IncidentStatistics{
|
||||
ByStatus: make(map[string]int),
|
||||
BySeverity: make(map[string]int),
|
||||
ByCategory: make(map[string]int),
|
||||
}
|
||||
|
||||
// Total incidents
|
||||
s.pool.QueryRow(ctx,
|
||||
"SELECT COUNT(*) FROM incident_incidents WHERE tenant_id = $1",
|
||||
tenantID).Scan(&stats.TotalIncidents)
|
||||
|
||||
// Open incidents (not closed)
|
||||
s.pool.QueryRow(ctx,
|
||||
"SELECT COUNT(*) FROM incident_incidents WHERE tenant_id = $1 AND status != 'closed'",
|
||||
tenantID).Scan(&stats.OpenIncidents)
|
||||
|
||||
// By status
|
||||
rows, err := s.pool.Query(ctx,
|
||||
"SELECT status, COUNT(*) FROM incident_incidents WHERE tenant_id = $1 GROUP BY status",
|
||||
tenantID)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var status string
|
||||
var count int
|
||||
rows.Scan(&status, &count)
|
||||
stats.ByStatus[status] = count
|
||||
}
|
||||
}
|
||||
|
||||
// By severity
|
||||
rows, err = s.pool.Query(ctx,
|
||||
"SELECT severity, COUNT(*) FROM incident_incidents WHERE tenant_id = $1 GROUP BY severity",
|
||||
tenantID)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var severity string
|
||||
var count int
|
||||
rows.Scan(&severity, &count)
|
||||
stats.BySeverity[severity] = count
|
||||
}
|
||||
}
|
||||
|
||||
// By category
|
||||
rows, err = s.pool.Query(ctx,
|
||||
"SELECT category, COUNT(*) FROM incident_incidents WHERE tenant_id = $1 GROUP BY category",
|
||||
tenantID)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var category string
|
||||
var count int
|
||||
rows.Scan(&category, &count)
|
||||
stats.ByCategory[category] = count
|
||||
}
|
||||
}
|
||||
|
||||
// Notifications pending
|
||||
s.pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM incident_incidents
|
||||
WHERE tenant_id = $1
|
||||
AND (authority_notification->>'status' = 'pending'
|
||||
OR data_subject_notification->>'status' = 'pending')
|
||||
`, tenantID).Scan(&stats.NotificationsPending)
|
||||
|
||||
// Average resolution hours (for closed incidents)
|
||||
s.pool.QueryRow(ctx, `
|
||||
SELECT COALESCE(AVG(EXTRACT(EPOCH FROM (closed_at - detected_at)) / 3600), 0)
|
||||
FROM incident_incidents
|
||||
WHERE tenant_id = $1 AND status = 'closed' AND closed_at IS NOT NULL
|
||||
`, tenantID).Scan(&stats.AvgResolutionHours)
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
488
ai-compliance-sdk/internal/vendor/models.go
vendored
488
ai-compliance-sdk/internal/vendor/models.go
vendored
@@ -1,488 +0,0 @@
|
||||
package vendor
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Constants / Enums
|
||||
// ============================================================================
|
||||
|
||||
// VendorRole represents the GDPR role of a vendor in data processing
|
||||
type VendorRole string
|
||||
|
||||
const (
|
||||
VendorRoleProcessor VendorRole = "PROCESSOR"
|
||||
VendorRoleController VendorRole = "CONTROLLER"
|
||||
VendorRoleJointController VendorRole = "JOINT_CONTROLLER"
|
||||
VendorRoleSubProcessor VendorRole = "SUB_PROCESSOR"
|
||||
VendorRoleThirdParty VendorRole = "THIRD_PARTY"
|
||||
)
|
||||
|
||||
// VendorStatus represents the lifecycle status of a vendor
|
||||
type VendorStatus string
|
||||
|
||||
const (
|
||||
VendorStatusActive VendorStatus = "ACTIVE"
|
||||
VendorStatusInactive VendorStatus = "INACTIVE"
|
||||
VendorStatusPendingReview VendorStatus = "PENDING_REVIEW"
|
||||
VendorStatusTerminated VendorStatus = "TERMINATED"
|
||||
)
|
||||
|
||||
// DocumentType represents the type of a contract/compliance document
|
||||
type DocumentType string
|
||||
|
||||
const (
|
||||
DocumentTypeAVV DocumentType = "AVV"
|
||||
DocumentTypeMSA DocumentType = "MSA"
|
||||
DocumentTypeSLA DocumentType = "SLA"
|
||||
DocumentTypeSCC DocumentType = "SCC"
|
||||
DocumentTypeNDA DocumentType = "NDA"
|
||||
DocumentTypeTOMAnnex DocumentType = "TOM_ANNEX"
|
||||
DocumentTypeCertification DocumentType = "CERTIFICATION"
|
||||
DocumentTypeSubProcessorList DocumentType = "SUB_PROCESSOR_LIST"
|
||||
)
|
||||
|
||||
// FindingType represents the type of a compliance finding
|
||||
type FindingType string
|
||||
|
||||
const (
|
||||
FindingTypeOK FindingType = "OK"
|
||||
FindingTypeGap FindingType = "GAP"
|
||||
FindingTypeRisk FindingType = "RISK"
|
||||
FindingTypeUnknown FindingType = "UNKNOWN"
|
||||
)
|
||||
|
||||
// FindingStatus represents the resolution status of a finding
|
||||
type FindingStatus string
|
||||
|
||||
const (
|
||||
FindingStatusOpen FindingStatus = "OPEN"
|
||||
FindingStatusInProgress FindingStatus = "IN_PROGRESS"
|
||||
FindingStatusResolved FindingStatus = "RESOLVED"
|
||||
FindingStatusAccepted FindingStatus = "ACCEPTED"
|
||||
FindingStatusFalsePositive FindingStatus = "FALSE_POSITIVE"
|
||||
)
|
||||
|
||||
// ControlStatus represents the assessment status of a control instance
|
||||
type ControlStatus string
|
||||
|
||||
const (
|
||||
ControlStatusPass ControlStatus = "PASS"
|
||||
ControlStatusPartial ControlStatus = "PARTIAL"
|
||||
ControlStatusFail ControlStatus = "FAIL"
|
||||
ControlStatusNotApplicable ControlStatus = "NOT_APPLICABLE"
|
||||
ControlStatusPlanned ControlStatus = "PLANNED"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Main Entities
|
||||
// ============================================================================
|
||||
|
||||
// Vendor represents a third-party vendor/service provider subject to GDPR compliance
|
||||
type Vendor struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id" db:"tenant_id"`
|
||||
|
||||
// Basic info
|
||||
Name string `json:"name" db:"name"`
|
||||
LegalForm string `json:"legal_form,omitempty" db:"legal_form"`
|
||||
Country string `json:"country" db:"country"`
|
||||
Address json.RawMessage `json:"address,omitempty" db:"address"`
|
||||
Website string `json:"website,omitempty" db:"website"`
|
||||
|
||||
// Contact
|
||||
ContactName string `json:"contact_name,omitempty" db:"contact_name"`
|
||||
ContactEmail string `json:"contact_email,omitempty" db:"contact_email"`
|
||||
ContactPhone string `json:"contact_phone,omitempty" db:"contact_phone"`
|
||||
ContactDepartment string `json:"contact_department,omitempty" db:"contact_department"`
|
||||
|
||||
// GDPR role & service
|
||||
Role VendorRole `json:"role" db:"role"`
|
||||
ServiceCategory string `json:"service_category,omitempty" db:"service_category"`
|
||||
ServiceDescription string `json:"service_description,omitempty" db:"service_description"`
|
||||
DataAccessLevel string `json:"data_access_level,omitempty" db:"data_access_level"`
|
||||
|
||||
// Processing details (JSONB)
|
||||
ProcessingLocations json.RawMessage `json:"processing_locations,omitempty" db:"processing_locations"`
|
||||
Certifications json.RawMessage `json:"certifications,omitempty" db:"certifications"`
|
||||
|
||||
// Risk scoring
|
||||
InherentRiskScore *int `json:"inherent_risk_score,omitempty" db:"inherent_risk_score"`
|
||||
ResidualRiskScore *int `json:"residual_risk_score,omitempty" db:"residual_risk_score"`
|
||||
ManualRiskAdjustment *int `json:"manual_risk_adjustment,omitempty" db:"manual_risk_adjustment"`
|
||||
|
||||
// Review schedule
|
||||
ReviewFrequency string `json:"review_frequency,omitempty" db:"review_frequency"`
|
||||
LastReviewDate *time.Time `json:"last_review_date,omitempty" db:"last_review_date"`
|
||||
NextReviewDate *time.Time `json:"next_review_date,omitempty" db:"next_review_date"`
|
||||
|
||||
// Links to processing activities (JSONB)
|
||||
ProcessingActivityIDs json.RawMessage `json:"processing_activity_ids,omitempty" db:"processing_activity_ids"`
|
||||
|
||||
// Status & template
|
||||
Status VendorStatus `json:"status" db:"status"`
|
||||
TemplateID *string `json:"template_id,omitempty" db:"template_id"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
CreatedBy string `json:"created_by" db:"created_by"`
|
||||
}
|
||||
|
||||
// Contract represents a contract/AVV document associated with a vendor
|
||||
type Contract struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id" db:"tenant_id"`
|
||||
VendorID uuid.UUID `json:"vendor_id" db:"vendor_id"`
|
||||
|
||||
// File metadata
|
||||
FileName string `json:"file_name" db:"file_name"`
|
||||
OriginalName string `json:"original_name" db:"original_name"`
|
||||
MimeType string `json:"mime_type" db:"mime_type"`
|
||||
FileSize *int64 `json:"file_size,omitempty" db:"file_size"`
|
||||
StoragePath string `json:"storage_path" db:"storage_path"`
|
||||
|
||||
// Document classification
|
||||
DocumentType DocumentType `json:"document_type" db:"document_type"`
|
||||
|
||||
// Contract details
|
||||
Parties json.RawMessage `json:"parties,omitempty" db:"parties"`
|
||||
EffectiveDate *time.Time `json:"effective_date,omitempty" db:"effective_date"`
|
||||
ExpirationDate *time.Time `json:"expiration_date,omitempty" db:"expiration_date"`
|
||||
AutoRenewal bool `json:"auto_renewal" db:"auto_renewal"`
|
||||
RenewalNoticePeriod string `json:"renewal_notice_period,omitempty" db:"renewal_notice_period"`
|
||||
|
||||
// Review
|
||||
ReviewStatus string `json:"review_status" db:"review_status"`
|
||||
ReviewCompletedAt *time.Time `json:"review_completed_at,omitempty" db:"review_completed_at"`
|
||||
ComplianceScore *int `json:"compliance_score,omitempty" db:"compliance_score"`
|
||||
|
||||
// Versioning
|
||||
Version string `json:"version" db:"version"`
|
||||
PreviousVersionID *string `json:"previous_version_id,omitempty" db:"previous_version_id"`
|
||||
|
||||
// Extracted content
|
||||
ExtractedText string `json:"extracted_text,omitempty" db:"extracted_text"`
|
||||
PageCount *int `json:"page_count,omitempty" db:"page_count"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
CreatedBy string `json:"created_by" db:"created_by"`
|
||||
}
|
||||
|
||||
// Finding represents a compliance finding from a contract review
|
||||
type Finding struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id" db:"tenant_id"`
|
||||
ContractID *string `json:"contract_id,omitempty" db:"contract_id"`
|
||||
VendorID uuid.UUID `json:"vendor_id" db:"vendor_id"`
|
||||
|
||||
// Finding details
|
||||
FindingType FindingType `json:"finding_type" db:"finding_type"`
|
||||
Category string `json:"category" db:"category"`
|
||||
Severity string `json:"severity" db:"severity"`
|
||||
Title string `json:"title" db:"title"`
|
||||
Description string `json:"description" db:"description"`
|
||||
Recommendation string `json:"recommendation,omitempty" db:"recommendation"`
|
||||
|
||||
// Evidence (JSONB)
|
||||
Citations json.RawMessage `json:"citations,omitempty" db:"citations"`
|
||||
|
||||
// Resolution workflow
|
||||
Status FindingStatus `json:"status" db:"status"`
|
||||
Assignee string `json:"assignee,omitempty" db:"assignee"`
|
||||
DueDate *time.Time `json:"due_date,omitempty" db:"due_date"`
|
||||
Resolution string `json:"resolution,omitempty" db:"resolution"`
|
||||
ResolvedAt *time.Time `json:"resolved_at,omitempty" db:"resolved_at"`
|
||||
ResolvedBy *string `json:"resolved_by,omitempty" db:"resolved_by"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
// ControlInstance represents an applied control assessment for a specific vendor
|
||||
type ControlInstance struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id" db:"tenant_id"`
|
||||
VendorID uuid.UUID `json:"vendor_id" db:"vendor_id"`
|
||||
|
||||
// Control reference
|
||||
ControlID string `json:"control_id" db:"control_id"`
|
||||
ControlDomain string `json:"control_domain" db:"control_domain"`
|
||||
|
||||
// Assessment
|
||||
Status ControlStatus `json:"status" db:"status"`
|
||||
EvidenceIDs json.RawMessage `json:"evidence_ids,omitempty" db:"evidence_ids"`
|
||||
Notes string `json:"notes,omitempty" db:"notes"`
|
||||
|
||||
// Assessment tracking
|
||||
LastAssessedAt *time.Time `json:"last_assessed_at,omitempty" db:"last_assessed_at"`
|
||||
LastAssessedBy *string `json:"last_assessed_by,omitempty" db:"last_assessed_by"`
|
||||
NextAssessmentDate *time.Time `json:"next_assessment_date,omitempty" db:"next_assessment_date"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
// Template represents a pre-filled vendor compliance template
|
||||
type Template struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
TenantID *string `json:"tenant_id,omitempty" db:"tenant_id"`
|
||||
|
||||
// Template classification
|
||||
TemplateType string `json:"template_type" db:"template_type"`
|
||||
TemplateID string `json:"template_id" db:"template_id"`
|
||||
Category string `json:"category" db:"category"`
|
||||
|
||||
// Localized names & descriptions
|
||||
NameDE string `json:"name_de" db:"name_de"`
|
||||
NameEN string `json:"name_en" db:"name_en"`
|
||||
DescriptionDE string `json:"description_de" db:"description_de"`
|
||||
DescriptionEN string `json:"description_en" db:"description_en"`
|
||||
|
||||
// Template content (JSONB)
|
||||
TemplateData json.RawMessage `json:"template_data" db:"template_data"`
|
||||
|
||||
// Classification
|
||||
Industry string `json:"industry,omitempty" db:"industry"`
|
||||
Tags json.RawMessage `json:"tags,omitempty" db:"tags"`
|
||||
|
||||
// Flags
|
||||
IsSystem bool `json:"is_system" db:"is_system"`
|
||||
IsActive bool `json:"is_active" db:"is_active"`
|
||||
|
||||
// Usage tracking
|
||||
UsageCount int `json:"usage_count" db:"usage_count"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// VendorStats contains aggregated vendor compliance statistics for a tenant
|
||||
type VendorStats struct {
|
||||
TotalVendors int `json:"total_vendors"`
|
||||
ByStatus map[string]int `json:"by_status"`
|
||||
ByRole map[string]int `json:"by_role"`
|
||||
ByRiskLevel map[string]int `json:"by_risk_level"`
|
||||
PendingReviews int `json:"pending_reviews"`
|
||||
ExpiredContracts int `json:"expired_contracts"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API Request/Response Types
|
||||
// ============================================================================
|
||||
|
||||
// -- Vendor -------------------------------------------------------------------
|
||||
|
||||
// CreateVendorRequest is the API request for creating a vendor
|
||||
type CreateVendorRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
LegalForm string `json:"legal_form,omitempty"`
|
||||
Country string `json:"country" binding:"required"`
|
||||
Address json.RawMessage `json:"address,omitempty"`
|
||||
Website string `json:"website,omitempty"`
|
||||
ContactName string `json:"contact_name,omitempty"`
|
||||
ContactEmail string `json:"contact_email,omitempty"`
|
||||
ContactPhone string `json:"contact_phone,omitempty"`
|
||||
ContactDepartment string `json:"contact_department,omitempty"`
|
||||
Role VendorRole `json:"role" binding:"required"`
|
||||
ServiceCategory string `json:"service_category,omitempty"`
|
||||
ServiceDescription string `json:"service_description,omitempty"`
|
||||
DataAccessLevel string `json:"data_access_level,omitempty"`
|
||||
ProcessingLocations json.RawMessage `json:"processing_locations,omitempty"`
|
||||
Certifications json.RawMessage `json:"certifications,omitempty"`
|
||||
ReviewFrequency string `json:"review_frequency,omitempty"`
|
||||
ProcessingActivityIDs json.RawMessage `json:"processing_activity_ids,omitempty"`
|
||||
TemplateID *string `json:"template_id,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateVendorRequest is the API request for updating a vendor
|
||||
type UpdateVendorRequest struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
LegalForm *string `json:"legal_form,omitempty"`
|
||||
Country *string `json:"country,omitempty"`
|
||||
Address json.RawMessage `json:"address,omitempty"`
|
||||
Website *string `json:"website,omitempty"`
|
||||
ContactName *string `json:"contact_name,omitempty"`
|
||||
ContactEmail *string `json:"contact_email,omitempty"`
|
||||
ContactPhone *string `json:"contact_phone,omitempty"`
|
||||
ContactDepartment *string `json:"contact_department,omitempty"`
|
||||
Role *VendorRole `json:"role,omitempty"`
|
||||
ServiceCategory *string `json:"service_category,omitempty"`
|
||||
ServiceDescription *string `json:"service_description,omitempty"`
|
||||
DataAccessLevel *string `json:"data_access_level,omitempty"`
|
||||
ProcessingLocations json.RawMessage `json:"processing_locations,omitempty"`
|
||||
Certifications json.RawMessage `json:"certifications,omitempty"`
|
||||
InherentRiskScore *int `json:"inherent_risk_score,omitempty"`
|
||||
ResidualRiskScore *int `json:"residual_risk_score,omitempty"`
|
||||
ManualRiskAdjustment *int `json:"manual_risk_adjustment,omitempty"`
|
||||
ReviewFrequency *string `json:"review_frequency,omitempty"`
|
||||
LastReviewDate *time.Time `json:"last_review_date,omitempty"`
|
||||
NextReviewDate *time.Time `json:"next_review_date,omitempty"`
|
||||
ProcessingActivityIDs json.RawMessage `json:"processing_activity_ids,omitempty"`
|
||||
Status *VendorStatus `json:"status,omitempty"`
|
||||
TemplateID *string `json:"template_id,omitempty"`
|
||||
}
|
||||
|
||||
// -- Contract -----------------------------------------------------------------
|
||||
|
||||
// CreateContractRequest is the API request for creating a contract
|
||||
type CreateContractRequest struct {
|
||||
VendorID uuid.UUID `json:"vendor_id" binding:"required"`
|
||||
FileName string `json:"file_name" binding:"required"`
|
||||
OriginalName string `json:"original_name" binding:"required"`
|
||||
MimeType string `json:"mime_type" binding:"required"`
|
||||
FileSize *int64 `json:"file_size,omitempty"`
|
||||
StoragePath string `json:"storage_path" binding:"required"`
|
||||
DocumentType DocumentType `json:"document_type" binding:"required"`
|
||||
Parties json.RawMessage `json:"parties,omitempty"`
|
||||
EffectiveDate *time.Time `json:"effective_date,omitempty"`
|
||||
ExpirationDate *time.Time `json:"expiration_date,omitempty"`
|
||||
AutoRenewal bool `json:"auto_renewal"`
|
||||
RenewalNoticePeriod string `json:"renewal_notice_period,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
PreviousVersionID *string `json:"previous_version_id,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateContractRequest is the API request for updating a contract
|
||||
type UpdateContractRequest struct {
|
||||
DocumentType *DocumentType `json:"document_type,omitempty"`
|
||||
Parties json.RawMessage `json:"parties,omitempty"`
|
||||
EffectiveDate *time.Time `json:"effective_date,omitempty"`
|
||||
ExpirationDate *time.Time `json:"expiration_date,omitempty"`
|
||||
AutoRenewal *bool `json:"auto_renewal,omitempty"`
|
||||
RenewalNoticePeriod *string `json:"renewal_notice_period,omitempty"`
|
||||
ReviewStatus *string `json:"review_status,omitempty"`
|
||||
ReviewCompletedAt *time.Time `json:"review_completed_at,omitempty"`
|
||||
ComplianceScore *int `json:"compliance_score,omitempty"`
|
||||
Version *string `json:"version,omitempty"`
|
||||
ExtractedText *string `json:"extracted_text,omitempty"`
|
||||
PageCount *int `json:"page_count,omitempty"`
|
||||
}
|
||||
|
||||
// -- Finding ------------------------------------------------------------------
|
||||
|
||||
// CreateFindingRequest is the API request for creating a compliance finding
|
||||
type CreateFindingRequest struct {
|
||||
ContractID *string `json:"contract_id,omitempty"`
|
||||
VendorID uuid.UUID `json:"vendor_id" binding:"required"`
|
||||
FindingType FindingType `json:"finding_type" binding:"required"`
|
||||
Category string `json:"category" binding:"required"`
|
||||
Severity string `json:"severity" binding:"required"`
|
||||
Title string `json:"title" binding:"required"`
|
||||
Description string `json:"description" binding:"required"`
|
||||
Recommendation string `json:"recommendation,omitempty"`
|
||||
Citations json.RawMessage `json:"citations,omitempty"`
|
||||
Assignee string `json:"assignee,omitempty"`
|
||||
DueDate *time.Time `json:"due_date,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateFindingRequest is the API request for updating a finding
|
||||
type UpdateFindingRequest struct {
|
||||
FindingType *FindingType `json:"finding_type,omitempty"`
|
||||
Category *string `json:"category,omitempty"`
|
||||
Severity *string `json:"severity,omitempty"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
Recommendation *string `json:"recommendation,omitempty"`
|
||||
Citations json.RawMessage `json:"citations,omitempty"`
|
||||
Status *FindingStatus `json:"status,omitempty"`
|
||||
Assignee *string `json:"assignee,omitempty"`
|
||||
DueDate *time.Time `json:"due_date,omitempty"`
|
||||
Resolution *string `json:"resolution,omitempty"`
|
||||
}
|
||||
|
||||
// ResolveFindingRequest is the API request for resolving a finding
|
||||
type ResolveFindingRequest struct {
|
||||
Resolution string `json:"resolution" binding:"required"`
|
||||
}
|
||||
|
||||
// -- ControlInstance ----------------------------------------------------------
|
||||
|
||||
// UpdateControlInstanceRequest is the API request for updating a control instance
|
||||
type UpdateControlInstanceRequest struct {
|
||||
Status *ControlStatus `json:"status,omitempty"`
|
||||
EvidenceIDs json.RawMessage `json:"evidence_ids,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
NextAssessmentDate *time.Time `json:"next_assessment_date,omitempty"`
|
||||
}
|
||||
|
||||
// -- Template -----------------------------------------------------------------
|
||||
|
||||
// CreateTemplateRequest is the API request for creating a vendor template
|
||||
type CreateTemplateRequest struct {
|
||||
TemplateType string `json:"template_type" binding:"required"`
|
||||
TemplateID string `json:"template_id" binding:"required"`
|
||||
Category string `json:"category" binding:"required"`
|
||||
NameDE string `json:"name_de" binding:"required"`
|
||||
NameEN string `json:"name_en" binding:"required"`
|
||||
DescriptionDE string `json:"description_de,omitempty"`
|
||||
DescriptionEN string `json:"description_en,omitempty"`
|
||||
TemplateData json.RawMessage `json:"template_data" binding:"required"`
|
||||
Industry string `json:"industry,omitempty"`
|
||||
Tags json.RawMessage `json:"tags,omitempty"`
|
||||
IsSystem bool `json:"is_system"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// List / Filter Types
|
||||
// ============================================================================
|
||||
|
||||
// VendorFilters defines filters for listing vendors
|
||||
type VendorFilters struct {
|
||||
Status VendorStatus
|
||||
Role VendorRole
|
||||
Search string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// ContractFilters defines filters for listing contracts
|
||||
type ContractFilters struct {
|
||||
VendorID *uuid.UUID
|
||||
DocumentType DocumentType
|
||||
ReviewStatus string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// FindingFilters defines filters for listing findings
|
||||
type FindingFilters struct {
|
||||
VendorID *uuid.UUID
|
||||
ContractID *string
|
||||
Status FindingStatus
|
||||
FindingType FindingType
|
||||
Severity string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// VendorListResponse is the API response for listing vendors
|
||||
type VendorListResponse struct {
|
||||
Vendors []Vendor `json:"vendors"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// ContractListResponse is the API response for listing contracts
|
||||
type ContractListResponse struct {
|
||||
Contracts []Contract `json:"contracts"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// FindingListResponse is the API response for listing findings
|
||||
type FindingListResponse struct {
|
||||
Findings []Finding `json:"findings"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
1116
ai-compliance-sdk/internal/vendor/store.go
vendored
1116
ai-compliance-sdk/internal/vendor/store.go
vendored
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user